edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from skywalking import Layer, Component
from skywalking import config
from skywalking.trace.carrier import Carrier
from skywalking.trace.context import get_context
from skywalking.trace.tags import TagMqBroker, TagMqTopic
link_vector = ['https://kafka-python.readthedocs.io']
support_matrix = {
'kafka-python': {
'>=3.6': ['2.0']
}
}
note = """"""
def install():
from kafka import KafkaProducer
from kafka import KafkaConsumer
_send = KafkaProducer.send
__poll_once = KafkaConsumer._poll_once
KafkaProducer.send = _sw_send_func(_send)
KafkaConsumer._poll_once = _sw__poll_once_func(__poll_once)
def _sw__poll_once_func(__poll_once):
def _sw__poll_once(this, timeout_ms, max_records, update_offsets=True):
res = __poll_once(this, timeout_ms, max_records, update_offsets=update_offsets)
if res:
brokers = ';'.join(this.config['bootstrap_servers'])
context = get_context()
topics = ';'.join(this._subscription.subscription
or [t.topic for t in this._subscription._user_assignment])
with context.new_entry_span(
op=f"Kafka/{topics}/Consumer/{this.config["group_id"] or ""}") as span:
for consumer_records in res.values():
for record in consumer_records:
carrier = Carrier()
for item in carrier:
for header in record.headers:
if item.key == header[0]:
item.val = str(header[1])
span.extract(carrier)
span.tag(TagMqBroker(brokers))
span.tag(TagMqTopic(topics))
span.layer = Layer.MQ
span.component = Component.KafkaConsumer
return res
return _sw__poll_once
def _sw_send_func(_send):
def _sw_send(this, topic, value=None, key=None, headers=None, partition=None, timestamp_ms=None):
# ignore trace & log reporter - skywalking self request
if config.protocol == 'kafka' and config.kafka_topic_segment == topic \
or config.kafka_topic_log == topic \
or config.kafka_topic_management == topic:
return _send(this, topic, value=value, key=key, headers=headers, partition=partition,
timestamp_ms=timestamp_ms)
peer = ';'.join(this.config['bootstrap_servers'])
context = get_context()
with context.new_exit_span(op=f'Kafka/{topic}/Producer' or '/', peer=peer,
component=Component.KafkaProducer) as span:
carrier = span.inject()
span.layer = Layer.MQ
if headers is None:
headers = []
for item in carrier:
headers.append((item.key, item.val.encode('utf-8')))
res = _send(this, topic, value=value, key=key, headers=headers, partition=partition,
timestamp_ms=timestamp_ms)
span.tag(TagMqBroker(peer))
span.tag(TagMqTopic(topic))
return res
return _sw_send
| #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from skywalking import Layer, Component
from skywalking import config
from skywalking.trace.carrier import Carrier
from skywalking.trace.context import get_context
from skywalking.trace.tags import TagMqBroker, TagMqTopic
link_vector = ['https://kafka-python.readthedocs.io']
support_matrix = {
'kafka-python': {
'>=3.6': ['2.0']
}
}
note = """"""
def install():
from kafka import KafkaProducer
from kafka import KafkaConsumer
_send = KafkaProducer.send
__poll_once = KafkaConsumer._poll_once
KafkaProducer.send = _sw_send_func(_send)
KafkaConsumer._poll_once = _sw__poll_once_func(__poll_once)
def _sw__poll_once_func(__poll_once):
def _sw__poll_once(this, timeout_ms, max_records, update_offsets=True):
res = __poll_once(this, timeout_ms, max_records, update_offsets=update_offsets)
if res:
brokers = ';'.join(this.config['bootstrap_servers'])
context = get_context()
topics = ';'.join(this._subscription.subscription
or [t.topic for t in this._subscription._user_assignment])
with context.new_entry_span(
op=f"Kafka/{topics}/Consumer/{this.config['group_id'] or ''}") as span:
for consumer_records in res.values():
for record in consumer_records:
carrier = Carrier()
for item in carrier:
for header in record.headers:
if item.key == header[0]:
item.val = str(header[1])
span.extract(carrier)
span.tag(TagMqBroker(brokers))
span.tag(TagMqTopic(topics))
span.layer = Layer.MQ
span.component = Component.KafkaConsumer
return res
return _sw__poll_once
def _sw_send_func(_send):
def _sw_send(this, topic, value=None, key=None, headers=None, partition=None, timestamp_ms=None):
# ignore trace & log reporter - skywalking self request
if config.protocol == 'kafka' and config.kafka_topic_segment == topic \
or config.kafka_topic_log == topic \
or config.kafka_topic_management == topic:
return _send(this, topic, value=value, key=key, headers=headers, partition=partition,
timestamp_ms=timestamp_ms)
peer = ';'.join(this.config['bootstrap_servers'])
context = get_context()
with context.new_exit_span(op=f'Kafka/{topic}/Producer' or '/', peer=peer,
component=Component.KafkaProducer) as span:
carrier = span.inject()
span.layer = Layer.MQ
if headers is None:
headers = []
for item in carrier:
headers.append((item.key, item.val.encode('utf-8')))
res = _send(this, topic, value=value, key=key, headers=headers, partition=partition,
timestamp_ms=timestamp_ms)
span.tag(TagMqBroker(peer))
span.tag(TagMqTopic(topic))
return res
return _sw_send
|
import os
import json
from web3 import Web3
import discord
from discord.ext import commands, tasks
BOT_TOKEN = os.environ["DISCORD_BOT_TOKEN"]
# Initialized Discord client
intents = discord.Intents.all()
intents.members = True
client = commands.Bot(intents=intents, help_command=None, command_prefix='&?')
# Initialize web3
project_id = os.environ['WEB3_INFURA_PROJECT_ID']
polygon_mainnet_endpoint = f'https://polygon-mainnet.infura.io/v3/{project_id}'
web3 = Web3(Web3.HTTPProvider(polygon_mainnet_endpoint))
assert(web3.isConnected())
def lp_contract_info(sushi_address, basePrice=1):
address = Web3.toChecksumAddress(sushi_address)
abi = json.loads('[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0Out","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1Out","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint112","name":"reserve0","type":"uint112"},{"indexed":false,"internalType":"uint112","name":"reserve1","type":"uint112"}],"name":"Sync","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MINIMUM_LIQUIDITY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getReserves","outputs":[{"internalType":"uint112","name":"_reserve0","type":"uint112"},{"internalType":"uint112","name":"_reserve1","type":"uint112"},{"internalType":"uint32","name":"_blockTimestampLast","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"kLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"liquidity","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"price0CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"price1CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"skim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount0Out","type":"uint256"},{"internalType":"uint256","name":"amount1Out","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sync","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"token0","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token1","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]') # noqa: E501
sushiLP = web3.eth.contract(address=address, abi=abi)
try:
Reserves = sushiLP.functions.getReserves().call()
# usdc-bct
if sushi_address == '0x1e67124681b402064cd0abe8ed1b5c79d2e02f64':
tokenPrice = Reserves[0]*basePrice*1e12/Reserves[1]
# bct-klima
else:
tokenPrice = Reserves[0]*basePrice/(Reserves[1]*1e9)
return(tokenPrice)
except Exception:
pass
def klima_info():
address = Web3.toChecksumAddress("0x4e78011Ce80ee02d2c3e649Fb657E45898257815")
abi = json.loads('[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"previousTWAPEpochPeriod","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTWAPEpochPeriod","type":"uint256"}],"name":"TWAPEpochChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousTWAPOracle","type":"address"},{"indexed":true,"internalType":"address","name":"newTWAPOracle","type":"address"}],"name":"TWAPOracleChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newTWAPSource","type":"address"}],"name":"TWAPSourceAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"removedTWAPSource","type":"address"}],"name":"TWAPSourceRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account_","type":"address"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"_burnFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newTWAPSourceDexPool_","type":"address"}],"name":"addTWAPSource","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account_","type":"address"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"burnFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newTWAPEpochPeriod_","type":"uint256"}],"name":"changeTWAPEpochPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newTWAPOracle_","type":"address"}],"name":"changeTWAPOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account_","type":"address"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"twapSourceToRemove_","type":"address"}],"name":"removeTWAPSource","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"vault_","type":"address"}],"name":"setVault","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner_","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"twapEpochPeriod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"twapOracle","outputs":[{"internalType":"contract ITWAPOracle","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"vault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}]') # noqa: E501
klima_contract = web3.eth.contract(address=address, abi=abi)
try:
total_supply = klima_contract.functions.totalSupply().call()
return(total_supply/1e9)
except Exception:
pass
def get_info():
bct_price = lp_contract_info(sushi_address='0x1e67124681b402064cd0abe8ed1b5c79d2e02f64')
klima_price = lp_contract_info(sushi_address='0x9803c7ae526049210a1725f7487af26fe2c24614', basePrice=bct_price) # noqa: E501
supply = klima_info()
return(klima_price, supply)
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
if not update_info.is_running():
update_info.start()
@tasks.loop(seconds=300)
async def update_info():
price, supply = get_info()
if price is not None:
print(f'${price:,.2f} KLIMA')
print(f'Marketcap: ${price*supply/1e6:,.1f}M')
for guild in client.guilds:
guser = guild.get_member(client.user.id)
await guser.edit(nick=f'${price:,.2f} KLIMA')
if supply is not None:
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=f'Marketcap: ${price*supply/1e6:,.1f}M')) # noqa: E501
client.run(BOT_TOKEN)
| import os
import json
from web3 import Web3
import discord
from discord.ext import commands, tasks
BOT_TOKEN = os.environ["DISCORD_BOT_TOKEN"]
# Initialized Discord client
intents = discord.Intents.all()
intents.members = True
client = commands.Bot(intents=intents, help_command=None, command_prefix='&?')
# Initialize web3
project_id = os.environ['WEB3_INFURA_PROJECT_ID']
polygon_mainnet_endpoint = f'https://polygon-mainnet.infura.io/v3/{project_id}'
web3 = Web3(Web3.HTTPProvider(polygon_mainnet_endpoint))
assert(web3.isConnected())
def lp_contract_info(sushi_address, basePrice=1):
address = Web3.toChecksumAddress(sushi_address)
abi = json.loads('[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0Out","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1Out","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint112","name":"reserve0","type":"uint112"},{"indexed":false,"internalType":"uint112","name":"reserve1","type":"uint112"}],"name":"Sync","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MINIMUM_LIQUIDITY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getReserves","outputs":[{"internalType":"uint112","name":"_reserve0","type":"uint112"},{"internalType":"uint112","name":"_reserve1","type":"uint112"},{"internalType":"uint32","name":"_blockTimestampLast","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"kLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"liquidity","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"price0CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"price1CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"skim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount0Out","type":"uint256"},{"internalType":"uint256","name":"amount1Out","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sync","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"token0","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token1","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]') # noqa: E501
sushiLP = web3.eth.contract(address=address, abi=abi)
try:
Reserves = sushiLP.functions.getReserves().call()
# usdc-bct
if sushi_address == '0x1e67124681b402064cd0abe8ed1b5c79d2e02f64':
tokenPrice = Reserves[0]*basePrice*1e12/Reserves[1]
# bct-klima
else:
tokenPrice = Reserves[0]*basePrice/(Reserves[1]*1e9)
return(tokenPrice)
except Exception:
pass
def klima_info():
address = Web3.toChecksumAddress("0x4e78011Ce80ee02d2c3e649Fb657E45898257815")
abi = json.loads('[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"previousTWAPEpochPeriod","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTWAPEpochPeriod","type":"uint256"}],"name":"TWAPEpochChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousTWAPOracle","type":"address"},{"indexed":true,"internalType":"address","name":"newTWAPOracle","type":"address"}],"name":"TWAPOracleChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newTWAPSource","type":"address"}],"name":"TWAPSourceAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"removedTWAPSource","type":"address"}],"name":"TWAPSourceRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account_","type":"address"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"_burnFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newTWAPSourceDexPool_","type":"address"}],"name":"addTWAPSource","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account_","type":"address"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"burnFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newTWAPEpochPeriod_","type":"uint256"}],"name":"changeTWAPEpochPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newTWAPOracle_","type":"address"}],"name":"changeTWAPOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account_","type":"address"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"twapSourceToRemove_","type":"address"}],"name":"removeTWAPSource","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"vault_","type":"address"}],"name":"setVault","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner_","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"twapEpochPeriod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"twapOracle","outputs":[{"internalType":"contract ITWAPOracle","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"vault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}]') # noqa: E501
klima_contract = web3.eth.contract(address=address, abi=abi)
try:
total_supply = klima_contract.functions.totalSupply().call()
return(total_supply/1e9)
except Exception:
pass
def get_info():
bct_price = lp_contract_info(sushi_address='0x1e67124681b402064cd0abe8ed1b5c79d2e02f64')
klima_price = lp_contract_info(sushi_address='0x9803c7ae526049210a1725f7487af26fe2c24614', basePrice=bct_price) # noqa: E501
supply = klima_info()
return(klima_price, supply)
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
if not update_info.is_running():
update_info.start()
@tasks.loop(seconds=300)
async def update_info():
price, supply = get_info()
if price is not None:
print(f'${price:,.2f} KLIMA')
print(f'Marketcap: ${price*supply/1e6:,.1f}M')
for guild in client.guilds:
guser = guild.get_member(client.user.id)
await guser.edit(nick=f'${price:,.2f} KLIMA')
if supply is not None:
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=f'Marketcap: ${price*supply/1e6:,.1f}M')) # noqa: E501
client.run(BOT_TOKEN)
|
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2017-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
from typing import *
import asyncio
import binascii
import collections
import collections.abc
import csv
import dataclasses
import enum
import io
import itertools
import json
import multiprocessing
import multiprocessing.reduction
import multiprocessing.util
import os
import random
import re
import sys
import threading
import time
import types
import unittest.case
import unittest.result
import unittest.runner
import unittest.signals
import warnings
import click
import edgedb
from edb.common import devmode
from edb.testbase import lang as tb_lang
from edb.testbase import server as tb
from . import cpython_state
from . import mproc_fixes
from . import styles
result: Optional[unittest.result.TestResult] = None
coverage_run: Optional[Any] = None
py_hash_secret: bytes = cpython_state.get_py_hash_secret()
py_random_seed: bytes = random.SystemRandom().randbytes(8)
def teardown_suite() -> None:
# The TestSuite methods are mutating the *result* object,
# and the suite itself does not hold any state whatsoever,
# and, in our case specifically, it doesn't even hold
# references to tests being run, so we can think of
# its methods as static.
suite = StreamingTestSuite()
suite._tearDownPreviousClass(None, result) # type: ignore[attr-defined]
suite._handleModuleTearDown(result) # type: ignore[attr-defined]
def init_worker(status_queue: multiprocessing.SimpleQueue,
param_queue: multiprocessing.SimpleQueue,
result_queue: multiprocessing.SimpleQueue) -> None:
global result
global coverage_run
global py_hash_secret
global py_random_seed
# Make sure the generator is re-seeded, as we have inherited
# the seed from the parent process.
py_random_seed = random.SystemRandom().randbytes(8)
random.seed(py_random_seed)
result = ChannelingTestResult(result_queue)
if not param_queue.empty():
server_addr, backend_dsn = param_queue.get()
if server_addr is not None:
os.environ['EDGEDB_TEST_CLUSTER_ADDR'] = json.dumps(server_addr)
if backend_dsn:
os.environ['EDGEDB_TEST_BACKEND_DSN'] = backend_dsn
os.environ['EDGEDB_TEST_PARALLEL'] = '1'
coverage_run = devmode.CoverageConfig.start_coverage_if_requested()
py_hash_secret = cpython_state.get_py_hash_secret()
status_queue.put(True)
def shutdown_worker() -> None:
global coverage_run
teardown_suite()
if coverage_run is not None:
coverage_run.stop()
coverage_run.save()
class StreamingTestSuite(unittest.TestSuite):
_cleanup = False
def run(self, test, result):
with warnings.catch_warnings(record=True) as ww:
warnings.resetwarnings()
warnings.simplefilter('default')
# This is temporary, until we implement `subtransaction`
# functionality of RFC1004
warnings.filterwarnings(
'ignore',
message=r'The "transaction\(\)" method is deprecated'
r' and is scheduled to be removed',
category=DeprecationWarning)
self._run(test, result)
if ww:
for wmsg in ww:
if wmsg.source is not None:
wmsg.source = str(wmsg.source)
result.addWarning(test, wmsg)
def _run(self, test, result):
result._testRunEntered = True
self._tearDownPreviousClass(test, result)
self._handleModuleFixture(test, result)
self._handleClassSetUp(test, result)
result._previousTestClass = test.__class__
if (getattr(test.__class__, '_classSetupFailed', False) or
getattr(result, '_moduleSetUpFailed', False)):
return
start = time.monotonic()
test.run(result)
elapsed = time.monotonic() - start
result.record_test_stats(test, {'running-time': elapsed})
result.annotate_test(test, {
'py-hash-secret': py_hash_secret,
'py-random-seed': py_random_seed,
})
result._testRunEntered = False
return result
def _run_test(workload):
suite = StreamingTestSuite()
if isinstance(workload, collections.abc.Iterable):
# Got a test suite
for test in workload:
suite.run(test, result)
else:
suite.run(workload, result)
def _is_exc_info(args):
return (
isinstance(args, tuple) and
len(args) == 3 and
issubclass(args[0], BaseException)
)
@dataclasses.dataclass
class SerializedServerError:
test_error: str
server_error: str
class ChannelingTestResultMeta(type):
@staticmethod
def get_wrapper(meth):
def _wrapper(self, *args, **kwargs):
args = list(args)
if args and _is_exc_info(args[-1]):
exc_info = args[-1]
err = self._exc_info_to_string(exc_info, args[0])
if isinstance(exc_info[1], edgedb.EdgeDBError):
srv_tb = exc_info[1].get_server_context()
if srv_tb:
err = SerializedServerError(err, srv_tb)
args[-1] = err
try:
self._queue.put((meth, args, kwargs))
except Exception:
print(
f'!!! Test worker child process: '
f'failed to serialize arguments for {meth}: '
f'*args={args} **kwargs={kwargs} !!!')
raise
return _wrapper
def __new__(mcls, name, bases, dct):
for meth in {'startTest', 'addSuccess', 'addError', 'addFailure',
'addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
'addSubTest', 'addWarning', 'record_test_stats',
'annotate_test'}:
dct[meth] = mcls.get_wrapper(meth)
return super().__new__(mcls, name, bases, dct)
class ChannelingTestResult(unittest.result.TestResult,
metaclass=ChannelingTestResultMeta):
def __init__(self, queue):
super().__init__(io.StringIO(), False, 1)
self._queue = queue
def _setupStdout(self):
pass
def _restoreStdout(self):
pass
def printErrors(self):
pass
def printErrorList(self, flavour, errors):
pass
def __getstate__(self):
state = self.__dict__.copy()
state.pop('_queue')
state.pop('_original_stdout')
state.pop('_original_stderr')
return state
def monitor_thread(queue, result):
while True:
methname, args, kwargs = queue.get()
if methname is None and args is None and kwargs is None:
# This must be the last message in the queue, injected
# when all tests are completed and the pool is about
# to be closed.
break
method = result
for part in methname.split('.'):
method = getattr(method, part)
method(*args, **kwargs)
class ParallelTestSuite(unittest.TestSuite):
def __init__(self, tests, server_conn, num_workers, backend_dsn):
self.tests = tests
self.server_conn = server_conn
self.num_workers = num_workers
self.stop_requested = False
self.backend_dsn = backend_dsn
def run(self, result):
# We use SimpleQueues because they are more predictable.
# They do the necessary IO directly, without using a
# helper thread.
result_queue = multiprocessing.SimpleQueue()
status_queue = multiprocessing.SimpleQueue()
worker_param_queue = multiprocessing.SimpleQueue()
# Prepopulate the worker param queue with server connection
# information.
for _ in range(self.num_workers):
worker_param_queue.put((self.server_conn, self.backend_dsn))
result_thread = threading.Thread(
name='test-monitor', target=monitor_thread,
args=(result_queue, result), daemon=True)
result_thread.start()
initargs = (status_queue, worker_param_queue, result_queue)
pool = multiprocessing.Pool(
self.num_workers,
initializer=mproc_fixes.WorkerScope(init_worker, shutdown_worker),
initargs=initargs)
# Wait for all workers to initialize.
for _ in range(self.num_workers):
status_queue.get()
with pool:
ar = pool.map_async(_run_test, iter(self.tests), chunksize=1)
while True:
try:
ar.get(timeout=0.1)
except multiprocessing.TimeoutError:
if self.stop_requested:
break
else:
continue
else:
break
# Post the terminal message to the queue so that
# test-monitor can stop.
result_queue.put((None, None, None))
# Give the test-monitor thread some time to
# process the queue messages. If something
# goes wrong, the thread will be forcibly
# joined by a timeout.
result_thread.join(timeout=3)
# Wait for pool to shutdown, this includes test teardowns.
pool.join()
return result
class SequentialTestSuite(unittest.TestSuite):
def __init__(self, tests, server_conn, backend_dsn):
self.tests = tests
self.server_conn = server_conn
self.stop_requested = False
self.backend_dsn = backend_dsn
def run(self, result_):
global result
result = result_
if self.server_conn:
os.environ['EDGEDB_TEST_CLUSTER_ADDR'] = \
json.dumps(self.server_conn)
if self.backend_dsn:
os.environ['EDGEDB_TEST_BACKEND_DSN'] = self.backend_dsn
random.seed(py_random_seed)
for test in self.tests:
_run_test(test)
if self.stop_requested:
break
# Make sure the class and the module teardown methods are
# executed for the trailing test, _run_test() does not do
# this for us.
teardown_suite()
return result
class Markers(enum.Enum):
passed = '.'
errored = 'E'
skipped = 's'
failed = 'F'
xfailed = 'x' # expected fail
not_implemented = '-'
upassed = 'U' # unexpected success
class OutputFormat(enum.Enum):
auto = 'auto'
simple = 'simple'
stacked = 'stacked'
verbose = 'verbose'
class BaseRenderer:
def __init__(self, *, tests, stream):
self.stream = stream
self.styles_map = {
marker.value: getattr(styles, f'marker_{marker.name}')
for marker in Markers}
def format_test(self, test):
if isinstance(test, unittest.case._SubTest):
if test.params:
params = ', '.join(
f'{k}={v!r}' for k, v in test.params.items())
else:
params = '<subtest>'
return f'{test.test_case} {{{params}}}'
else:
if hasattr(test, 'fail_notes') and test.fail_notes:
fail_notes = ', '.join(
f'{k}={v!r}' for k, v in test.fail_notes.items())
return f'{test} {{{fail_notes}}}'
else:
return str(test)
def report(self, test, marker, description=None, *, currently_running):
raise NotImplementedError
class SimpleRenderer(BaseRenderer):
def report(self, test, marker, description=None, *, currently_running):
click.echo(self.styles_map[marker.value](marker.value),
nl=False, file=self.stream)
class VerboseRenderer(BaseRenderer):
fullnames = {
Markers.passed: 'OK',
Markers.errored: 'ERROR',
Markers.skipped: 'SKIPPED',
Markers.failed: 'FAILED',
Markers.xfailed: 'expected failure',
Markers.not_implemented: 'not implemented',
Markers.upassed: 'unexpected success',
}
def _render_test(self, test, marker, description):
test_title = self.format_test(test)
if description:
return f'{test_title}: {self.fullnames[marker]}: {description}'
else:
return f'{test_title}: {self.fullnames[marker]}'
def report(self, test, marker, description=None, *, currently_running):
style = self.styles_map[marker.value]
click.echo(style(self._render_test(test, marker, description)),
file=self.stream)
class MultiLineRenderer(BaseRenderer):
FT_LABEL = 'First few failed: '
FT_MAX_LINES = 3
R_LABEL = 'Running: '
R_MAX_LINES = 3
def __init__(self, *, tests, stream):
super().__init__(tests=tests, stream=stream)
self.total_tests = len(tests)
self.completed_tests = 0
test_modules = {test.__class__.__module__ for test in tests}
max_test_module_len = max((len(self._render_modname(name))
for name in test_modules), default=0)
self.first_col_width = max_test_module_len + 1 # 1 == len(' ')
self.failed_tests = set()
self.buffer = collections.defaultdict(str)
self.last_lines = -1
self.max_lines = 0
self.max_label_lines_rendered = collections.defaultdict(int)
def report(self, test, marker, description=None, *, currently_running):
if marker in {Markers.failed, Markers.errored}:
test_name = test.id().rpartition('.')[2]
if ' ' in test_name:
test_name = test_name.split(' ')[0]
self.failed_tests.add(test_name)
self.buffer[test.__class__.__module__] += marker.value
self.completed_tests += 1
self._render(currently_running)
def _render_modname(self, name):
return name.replace('.', '/') + '.py'
def _color_second_column(self, line, style):
return line[:self.first_col_width] + style(line[self.first_col_width:])
def _render(self, currently_running):
def print_line(line):
if len(line) < cols:
line += ' ' * (cols - len(line))
lines.append(line)
def print_empty_line():
print_line(' ')
last_render = self.completed_tests == self.total_tests
cols, rows = click.get_terminal_size()
second_col_width = cols - self.first_col_width
def _render_test_list(label, max_lines, tests, style):
if (
len(label) > self.first_col_width
or cols - self.first_col_width <= 40
):
return
print_empty_line()
line = f'{label}{' ' * (self.first_col_width - len(label))}'
tests_lines = 1
for testi, test in enumerate(tests, 1):
last = testi == len(tests)
if not last:
test += ', '
test_name_len = len(test)
if len(line) + test_name_len < cols:
line += test
else:
if tests_lines == max_lines:
if len(line) + 3 < cols:
line += '...'
break
else:
line += (cols - len(line)) * ' '
line = self._color_second_column(line, style)
lines.append(line)
tests_lines += 1
line = self.first_col_width * ' '
if len(line) + test_name_len > cols:
continue
line += test
line += (cols - len(line)) * ' '
line = self._color_second_column(line, style)
lines.append(line)
# Prevent the rendered output from "jumping" up/down when we
# render 2 lines worth of running tests just after we rendered
# 3 lines.
for _ in range(self.max_label_lines_rendered[label] - tests_lines):
lines.append(' ' * cols)
self.max_label_lines_rendered[label] = max(
self.max_label_lines_rendered[label],
tests_lines
)
clear_cmd = ''
if self.last_lines > 0:
# Move cursor up `last_lines` times.
clear_cmd = f'\r\033[{self.last_lines}A'
lines = []
for mod, progress in self.buffer.items():
line = self._render_modname(mod).ljust(self.first_col_width, ' ')
while progress:
second_col = progress[:second_col_width]
second_col = second_col.ljust(second_col_width, ' ')
progress = progress[second_col_width:]
# Apply styles *after* slicing and padding the string
# (otherwise ANSI codes could be sliced in half).
second_col = re.sub(
r'\S',
lambda x: self.styles_map[x[0]](x[0]),
second_col)
lines.append(f'{line}{second_col}')
if line[0] != ' ':
line = ' ' * self.first_col_width
if not last_render:
if self.failed_tests:
_render_test_list(
self.FT_LABEL,
self.FT_MAX_LINES,
self.failed_tests,
styles.marker_errored,
)
running_tests = []
for test in currently_running:
test_name = test.id().rpartition('.')[2]
if ' ' in test_name:
test_name = test_name.split(' ')[0]
running_tests.append(test_name)
if not running_tests:
running_tests.append('...')
_render_test_list(
self.R_LABEL,
self.R_MAX_LINES,
running_tests,
styles.marker_passed
)
print_empty_line()
print_line(
f'Progress: {self.completed_tests}/{self.total_tests} tests.')
if last_render:
if self.max_lines > len(lines):
for _ in range(self.max_lines - len(lines)):
lines.insert(0, ' ' * cols)
else:
# If it's not the last test, check if our render buffer
# requires more rows than currently visible.
if len(lines) + 1 > rows:
# Scroll the render buffer to the bottom and
# cut the lines from the beginning, so that it
# will fit the screen.
#
# We need to do this because we can't move the
# cursor past the visible screen area, so if we
# render more data than the screen can fit, we
# will have lot's of garbage output.
lines = lines[len(lines) + 1 - rows:]
lines[0] = '^' * cols
# Hide cursor.
print('\033[?25l', end='', flush=True, file=self.stream)
try:
# Use `print` (not `click.echo`) because we want to
# precisely control when the output is flushed.
print(clear_cmd + '\n'.join(lines), flush=False, file=self.stream)
finally:
# Show cursor.
print('\033[?25h', end='', flush=True, file=self.stream)
self.last_lines = len(lines)
self.max_lines = max(self.last_lines, self.max_lines)
class ParallelTextTestResult(unittest.result.TestResult):
def __init__(self, *, stream, verbosity, warnings, tests,
output_format=OutputFormat.auto, failfast=False, suite):
super().__init__(stream, False, verbosity)
self.verbosity = verbosity
self.catch_warnings = warnings
self.failfast = failfast
self.test_stats = []
self.test_annotations = collections.defaultdict(dict)
self.warnings = []
self.notImplemented = []
self.currently_running = {}
# An index of all seen warnings to keep track
# of repeated warnings.
self._warnings = {}
self.suite = suite
if (output_format is OutputFormat.verbose or
(output_format is OutputFormat.auto and self.verbosity > 1)):
self.ren = VerboseRenderer(tests=tests, stream=stream)
elif (output_format is OutputFormat.stacked or
(output_format is OutputFormat.auto and stream.isatty() and
click.get_terminal_size()[0] > 60 and
os.name != 'nt')):
self.ren = MultiLineRenderer(tests=tests, stream=stream)
else:
self.ren = SimpleRenderer(tests=tests, stream=stream)
def report_progress(self, test, marker, description=None):
self.currently_running.pop(test, None)
self.ren.report(
test,
marker,
description,
currently_running=list(self.currently_running),
)
def record_test_stats(self, test, stats):
self.test_stats.append((test, stats))
def annotate_test(self, test, annotations: Dict[str, Any]) -> None:
self.test_annotations[test].update(annotations)
def get_test_annotations(self, test) -> Optional[Dict[str, Any]]:
return self.test_annotations.get(test)
def _exc_info_to_string(self, err, test):
# Errors are serialized in the worker.
return err
def getDescription(self, test):
return self.ren.format_test(test)
def startTest(self, test):
super().startTest(test)
self.currently_running[test] = True
def addSuccess(self, test):
super().addSuccess(test)
self.report_progress(test, Markers.passed)
def addError(self, test, err):
super().addError(test, err)
self.report_progress(test, Markers.errored)
if self.failfast:
self.suite.stop_requested = True
def addFailure(self, test, err):
super().addFailure(test, err)
self.report_progress(test, Markers.failed)
if self.failfast:
self.suite.stop_requested = True
def addSubTest(self, test, subtest, err):
if err is not None:
self.errors.append((subtest, self._exc_info_to_string(err, test)))
self._mirrorOutput = True
self.ren.report(
subtest,
Markers.errored,
currently_running=list(self.currently_running))
if self.failfast:
self.suite.stop_requested = True
def addSkip(self, test, reason):
super().addSkip(test, reason)
self.report_progress(test, Markers.skipped)
def addExpectedFailure(self, test, err):
method = getattr(test, test._testMethodName)
try:
reason = method.__et_xfail_reason__
not_impl = getattr(method, '__et_xfail_not_implemented__', False)
except AttributeError:
# Maybe the whole test case class is decorated?
reason = getattr(test, '__et_xfail_reason__', None)
not_impl = getattr(test, '__et_xfail_not_implemented__', False)
marker = Markers.not_implemented if not_impl else Markers.xfailed
if not_impl:
self.notImplemented.append(
(test, self._exc_info_to_string(err, test)))
else:
super().addExpectedFailure(test, err)
self.report_progress(test, marker, reason)
def addUnexpectedSuccess(self, test):
super().addUnexpectedSuccess(test)
self.report_progress(test, Markers.upassed)
def addWarning(self, test, wmsg):
if not self.catch_warnings:
return
key = str(wmsg.message), wmsg.filename, wmsg.lineno
if key not in self._warnings:
self._warnings[key] = wmsg
self.warnings.append((test, warnings.formatwarning(
wmsg.message, wmsg.category, wmsg.filename, wmsg.lineno,
wmsg.line
)))
def wasSuccessful(self):
# Overload TestResult.wasSuccessful to ignore unexpected successes
return (len(self.failures) == len(self.errors) == 0)
class ParallelTextTestRunner:
def __init__(self, *, stream=None, num_workers=1, verbosity=1,
output_format=OutputFormat.auto, warnings=True,
failfast=False, shuffle=False, backend_dsn=None):
self.stream = stream if stream is not None else sys.stderr
self.num_workers = num_workers
self.verbosity = verbosity
self.warnings = warnings
self.failfast = failfast
self.shuffle = shuffle
self.output_format = output_format
self.backend_dsn = backend_dsn
def run(self, test, selected_shard, total_shards, running_times_log_file):
session_start = time.monotonic()
cases = tb.get_test_cases([test])
stats = {}
if running_times_log_file:
running_times_log_file.seek(0)
stats = {
k: (float(v), int(c))
for k, v, c in csv.reader(running_times_log_file)
}
cases = tb.get_cases_by_shard(
cases, selected_shard, total_shards, self.verbosity, stats,
)
setup = tb.get_test_cases_setup(cases)
lang_setup = tb_lang.get_test_cases_setup(cases)
bootstrap_time_taken = 0
tests_time_taken = 0
result = None
cluster = None
conn = None
setup_stats = []
if lang_setup:
tb_lang.run_test_cases_setup(lang_setup, jobs=self.num_workers)
try:
if setup:
if self.verbosity >= 1:
self._echo(
'Populating test databases... ',
fg='white',
nl=False,
)
if self.verbosity > 1:
self._echo(
'\n -> Bootstrapping EdgeDB instance...',
fg='white',
nl=False,
)
async def _setup():
nonlocal cluster
nonlocal conn
cluster = await tb.init_cluster(
backend_dsn=self.backend_dsn,
cleanup_atexit=False,
)
if self.verbosity > 1:
self._echo(' OK')
conn = cluster.get_connect_args()
if cluster.has_create_database():
return await tb.setup_test_cases(
cases,
conn,
self.num_workers,
verbose=self.verbosity > 1,
)
else:
return []
setup_stats = asyncio.run(_setup())
if cluster.has_create_database():
os.environ.update({
'EDGEDB_TEST_CASES_SET_UP': "skip"
})
else:
os.environ.update({
'EDGEDB_TEST_CASES_SET_UP': "inplace"
})
os.environ.update({
'EDGEDB_TEST_HAS_CREATE_ROLE': str(
cluster.has_create_role()
)
})
bootstrap_time_taken = time.monotonic() - session_start
if self.verbosity >= 1:
self._echo('OK')
start = time.monotonic()
all_tests = list(itertools.chain.from_iterable(
tests for tests in cases.values()))
if self.num_workers > 1:
suite = ParallelTestSuite(
self._sort_tests(cases),
conn,
self.num_workers,
self.backend_dsn,
)
else:
suite = SequentialTestSuite(
self._sort_tests(cases),
conn,
self.backend_dsn,
)
result = ParallelTextTestResult(
stream=self.stream, verbosity=self.verbosity,
warnings=self.warnings, failfast=self.failfast,
output_format=self.output_format,
tests=all_tests, suite=suite)
unittest.signals.registerResult(result)
self._echo()
suite.run(result)
if running_times_log_file:
for test, stat in result.test_stats + setup_stats:
name = str(test)
t = stat['running-time']
at, c = stats.get(name, (0, 0))
stats[name] = (at + (t - at) / (c + 1), c + 1)
running_times_log_file.seek(0)
running_times_log_file.truncate()
writer = csv.writer(running_times_log_file)
for k, v in stats.items():
writer.writerow((k, ) + v)
tests_time_taken = time.monotonic() - start
except KeyboardInterrupt:
raise
finally:
if self.verbosity == 1:
self._echo()
if setup:
self._echo()
self._echo('Shutting down test cluster... ', nl=False)
tb._shutdown_cluster(cluster, destroy=True)
self._echo('OK.')
if result is not None:
self._render_result(
result, bootstrap_time_taken, tests_time_taken)
return result
def _get_term_width(self):
return click.get_terminal_size()[0] or 70
def _echo(self, s='', **kwargs):
if self.verbosity > 0:
click.secho(s, file=self.stream, **kwargs)
def _fill(self, char, **kwargs):
self._echo(char * self._get_term_width(), **kwargs)
def _format_time(self, seconds):
hours = int(seconds // 3600)
seconds %= 3600
minutes = int(seconds // 60)
seconds %= 60
return f'{hours:02d}:{minutes:02d}:{seconds:04.1f}'
def _print_errors(self, result):
uxsuccesses = ((s, '') for s in result.unexpectedSuccesses)
data = zip(
('WARNING', 'ERROR', 'FAIL', 'UNEXPECTED SUCCESS'),
('yellow', 'red', 'red', 'red'),
(result.warnings, result.errors, result.failures, uxsuccesses)
)
for kind, fg, errors in data:
for test, err in errors:
self._fill('=', fg=fg)
self._echo(f'{kind}: {result.getDescription(test)}',
fg=fg, bold=True)
self._fill('-', fg=fg)
if annos := result.get_test_annotations(test):
if phs := annos.get('py-hash-secret'):
phs_hex = binascii.hexlify(phs).decode()
self._echo(f'Py_HashSecret: {phs_hex}')
if prs := annos.get('py-random-seed'):
prs_hex = binascii.hexlify(prs).decode()
self._echo(f'random.seed(): {prs_hex}')
self._fill('-', fg=fg)
srv_tb = None
if _is_exc_info(err):
if isinstance(err[1], edgedb.EdgeDBError):
srv_tb = err[1].get_server_context()
err = unittest.result.TestResult._exc_info_to_string(
result, err, test)
elif isinstance(err, SerializedServerError):
err, srv_tb = err.test_error, err.server_error
if srv_tb:
self._echo('Server Traceback:',
fg='red', bold=True)
self._echo(srv_tb)
self._echo('Test Traceback:',
fg='red', bold=True)
self._echo(err)
def _render_result(self, result, boot_time_taken, tests_time_taken):
self._echo()
if self.verbosity > 0:
self._print_errors(result)
if result.wasSuccessful():
fg = 'green'
outcome = 'SUCCESS'
else:
fg = 'red'
outcome = 'FAILURE'
if self.verbosity > 1:
self._fill('=', fg=fg)
self._echo(outcome, fg=fg, bold=True)
counts = [('tests ran', result.testsRun)]
display = {
'expectedFailures': 'expected failures',
'notImplemented': 'not implemented',
'unexpectedSuccesses': 'unexpected successes',
}
for bit in ['failures', 'errors', 'expectedFailures',
'notImplemented', 'unexpectedSuccesses', 'skipped']:
count = len(getattr(result, bit))
if count:
counts.append((display.get(bit, bit), count))
for bit, count in counts:
self._echo(f' {bit}: ', nl=False)
self._echo(f'{count}', bold=True)
self._echo()
self._echo(f'Running times: ')
if boot_time_taken:
self._echo(' bootstrap: ', nl=False)
self._echo(self._format_time(boot_time_taken), bold=True)
self._echo(' tests: ', nl=False)
self._echo(self._format_time(tests_time_taken), bold=True)
if boot_time_taken:
self._echo(' total: ', nl=False)
self._echo(self._format_time(boot_time_taken + tests_time_taken),
bold=True)
self._echo()
return result
def _sort_tests(self, cases):
serialized_suites = {}
exclusive_suites = set()
exclusive_tests = []
for casecls, tests in cases.items():
gg = getattr(casecls, 'get_parallelism_granularity', None)
granularity = gg() if gg is not None else 'default'
if granularity == 'suite':
serialized_suites[casecls] = unittest.TestSuite(tests)
elif granularity == 'system':
exclusive_tests.extend(tests)
exclusive_suites.add(casecls)
tests = itertools.chain(
serialized_suites.values(),
itertools.chain.from_iterable(
tests for casecls, tests in cases.items()
if (
casecls not in serialized_suites
and casecls not in exclusive_suites
)
),
[unittest.TestSuite(exclusive_tests)],
)
test_list = list(tests)
if self.shuffle:
random.shuffle(test_list)
return test_list
# Disable pickling of traceback objects in multiprocessing.
# Test errors' tracebacks are serialized manually by
# `TestReesult._exc_info_to_string()`. Therefore we need
# to make sure that some random __traceback__ attribute
# doesn't crash the test results queue.
multiprocessing.reduction.ForkingPickler.register(
types.TracebackType,
lambda o: (_restore_Traceback, ()))
def _restore_Traceback():
return None
| #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2017-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
from typing import *
import asyncio
import binascii
import collections
import collections.abc
import csv
import dataclasses
import enum
import io
import itertools
import json
import multiprocessing
import multiprocessing.reduction
import multiprocessing.util
import os
import random
import re
import sys
import threading
import time
import types
import unittest.case
import unittest.result
import unittest.runner
import unittest.signals
import warnings
import click
import edgedb
from edb.common import devmode
from edb.testbase import lang as tb_lang
from edb.testbase import server as tb
from . import cpython_state
from . import mproc_fixes
from . import styles
result: Optional[unittest.result.TestResult] = None
coverage_run: Optional[Any] = None
py_hash_secret: bytes = cpython_state.get_py_hash_secret()
py_random_seed: bytes = random.SystemRandom().randbytes(8)
def teardown_suite() -> None:
# The TestSuite methods are mutating the *result* object,
# and the suite itself does not hold any state whatsoever,
# and, in our case specifically, it doesn't even hold
# references to tests being run, so we can think of
# its methods as static.
suite = StreamingTestSuite()
suite._tearDownPreviousClass(None, result) # type: ignore[attr-defined]
suite._handleModuleTearDown(result) # type: ignore[attr-defined]
def init_worker(status_queue: multiprocessing.SimpleQueue,
param_queue: multiprocessing.SimpleQueue,
result_queue: multiprocessing.SimpleQueue) -> None:
global result
global coverage_run
global py_hash_secret
global py_random_seed
# Make sure the generator is re-seeded, as we have inherited
# the seed from the parent process.
py_random_seed = random.SystemRandom().randbytes(8)
random.seed(py_random_seed)
result = ChannelingTestResult(result_queue)
if not param_queue.empty():
server_addr, backend_dsn = param_queue.get()
if server_addr is not None:
os.environ['EDGEDB_TEST_CLUSTER_ADDR'] = json.dumps(server_addr)
if backend_dsn:
os.environ['EDGEDB_TEST_BACKEND_DSN'] = backend_dsn
os.environ['EDGEDB_TEST_PARALLEL'] = '1'
coverage_run = devmode.CoverageConfig.start_coverage_if_requested()
py_hash_secret = cpython_state.get_py_hash_secret()
status_queue.put(True)
def shutdown_worker() -> None:
global coverage_run
teardown_suite()
if coverage_run is not None:
coverage_run.stop()
coverage_run.save()
class StreamingTestSuite(unittest.TestSuite):
_cleanup = False
def run(self, test, result):
with warnings.catch_warnings(record=True) as ww:
warnings.resetwarnings()
warnings.simplefilter('default')
# This is temporary, until we implement `subtransaction`
# functionality of RFC1004
warnings.filterwarnings(
'ignore',
message=r'The "transaction\(\)" method is deprecated'
r' and is scheduled to be removed',
category=DeprecationWarning)
self._run(test, result)
if ww:
for wmsg in ww:
if wmsg.source is not None:
wmsg.source = str(wmsg.source)
result.addWarning(test, wmsg)
def _run(self, test, result):
result._testRunEntered = True
self._tearDownPreviousClass(test, result)
self._handleModuleFixture(test, result)
self._handleClassSetUp(test, result)
result._previousTestClass = test.__class__
if (getattr(test.__class__, '_classSetupFailed', False) or
getattr(result, '_moduleSetUpFailed', False)):
return
start = time.monotonic()
test.run(result)
elapsed = time.monotonic() - start
result.record_test_stats(test, {'running-time': elapsed})
result.annotate_test(test, {
'py-hash-secret': py_hash_secret,
'py-random-seed': py_random_seed,
})
result._testRunEntered = False
return result
def _run_test(workload):
suite = StreamingTestSuite()
if isinstance(workload, collections.abc.Iterable):
# Got a test suite
for test in workload:
suite.run(test, result)
else:
suite.run(workload, result)
def _is_exc_info(args):
return (
isinstance(args, tuple) and
len(args) == 3 and
issubclass(args[0], BaseException)
)
@dataclasses.dataclass
class SerializedServerError:
test_error: str
server_error: str
class ChannelingTestResultMeta(type):
@staticmethod
def get_wrapper(meth):
def _wrapper(self, *args, **kwargs):
args = list(args)
if args and _is_exc_info(args[-1]):
exc_info = args[-1]
err = self._exc_info_to_string(exc_info, args[0])
if isinstance(exc_info[1], edgedb.EdgeDBError):
srv_tb = exc_info[1].get_server_context()
if srv_tb:
err = SerializedServerError(err, srv_tb)
args[-1] = err
try:
self._queue.put((meth, args, kwargs))
except Exception:
print(
f'!!! Test worker child process: '
f'failed to serialize arguments for {meth}: '
f'*args={args} **kwargs={kwargs} !!!')
raise
return _wrapper
def __new__(mcls, name, bases, dct):
for meth in {'startTest', 'addSuccess', 'addError', 'addFailure',
'addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
'addSubTest', 'addWarning', 'record_test_stats',
'annotate_test'}:
dct[meth] = mcls.get_wrapper(meth)
return super().__new__(mcls, name, bases, dct)
class ChannelingTestResult(unittest.result.TestResult,
metaclass=ChannelingTestResultMeta):
def __init__(self, queue):
super().__init__(io.StringIO(), False, 1)
self._queue = queue
def _setupStdout(self):
pass
def _restoreStdout(self):
pass
def printErrors(self):
pass
def printErrorList(self, flavour, errors):
pass
def __getstate__(self):
state = self.__dict__.copy()
state.pop('_queue')
state.pop('_original_stdout')
state.pop('_original_stderr')
return state
def monitor_thread(queue, result):
while True:
methname, args, kwargs = queue.get()
if methname is None and args is None and kwargs is None:
# This must be the last message in the queue, injected
# when all tests are completed and the pool is about
# to be closed.
break
method = result
for part in methname.split('.'):
method = getattr(method, part)
method(*args, **kwargs)
class ParallelTestSuite(unittest.TestSuite):
def __init__(self, tests, server_conn, num_workers, backend_dsn):
self.tests = tests
self.server_conn = server_conn
self.num_workers = num_workers
self.stop_requested = False
self.backend_dsn = backend_dsn
def run(self, result):
# We use SimpleQueues because they are more predictable.
# They do the necessary IO directly, without using a
# helper thread.
result_queue = multiprocessing.SimpleQueue()
status_queue = multiprocessing.SimpleQueue()
worker_param_queue = multiprocessing.SimpleQueue()
# Prepopulate the worker param queue with server connection
# information.
for _ in range(self.num_workers):
worker_param_queue.put((self.server_conn, self.backend_dsn))
result_thread = threading.Thread(
name='test-monitor', target=monitor_thread,
args=(result_queue, result), daemon=True)
result_thread.start()
initargs = (status_queue, worker_param_queue, result_queue)
pool = multiprocessing.Pool(
self.num_workers,
initializer=mproc_fixes.WorkerScope(init_worker, shutdown_worker),
initargs=initargs)
# Wait for all workers to initialize.
for _ in range(self.num_workers):
status_queue.get()
with pool:
ar = pool.map_async(_run_test, iter(self.tests), chunksize=1)
while True:
try:
ar.get(timeout=0.1)
except multiprocessing.TimeoutError:
if self.stop_requested:
break
else:
continue
else:
break
# Post the terminal message to the queue so that
# test-monitor can stop.
result_queue.put((None, None, None))
# Give the test-monitor thread some time to
# process the queue messages. If something
# goes wrong, the thread will be forcibly
# joined by a timeout.
result_thread.join(timeout=3)
# Wait for pool to shutdown, this includes test teardowns.
pool.join()
return result
class SequentialTestSuite(unittest.TestSuite):
def __init__(self, tests, server_conn, backend_dsn):
self.tests = tests
self.server_conn = server_conn
self.stop_requested = False
self.backend_dsn = backend_dsn
def run(self, result_):
global result
result = result_
if self.server_conn:
os.environ['EDGEDB_TEST_CLUSTER_ADDR'] = \
json.dumps(self.server_conn)
if self.backend_dsn:
os.environ['EDGEDB_TEST_BACKEND_DSN'] = self.backend_dsn
random.seed(py_random_seed)
for test in self.tests:
_run_test(test)
if self.stop_requested:
break
# Make sure the class and the module teardown methods are
# executed for the trailing test, _run_test() does not do
# this for us.
teardown_suite()
return result
class Markers(enum.Enum):
passed = '.'
errored = 'E'
skipped = 's'
failed = 'F'
xfailed = 'x' # expected fail
not_implemented = '-'
upassed = 'U' # unexpected success
class OutputFormat(enum.Enum):
auto = 'auto'
simple = 'simple'
stacked = 'stacked'
verbose = 'verbose'
class BaseRenderer:
def __init__(self, *, tests, stream):
self.stream = stream
self.styles_map = {
marker.value: getattr(styles, f'marker_{marker.name}')
for marker in Markers}
def format_test(self, test):
if isinstance(test, unittest.case._SubTest):
if test.params:
params = ', '.join(
f'{k}={v!r}' for k, v in test.params.items())
else:
params = '<subtest>'
return f'{test.test_case} {{{params}}}'
else:
if hasattr(test, 'fail_notes') and test.fail_notes:
fail_notes = ', '.join(
f'{k}={v!r}' for k, v in test.fail_notes.items())
return f'{test} {{{fail_notes}}}'
else:
return str(test)
def report(self, test, marker, description=None, *, currently_running):
raise NotImplementedError
class SimpleRenderer(BaseRenderer):
def report(self, test, marker, description=None, *, currently_running):
click.echo(self.styles_map[marker.value](marker.value),
nl=False, file=self.stream)
class VerboseRenderer(BaseRenderer):
fullnames = {
Markers.passed: 'OK',
Markers.errored: 'ERROR',
Markers.skipped: 'SKIPPED',
Markers.failed: 'FAILED',
Markers.xfailed: 'expected failure',
Markers.not_implemented: 'not implemented',
Markers.upassed: 'unexpected success',
}
def _render_test(self, test, marker, description):
test_title = self.format_test(test)
if description:
return f'{test_title}: {self.fullnames[marker]}: {description}'
else:
return f'{test_title}: {self.fullnames[marker]}'
def report(self, test, marker, description=None, *, currently_running):
style = self.styles_map[marker.value]
click.echo(style(self._render_test(test, marker, description)),
file=self.stream)
class MultiLineRenderer(BaseRenderer):
FT_LABEL = 'First few failed: '
FT_MAX_LINES = 3
R_LABEL = 'Running: '
R_MAX_LINES = 3
def __init__(self, *, tests, stream):
super().__init__(tests=tests, stream=stream)
self.total_tests = len(tests)
self.completed_tests = 0
test_modules = {test.__class__.__module__ for test in tests}
max_test_module_len = max((len(self._render_modname(name))
for name in test_modules), default=0)
self.first_col_width = max_test_module_len + 1 # 1 == len(' ')
self.failed_tests = set()
self.buffer = collections.defaultdict(str)
self.last_lines = -1
self.max_lines = 0
self.max_label_lines_rendered = collections.defaultdict(int)
def report(self, test, marker, description=None, *, currently_running):
if marker in {Markers.failed, Markers.errored}:
test_name = test.id().rpartition('.')[2]
if ' ' in test_name:
test_name = test_name.split(' ')[0]
self.failed_tests.add(test_name)
self.buffer[test.__class__.__module__] += marker.value
self.completed_tests += 1
self._render(currently_running)
def _render_modname(self, name):
return name.replace('.', '/') + '.py'
def _color_second_column(self, line, style):
return line[:self.first_col_width] + style(line[self.first_col_width:])
def _render(self, currently_running):
def print_line(line):
if len(line) < cols:
line += ' ' * (cols - len(line))
lines.append(line)
def print_empty_line():
print_line(' ')
last_render = self.completed_tests == self.total_tests
cols, rows = click.get_terminal_size()
second_col_width = cols - self.first_col_width
def _render_test_list(label, max_lines, tests, style):
if (
len(label) > self.first_col_width
or cols - self.first_col_width <= 40
):
return
print_empty_line()
line = f'{label}{" " * (self.first_col_width - len(label))}'
tests_lines = 1
for testi, test in enumerate(tests, 1):
last = testi == len(tests)
if not last:
test += ', '
test_name_len = len(test)
if len(line) + test_name_len < cols:
line += test
else:
if tests_lines == max_lines:
if len(line) + 3 < cols:
line += '...'
break
else:
line += (cols - len(line)) * ' '
line = self._color_second_column(line, style)
lines.append(line)
tests_lines += 1
line = self.first_col_width * ' '
if len(line) + test_name_len > cols:
continue
line += test
line += (cols - len(line)) * ' '
line = self._color_second_column(line, style)
lines.append(line)
# Prevent the rendered output from "jumping" up/down when we
# render 2 lines worth of running tests just after we rendered
# 3 lines.
for _ in range(self.max_label_lines_rendered[label] - tests_lines):
lines.append(' ' * cols)
self.max_label_lines_rendered[label] = max(
self.max_label_lines_rendered[label],
tests_lines
)
clear_cmd = ''
if self.last_lines > 0:
# Move cursor up `last_lines` times.
clear_cmd = f'\r\033[{self.last_lines}A'
lines = []
for mod, progress in self.buffer.items():
line = self._render_modname(mod).ljust(self.first_col_width, ' ')
while progress:
second_col = progress[:second_col_width]
second_col = second_col.ljust(second_col_width, ' ')
progress = progress[second_col_width:]
# Apply styles *after* slicing and padding the string
# (otherwise ANSI codes could be sliced in half).
second_col = re.sub(
r'\S',
lambda x: self.styles_map[x[0]](x[0]),
second_col)
lines.append(f'{line}{second_col}')
if line[0] != ' ':
line = ' ' * self.first_col_width
if not last_render:
if self.failed_tests:
_render_test_list(
self.FT_LABEL,
self.FT_MAX_LINES,
self.failed_tests,
styles.marker_errored,
)
running_tests = []
for test in currently_running:
test_name = test.id().rpartition('.')[2]
if ' ' in test_name:
test_name = test_name.split(' ')[0]
running_tests.append(test_name)
if not running_tests:
running_tests.append('...')
_render_test_list(
self.R_LABEL,
self.R_MAX_LINES,
running_tests,
styles.marker_passed
)
print_empty_line()
print_line(
f'Progress: {self.completed_tests}/{self.total_tests} tests.')
if last_render:
if self.max_lines > len(lines):
for _ in range(self.max_lines - len(lines)):
lines.insert(0, ' ' * cols)
else:
# If it's not the last test, check if our render buffer
# requires more rows than currently visible.
if len(lines) + 1 > rows:
# Scroll the render buffer to the bottom and
# cut the lines from the beginning, so that it
# will fit the screen.
#
# We need to do this because we can't move the
# cursor past the visible screen area, so if we
# render more data than the screen can fit, we
# will have lot's of garbage output.
lines = lines[len(lines) + 1 - rows:]
lines[0] = '^' * cols
# Hide cursor.
print('\033[?25l', end='', flush=True, file=self.stream)
try:
# Use `print` (not `click.echo`) because we want to
# precisely control when the output is flushed.
print(clear_cmd + '\n'.join(lines), flush=False, file=self.stream)
finally:
# Show cursor.
print('\033[?25h', end='', flush=True, file=self.stream)
self.last_lines = len(lines)
self.max_lines = max(self.last_lines, self.max_lines)
class ParallelTextTestResult(unittest.result.TestResult):
def __init__(self, *, stream, verbosity, warnings, tests,
output_format=OutputFormat.auto, failfast=False, suite):
super().__init__(stream, False, verbosity)
self.verbosity = verbosity
self.catch_warnings = warnings
self.failfast = failfast
self.test_stats = []
self.test_annotations = collections.defaultdict(dict)
self.warnings = []
self.notImplemented = []
self.currently_running = {}
# An index of all seen warnings to keep track
# of repeated warnings.
self._warnings = {}
self.suite = suite
if (output_format is OutputFormat.verbose or
(output_format is OutputFormat.auto and self.verbosity > 1)):
self.ren = VerboseRenderer(tests=tests, stream=stream)
elif (output_format is OutputFormat.stacked or
(output_format is OutputFormat.auto and stream.isatty() and
click.get_terminal_size()[0] > 60 and
os.name != 'nt')):
self.ren = MultiLineRenderer(tests=tests, stream=stream)
else:
self.ren = SimpleRenderer(tests=tests, stream=stream)
def report_progress(self, test, marker, description=None):
self.currently_running.pop(test, None)
self.ren.report(
test,
marker,
description,
currently_running=list(self.currently_running),
)
def record_test_stats(self, test, stats):
self.test_stats.append((test, stats))
def annotate_test(self, test, annotations: Dict[str, Any]) -> None:
self.test_annotations[test].update(annotations)
def get_test_annotations(self, test) -> Optional[Dict[str, Any]]:
return self.test_annotations.get(test)
def _exc_info_to_string(self, err, test):
# Errors are serialized in the worker.
return err
def getDescription(self, test):
return self.ren.format_test(test)
def startTest(self, test):
super().startTest(test)
self.currently_running[test] = True
def addSuccess(self, test):
super().addSuccess(test)
self.report_progress(test, Markers.passed)
def addError(self, test, err):
super().addError(test, err)
self.report_progress(test, Markers.errored)
if self.failfast:
self.suite.stop_requested = True
def addFailure(self, test, err):
super().addFailure(test, err)
self.report_progress(test, Markers.failed)
if self.failfast:
self.suite.stop_requested = True
def addSubTest(self, test, subtest, err):
if err is not None:
self.errors.append((subtest, self._exc_info_to_string(err, test)))
self._mirrorOutput = True
self.ren.report(
subtest,
Markers.errored,
currently_running=list(self.currently_running))
if self.failfast:
self.suite.stop_requested = True
def addSkip(self, test, reason):
super().addSkip(test, reason)
self.report_progress(test, Markers.skipped)
def addExpectedFailure(self, test, err):
method = getattr(test, test._testMethodName)
try:
reason = method.__et_xfail_reason__
not_impl = getattr(method, '__et_xfail_not_implemented__', False)
except AttributeError:
# Maybe the whole test case class is decorated?
reason = getattr(test, '__et_xfail_reason__', None)
not_impl = getattr(test, '__et_xfail_not_implemented__', False)
marker = Markers.not_implemented if not_impl else Markers.xfailed
if not_impl:
self.notImplemented.append(
(test, self._exc_info_to_string(err, test)))
else:
super().addExpectedFailure(test, err)
self.report_progress(test, marker, reason)
def addUnexpectedSuccess(self, test):
super().addUnexpectedSuccess(test)
self.report_progress(test, Markers.upassed)
def addWarning(self, test, wmsg):
if not self.catch_warnings:
return
key = str(wmsg.message), wmsg.filename, wmsg.lineno
if key not in self._warnings:
self._warnings[key] = wmsg
self.warnings.append((test, warnings.formatwarning(
wmsg.message, wmsg.category, wmsg.filename, wmsg.lineno,
wmsg.line
)))
def wasSuccessful(self):
# Overload TestResult.wasSuccessful to ignore unexpected successes
return (len(self.failures) == len(self.errors) == 0)
class ParallelTextTestRunner:
def __init__(self, *, stream=None, num_workers=1, verbosity=1,
output_format=OutputFormat.auto, warnings=True,
failfast=False, shuffle=False, backend_dsn=None):
self.stream = stream if stream is not None else sys.stderr
self.num_workers = num_workers
self.verbosity = verbosity
self.warnings = warnings
self.failfast = failfast
self.shuffle = shuffle
self.output_format = output_format
self.backend_dsn = backend_dsn
def run(self, test, selected_shard, total_shards, running_times_log_file):
session_start = time.monotonic()
cases = tb.get_test_cases([test])
stats = {}
if running_times_log_file:
running_times_log_file.seek(0)
stats = {
k: (float(v), int(c))
for k, v, c in csv.reader(running_times_log_file)
}
cases = tb.get_cases_by_shard(
cases, selected_shard, total_shards, self.verbosity, stats,
)
setup = tb.get_test_cases_setup(cases)
lang_setup = tb_lang.get_test_cases_setup(cases)
bootstrap_time_taken = 0
tests_time_taken = 0
result = None
cluster = None
conn = None
setup_stats = []
if lang_setup:
tb_lang.run_test_cases_setup(lang_setup, jobs=self.num_workers)
try:
if setup:
if self.verbosity >= 1:
self._echo(
'Populating test databases... ',
fg='white',
nl=False,
)
if self.verbosity > 1:
self._echo(
'\n -> Bootstrapping EdgeDB instance...',
fg='white',
nl=False,
)
async def _setup():
nonlocal cluster
nonlocal conn
cluster = await tb.init_cluster(
backend_dsn=self.backend_dsn,
cleanup_atexit=False,
)
if self.verbosity > 1:
self._echo(' OK')
conn = cluster.get_connect_args()
if cluster.has_create_database():
return await tb.setup_test_cases(
cases,
conn,
self.num_workers,
verbose=self.verbosity > 1,
)
else:
return []
setup_stats = asyncio.run(_setup())
if cluster.has_create_database():
os.environ.update({
'EDGEDB_TEST_CASES_SET_UP': "skip"
})
else:
os.environ.update({
'EDGEDB_TEST_CASES_SET_UP': "inplace"
})
os.environ.update({
'EDGEDB_TEST_HAS_CREATE_ROLE': str(
cluster.has_create_role()
)
})
bootstrap_time_taken = time.monotonic() - session_start
if self.verbosity >= 1:
self._echo('OK')
start = time.monotonic()
all_tests = list(itertools.chain.from_iterable(
tests for tests in cases.values()))
if self.num_workers > 1:
suite = ParallelTestSuite(
self._sort_tests(cases),
conn,
self.num_workers,
self.backend_dsn,
)
else:
suite = SequentialTestSuite(
self._sort_tests(cases),
conn,
self.backend_dsn,
)
result = ParallelTextTestResult(
stream=self.stream, verbosity=self.verbosity,
warnings=self.warnings, failfast=self.failfast,
output_format=self.output_format,
tests=all_tests, suite=suite)
unittest.signals.registerResult(result)
self._echo()
suite.run(result)
if running_times_log_file:
for test, stat in result.test_stats + setup_stats:
name = str(test)
t = stat['running-time']
at, c = stats.get(name, (0, 0))
stats[name] = (at + (t - at) / (c + 1), c + 1)
running_times_log_file.seek(0)
running_times_log_file.truncate()
writer = csv.writer(running_times_log_file)
for k, v in stats.items():
writer.writerow((k, ) + v)
tests_time_taken = time.monotonic() - start
except KeyboardInterrupt:
raise
finally:
if self.verbosity == 1:
self._echo()
if setup:
self._echo()
self._echo('Shutting down test cluster... ', nl=False)
tb._shutdown_cluster(cluster, destroy=True)
self._echo('OK.')
if result is not None:
self._render_result(
result, bootstrap_time_taken, tests_time_taken)
return result
def _get_term_width(self):
return click.get_terminal_size()[0] or 70
def _echo(self, s='', **kwargs):
if self.verbosity > 0:
click.secho(s, file=self.stream, **kwargs)
def _fill(self, char, **kwargs):
self._echo(char * self._get_term_width(), **kwargs)
def _format_time(self, seconds):
hours = int(seconds // 3600)
seconds %= 3600
minutes = int(seconds // 60)
seconds %= 60
return f'{hours:02d}:{minutes:02d}:{seconds:04.1f}'
def _print_errors(self, result):
uxsuccesses = ((s, '') for s in result.unexpectedSuccesses)
data = zip(
('WARNING', 'ERROR', 'FAIL', 'UNEXPECTED SUCCESS'),
('yellow', 'red', 'red', 'red'),
(result.warnings, result.errors, result.failures, uxsuccesses)
)
for kind, fg, errors in data:
for test, err in errors:
self._fill('=', fg=fg)
self._echo(f'{kind}: {result.getDescription(test)}',
fg=fg, bold=True)
self._fill('-', fg=fg)
if annos := result.get_test_annotations(test):
if phs := annos.get('py-hash-secret'):
phs_hex = binascii.hexlify(phs).decode()
self._echo(f'Py_HashSecret: {phs_hex}')
if prs := annos.get('py-random-seed'):
prs_hex = binascii.hexlify(prs).decode()
self._echo(f'random.seed(): {prs_hex}')
self._fill('-', fg=fg)
srv_tb = None
if _is_exc_info(err):
if isinstance(err[1], edgedb.EdgeDBError):
srv_tb = err[1].get_server_context()
err = unittest.result.TestResult._exc_info_to_string(
result, err, test)
elif isinstance(err, SerializedServerError):
err, srv_tb = err.test_error, err.server_error
if srv_tb:
self._echo('Server Traceback:',
fg='red', bold=True)
self._echo(srv_tb)
self._echo('Test Traceback:',
fg='red', bold=True)
self._echo(err)
def _render_result(self, result, boot_time_taken, tests_time_taken):
self._echo()
if self.verbosity > 0:
self._print_errors(result)
if result.wasSuccessful():
fg = 'green'
outcome = 'SUCCESS'
else:
fg = 'red'
outcome = 'FAILURE'
if self.verbosity > 1:
self._fill('=', fg=fg)
self._echo(outcome, fg=fg, bold=True)
counts = [('tests ran', result.testsRun)]
display = {
'expectedFailures': 'expected failures',
'notImplemented': 'not implemented',
'unexpectedSuccesses': 'unexpected successes',
}
for bit in ['failures', 'errors', 'expectedFailures',
'notImplemented', 'unexpectedSuccesses', 'skipped']:
count = len(getattr(result, bit))
if count:
counts.append((display.get(bit, bit), count))
for bit, count in counts:
self._echo(f' {bit}: ', nl=False)
self._echo(f'{count}', bold=True)
self._echo()
self._echo(f'Running times: ')
if boot_time_taken:
self._echo(' bootstrap: ', nl=False)
self._echo(self._format_time(boot_time_taken), bold=True)
self._echo(' tests: ', nl=False)
self._echo(self._format_time(tests_time_taken), bold=True)
if boot_time_taken:
self._echo(' total: ', nl=False)
self._echo(self._format_time(boot_time_taken + tests_time_taken),
bold=True)
self._echo()
return result
def _sort_tests(self, cases):
serialized_suites = {}
exclusive_suites = set()
exclusive_tests = []
for casecls, tests in cases.items():
gg = getattr(casecls, 'get_parallelism_granularity', None)
granularity = gg() if gg is not None else 'default'
if granularity == 'suite':
serialized_suites[casecls] = unittest.TestSuite(tests)
elif granularity == 'system':
exclusive_tests.extend(tests)
exclusive_suites.add(casecls)
tests = itertools.chain(
serialized_suites.values(),
itertools.chain.from_iterable(
tests for casecls, tests in cases.items()
if (
casecls not in serialized_suites
and casecls not in exclusive_suites
)
),
[unittest.TestSuite(exclusive_tests)],
)
test_list = list(tests)
if self.shuffle:
random.shuffle(test_list)
return test_list
# Disable pickling of traceback objects in multiprocessing.
# Test errors' tracebacks are serialized manually by
# `TestReesult._exc_info_to_string()`. Therefore we need
# to make sure that some random __traceback__ attribute
# doesn't crash the test results queue.
multiprocessing.reduction.ForkingPickler.register(
types.TracebackType,
lambda o: (_restore_Traceback, ()))
def _restore_Traceback():
return None
|
#!/usr/bin/env python3
"""
Adapted from https://github.com/numba/conda-recipe-cudatoolkit
BSD 2-Clause License
Copyright (c) 2018 Onwards, Quansight, LLC
Copyright (c) 2017, Continuum Analytics, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """
import glob
import json
import os
import shutil
import subprocess
import sys
import platform
import urllib.parse as urlparse
from pathlib import Path
from contextlib import contextmanager
from tempfile import TemporaryDirectory as tempdir
from distutils.dir_util import copy_tree
class Extractor(object):
"""Extractor base class, platform specific extractors should inherit
from this class.
"""
def __init__(self, cudatoolkit_config):
"""Initialise an instance:
Arguments:
cudatoolkit_config: the configuration for CUDA
platform_config - the configuration for this platform
"""
self.cu_name = cudatoolkit_config["name"]
self.cu_version = cudatoolkit_config["release"]
self.md5_url = cudatoolkit_config["md5_url"]
self.base_url = cudatoolkit_config["base_url"]
self.patch_url_text = cudatoolkit_config["patch_url_ext"]
self.installers_url_ext = cudatoolkit_config["installers_url_ext"]
self.cu_blob = cudatoolkit_config["blob"]
self.conda_prefix = os.environ.get("CONDA_PREFIX")
self.prefix = os.environ["PREFIX"]
self.src_dir = Path(self.conda_prefix) / "pkgs" / "cuda-toolkit"
self.blob_dir = Path(self.conda_prefix) / "pkgs" / self.cu_name
os.makedirs(self.blob_dir, exist_ok=True)
def download(self, url, target_full_path):
cmd = ["wget", url, "-O", target_full_path, "-q"]
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError as exc:
raise exc
def download_blobs(self):
"""Downloads the binary blobs to the $BLOB_DIR
"""
dl_url = urlparse.urljoin(self.base_url, self.installers_url_ext)
dl_url = urlparse.urljoin(dl_url, self.cu_blob)
dl_path = os.path.join(self.blob_dir, self.cu_blob)
if os.path.isfile(dl_path):
print("re-using previously downloaded %s" % (dl_path))
else:
print("downloading %s to %s" % (dl_url, dl_path))
self.download(dl_url, dl_path)
def extract(self, *args):
"""The method to extract files from the cuda binary blobs.
Platform specific extractors must implement.
"""
raise NotImplementedError("%s.extract(..)" % (type(self).__name__))
def copy_files(self, source, destination, ignore=None):
dest = Path(destination)
if dest.exists() and dest.is_dir():
shutil.rmtree(dest, ignore_errors=True)
elif dest.exists() and dest.is_file():
dest.unlink()
else:
shutil.copytree(
source, destination, symlinks=True, ignore=ignore, ignore_dangling_symlinks=True)
class LinuxExtractor(Extractor):
"""The Linux Extractor
"""
def extract(self):
# For better error messages
if os.path.exists("/tmp/cuda-installer.log"):
try:
os.remove("/tmp/cuda-installer.log")
except OSError as e:
raise RuntimeError(
"Failed to remove /tmp/cuda-installer.log") from e
print("Extracting on Linux")
runfile = self.blob_dir / self.cu_blob
os.chmod(runfile, 0o777)
with tempdir() as tmpdir:
cmd = [
str(runfile),
"--silent",
"--toolkit",
f"--toolkitpath={tmpdir}",
"--override"
]
subprocess.run(cmd, env=os.environ.copy(), check=True)
# Fix for conda-forge/cudatoolkit-dev-feedstock#44
if os.path.exists("/tmp/cuda-installer.log"):
os.remove("/tmp/cuda-installer.log")
toolkitpath = tmpdir
if not os.path.isdir(toolkitpath):
print('STATUS:',status)
for fn in glob.glob('/tmp/cuda_install_*.log'):
f = open(fn, 'r')
print('-'*100, fn)
print(f.read())
print('-'*100)
f.close()
os.system('ldd --version')
os.system('ls -la %s' % (tmpdir))
raise RuntimeError(
'Something went wrong in executing `{}`: directory `{}` does not exist'
.format(' '.join(cmd), toolkitpath))
self.copy_files(toolkitpath, self.src_dir)
os.remove(runfile)
class WinExtractor(Extractor):
"""The Windows extractor
"""
def download(self, url, target_full_path):
cmd = ["curl", url, "-o", target_full_path]
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError as exc:
raise exc
def extract(self):
print("Extracting on Windows")
runfile = self.blob_dir / self.cu_blob
with tempdir() as tmpdir:
cmd = [
"7za",
"x",
str(runfile),
f"-o{tmpdir}"
]
subprocess.run(cmd, env=os.environ.copy(), check=True)
toolkitpath = tmpdir
if not os.path.isdir(toolkitpath):
print('STATUS:',status)
os.system('dir %s' % (tmpdir))
raise RuntimeError(
'Something went wrong in executing `{}`: directory `{}` does not exist'
.format(' '.join(cmd), toolkitpath))
# Copy installation to pkgs folder, to be linked to conda_prefix by hardlinks.
# Hardlinks are selected over symlinks, because Windows 10 requires either admin privileges or developer mode enabled (since Creators Update) for the creation of symlinks.
# These options are not guaranteed at the user end.
target_dir = self.src_dir
nvcc_dir = os.path.join(target_dir, "nvcc")
# ignore=shutil.ignore_patterns('*.nvi')
for toolkitpathroot, subdirs, files in os.walk(toolkitpath):
for file in files:
src_file = os.path.join(toolkitpathroot, file)
os.chmod(src_file, 0o777)
for subdir in subdirs:
if subdir in ['CUDAVisualStudioIntegration'] and (subdir not in Path(toolkitpathroot).parts ):
src = os.path.join(toolkitpathroot, subdir)
dst = os.path.join(target_dir, subdir)
copy_tree(src, dst)
elif subdir in ['bin','include','lib','extras','libdevice','nvvm'] and (subdir not in Path(toolkitpathroot).parts ):
src = os.path.join(toolkitpathroot, subdir)
nvcc_dst = os.path.join(nvcc_dir, subdir)
copy_tree(src, nvcc_dst)
os.remove(runfile)
# create hard links of the whole toolkit into %LIBRARY_PREFIX%
self.create_hardlinks_into_prefix()
def create_hardlinks_into_prefix(self):
src_root = os.path.join(self.src_dir, "nvcc")
dst_root = os.path.join(self.prefix, "Library")
for root, dirs, files in os.walk(src_root):
current_dst_root = os.path.join(dst_root, os.path.relpath(root, src_root))
for d in dirs:
os.makedirs(os.path.join(current_dst_root, d), exist_ok=True)
for f in files:
dst_file = os.path.join(current_dst_root, f)
src_file = os.path.join(root, f)
# if dst_file does not exist yet, create a hard link
if not os.path.exists(dst_file):
os.link(src_file, dst_file)
#print("hard link: {} --> {}".format(src_file, dst_file))
@contextmanager
def _hdiutil_mount(mntpnt, image):
subprocess.check_call(["hdiutil", "attach", "-mountpoint", mntpnt, image])
yield mntpnt
subprocess.check_call(["hdiutil", "detach", mntpnt])
def check_platform():
plt = sys.platform
if plt.startswith("linux") or plt.startswith("win"):
return
else:
raise RuntimeError("Unsupported platform: %s" % (plt))
def set_config():
"""Set necessary configurations"""
cudatoolkit = {}
prefix = Path(os.environ["PREFIX"])
extra_args = dict()
with open(prefix / "bin" / "cudatoolkit-dev-extra-args.json", "r") as f:
extra_args = json.loads(f.read())
cudatoolkit["version"] = os.environ["PKG_VERSION"]
cudatoolkit["name"] = os.environ["PKG_NAME"]
cudatoolkit["buildnum"] = os.environ["PKG_BUILDNUM"]
cudatoolkit["version_build"] = extra_args["version_build"]
cudatoolkit["driver_version"] = extra_args["driver_version"]
cudatoolkit["release"] = extra_args["release"]
url_dev = os.environ.get(
"PROXY_DEV_NVIDIA", "https://developer.download.nvidia.com/"
)
url_dev_download = os.environ.get(
"PROXY_DEV_DOWNLOAD_NVIDIA", "http://developer.download.nvidia.com/"
)
url_prod_ext = f'compute/cuda/{cudatoolkit['version']}/'
cudatoolkit["base_url"] = urlparse.urljoin(url_dev, url_prod_ext)
cudatoolkit["md5_url"] = urlparse.urljoin(
url_dev_download, url_prod_ext + "docs/sidebar/md5sum.txt"
)
cudatoolkit["installers_url_ext"] = f"local_installers/"
cudatoolkit["patch_url_ext"] = f""
if sys.platform.startswith("win"):
cudatoolkit["blob"] = f'cuda_{cudatoolkit['version']}_{cudatoolkit['driver_version']}_win10.exe'
else:
cudatoolkit["blob"] = f'cuda_{cudatoolkit['version']}_{cudatoolkit['driver_version']}_linux.run'
return cudatoolkit
def _main():
print("Running Post installation")
os.environ['DISPLAY'] = ''
cudatoolkit_config = set_config()
# get an extractor
check_platform()
extractor = WinExtractor(cudatoolkit_config) if sys.platform.startswith("win") else LinuxExtractor(cudatoolkit_config)
# download binaries
extractor.download_blobs()
# Extract
extractor.extract()
if __name__ == "__main__":
_main()
| #!/usr/bin/env python3
"""
Adapted from https://github.com/numba/conda-recipe-cudatoolkit
BSD 2-Clause License
Copyright (c) 2018 Onwards, Quansight, LLC
Copyright (c) 2017, Continuum Analytics, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """
import glob
import json
import os
import shutil
import subprocess
import sys
import platform
import urllib.parse as urlparse
from pathlib import Path
from contextlib import contextmanager
from tempfile import TemporaryDirectory as tempdir
from distutils.dir_util import copy_tree
class Extractor(object):
"""Extractor base class, platform specific extractors should inherit
from this class.
"""
def __init__(self, cudatoolkit_config):
"""Initialise an instance:
Arguments:
cudatoolkit_config: the configuration for CUDA
platform_config - the configuration for this platform
"""
self.cu_name = cudatoolkit_config["name"]
self.cu_version = cudatoolkit_config["release"]
self.md5_url = cudatoolkit_config["md5_url"]
self.base_url = cudatoolkit_config["base_url"]
self.patch_url_text = cudatoolkit_config["patch_url_ext"]
self.installers_url_ext = cudatoolkit_config["installers_url_ext"]
self.cu_blob = cudatoolkit_config["blob"]
self.conda_prefix = os.environ.get("CONDA_PREFIX")
self.prefix = os.environ["PREFIX"]
self.src_dir = Path(self.conda_prefix) / "pkgs" / "cuda-toolkit"
self.blob_dir = Path(self.conda_prefix) / "pkgs" / self.cu_name
os.makedirs(self.blob_dir, exist_ok=True)
def download(self, url, target_full_path):
cmd = ["wget", url, "-O", target_full_path, "-q"]
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError as exc:
raise exc
def download_blobs(self):
"""Downloads the binary blobs to the $BLOB_DIR
"""
dl_url = urlparse.urljoin(self.base_url, self.installers_url_ext)
dl_url = urlparse.urljoin(dl_url, self.cu_blob)
dl_path = os.path.join(self.blob_dir, self.cu_blob)
if os.path.isfile(dl_path):
print("re-using previously downloaded %s" % (dl_path))
else:
print("downloading %s to %s" % (dl_url, dl_path))
self.download(dl_url, dl_path)
def extract(self, *args):
"""The method to extract files from the cuda binary blobs.
Platform specific extractors must implement.
"""
raise NotImplementedError("%s.extract(..)" % (type(self).__name__))
def copy_files(self, source, destination, ignore=None):
dest = Path(destination)
if dest.exists() and dest.is_dir():
shutil.rmtree(dest, ignore_errors=True)
elif dest.exists() and dest.is_file():
dest.unlink()
else:
shutil.copytree(
source, destination, symlinks=True, ignore=ignore, ignore_dangling_symlinks=True)
class LinuxExtractor(Extractor):
"""The Linux Extractor
"""
def extract(self):
# For better error messages
if os.path.exists("/tmp/cuda-installer.log"):
try:
os.remove("/tmp/cuda-installer.log")
except OSError as e:
raise RuntimeError(
"Failed to remove /tmp/cuda-installer.log") from e
print("Extracting on Linux")
runfile = self.blob_dir / self.cu_blob
os.chmod(runfile, 0o777)
with tempdir() as tmpdir:
cmd = [
str(runfile),
"--silent",
"--toolkit",
f"--toolkitpath={tmpdir}",
"--override"
]
subprocess.run(cmd, env=os.environ.copy(), check=True)
# Fix for conda-forge/cudatoolkit-dev-feedstock#44
if os.path.exists("/tmp/cuda-installer.log"):
os.remove("/tmp/cuda-installer.log")
toolkitpath = tmpdir
if not os.path.isdir(toolkitpath):
print('STATUS:',status)
for fn in glob.glob('/tmp/cuda_install_*.log'):
f = open(fn, 'r')
print('-'*100, fn)
print(f.read())
print('-'*100)
f.close()
os.system('ldd --version')
os.system('ls -la %s' % (tmpdir))
raise RuntimeError(
'Something went wrong in executing `{}`: directory `{}` does not exist'
.format(' '.join(cmd), toolkitpath))
self.copy_files(toolkitpath, self.src_dir)
os.remove(runfile)
class WinExtractor(Extractor):
"""The Windows extractor
"""
def download(self, url, target_full_path):
cmd = ["curl", url, "-o", target_full_path]
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError as exc:
raise exc
def extract(self):
print("Extracting on Windows")
runfile = self.blob_dir / self.cu_blob
with tempdir() as tmpdir:
cmd = [
"7za",
"x",
str(runfile),
f"-o{tmpdir}"
]
subprocess.run(cmd, env=os.environ.copy(), check=True)
toolkitpath = tmpdir
if not os.path.isdir(toolkitpath):
print('STATUS:',status)
os.system('dir %s' % (tmpdir))
raise RuntimeError(
'Something went wrong in executing `{}`: directory `{}` does not exist'
.format(' '.join(cmd), toolkitpath))
# Copy installation to pkgs folder, to be linked to conda_prefix by hardlinks.
# Hardlinks are selected over symlinks, because Windows 10 requires either admin privileges or developer mode enabled (since Creators Update) for the creation of symlinks.
# These options are not guaranteed at the user end.
target_dir = self.src_dir
nvcc_dir = os.path.join(target_dir, "nvcc")
# ignore=shutil.ignore_patterns('*.nvi')
for toolkitpathroot, subdirs, files in os.walk(toolkitpath):
for file in files:
src_file = os.path.join(toolkitpathroot, file)
os.chmod(src_file, 0o777)
for subdir in subdirs:
if subdir in ['CUDAVisualStudioIntegration'] and (subdir not in Path(toolkitpathroot).parts ):
src = os.path.join(toolkitpathroot, subdir)
dst = os.path.join(target_dir, subdir)
copy_tree(src, dst)
elif subdir in ['bin','include','lib','extras','libdevice','nvvm'] and (subdir not in Path(toolkitpathroot).parts ):
src = os.path.join(toolkitpathroot, subdir)
nvcc_dst = os.path.join(nvcc_dir, subdir)
copy_tree(src, nvcc_dst)
os.remove(runfile)
# create hard links of the whole toolkit into %LIBRARY_PREFIX%
self.create_hardlinks_into_prefix()
def create_hardlinks_into_prefix(self):
src_root = os.path.join(self.src_dir, "nvcc")
dst_root = os.path.join(self.prefix, "Library")
for root, dirs, files in os.walk(src_root):
current_dst_root = os.path.join(dst_root, os.path.relpath(root, src_root))
for d in dirs:
os.makedirs(os.path.join(current_dst_root, d), exist_ok=True)
for f in files:
dst_file = os.path.join(current_dst_root, f)
src_file = os.path.join(root, f)
# if dst_file does not exist yet, create a hard link
if not os.path.exists(dst_file):
os.link(src_file, dst_file)
#print("hard link: {} --> {}".format(src_file, dst_file))
@contextmanager
def _hdiutil_mount(mntpnt, image):
subprocess.check_call(["hdiutil", "attach", "-mountpoint", mntpnt, image])
yield mntpnt
subprocess.check_call(["hdiutil", "detach", mntpnt])
def check_platform():
plt = sys.platform
if plt.startswith("linux") or plt.startswith("win"):
return
else:
raise RuntimeError("Unsupported platform: %s" % (plt))
def set_config():
"""Set necessary configurations"""
cudatoolkit = {}
prefix = Path(os.environ["PREFIX"])
extra_args = dict()
with open(prefix / "bin" / "cudatoolkit-dev-extra-args.json", "r") as f:
extra_args = json.loads(f.read())
cudatoolkit["version"] = os.environ["PKG_VERSION"]
cudatoolkit["name"] = os.environ["PKG_NAME"]
cudatoolkit["buildnum"] = os.environ["PKG_BUILDNUM"]
cudatoolkit["version_build"] = extra_args["version_build"]
cudatoolkit["driver_version"] = extra_args["driver_version"]
cudatoolkit["release"] = extra_args["release"]
url_dev = os.environ.get(
"PROXY_DEV_NVIDIA", "https://developer.download.nvidia.com/"
)
url_dev_download = os.environ.get(
"PROXY_DEV_DOWNLOAD_NVIDIA", "http://developer.download.nvidia.com/"
)
url_prod_ext = f'compute/cuda/{cudatoolkit["version"]}/'
cudatoolkit["base_url"] = urlparse.urljoin(url_dev, url_prod_ext)
cudatoolkit["md5_url"] = urlparse.urljoin(
url_dev_download, url_prod_ext + "docs/sidebar/md5sum.txt"
)
cudatoolkit["installers_url_ext"] = f"local_installers/"
cudatoolkit["patch_url_ext"] = f""
if sys.platform.startswith("win"):
cudatoolkit["blob"] = f'cuda_{cudatoolkit["version"]}_{cudatoolkit["driver_version"]}_win10.exe'
else:
cudatoolkit["blob"] = f'cuda_{cudatoolkit["version"]}_{cudatoolkit["driver_version"]}_linux.run'
return cudatoolkit
def _main():
print("Running Post installation")
os.environ['DISPLAY'] = ''
cudatoolkit_config = set_config()
# get an extractor
check_platform()
extractor = WinExtractor(cudatoolkit_config) if sys.platform.startswith("win") else LinuxExtractor(cudatoolkit_config)
# download binaries
extractor.download_blobs()
# Extract
extractor.extract()
if __name__ == "__main__":
_main()
|
import contextlib
import fnmatch
import io
import math
import os
import re
import shutil
import sys
import tempfile
import textwrap
import zipfile
from datetime import datetime
import requests
import sarge
from .xml import ( # noqa
elementtree_parse_file,
remove_xml_element,
remove_xml_element_file,
remove_xml_element_string,
)
from .ziputils import process_text_in_zipfile # noqa
from .ziputils import zip_subfolder
CUMULUSCI_PATH = os.path.realpath(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..")
)
META_XML_CLEAN_DIRS = ("classes/", "triggers/", "pages/", "aura/", "components/")
API_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
DATETIME_LEN = len("2018-08-07T16:00:56.000")
BREW_UPDATE_CMD = "brew upgrade cumulusci"
PIP_UPDATE_CMD = "pip install --upgrade cumulusci"
PIPX_UPDATE_CMD = "pipx upgrade cumulusci"
def parse_api_datetime(value):
"""parse a datetime returned from the salesforce API.
in python 3 we should just use a strptime %z, but until then we're just going
to assert that its a fixed offset of +0000 since thats the observed behavior. getting
python 2 to support fixed offset parsing is too complicated for what we need imo."""
dt = datetime.strptime(value[0:DATETIME_LEN], API_DATE_FORMAT)
offset_str = value[DATETIME_LEN:]
assert offset_str in ["+0000", "Z"], "The Salesforce API returned a weird timezone."
return dt
def find_replace(find, replace, directory, filePattern, logger=None, max=None):
"""Recursive find/replace.
Walks through files matching `filePattern` within `directory`
and does a string substitution of `find` with `replace`.
"""
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
with io.open(filepath, encoding="utf-8") as f:
s = f.read()
if max:
s_updated = s.replace(find, replace, max)
else:
s_updated = s.replace(find, replace)
if s != s_updated:
if logger:
logger.info("Updating {}".format(filepath))
with io.open(filepath, "w", encoding="utf-8") as f:
f.write(s_updated)
def find_replace_regex(find, replace, directory, filePattern, logger=None):
"""Recursive find/replace using a regular expression.
Walks through files matching `filePattern` within `directory`
and does a regex substitution of `find` with `replace`.
"""
pattern = re.compile(find)
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
with io.open(filepath, encoding="utf-8") as f:
s = f.read()
s_updated = pattern.sub(replace, s)
if s != s_updated:
if logger:
logger.info("Updating {}".format(filepath))
with io.open(filepath, "w", encoding="utf-8") as f:
f.write(s_updated)
def find_rename(find, replace, directory, logger=None):
"""Recursive find/replace within filenames.
Walks through files within `directory`
and renames files to replace `find` with `replace`.
"""
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in files:
filepath = os.path.join(path, filename)
if logger:
logger.info("Renaming {}".format(filepath))
os.rename(filepath, os.path.join(path, filename.replace(find, replace)))
def remove_xml_element_directory(name, directory, file_pattern, logger=None):
"""Recursively walk a directory and remove XML elements"""
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, file_pattern):
filepath = os.path.join(path, filename)
remove_xml_element_file(name, filepath)
# backwards-compatibility aliases
findReplace = find_replace
findReplaceRegex = find_replace_regex
findRename = find_rename
removeXmlElement = remove_xml_element_directory
def download_extract_zip(url, target=None, subfolder=None, headers=None):
if not headers:
headers = {}
resp = requests.get(url, headers=headers)
zip_content = io.BytesIO(resp.content)
zip_file = zipfile.ZipFile(zip_content)
if subfolder:
zip_file = zip_subfolder(zip_file, subfolder)
if target:
zip_file.extractall(target)
return
return zip_file
def download_extract_github(
github_api, repo_owner, repo_name, subfolder=None, ref=None
):
return download_extract_github_from_repo(
github_api.repository(repo_owner, repo_name), subfolder, ref
)
def download_extract_github_from_repo(github_repo, subfolder=None, ref=None):
if not ref:
ref = github_repo.default_branch
zip_content = io.BytesIO()
github_repo.archive("zipball", zip_content, ref=ref)
zip_file = zipfile.ZipFile(zip_content)
path = sorted(zip_file.namelist())[0]
if subfolder:
path = path + subfolder
zip_file = zip_subfolder(zip_file, path)
return zip_file
def process_text_in_directory(path, process_file):
"""Process each file in a directory using the `process_file` function.
`process_file` should be a function which accepts a filename and content as text
and returns a (possibly modified) filename and content. The file will be
updated with the new content, and renamed if necessary.
Files with content that cannot be decoded as UTF-8 will be skipped.
"""
for path, dirs, files in os.walk(path):
for orig_name in files:
orig_path = os.path.join(path, orig_name)
try:
with open(orig_path, "r", encoding="utf-8") as f:
orig_content = f.read()
except UnicodeDecodeError:
# Probably a binary file; skip it
continue
new_name, new_content = process_file(orig_name, orig_content)
new_path = os.path.join(path, new_name)
if new_name != orig_name:
os.rename(orig_path, new_path)
with open(new_path, "w", encoding="utf-8") as f:
f.write(new_content)
def inject_namespace(
name,
content,
namespace=None,
managed=None,
filename_token=None,
namespace_token=None,
namespaced_org=None,
logger=None,
):
"""Replaces %%%NAMESPACE%%% in file content and ___NAMESPACE___ in file name
with either '' if no namespace is provided or 'namespace__' if provided.
"""
# Handle namespace and filename tokens
if not filename_token:
filename_token = "___NAMESPACE___"
if not namespace_token:
namespace_token = "%%%NAMESPACE%%%"
if managed is True and namespace:
namespace_prefix = namespace + "__"
namespace_dot_prefix = namespace + "."
else:
namespace_prefix = ""
namespace_dot_prefix = ""
namespace_dot_token = "%%%NAMESPACE_DOT%%%"
# Handle tokens %%%NAMESPACED_ORG%%% and ___NAMESPACED_ORG___
namespaced_org_token = "%%%NAMESPACED_ORG%%%"
namespaced_org_file_token = "___NAMESPACED_ORG___"
namespaced_org = namespace + "__" if namespaced_org else ""
# Handle token %%%NAMESPACE_OR_C%%% for lightning components
namespace_or_c_token = "%%%NAMESPACE_OR_C%%%"
namespace_or_c = namespace if managed and namespace else "c"
# Handle token %%%NAMESPACED_ORG_OR_C%%%
namespaced_org_or_c_token = "%%%NAMESPACED_ORG_OR_C%%%"
namespaced_org_or_c = namespace if namespaced_org else "c"
orig_name = name
prev_content = content
content = content.replace(namespace_token, namespace_prefix)
if logger and content != prev_content:
logger.info(f' {name}: Replaced {namespace_token} with "{namespace_prefix}"')
prev_content = content
content = content.replace(namespace_dot_token, namespace_dot_prefix)
if logger and content != prev_content:
logger.info(
f' {name}: Replaced {namespace_dot_token} with "{namespace_dot_prefix}"'
)
prev_content = content
content = content.replace(namespace_or_c_token, namespace_or_c)
if logger and content != prev_content:
logger.info(
f' {name}: Replaced {namespace_or_c_token} with "{namespace_or_c}"'
)
if name == "package.xml":
prev_content = content
content = content.replace(filename_token, namespace_prefix)
if logger and content != prev_content:
logger.info(
f' {name}: Replaced {filename_token} with "{namespace_prefix}"'
)
prev_content = content
content = content.replace(namespaced_org_token, namespaced_org)
if logger and content != prev_content:
logger.info(
f' {name}: Replaced {namespaced_org_token} with "{namespaced_org}"'
)
prev_content = content
content = content.replace(namespaced_org_or_c_token, namespaced_org_or_c)
if logger and content != prev_content:
logger.info(
f' {name}: Replaced {namespaced_org_or_c_token} with "{namespaced_org_or_c}"'
)
# Replace namespace token in file name
name = name.replace(filename_token, namespace_prefix)
name = name.replace(namespaced_org_file_token, namespaced_org)
if logger and name != orig_name:
logger.info(f" {orig_name}: renamed to {name}")
return name, content
def strip_namespace(name, content, namespace, logger=None):
"""Given a namespace, strips 'namespace__' from file name and content"""
namespace_prefix = "{}__".format(namespace)
lightning_namespace = "{}:".format(namespace)
orig_content = content
new_content = orig_content.replace(namespace_prefix, "")
new_content = new_content.replace(lightning_namespace, "c:")
name = name.replace(namespace_prefix, "")
if orig_content != new_content and logger:
logger.info(
" {file_name}: removed {namespace}".format(
file_name=name, namespace=namespace_prefix
)
)
return name, new_content
def tokenize_namespace(name, content, namespace, logger=None):
"""Given a namespace, replaces 'namespace__' with %%%NAMESPACE%%%
in file content and ___NAMESPACE___ in file name
"""
if not namespace:
return name, content
namespace_prefix = "{}__".format(namespace)
lightning_namespace = "{}:".format(namespace)
content = content.replace(namespace_prefix, "%%%NAMESPACE%%%")
content = content.replace(lightning_namespace, "%%%NAMESPACE_OR_C%%%")
name = name.replace(namespace_prefix, "___NAMESPACE___")
return name, content
def zip_clean_metaxml(zip_src, logger=None):
"""Given a zipfile, cleans all ``*-meta.xml`` files in the zip for
deployment by stripping all ``<packageVersions/>`` elements
"""
zip_dest = zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZIP_DEFLATED)
changed = []
for name in zip_src.namelist():
content = zip_src.read(name)
if name.startswith(META_XML_CLEAN_DIRS) and name.endswith("-meta.xml"):
try:
content.decode("utf-8")
except UnicodeDecodeError:
# if we cannot decode the content, it may be binary;
# don't try and replace it.
pass
else:
clean_content = remove_xml_element_string("packageVersions", content)
if clean_content != content:
changed.append(name)
content = clean_content
zip_dest.writestr(name, content)
if changed and logger:
logger.info(
"Cleaned package versions from {} meta.xml files".format(len(changed))
)
zip_src.close()
return zip_dest
def doc_task(task_name, task_config, project_config=None, org_config=None):
"""Document a (project specific) task configuration in RST format."""
from cumulusci.core.utils import import_global
doc = []
doc.append(f"**{task_name}**\n==========================================\n")
doc.append(f"**Description:** {task_config.description}\n")
doc.append(f"**Class:** {task_config.class_path}\n")
task_class = import_global(task_config.class_path)
if "task_docs" in task_class.__dict__:
task_docs = textwrap.dedent(task_class.task_docs.strip("\n"))
doc.append(task_docs)
task_option_info = get_task_option_info(task_config, task_class)
doc.append("Command Syntax\n------------------------------------------\n")
command_syntax = get_command_syntax(task_name)
doc.append(command_syntax)
task_option_doc = create_task_options_doc(task_option_info)
if task_option_doc:
doc.append("Options\n------------------------------------------\n")
doc.extend(task_option_doc)
return "\n".join(doc)
def get_command_syntax(task_name):
"""Return an example command syntax string in .rst format"""
return f"``$ cci task run {task_name}``\n\n"
def get_task_option_info(task_config, task_class):
"""Gets the the following info for each option in the task
usage: example usage statement (i.e. -o name VALUE)
required: True/False
default: If a default value is present
description: Description string provided on the task option
option_type: A type string provided on the task option
Returns list of option dicts with required at the front of the map
"""
required_options = []
optional_options = []
defaults = task_config.options or {}
for name, option in list(task_class.task_options.items()):
usage = get_option_usage_string(name, option)
required = True if option.get("required") else False
default = defaults.get(name)
description = option.get("description")
option_type = option.get("type")
info = {
"usage": usage,
"name": name,
"required": required,
"default": default,
"description": description,
"option_type": option_type,
}
if required:
required_options.append(info)
else:
optional_options.append(info)
return [*required_options, *optional_options]
def get_option_usage_string(name, option):
"""Returns a usage string if one exists
else creates a usage string in the form of:
--option-name OPTIONNAME
"""
usage_str = option.get("usage")
if not usage_str:
usage_str = f"--{name} {name.replace("_","").upper()}"
return usage_str
def create_task_options_doc(task_options):
"""Generate the 'Options' section for a given tasks documentation"""
doc = []
for option in task_options:
usage_str = option.get("usage")
if usage_str:
doc.append(f"\n``{usage_str}``")
if option.get("required"):
doc.append("\t *Required*")
else:
doc.append("\t *Optional*")
description = option.get("description")
if description:
doc.append(f"\n\t {description}")
default = option.get("default")
if default:
doc.append(f"\n\t Default: {default}")
option_type = option.get("option_type")
if option_type:
doc.append(f"\n\t Type: {option_type}")
return doc
def flow_ref_title_and_intro(intro_blurb):
return f"""Flow Reference
==========================================
\n{intro_blurb}
"""
def document_flow(flow_name, description, flow_coordinator, additional_info=None):
"""Document (project specific) flow configurations in RST format"""
doc = []
doc.append(f"{flow_name}\n{"^" * len(flow_name)}\n")
doc.append(f"**Description:** {description}\n")
if additional_info:
doc.append(additional_info)
doc.append("**Flow Steps**\n")
doc.append(".. code-block:: console\n")
flow_step_lines = flow_coordinator.get_flow_steps(for_docs=True)
# extra indent beneath code-block and finish with pipe for extra space afterwards
flow_step_lines = [f"\t{line}" for line in flow_step_lines]
# fix when clauses
lines = []
for line in flow_step_lines:
if line.startswith("when"):
line = f"\t\t{line}"
lines.append(line)
doc.extend(lines)
return "\n".join(doc)
def package_xml_from_dict(items, api_version, package_name=None):
lines = []
# Print header
lines.append('<?xml version="1.0" encoding="UTF-8"?>')
lines.append('<Package xmlns="http://soap.sforce.com/2006/04/metadata">')
# Include package name if specified
if package_name:
lines.append(" <fullName>{}</fullName>".format(package_name))
# Print types sections
for md_type, members in sorted(items.items()):
members.sort()
lines.append(" <types>")
for member in members:
lines.append(" <members>{}</members>".format(member))
lines.append(" <name>{}</name>".format(md_type))
lines.append(" </types>")
# Print footer
lines.append(" <version>{0}</version>".format(api_version))
lines.append("</Package>")
return "\n".join(lines)
@contextlib.contextmanager
def cd(path):
"""Context manager that changes to another directory"""
if not path:
yield
return
cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(cwd)
@contextlib.contextmanager
def temporary_dir(chdir=True):
"""Context manager that creates a temporary directory and chdirs to it.
When the context manager exits it returns to the previous cwd
and deletes the temporary directory.
"""
d = tempfile.mkdtemp()
try:
with contextlib.ExitStack() as stack:
if chdir:
stack.enter_context(cd(d))
yield d
finally:
if os.path.exists(d):
shutil.rmtree(d)
def touch(path):
"""Ensure a file exists."""
with open(path, "a"):
pass
def in_directory(filepath, dirpath):
"""Returns a boolean for whether filepath is contained in dirpath.
Normalizes the paths (e.g. resolving symlinks and ..)
so this is the safe way to make sure a user-configured path
is located inside the user's project repo.
"""
filepath = os.path.realpath(filepath)
dirpath = os.path.realpath(dirpath)
return filepath == dirpath or filepath.startswith(os.path.join(dirpath, ""))
def log_progress(
iterable,
logger,
batch_size=10000,
progress_message="Processing... ({})",
done_message="Done! (Total: {})",
):
"""Log progress while iterating."""
i = 0
for x in iterable:
yield x
i += 1
if not i % batch_size:
logger.info(progress_message.format(i))
logger.info(done_message.format(i))
def random_alphanumeric_underscore(length):
import secrets
# Ensure the string is the right length
byte_length = math.ceil((length * 3) / 4)
return secrets.token_urlsafe(byte_length).replace("-", "_")[:length]
def get_cci_upgrade_command():
commands_by_path = {
"cellar": BREW_UPDATE_CMD,
"linuxbrew": BREW_UPDATE_CMD,
"pipx": PIPX_UPDATE_CMD,
}
for path, cmd in commands_by_path.items():
if path in CUMULUSCI_PATH.lower():
return cmd
return PIP_UPDATE_CMD
def convert_to_snake_case(content):
s1 = re.sub("([^_])([A-Z][a-z]+)", r"\1_\2", content)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
def get_git_config(config_key):
p = sarge.Command(
sarge.shell_format('git config --get "{0!s}"', config_key),
stderr=sarge.Capture(buffer_size=-1),
stdout=sarge.Capture(buffer_size=-1),
shell=True,
)
p.run()
config_value = (
io.TextIOWrapper(p.stdout, encoding=sys.stdout.encoding).read().strip()
)
return config_value if config_value and not p.returncode else None
| import contextlib
import fnmatch
import io
import math
import os
import re
import shutil
import sys
import tempfile
import textwrap
import zipfile
from datetime import datetime
import requests
import sarge
from .xml import ( # noqa
elementtree_parse_file,
remove_xml_element,
remove_xml_element_file,
remove_xml_element_string,
)
from .ziputils import process_text_in_zipfile # noqa
from .ziputils import zip_subfolder
CUMULUSCI_PATH = os.path.realpath(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..")
)
META_XML_CLEAN_DIRS = ("classes/", "triggers/", "pages/", "aura/", "components/")
API_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
DATETIME_LEN = len("2018-08-07T16:00:56.000")
BREW_UPDATE_CMD = "brew upgrade cumulusci"
PIP_UPDATE_CMD = "pip install --upgrade cumulusci"
PIPX_UPDATE_CMD = "pipx upgrade cumulusci"
def parse_api_datetime(value):
"""parse a datetime returned from the salesforce API.
in python 3 we should just use a strptime %z, but until then we're just going
to assert that its a fixed offset of +0000 since thats the observed behavior. getting
python 2 to support fixed offset parsing is too complicated for what we need imo."""
dt = datetime.strptime(value[0:DATETIME_LEN], API_DATE_FORMAT)
offset_str = value[DATETIME_LEN:]
assert offset_str in ["+0000", "Z"], "The Salesforce API returned a weird timezone."
return dt
def find_replace(find, replace, directory, filePattern, logger=None, max=None):
"""Recursive find/replace.
Walks through files matching `filePattern` within `directory`
and does a string substitution of `find` with `replace`.
"""
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
with io.open(filepath, encoding="utf-8") as f:
s = f.read()
if max:
s_updated = s.replace(find, replace, max)
else:
s_updated = s.replace(find, replace)
if s != s_updated:
if logger:
logger.info("Updating {}".format(filepath))
with io.open(filepath, "w", encoding="utf-8") as f:
f.write(s_updated)
def find_replace_regex(find, replace, directory, filePattern, logger=None):
"""Recursive find/replace using a regular expression.
Walks through files matching `filePattern` within `directory`
and does a regex substitution of `find` with `replace`.
"""
pattern = re.compile(find)
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
with io.open(filepath, encoding="utf-8") as f:
s = f.read()
s_updated = pattern.sub(replace, s)
if s != s_updated:
if logger:
logger.info("Updating {}".format(filepath))
with io.open(filepath, "w", encoding="utf-8") as f:
f.write(s_updated)
def find_rename(find, replace, directory, logger=None):
"""Recursive find/replace within filenames.
Walks through files within `directory`
and renames files to replace `find` with `replace`.
"""
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in files:
filepath = os.path.join(path, filename)
if logger:
logger.info("Renaming {}".format(filepath))
os.rename(filepath, os.path.join(path, filename.replace(find, replace)))
def remove_xml_element_directory(name, directory, file_pattern, logger=None):
"""Recursively walk a directory and remove XML elements"""
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, file_pattern):
filepath = os.path.join(path, filename)
remove_xml_element_file(name, filepath)
# backwards-compatibility aliases
findReplace = find_replace
findReplaceRegex = find_replace_regex
findRename = find_rename
removeXmlElement = remove_xml_element_directory
def download_extract_zip(url, target=None, subfolder=None, headers=None):
if not headers:
headers = {}
resp = requests.get(url, headers=headers)
zip_content = io.BytesIO(resp.content)
zip_file = zipfile.ZipFile(zip_content)
if subfolder:
zip_file = zip_subfolder(zip_file, subfolder)
if target:
zip_file.extractall(target)
return
return zip_file
def download_extract_github(
github_api, repo_owner, repo_name, subfolder=None, ref=None
):
return download_extract_github_from_repo(
github_api.repository(repo_owner, repo_name), subfolder, ref
)
def download_extract_github_from_repo(github_repo, subfolder=None, ref=None):
if not ref:
ref = github_repo.default_branch
zip_content = io.BytesIO()
github_repo.archive("zipball", zip_content, ref=ref)
zip_file = zipfile.ZipFile(zip_content)
path = sorted(zip_file.namelist())[0]
if subfolder:
path = path + subfolder
zip_file = zip_subfolder(zip_file, path)
return zip_file
def process_text_in_directory(path, process_file):
"""Process each file in a directory using the `process_file` function.
`process_file` should be a function which accepts a filename and content as text
and returns a (possibly modified) filename and content. The file will be
updated with the new content, and renamed if necessary.
Files with content that cannot be decoded as UTF-8 will be skipped.
"""
for path, dirs, files in os.walk(path):
for orig_name in files:
orig_path = os.path.join(path, orig_name)
try:
with open(orig_path, "r", encoding="utf-8") as f:
orig_content = f.read()
except UnicodeDecodeError:
# Probably a binary file; skip it
continue
new_name, new_content = process_file(orig_name, orig_content)
new_path = os.path.join(path, new_name)
if new_name != orig_name:
os.rename(orig_path, new_path)
with open(new_path, "w", encoding="utf-8") as f:
f.write(new_content)
def inject_namespace(
name,
content,
namespace=None,
managed=None,
filename_token=None,
namespace_token=None,
namespaced_org=None,
logger=None,
):
"""Replaces %%%NAMESPACE%%% in file content and ___NAMESPACE___ in file name
with either '' if no namespace is provided or 'namespace__' if provided.
"""
# Handle namespace and filename tokens
if not filename_token:
filename_token = "___NAMESPACE___"
if not namespace_token:
namespace_token = "%%%NAMESPACE%%%"
if managed is True and namespace:
namespace_prefix = namespace + "__"
namespace_dot_prefix = namespace + "."
else:
namespace_prefix = ""
namespace_dot_prefix = ""
namespace_dot_token = "%%%NAMESPACE_DOT%%%"
# Handle tokens %%%NAMESPACED_ORG%%% and ___NAMESPACED_ORG___
namespaced_org_token = "%%%NAMESPACED_ORG%%%"
namespaced_org_file_token = "___NAMESPACED_ORG___"
namespaced_org = namespace + "__" if namespaced_org else ""
# Handle token %%%NAMESPACE_OR_C%%% for lightning components
namespace_or_c_token = "%%%NAMESPACE_OR_C%%%"
namespace_or_c = namespace if managed and namespace else "c"
# Handle token %%%NAMESPACED_ORG_OR_C%%%
namespaced_org_or_c_token = "%%%NAMESPACED_ORG_OR_C%%%"
namespaced_org_or_c = namespace if namespaced_org else "c"
orig_name = name
prev_content = content
content = content.replace(namespace_token, namespace_prefix)
if logger and content != prev_content:
logger.info(f' {name}: Replaced {namespace_token} with "{namespace_prefix}"')
prev_content = content
content = content.replace(namespace_dot_token, namespace_dot_prefix)
if logger and content != prev_content:
logger.info(
f' {name}: Replaced {namespace_dot_token} with "{namespace_dot_prefix}"'
)
prev_content = content
content = content.replace(namespace_or_c_token, namespace_or_c)
if logger and content != prev_content:
logger.info(
f' {name}: Replaced {namespace_or_c_token} with "{namespace_or_c}"'
)
if name == "package.xml":
prev_content = content
content = content.replace(filename_token, namespace_prefix)
if logger and content != prev_content:
logger.info(
f' {name}: Replaced {filename_token} with "{namespace_prefix}"'
)
prev_content = content
content = content.replace(namespaced_org_token, namespaced_org)
if logger and content != prev_content:
logger.info(
f' {name}: Replaced {namespaced_org_token} with "{namespaced_org}"'
)
prev_content = content
content = content.replace(namespaced_org_or_c_token, namespaced_org_or_c)
if logger and content != prev_content:
logger.info(
f' {name}: Replaced {namespaced_org_or_c_token} with "{namespaced_org_or_c}"'
)
# Replace namespace token in file name
name = name.replace(filename_token, namespace_prefix)
name = name.replace(namespaced_org_file_token, namespaced_org)
if logger and name != orig_name:
logger.info(f" {orig_name}: renamed to {name}")
return name, content
def strip_namespace(name, content, namespace, logger=None):
"""Given a namespace, strips 'namespace__' from file name and content"""
namespace_prefix = "{}__".format(namespace)
lightning_namespace = "{}:".format(namespace)
orig_content = content
new_content = orig_content.replace(namespace_prefix, "")
new_content = new_content.replace(lightning_namespace, "c:")
name = name.replace(namespace_prefix, "")
if orig_content != new_content and logger:
logger.info(
" {file_name}: removed {namespace}".format(
file_name=name, namespace=namespace_prefix
)
)
return name, new_content
def tokenize_namespace(name, content, namespace, logger=None):
"""Given a namespace, replaces 'namespace__' with %%%NAMESPACE%%%
in file content and ___NAMESPACE___ in file name
"""
if not namespace:
return name, content
namespace_prefix = "{}__".format(namespace)
lightning_namespace = "{}:".format(namespace)
content = content.replace(namespace_prefix, "%%%NAMESPACE%%%")
content = content.replace(lightning_namespace, "%%%NAMESPACE_OR_C%%%")
name = name.replace(namespace_prefix, "___NAMESPACE___")
return name, content
def zip_clean_metaxml(zip_src, logger=None):
"""Given a zipfile, cleans all ``*-meta.xml`` files in the zip for
deployment by stripping all ``<packageVersions/>`` elements
"""
zip_dest = zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZIP_DEFLATED)
changed = []
for name in zip_src.namelist():
content = zip_src.read(name)
if name.startswith(META_XML_CLEAN_DIRS) and name.endswith("-meta.xml"):
try:
content.decode("utf-8")
except UnicodeDecodeError:
# if we cannot decode the content, it may be binary;
# don't try and replace it.
pass
else:
clean_content = remove_xml_element_string("packageVersions", content)
if clean_content != content:
changed.append(name)
content = clean_content
zip_dest.writestr(name, content)
if changed and logger:
logger.info(
"Cleaned package versions from {} meta.xml files".format(len(changed))
)
zip_src.close()
return zip_dest
def doc_task(task_name, task_config, project_config=None, org_config=None):
"""Document a (project specific) task configuration in RST format."""
from cumulusci.core.utils import import_global
doc = []
doc.append(f"**{task_name}**\n==========================================\n")
doc.append(f"**Description:** {task_config.description}\n")
doc.append(f"**Class:** {task_config.class_path}\n")
task_class = import_global(task_config.class_path)
if "task_docs" in task_class.__dict__:
task_docs = textwrap.dedent(task_class.task_docs.strip("\n"))
doc.append(task_docs)
task_option_info = get_task_option_info(task_config, task_class)
doc.append("Command Syntax\n------------------------------------------\n")
command_syntax = get_command_syntax(task_name)
doc.append(command_syntax)
task_option_doc = create_task_options_doc(task_option_info)
if task_option_doc:
doc.append("Options\n------------------------------------------\n")
doc.extend(task_option_doc)
return "\n".join(doc)
def get_command_syntax(task_name):
"""Return an example command syntax string in .rst format"""
return f"``$ cci task run {task_name}``\n\n"
def get_task_option_info(task_config, task_class):
"""Gets the the following info for each option in the task
usage: example usage statement (i.e. -o name VALUE)
required: True/False
default: If a default value is present
description: Description string provided on the task option
option_type: A type string provided on the task option
Returns list of option dicts with required at the front of the map
"""
required_options = []
optional_options = []
defaults = task_config.options or {}
for name, option in list(task_class.task_options.items()):
usage = get_option_usage_string(name, option)
required = True if option.get("required") else False
default = defaults.get(name)
description = option.get("description")
option_type = option.get("type")
info = {
"usage": usage,
"name": name,
"required": required,
"default": default,
"description": description,
"option_type": option_type,
}
if required:
required_options.append(info)
else:
optional_options.append(info)
return [*required_options, *optional_options]
def get_option_usage_string(name, option):
"""Returns a usage string if one exists
else creates a usage string in the form of:
--option-name OPTIONNAME
"""
usage_str = option.get("usage")
if not usage_str:
usage_str = f"--{name} {name.replace('_','').upper()}"
return usage_str
def create_task_options_doc(task_options):
"""Generate the 'Options' section for a given tasks documentation"""
doc = []
for option in task_options:
usage_str = option.get("usage")
if usage_str:
doc.append(f"\n``{usage_str}``")
if option.get("required"):
doc.append("\t *Required*")
else:
doc.append("\t *Optional*")
description = option.get("description")
if description:
doc.append(f"\n\t {description}")
default = option.get("default")
if default:
doc.append(f"\n\t Default: {default}")
option_type = option.get("option_type")
if option_type:
doc.append(f"\n\t Type: {option_type}")
return doc
def flow_ref_title_and_intro(intro_blurb):
return f"""Flow Reference
==========================================
\n{intro_blurb}
"""
def document_flow(flow_name, description, flow_coordinator, additional_info=None):
"""Document (project specific) flow configurations in RST format"""
doc = []
doc.append(f"{flow_name}\n{'^' * len(flow_name)}\n")
doc.append(f"**Description:** {description}\n")
if additional_info:
doc.append(additional_info)
doc.append("**Flow Steps**\n")
doc.append(".. code-block:: console\n")
flow_step_lines = flow_coordinator.get_flow_steps(for_docs=True)
# extra indent beneath code-block and finish with pipe for extra space afterwards
flow_step_lines = [f"\t{line}" for line in flow_step_lines]
# fix when clauses
lines = []
for line in flow_step_lines:
if line.startswith("when"):
line = f"\t\t{line}"
lines.append(line)
doc.extend(lines)
return "\n".join(doc)
def package_xml_from_dict(items, api_version, package_name=None):
lines = []
# Print header
lines.append('<?xml version="1.0" encoding="UTF-8"?>')
lines.append('<Package xmlns="http://soap.sforce.com/2006/04/metadata">')
# Include package name if specified
if package_name:
lines.append(" <fullName>{}</fullName>".format(package_name))
# Print types sections
for md_type, members in sorted(items.items()):
members.sort()
lines.append(" <types>")
for member in members:
lines.append(" <members>{}</members>".format(member))
lines.append(" <name>{}</name>".format(md_type))
lines.append(" </types>")
# Print footer
lines.append(" <version>{0}</version>".format(api_version))
lines.append("</Package>")
return "\n".join(lines)
@contextlib.contextmanager
def cd(path):
"""Context manager that changes to another directory"""
if not path:
yield
return
cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(cwd)
@contextlib.contextmanager
def temporary_dir(chdir=True):
"""Context manager that creates a temporary directory and chdirs to it.
When the context manager exits it returns to the previous cwd
and deletes the temporary directory.
"""
d = tempfile.mkdtemp()
try:
with contextlib.ExitStack() as stack:
if chdir:
stack.enter_context(cd(d))
yield d
finally:
if os.path.exists(d):
shutil.rmtree(d)
def touch(path):
"""Ensure a file exists."""
with open(path, "a"):
pass
def in_directory(filepath, dirpath):
"""Returns a boolean for whether filepath is contained in dirpath.
Normalizes the paths (e.g. resolving symlinks and ..)
so this is the safe way to make sure a user-configured path
is located inside the user's project repo.
"""
filepath = os.path.realpath(filepath)
dirpath = os.path.realpath(dirpath)
return filepath == dirpath or filepath.startswith(os.path.join(dirpath, ""))
def log_progress(
iterable,
logger,
batch_size=10000,
progress_message="Processing... ({})",
done_message="Done! (Total: {})",
):
"""Log progress while iterating."""
i = 0
for x in iterable:
yield x
i += 1
if not i % batch_size:
logger.info(progress_message.format(i))
logger.info(done_message.format(i))
def random_alphanumeric_underscore(length):
import secrets
# Ensure the string is the right length
byte_length = math.ceil((length * 3) / 4)
return secrets.token_urlsafe(byte_length).replace("-", "_")[:length]
def get_cci_upgrade_command():
commands_by_path = {
"cellar": BREW_UPDATE_CMD,
"linuxbrew": BREW_UPDATE_CMD,
"pipx": PIPX_UPDATE_CMD,
}
for path, cmd in commands_by_path.items():
if path in CUMULUSCI_PATH.lower():
return cmd
return PIP_UPDATE_CMD
def convert_to_snake_case(content):
s1 = re.sub("([^_])([A-Z][a-z]+)", r"\1_\2", content)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
def get_git_config(config_key):
p = sarge.Command(
sarge.shell_format('git config --get "{0!s}"', config_key),
stderr=sarge.Capture(buffer_size=-1),
stdout=sarge.Capture(buffer_size=-1),
shell=True,
)
p.run()
config_value = (
io.TextIOWrapper(p.stdout, encoding=sys.stdout.encoding).read().strip()
)
return config_value if config_value and not p.returncode else None
|
#!/usr/bin/env python3
import json
import time
import fnmatch
from collections import namedtuple
import jwt
import requests # type: ignore
import boto3 # type: ignore
API_URL = "https://api.github.com/repos/ClickHouse/ClickHouse"
SUSPICIOUS_CHANGED_FILES_NUMBER = 200
SUSPICIOUS_PATTERNS = [
"tests/ci/*",
"docs/tools/*",
".github/*",
"utils/release/*",
"docker/*",
"release",
]
# Number of retries for API calls.
MAX_RETRY = 5
# Number of times a check can re-run as a whole.
# It is needed, because we are using AWS "spot" instances, that are terminated very frequently.
MAX_WORKFLOW_RERUN = 20
WorkflowDescription = namedtuple(
"WorkflowDescription",
[
"name",
"action",
"run_id",
"event",
"workflow_id",
"conclusion",
"status",
"api_url",
"fork_owner_login",
"fork_branch",
"rerun_url",
"jobs_url",
"attempt",
"url",
],
)
# See https://api.github.com/orgs/{name}
TRUSTED_ORG_IDS = {
7409213, # yandex
28471076, # altinity
54801242, # clickhouse
}
# See https://api.github.com/repos/ClickHouse/ClickHouse/actions/workflows
# Use ID to not inject a malicious workflow
TRUSTED_WORKFLOW_IDS = {
14586616, # Cancel workflows, always trusted
}
NEED_RERUN_WORKFLOWS = {
"BackportPR",
"Docs",
"DocsRelease",
"MasterCI",
"PullRequestCI",
"ReleaseCI",
}
# Individual trusted contirbutors who are not in any trusted organization.
# Can be changed in runtime: we will append users that we learned to be in
# a trusted org, to save GitHub API calls.
TRUSTED_CONTRIBUTORS = {
e.lower()
for e in [
"achimbab",
"adevyatova ", # DOCSUP
"Algunenano", # Raúl Marín, Tinybird
"amosbird",
"AnaUvarova", # DOCSUP
"anauvarova", # technical writer, Yandex
"annvsh", # technical writer, Yandex
"atereh", # DOCSUP
"azat",
"bharatnc", # Newbie, but already with many contributions.
"bobrik", # Seasoned contributor, CloudFlare
"BohuTANG",
"cwurm", # Employee
"damozhaeva", # DOCSUP
"den-crane",
"gyuton", # DOCSUP
"hagen1778", # Roman Khavronenko, seasoned contributor
"hczhcz",
"hexiaoting", # Seasoned contributor
"ildus", # adjust, ex-pgpro
"javisantana", # a Spanish ClickHouse enthusiast, ex-Carto
"ka1bi4", # DOCSUP
"kirillikoff", # DOCSUP
"kreuzerkrieg",
"lehasm", # DOCSUP
"michon470", # DOCSUP
"MyroTk", # Tester in Altinity
"myrrc", # Michael Kot, Altinity
"nikvas0",
"nvartolomei",
"olgarev", # DOCSUP
"otrazhenia", # Yandex docs contractor
"pdv-ru", # DOCSUP
"podshumok", # cmake expert from QRator Labs
"s-mx", # Maxim Sabyanin, former employee, present contributor
"sevirov", # technical writer, Yandex
"spongedu", # Seasoned contributor
"taiyang-li",
"ucasFL", # Amos Bird's friend
"vdimir", # Employee
"vzakaznikov",
"YiuRULE",
"zlobober", # Developer of YT
"BoloniniD", # Seasoned contributor, HSE
"tylerhannan", # ClickHouse Employee
]
}
def get_installation_id(jwt_token):
headers = {
"Authorization": f"Bearer {jwt_token}",
"Accept": "application/vnd.github.v3+json",
}
response = requests.get("https://api.github.com/app/installations", headers=headers)
response.raise_for_status()
data = response.json()
return data[0]["id"]
def get_access_token(jwt_token, installation_id):
headers = {
"Authorization": f"Bearer {jwt_token}",
"Accept": "application/vnd.github.v3+json",
}
response = requests.post(
f"https://api.github.com/app/installations/{installation_id}/access_tokens",
headers=headers,
)
response.raise_for_status()
data = response.json()
return data["token"]
def get_key_and_app_from_aws():
secret_name = "clickhouse_github_secret_key"
session = boto3.session.Session()
client = session.client(
service_name="secretsmanager",
)
get_secret_value_response = client.get_secret_value(SecretId=secret_name)
data = json.loads(get_secret_value_response["SecretString"])
return data["clickhouse-app-key"], int(data["clickhouse-app-id"])
def is_trusted_contributor(pr_user_login, pr_user_orgs):
if pr_user_login.lower() in TRUSTED_CONTRIBUTORS:
print(f"User '{pr_user_login}' is trusted")
return True
print(f"User '{pr_user_login}' is not trusted")
for org_id in pr_user_orgs:
if org_id in TRUSTED_ORG_IDS:
print(
f"Org '{org_id}' is trusted; will mark user {pr_user_login} as trusted"
)
return True
print(f"Org '{org_id}' is not trusted")
return False
def _exec_get_with_retry(url):
for i in range(MAX_RETRY):
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except Exception as ex:
print("Got exception executing request", ex)
time.sleep(i + 1)
raise Exception("Cannot execute GET request with retries")
def _exec_post_with_retry(url, token, data=None):
headers = {"Authorization": f"token {token}"}
for i in range(MAX_RETRY):
try:
if data:
response = requests.post(url, headers=headers, json=data)
else:
response = requests.post(url, headers=headers)
if response.status_code == 403:
data = response.json()
if (
"message" in data
and data["message"]
== "This workflow run is not waiting for approval"
):
print("Workflow doesn't need approval")
return data
response.raise_for_status()
return response.json()
except Exception as ex:
print("Got exception executing request", ex)
time.sleep(i + 1)
raise Exception("Cannot execute POST request with retry")
def _get_pull_requests_from(owner, branch):
url = f"{API_URL}/pulls?head={owner}:{branch}"
return _exec_get_with_retry(url)
def get_workflow_description_from_event(event):
action = event["action"]
run_id = event["workflow_run"]["id"]
event_type = event["workflow_run"]["event"]
fork_owner = event["workflow_run"]["head_repository"]["owner"]["login"]
fork_branch = event["workflow_run"]["head_branch"]
name = event["workflow_run"]["name"]
workflow_id = event["workflow_run"]["workflow_id"]
conclusion = event["workflow_run"]["conclusion"]
attempt = event["workflow_run"]["run_attempt"]
status = event["workflow_run"]["status"]
jobs_url = event["workflow_run"]["jobs_url"]
rerun_url = event["workflow_run"]["rerun_url"]
url = event["workflow_run"]["html_url"]
api_url = event["workflow_run"]["url"]
return WorkflowDescription(
name=name,
action=action,
run_id=run_id,
event=event_type,
fork_owner_login=fork_owner,
fork_branch=fork_branch,
workflow_id=workflow_id,
conclusion=conclusion,
attempt=attempt,
status=status,
jobs_url=jobs_url,
rerun_url=rerun_url,
url=url,
api_url=api_url,
)
def get_pr_author_and_orgs(pull_request):
author = pull_request["user"]["login"]
orgs = _exec_get_with_retry(pull_request["user"]["organizations_url"])
return author, [org["id"] for org in orgs]
def get_changed_files_for_pull_request(pull_request):
number = pull_request["number"]
changed_files = set([])
for i in range(1, 31):
print("Requesting changed files page", i)
url = f"{API_URL}/pulls/{number}/files?page={i}&per_page=100"
data = _exec_get_with_retry(url)
print(f"Got {len(data)} changed files")
if len(data) == 0:
print("No more changed files")
break
for change in data:
# print("Adding changed file", change['filename'])
changed_files.add(change["filename"])
if len(changed_files) >= SUSPICIOUS_CHANGED_FILES_NUMBER:
print(
f"More than {len(changed_files)} changed files. "
"Will stop fetching new files."
)
break
return changed_files
def check_suspicious_changed_files(changed_files):
if len(changed_files) >= SUSPICIOUS_CHANGED_FILES_NUMBER:
print(f"Too many files changed {len(changed_files)}, need manual approve")
return True
for path in changed_files:
for pattern in SUSPICIOUS_PATTERNS:
if fnmatch.fnmatch(path, pattern):
print(
f"File {path} match suspicious pattern {pattern}, "
"will not approve automatically"
)
return True
print("No changed files match suspicious patterns, run will be approved")
return False
def approve_run(run_id, token):
url = f"{API_URL}/actions/runs/{run_id}/approve"
_exec_post_with_retry(url, token)
def label_manual_approve(pull_request, token):
number = pull_request["number"]
url = f"{API_URL}/issues/{number}/labels"
data = {"labels": "manual approve"}
_exec_post_with_retry(url, token, data)
def get_token_from_aws():
private_key, app_id = get_key_and_app_from_aws()
payload = {
"iat": int(time.time()) - 60,
"exp": int(time.time()) + (10 * 60),
"iss": app_id,
}
encoded_jwt = jwt.encode(payload, private_key, algorithm="RS256")
installation_id = get_installation_id(encoded_jwt)
return get_access_token(encoded_jwt, installation_id)
def get_workflow_jobs(workflow_description):
jobs_url = (
workflow_description.api_url + f"/attempts/{workflow_description.attempt}/jobs"
)
jobs = []
i = 1
while True:
got_jobs = _exec_get_with_retry(jobs_url + f"?page={i}")
if len(got_jobs["jobs"]) == 0:
break
jobs += got_jobs["jobs"]
i += 1
return jobs
def check_need_to_rerun(workflow_description):
if workflow_description.attempt >= MAX_WORKFLOW_RERUN:
print(
"Not going to rerun workflow because it's already tried more than two times"
)
return False
print("Going to check jobs")
jobs = get_workflow_jobs(workflow_description)
print("Got jobs", len(jobs))
for job in jobs:
if job["conclusion"] not in ("success", "skipped"):
print("Job", job["name"], "failed, checking steps")
for step in job["steps"]:
# always the last job
if step["name"] == "Complete job":
print("Found Complete job step for job", job["name"])
break
else:
print(
"Checked all steps and doesn't found Complete job, going to rerun"
)
return True
return False
def rerun_workflow(workflow_description, token):
print("Going to rerun workflow")
try:
_exec_post_with_retry(f"{workflow_description.rerun_url}-failed-jobs", token)
except Exception:
_exec_post_with_retry(workflow_description.rerun_url, token)
def main(event):
token = get_token_from_aws()
event_data = json.loads(event["body"])
print("The body received:", event_data)
workflow_description = get_workflow_description_from_event(event_data)
print("Got workflow description", workflow_description)
if (
workflow_description.action == "completed"
and workflow_description.conclusion == "failure"
):
print(
"Workflow",
workflow_description.url,
"completed and failed, let's check for rerun",
)
if workflow_description.name not in NEED_RERUN_WORKFLOWS:
print(
"Workflow",
workflow_description.name,
"not in list of rerunable workflows",
)
return
if check_need_to_rerun(workflow_description):
rerun_workflow(workflow_description, token)
return
if workflow_description.action != "requested":
print("Exiting, event action is", workflow_description.action)
return
if workflow_description.workflow_id in TRUSTED_WORKFLOW_IDS:
print("Workflow in trusted list, approving run")
approve_run(workflow_description.run_id, token)
return
pull_requests = _get_pull_requests_from(
workflow_description.fork_owner_login, workflow_description.fork_branch
)
print("Got pull requests for workflow", len(pull_requests))
if len(pull_requests) > 1:
raise Exception("Received more than one PR for workflow run")
if len(pull_requests) < 1:
raise Exception("Cannot find any pull requests for workflow run")
pull_request = pull_requests[0]
print("Pull request for workflow number", pull_request["number"])
author, author_orgs = get_pr_author_and_orgs(pull_request)
if is_trusted_contributor(author, author_orgs):
print("Contributor is trusted, approving run")
approve_run(workflow_description.run_id, token)
return
changed_files = get_changed_files_for_pull_request(pull_request)
print(f"Totally have {len(changed_files)} changed files in PR:", changed_files)
if check_suspicious_changed_files(changed_files):
print(
f"Pull Request {pull_request["number"]} has suspicious changes, "
"label it for manuall approve"
)
label_manual_approve(pull_request, token)
else:
print(f"Pull Request {pull_request["number"]} has no suspicious changes")
approve_run(workflow_description.run_id, token)
def handler(event, _):
main(event)
| #!/usr/bin/env python3
import json
import time
import fnmatch
from collections import namedtuple
import jwt
import requests # type: ignore
import boto3 # type: ignore
API_URL = "https://api.github.com/repos/ClickHouse/ClickHouse"
SUSPICIOUS_CHANGED_FILES_NUMBER = 200
SUSPICIOUS_PATTERNS = [
"tests/ci/*",
"docs/tools/*",
".github/*",
"utils/release/*",
"docker/*",
"release",
]
# Number of retries for API calls.
MAX_RETRY = 5
# Number of times a check can re-run as a whole.
# It is needed, because we are using AWS "spot" instances, that are terminated very frequently.
MAX_WORKFLOW_RERUN = 20
WorkflowDescription = namedtuple(
"WorkflowDescription",
[
"name",
"action",
"run_id",
"event",
"workflow_id",
"conclusion",
"status",
"api_url",
"fork_owner_login",
"fork_branch",
"rerun_url",
"jobs_url",
"attempt",
"url",
],
)
# See https://api.github.com/orgs/{name}
TRUSTED_ORG_IDS = {
7409213, # yandex
28471076, # altinity
54801242, # clickhouse
}
# See https://api.github.com/repos/ClickHouse/ClickHouse/actions/workflows
# Use ID to not inject a malicious workflow
TRUSTED_WORKFLOW_IDS = {
14586616, # Cancel workflows, always trusted
}
NEED_RERUN_WORKFLOWS = {
"BackportPR",
"Docs",
"DocsRelease",
"MasterCI",
"PullRequestCI",
"ReleaseCI",
}
# Individual trusted contirbutors who are not in any trusted organization.
# Can be changed in runtime: we will append users that we learned to be in
# a trusted org, to save GitHub API calls.
TRUSTED_CONTRIBUTORS = {
e.lower()
for e in [
"achimbab",
"adevyatova ", # DOCSUP
"Algunenano", # Raúl Marín, Tinybird
"amosbird",
"AnaUvarova", # DOCSUP
"anauvarova", # technical writer, Yandex
"annvsh", # technical writer, Yandex
"atereh", # DOCSUP
"azat",
"bharatnc", # Newbie, but already with many contributions.
"bobrik", # Seasoned contributor, CloudFlare
"BohuTANG",
"cwurm", # Employee
"damozhaeva", # DOCSUP
"den-crane",
"gyuton", # DOCSUP
"hagen1778", # Roman Khavronenko, seasoned contributor
"hczhcz",
"hexiaoting", # Seasoned contributor
"ildus", # adjust, ex-pgpro
"javisantana", # a Spanish ClickHouse enthusiast, ex-Carto
"ka1bi4", # DOCSUP
"kirillikoff", # DOCSUP
"kreuzerkrieg",
"lehasm", # DOCSUP
"michon470", # DOCSUP
"MyroTk", # Tester in Altinity
"myrrc", # Michael Kot, Altinity
"nikvas0",
"nvartolomei",
"olgarev", # DOCSUP
"otrazhenia", # Yandex docs contractor
"pdv-ru", # DOCSUP
"podshumok", # cmake expert from QRator Labs
"s-mx", # Maxim Sabyanin, former employee, present contributor
"sevirov", # technical writer, Yandex
"spongedu", # Seasoned contributor
"taiyang-li",
"ucasFL", # Amos Bird's friend
"vdimir", # Employee
"vzakaznikov",
"YiuRULE",
"zlobober", # Developer of YT
"BoloniniD", # Seasoned contributor, HSE
"tylerhannan", # ClickHouse Employee
]
}
def get_installation_id(jwt_token):
headers = {
"Authorization": f"Bearer {jwt_token}",
"Accept": "application/vnd.github.v3+json",
}
response = requests.get("https://api.github.com/app/installations", headers=headers)
response.raise_for_status()
data = response.json()
return data[0]["id"]
def get_access_token(jwt_token, installation_id):
headers = {
"Authorization": f"Bearer {jwt_token}",
"Accept": "application/vnd.github.v3+json",
}
response = requests.post(
f"https://api.github.com/app/installations/{installation_id}/access_tokens",
headers=headers,
)
response.raise_for_status()
data = response.json()
return data["token"]
def get_key_and_app_from_aws():
secret_name = "clickhouse_github_secret_key"
session = boto3.session.Session()
client = session.client(
service_name="secretsmanager",
)
get_secret_value_response = client.get_secret_value(SecretId=secret_name)
data = json.loads(get_secret_value_response["SecretString"])
return data["clickhouse-app-key"], int(data["clickhouse-app-id"])
def is_trusted_contributor(pr_user_login, pr_user_orgs):
if pr_user_login.lower() in TRUSTED_CONTRIBUTORS:
print(f"User '{pr_user_login}' is trusted")
return True
print(f"User '{pr_user_login}' is not trusted")
for org_id in pr_user_orgs:
if org_id in TRUSTED_ORG_IDS:
print(
f"Org '{org_id}' is trusted; will mark user {pr_user_login} as trusted"
)
return True
print(f"Org '{org_id}' is not trusted")
return False
def _exec_get_with_retry(url):
for i in range(MAX_RETRY):
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except Exception as ex:
print("Got exception executing request", ex)
time.sleep(i + 1)
raise Exception("Cannot execute GET request with retries")
def _exec_post_with_retry(url, token, data=None):
headers = {"Authorization": f"token {token}"}
for i in range(MAX_RETRY):
try:
if data:
response = requests.post(url, headers=headers, json=data)
else:
response = requests.post(url, headers=headers)
if response.status_code == 403:
data = response.json()
if (
"message" in data
and data["message"]
== "This workflow run is not waiting for approval"
):
print("Workflow doesn't need approval")
return data
response.raise_for_status()
return response.json()
except Exception as ex:
print("Got exception executing request", ex)
time.sleep(i + 1)
raise Exception("Cannot execute POST request with retry")
def _get_pull_requests_from(owner, branch):
url = f"{API_URL}/pulls?head={owner}:{branch}"
return _exec_get_with_retry(url)
def get_workflow_description_from_event(event):
action = event["action"]
run_id = event["workflow_run"]["id"]
event_type = event["workflow_run"]["event"]
fork_owner = event["workflow_run"]["head_repository"]["owner"]["login"]
fork_branch = event["workflow_run"]["head_branch"]
name = event["workflow_run"]["name"]
workflow_id = event["workflow_run"]["workflow_id"]
conclusion = event["workflow_run"]["conclusion"]
attempt = event["workflow_run"]["run_attempt"]
status = event["workflow_run"]["status"]
jobs_url = event["workflow_run"]["jobs_url"]
rerun_url = event["workflow_run"]["rerun_url"]
url = event["workflow_run"]["html_url"]
api_url = event["workflow_run"]["url"]
return WorkflowDescription(
name=name,
action=action,
run_id=run_id,
event=event_type,
fork_owner_login=fork_owner,
fork_branch=fork_branch,
workflow_id=workflow_id,
conclusion=conclusion,
attempt=attempt,
status=status,
jobs_url=jobs_url,
rerun_url=rerun_url,
url=url,
api_url=api_url,
)
def get_pr_author_and_orgs(pull_request):
author = pull_request["user"]["login"]
orgs = _exec_get_with_retry(pull_request["user"]["organizations_url"])
return author, [org["id"] for org in orgs]
def get_changed_files_for_pull_request(pull_request):
number = pull_request["number"]
changed_files = set([])
for i in range(1, 31):
print("Requesting changed files page", i)
url = f"{API_URL}/pulls/{number}/files?page={i}&per_page=100"
data = _exec_get_with_retry(url)
print(f"Got {len(data)} changed files")
if len(data) == 0:
print("No more changed files")
break
for change in data:
# print("Adding changed file", change['filename'])
changed_files.add(change["filename"])
if len(changed_files) >= SUSPICIOUS_CHANGED_FILES_NUMBER:
print(
f"More than {len(changed_files)} changed files. "
"Will stop fetching new files."
)
break
return changed_files
def check_suspicious_changed_files(changed_files):
if len(changed_files) >= SUSPICIOUS_CHANGED_FILES_NUMBER:
print(f"Too many files changed {len(changed_files)}, need manual approve")
return True
for path in changed_files:
for pattern in SUSPICIOUS_PATTERNS:
if fnmatch.fnmatch(path, pattern):
print(
f"File {path} match suspicious pattern {pattern}, "
"will not approve automatically"
)
return True
print("No changed files match suspicious patterns, run will be approved")
return False
def approve_run(run_id, token):
url = f"{API_URL}/actions/runs/{run_id}/approve"
_exec_post_with_retry(url, token)
def label_manual_approve(pull_request, token):
number = pull_request["number"]
url = f"{API_URL}/issues/{number}/labels"
data = {"labels": "manual approve"}
_exec_post_with_retry(url, token, data)
def get_token_from_aws():
private_key, app_id = get_key_and_app_from_aws()
payload = {
"iat": int(time.time()) - 60,
"exp": int(time.time()) + (10 * 60),
"iss": app_id,
}
encoded_jwt = jwt.encode(payload, private_key, algorithm="RS256")
installation_id = get_installation_id(encoded_jwt)
return get_access_token(encoded_jwt, installation_id)
def get_workflow_jobs(workflow_description):
jobs_url = (
workflow_description.api_url + f"/attempts/{workflow_description.attempt}/jobs"
)
jobs = []
i = 1
while True:
got_jobs = _exec_get_with_retry(jobs_url + f"?page={i}")
if len(got_jobs["jobs"]) == 0:
break
jobs += got_jobs["jobs"]
i += 1
return jobs
def check_need_to_rerun(workflow_description):
if workflow_description.attempt >= MAX_WORKFLOW_RERUN:
print(
"Not going to rerun workflow because it's already tried more than two times"
)
return False
print("Going to check jobs")
jobs = get_workflow_jobs(workflow_description)
print("Got jobs", len(jobs))
for job in jobs:
if job["conclusion"] not in ("success", "skipped"):
print("Job", job["name"], "failed, checking steps")
for step in job["steps"]:
# always the last job
if step["name"] == "Complete job":
print("Found Complete job step for job", job["name"])
break
else:
print(
"Checked all steps and doesn't found Complete job, going to rerun"
)
return True
return False
def rerun_workflow(workflow_description, token):
print("Going to rerun workflow")
try:
_exec_post_with_retry(f"{workflow_description.rerun_url}-failed-jobs", token)
except Exception:
_exec_post_with_retry(workflow_description.rerun_url, token)
def main(event):
token = get_token_from_aws()
event_data = json.loads(event["body"])
print("The body received:", event_data)
workflow_description = get_workflow_description_from_event(event_data)
print("Got workflow description", workflow_description)
if (
workflow_description.action == "completed"
and workflow_description.conclusion == "failure"
):
print(
"Workflow",
workflow_description.url,
"completed and failed, let's check for rerun",
)
if workflow_description.name not in NEED_RERUN_WORKFLOWS:
print(
"Workflow",
workflow_description.name,
"not in list of rerunable workflows",
)
return
if check_need_to_rerun(workflow_description):
rerun_workflow(workflow_description, token)
return
if workflow_description.action != "requested":
print("Exiting, event action is", workflow_description.action)
return
if workflow_description.workflow_id in TRUSTED_WORKFLOW_IDS:
print("Workflow in trusted list, approving run")
approve_run(workflow_description.run_id, token)
return
pull_requests = _get_pull_requests_from(
workflow_description.fork_owner_login, workflow_description.fork_branch
)
print("Got pull requests for workflow", len(pull_requests))
if len(pull_requests) > 1:
raise Exception("Received more than one PR for workflow run")
if len(pull_requests) < 1:
raise Exception("Cannot find any pull requests for workflow run")
pull_request = pull_requests[0]
print("Pull request for workflow number", pull_request["number"])
author, author_orgs = get_pr_author_and_orgs(pull_request)
if is_trusted_contributor(author, author_orgs):
print("Contributor is trusted, approving run")
approve_run(workflow_description.run_id, token)
return
changed_files = get_changed_files_for_pull_request(pull_request)
print(f"Totally have {len(changed_files)} changed files in PR:", changed_files)
if check_suspicious_changed_files(changed_files):
print(
f"Pull Request {pull_request['number']} has suspicious changes, "
"label it for manuall approve"
)
label_manual_approve(pull_request, token)
else:
print(f"Pull Request {pull_request['number']} has no suspicious changes")
approve_run(workflow_description.run_id, token)
def handler(event, _):
main(event)
|
import datetime as dt
import re
import string
import uuid
from contextlib import suppress
from urllib.parse import urlparse
import pytz
from django.db import models
from django.utils.functional import cached_property
from django_scopes import ScopedManager
from i18nfield.fields import I18nCharField
from pretalx.common.mixins.models import LogMixin
from pretalx.common.urls import get_base_url
INSTANCE_IDENTIFIER = None
with suppress(Exception):
from pretalx.common.models.settings import GlobalSettings
INSTANCE_IDENTIFIER = GlobalSettings().get_instance_identifier()
class TalkSlot(LogMixin, models.Model):
"""The TalkSlot object is the scheduled version of a.
:class:`~pretalx.submission.models.submission.Submission`.
TalkSlots always belong to one submission and one :class:`~pretalx.schedule.models.schedule.Schedule`.
:param is_visible: This parameter is set on schedule release. Only confirmed talks will be visible.
"""
submission = models.ForeignKey(
to="submission.Submission",
on_delete=models.PROTECT,
related_name="slots",
null=True,
blank=True, # If the submission is empty, this is a break or similar event
)
room = models.ForeignKey(
to="schedule.Room",
on_delete=models.PROTECT,
related_name="talks",
null=True,
blank=True,
)
schedule = models.ForeignKey(
to="schedule.Schedule", on_delete=models.PROTECT, related_name="talks"
)
is_visible = models.BooleanField(default=False)
start = models.DateTimeField(null=True)
end = models.DateTimeField(null=True)
description = I18nCharField(null=True)
objects = ScopedManager(event="schedule__event")
def __str__(self):
"""Help when debugging."""
return f'TalkSlot(event={self.schedule.event.slug}, submission={getattr(self.submission, 'title', None)}, schedule={self.schedule.version})'
@cached_property
def event(self):
return self.submission.event if self.submission else self.schedule.event
@property
def duration(self) -> int:
"""Returns the actual duration in minutes if the talk is scheduled, and
the planned duration in minutes otherwise."""
if self.start and self.end:
return int((self.end - self.start).total_seconds() / 60)
if not self.submission:
return None
return self.submission.get_duration()
@cached_property
def export_duration(self):
from pretalx.common.serialize import serialize_duration
return serialize_duration(minutes=self.duration)
@cached_property
def pentabarf_export_duration(self):
duration = dt.timedelta(minutes=self.duration)
days = duration.days
hours = duration.total_seconds() // 3600 - days * 24
minutes = duration.seconds // 60 % 60
return f"{hours:02}{minutes:02}00"
@cached_property
def real_end(self):
"""Guaranteed to provide a useful end datetime if ``start`` is set,
even if ``end`` is empty."""
result = self.end or (
self.start + dt.timedelta(minutes=self.duration) if self.start else None
)
if result:
return result.astimezone(self.event.tz)
@cached_property
def as_availability(self):
"""'Casts' a slot as.
:class:`~pretalx.schedule.models.availability.Availability`, useful for
availability arithmetic.
"""
from pretalx.schedule.models import Availability
return Availability(
start=self.start,
end=self.real_end,
)
def copy_to_schedule(self, new_schedule, save=True):
"""Create a new slot for the given.
:class:`~pretalx.schedule.models.schedule.Schedule` with all other
fields identical to this one.
"""
new_slot = TalkSlot(schedule=new_schedule)
for field in [f for f in self._meta.fields if f.name not in ("id", "schedule")]:
setattr(new_slot, field.name, getattr(self, field.name))
if save:
new_slot.save()
return new_slot
copy_to_schedule.alters_data = True
def is_same_slot(self, other_slot) -> bool:
"""Checks if both slots have the same room and start time."""
return self.room == other_slot.room and self.start == other_slot.start
@cached_property
def id_suffix(self):
if not self.event.settings.present_multiple_times:
return ""
all_slots = list(
TalkSlot.objects.filter(
submission_id=self.submission_id, schedule_id=self.schedule_id
)
)
if len(all_slots) == 1:
return ""
return "-" + str(all_slots.index(self))
@cached_property
def frab_slug(self):
title = re.sub(r"\W+", "-", self.submission.title)
legal_chars = string.ascii_letters + string.digits + "-"
pattern = f"[^{legal_chars}]+"
title = re.sub(pattern, "", title)
title = title.lower()
title = title.strip("_")
return f"{self.event.slug}-{self.submission.pk}{self.id_suffix}-{title}"
@cached_property
def uuid(self):
"""A UUID5, calculated from the submission code and the instance
identifier."""
global INSTANCE_IDENTIFIER
if not INSTANCE_IDENTIFIER:
from pretalx.common.models.settings import GlobalSettings
INSTANCE_IDENTIFIER = GlobalSettings().get_instance_identifier()
return uuid.uuid5(INSTANCE_IDENTIFIER, self.submission.code + self.id_suffix)
def build_ical(self, calendar, creation_time=None, netloc=None):
if not self.start or not self.end or not self.room or not self.submission:
return
creation_time = creation_time or dt.datetime.now(pytz.utc)
netloc = netloc or urlparse(get_base_url(self.event)).netloc
tz = pytz.timezone(self.submission.event.timezone)
vevent = calendar.add("vevent")
vevent.add(
"summary"
).value = f"{self.submission.title} - {self.submission.display_speaker_names}"
vevent.add("dtstamp").value = creation_time
vevent.add("location").value = str(self.room.name)
vevent.add("uid").value = "pretalx-{}-{}{}@{}".format(
self.submission.event.slug, self.submission.code, self.id_suffix, netloc
)
vevent.add("dtstart").value = self.start.astimezone(tz)
vevent.add("dtend").value = self.end.astimezone(tz)
vevent.add("description").value = self.submission.abstract or ""
vevent.add("url").value = self.submission.urls.public.full()
| import datetime as dt
import re
import string
import uuid
from contextlib import suppress
from urllib.parse import urlparse
import pytz
from django.db import models
from django.utils.functional import cached_property
from django_scopes import ScopedManager
from i18nfield.fields import I18nCharField
from pretalx.common.mixins.models import LogMixin
from pretalx.common.urls import get_base_url
INSTANCE_IDENTIFIER = None
with suppress(Exception):
from pretalx.common.models.settings import GlobalSettings
INSTANCE_IDENTIFIER = GlobalSettings().get_instance_identifier()
class TalkSlot(LogMixin, models.Model):
"""The TalkSlot object is the scheduled version of a.
:class:`~pretalx.submission.models.submission.Submission`.
TalkSlots always belong to one submission and one :class:`~pretalx.schedule.models.schedule.Schedule`.
:param is_visible: This parameter is set on schedule release. Only confirmed talks will be visible.
"""
submission = models.ForeignKey(
to="submission.Submission",
on_delete=models.PROTECT,
related_name="slots",
null=True,
blank=True, # If the submission is empty, this is a break or similar event
)
room = models.ForeignKey(
to="schedule.Room",
on_delete=models.PROTECT,
related_name="talks",
null=True,
blank=True,
)
schedule = models.ForeignKey(
to="schedule.Schedule", on_delete=models.PROTECT, related_name="talks"
)
is_visible = models.BooleanField(default=False)
start = models.DateTimeField(null=True)
end = models.DateTimeField(null=True)
description = I18nCharField(null=True)
objects = ScopedManager(event="schedule__event")
def __str__(self):
"""Help when debugging."""
return f'TalkSlot(event={self.schedule.event.slug}, submission={getattr(self.submission, "title", None)}, schedule={self.schedule.version})'
@cached_property
def event(self):
return self.submission.event if self.submission else self.schedule.event
@property
def duration(self) -> int:
"""Returns the actual duration in minutes if the talk is scheduled, and
the planned duration in minutes otherwise."""
if self.start and self.end:
return int((self.end - self.start).total_seconds() / 60)
if not self.submission:
return None
return self.submission.get_duration()
@cached_property
def export_duration(self):
from pretalx.common.serialize import serialize_duration
return serialize_duration(minutes=self.duration)
@cached_property
def pentabarf_export_duration(self):
duration = dt.timedelta(minutes=self.duration)
days = duration.days
hours = duration.total_seconds() // 3600 - days * 24
minutes = duration.seconds // 60 % 60
return f"{hours:02}{minutes:02}00"
@cached_property
def real_end(self):
"""Guaranteed to provide a useful end datetime if ``start`` is set,
even if ``end`` is empty."""
result = self.end or (
self.start + dt.timedelta(minutes=self.duration) if self.start else None
)
if result:
return result.astimezone(self.event.tz)
@cached_property
def as_availability(self):
"""'Casts' a slot as.
:class:`~pretalx.schedule.models.availability.Availability`, useful for
availability arithmetic.
"""
from pretalx.schedule.models import Availability
return Availability(
start=self.start,
end=self.real_end,
)
def copy_to_schedule(self, new_schedule, save=True):
"""Create a new slot for the given.
:class:`~pretalx.schedule.models.schedule.Schedule` with all other
fields identical to this one.
"""
new_slot = TalkSlot(schedule=new_schedule)
for field in [f for f in self._meta.fields if f.name not in ("id", "schedule")]:
setattr(new_slot, field.name, getattr(self, field.name))
if save:
new_slot.save()
return new_slot
copy_to_schedule.alters_data = True
def is_same_slot(self, other_slot) -> bool:
"""Checks if both slots have the same room and start time."""
return self.room == other_slot.room and self.start == other_slot.start
@cached_property
def id_suffix(self):
if not self.event.settings.present_multiple_times:
return ""
all_slots = list(
TalkSlot.objects.filter(
submission_id=self.submission_id, schedule_id=self.schedule_id
)
)
if len(all_slots) == 1:
return ""
return "-" + str(all_slots.index(self))
@cached_property
def frab_slug(self):
title = re.sub(r"\W+", "-", self.submission.title)
legal_chars = string.ascii_letters + string.digits + "-"
pattern = f"[^{legal_chars}]+"
title = re.sub(pattern, "", title)
title = title.lower()
title = title.strip("_")
return f"{self.event.slug}-{self.submission.pk}{self.id_suffix}-{title}"
@cached_property
def uuid(self):
"""A UUID5, calculated from the submission code and the instance
identifier."""
global INSTANCE_IDENTIFIER
if not INSTANCE_IDENTIFIER:
from pretalx.common.models.settings import GlobalSettings
INSTANCE_IDENTIFIER = GlobalSettings().get_instance_identifier()
return uuid.uuid5(INSTANCE_IDENTIFIER, self.submission.code + self.id_suffix)
def build_ical(self, calendar, creation_time=None, netloc=None):
if not self.start or not self.end or not self.room or not self.submission:
return
creation_time = creation_time or dt.datetime.now(pytz.utc)
netloc = netloc or urlparse(get_base_url(self.event)).netloc
tz = pytz.timezone(self.submission.event.timezone)
vevent = calendar.add("vevent")
vevent.add(
"summary"
).value = f"{self.submission.title} - {self.submission.display_speaker_names}"
vevent.add("dtstamp").value = creation_time
vevent.add("location").value = str(self.room.name)
vevent.add("uid").value = "pretalx-{}-{}{}@{}".format(
self.submission.event.slug, self.submission.code, self.id_suffix, netloc
)
vevent.add("dtstart").value = self.start.astimezone(tz)
vevent.add("dtend").value = self.end.astimezone(tz)
vevent.add("description").value = self.submission.abstract or ""
vevent.add("url").value = self.submission.urls.public.full()
|
import base64
import copy
import gzip
import json
import random
from typing import Dict, List, Optional, Tuple
from katrain.core.constants import (
ANALYSIS_FORMAT_VERSION,
PROGRAM_NAME,
REPORT_DT,
SGF_INTERNAL_COMMENTS_MARKER,
SGF_SEPARATOR_MARKER,
VERSION,
PRIORITY_DEFAULT,
ADDITIONAL_MOVE_ORDER,
)
from katrain.core.lang import i18n
from katrain.core.sgf_parser import Move, SGFNode
from katrain.core.utils import evaluation_class, pack_floats, unpack_floats, var_to_grid
from katrain.gui.theme import Theme
def analysis_dumps(analysis):
analysis = copy.deepcopy(analysis)
for movedict in analysis["moves"].values():
if "ownership" in movedict: # per-move ownership rarely used
del movedict["ownership"]
ownership_data = pack_floats(analysis.pop("ownership"))
policy_data = pack_floats(analysis.pop("policy"))
main_data = json.dumps(analysis).encode("utf-8")
return [
base64.standard_b64encode(gzip.compress(data)).decode("utf-8")
for data in [ownership_data, policy_data, main_data]
]
class GameNode(SGFNode):
"""Represents a single game node, with one or more moves and placements."""
def __init__(self, parent=None, properties=None, move=None):
super().__init__(parent=parent, properties=properties, move=move)
self.auto_undo = None # None = not analyzed. False: not undone (good move). True: undone (bad move)
self.played_sound = None
self.ai_thoughts = ""
self.note = ""
self.move_number = 0
self.time_used = 0
self.undo_threshold = random.random() # for fractional undos
self.end_state = None
self.shortcuts_to = []
self.shortcut_from = None
self.analysis_from_sgf = None
self.clear_analysis()
def add_shortcut(self, to_node): # collapses the branch between them
nodes = [to_node]
while nodes[-1].parent and nodes[-1] != self: # ensure on path
nodes.append(nodes[-1].parent)
if nodes[-1] == self and len(nodes) > 2:
via = nodes[-2]
self.shortcuts_to.append((to_node, via)) # and first child
to_node.shortcut_from = self
def remove_shortcut(self):
from_node = self.shortcut_from
if from_node:
from_node.shortcuts_to = [(m, v) for m, v in from_node.shortcuts_to if m != self]
self.shortcut_from = None
def load_analysis(self):
if not self.analysis_from_sgf:
return False
try:
szx, szy = self.root.board_size
board_squares = szx * szy
version = self.root.get_property("KTV", ANALYSIS_FORMAT_VERSION)
if version > ANALYSIS_FORMAT_VERSION:
raise ValueError(f"Can not decode analysis data with version {version}, please update {PROGRAM_NAME}")
ownership_data, policy_data, main_data, *_ = [
gzip.decompress(base64.standard_b64decode(data)) for data in self.analysis_from_sgf
]
self.analysis = {
**json.loads(main_data),
"policy": unpack_floats(policy_data, board_squares + 1),
"ownership": unpack_floats(ownership_data, board_squares),
}
return True
except Exception as e:
print(f"Error in loading analysis: {e}")
return False
def add_list_property(self, property: str, values: List):
if property == "KT":
self.analysis_from_sgf = values
elif property == "C":
comments = [ # strip out all previously auto generated comments
c
for v in values
for c in v.split(SGF_SEPARATOR_MARKER)
if c.strip() and SGF_INTERNAL_COMMENTS_MARKER not in c
]
self.note = "".join(comments).strip() # no super call intended, just save as note to be editable
else:
return super().add_list_property(property, values)
def clear_analysis(self):
self.analysis_visits_requested = 0
self.analysis = {"moves": {}, "root": None, "ownership": None, "policy": None, "completed": False}
def sgf_properties(
self,
save_comments_player=None,
save_comments_class=None,
eval_thresholds=None,
save_analysis=False,
save_marks=False,
):
properties = copy.copy(super().sgf_properties())
note = self.note.strip()
if save_analysis and self.analysis_complete:
try:
properties["KT"] = analysis_dumps(self.analysis)
except Exception as e:
print(f"Error in saving analysis: {e}")
if self.points_lost and save_comments_class is not None and eval_thresholds is not None:
show_class = save_comments_class[evaluation_class(self.points_lost, eval_thresholds)]
else:
show_class = False
comments = properties.get("C", [])
if (
self.parent
and self.parent.analysis_exists
and self.analysis_exists
and (note or ((save_comments_player or {}).get(self.player, False) and show_class))
):
if save_marks:
candidate_moves = self.parent.candidate_moves
top_x = Move.from_gtp(candidate_moves[0]["move"]).sgf(self.board_size)
best_sq = [
Move.from_gtp(d["move"]).sgf(self.board_size)
for d in candidate_moves
if d["pointsLost"] <= 0.5 and d["move"] != "pass" and d["order"] != 0
]
if best_sq and "SQ" not in properties:
properties["SQ"] = best_sq
if top_x and "MA" not in properties:
properties["MA"] = [top_x]
comments.append("\n" + self.comment(sgf=True, interactive=False) + SGF_INTERNAL_COMMENTS_MARKER)
if self.is_root:
if save_marks:
comments = [i18n._("SGF start message") + SGF_INTERNAL_COMMENTS_MARKER + "\n"]
else:
comments = []
comments += [
*comments,
f"\nSGF generated by {PROGRAM_NAME} {VERSION}{SGF_INTERNAL_COMMENTS_MARKER}\n",
]
properties["CA"] = ["UTF-8"]
properties["AP"] = [f"{PROGRAM_NAME}:{VERSION}"]
properties["KTV"] = [ANALYSIS_FORMAT_VERSION]
if self.shortcut_from:
properties["KTSF"] = [id(self.shortcut_from)]
elif "KTSF" in properties:
del properties["KTSF"]
if self.shortcuts_to:
properties["KTSID"] = [id(self)]
elif "KTSID" in properties:
del properties["KTSID"]
if note:
comments.insert(0, f"{self.note}\n") # user notes at top!
if comments:
properties["C"] = [SGF_SEPARATOR_MARKER.join(comments).strip("\n")]
elif "C" in properties:
del properties["C"]
return properties
@staticmethod
def order_children(children):
return sorted(
children, key=lambda c: 0.5 if c.auto_undo is None else int(c.auto_undo)
) # analyzed/not undone main, non-teach second, undone last
# various analysis functions
def analyze(
self,
engine,
priority=PRIORITY_DEFAULT,
visits=None,
time_limit=True,
refine_move=None,
analyze_fast=False,
find_alternatives=False,
region_of_interest=None,
report_every=REPORT_DT,
):
engine.request_analysis(
self,
callback=lambda result, partial_result: self.set_analysis(
result, refine_move, find_alternatives, region_of_interest, partial_result
),
priority=priority,
visits=visits,
analyze_fast=analyze_fast,
time_limit=time_limit,
next_move=refine_move,
find_alternatives=find_alternatives,
region_of_interest=region_of_interest,
report_every=report_every,
)
def update_move_analysis(self, move_analysis, move_gtp):
cur = self.analysis["moves"].get(move_gtp)
if cur is None:
self.analysis["moves"][move_gtp] = {
"move": move_gtp,
"order": ADDITIONAL_MOVE_ORDER,
**move_analysis,
} # some default values for keys missing in rootInfo
else:
cur["order"] = min(
cur["order"], move_analysis.get("order", ADDITIONAL_MOVE_ORDER)
) # parent arriving after child
if cur["visits"] < move_analysis["visits"]:
cur.update(move_analysis)
else: # prior etc only
cur.update({k: v for k, v in move_analysis.items() if k not in cur})
def set_analysis(
self,
analysis_json: Dict,
refine_move: Optional[Move] = None,
additional_moves: bool = False,
region_of_interest=None,
partial_result: bool = False,
):
if refine_move:
pvtail = analysis_json["moveInfos"][0]["pv"] if analysis_json["moveInfos"] else []
self.update_move_analysis(
{"pv": [refine_move.gtp()] + pvtail, **analysis_json["rootInfo"]}, refine_move.gtp()
)
else:
if additional_moves: # additional moves: old order matters, ignore new order
for m in analysis_json["moveInfos"]:
del m["order"]
elif refine_move is None: # normal update: old moves to end, new order matters. also for region?
for move_dict in self.analysis["moves"].values():
move_dict["order"] = ADDITIONAL_MOVE_ORDER # old moves to end
for move_analysis in analysis_json["moveInfos"]:
self.update_move_analysis(move_analysis, move_analysis["move"])
self.analysis["ownership"] = analysis_json.get("ownership")
self.analysis["policy"] = analysis_json.get("policy")
if not additional_moves and not region_of_interest:
self.analysis["root"] = analysis_json["rootInfo"]
if self.parent and self.move:
analysis_json["rootInfo"]["pv"] = [self.move.gtp()] + (
analysis_json["moveInfos"][0]["pv"] if analysis_json["moveInfos"] else []
)
self.parent.update_move_analysis(
analysis_json["rootInfo"], self.move.gtp()
) # update analysis in parent for consistency
is_normal_query = refine_move is None and not additional_moves
self.analysis["completed"] = self.analysis["completed"] or (is_normal_query and not partial_result)
@property
def ownership(self):
return self.analysis.get("ownership")
@property
def policy(self):
return self.analysis.get("policy")
@property
def analysis_exists(self):
return self.analysis["root"] is not None
@property
def analysis_complete(self):
return self.analysis["completed"] and self.analysis["root"] is not None
@property
def score(self) -> Optional[float]:
if self.analysis_exists:
return self.analysis["root"].get("scoreLead")
def format_score(self, score=None):
score = score or self.score
if score is not None:
return f"{"B" if score >= 0 else "W"}+{abs(score):.1f}"
@property
def winrate(self) -> Optional[float]:
if self.analysis_exists:
return self.analysis["root"].get("winrate")
def format_winrate(self, win_rate=None):
win_rate = win_rate or self.winrate
if win_rate is not None:
return f"{"B" if win_rate > 0.5 else "W"} {max(win_rate,1-win_rate):.1%}"
def move_policy_stats(self) -> Tuple[Optional[int], float, List]:
single_move = self.move
if single_move and self.parent:
policy_ranking = self.parent.policy_ranking
if policy_ranking:
for ix, (p, m) in enumerate(policy_ranking):
if m == single_move:
return ix + 1, p, policy_ranking
return None, 0.0, []
def make_pv(self, player, pv, interactive):
pvtext = f"{player}{" ".join(pv)}"
if interactive:
pvtext = f"[u][ref={pvtext}][color={Theme.INFO_PV_COLOR}]{pvtext}[/color][/ref][/u]"
return pvtext
def comment(self, sgf=False, teach=False, details=False, interactive=True):
single_move = self.move
if not self.parent or not single_move: # root
if self.root:
rules = self.get_property("RU", "Japanese")
if isinstance(rules, str): # else katago dict
rules = i18n._(rules.lower())
return f"{i18n._("komi")}: {self.komi:.1f}\n{i18n._("ruleset")}: {rules}\n"
return ""
text = i18n._("move").format(number=self.depth) + f": {single_move.player} {single_move.gtp()}\n"
if self.analysis_exists:
score = self.score
if sgf:
text += i18n._("Info:score").format(score=self.format_score(score)) + "\n"
text += i18n._("Info:winrate").format(winrate=self.format_winrate()) + "\n"
if self.parent and self.parent.analysis_exists:
previous_top_move = self.parent.candidate_moves[0]
if sgf or details:
if previous_top_move["move"] != single_move.gtp():
points_lost = self.points_lost
if sgf and points_lost > 0.5:
text += i18n._("Info:point loss").format(points_lost=points_lost) + "\n"
top_move = previous_top_move["move"]
score = self.format_score(previous_top_move["scoreLead"])
text += (
i18n._("Info:top move").format(
top_move=top_move,
score=score,
)
+ "\n"
)
else:
text += i18n._("Info:best move") + "\n"
if previous_top_move.get("pv") and (sgf or details):
pv = self.make_pv(single_move.player, previous_top_move["pv"], interactive)
text += i18n._("Info:PV").format(pv=pv) + "\n"
if sgf or details or teach:
currmove_pol_rank, currmove_pol_prob, policy_ranking = self.move_policy_stats()
if currmove_pol_rank is not None:
policy_rank_msg = i18n._("Info:policy rank")
text += policy_rank_msg.format(rank=currmove_pol_rank, probability=currmove_pol_prob) + "\n"
if currmove_pol_rank != 1 and policy_ranking and (sgf or details):
policy_best_msg = i18n._("Info:policy best")
pol_move, pol_prob = policy_ranking[0][1].gtp(), policy_ranking[0][0]
text += policy_best_msg.format(move=pol_move, probability=pol_prob) + "\n"
if self.auto_undo and sgf:
text += i18n._("Info:teaching undo") + "\n"
top_pv = self.analysis_exists and self.candidate_moves[0].get("pv")
if top_pv:
text += i18n._("Info:undo predicted PV").format(pv=f"{self.next_player}{" ".join(top_pv)}") + "\n"
else:
text = i18n._("No analysis available") if sgf else i18n._("Analyzing move...")
if self.ai_thoughts and (sgf or details):
text += "\n" + i18n._("Info:AI thoughts").format(thoughts=self.ai_thoughts)
if "C" in self.properties:
text += "\n[u]SGF Comments:[/u]\n" + "\n".join(self.properties["C"])
return text
@property
def points_lost(self) -> Optional[float]:
single_move = self.move
if single_move and self.parent and self.analysis_exists and self.parent.analysis_exists:
parent_score = self.parent.score
score = self.score
return self.player_sign(single_move.player) * (parent_score - score)
@property
def parent_realized_points_lost(self) -> Optional[float]:
single_move = self.move
if (
single_move
and self.parent
and self.parent.parent
and self.analysis_exists
and self.parent.parent.analysis_exists
):
parent_parent_score = self.parent.parent.score
score = self.score
return self.player_sign(single_move.player) * (score - parent_parent_score)
@staticmethod
def player_sign(player):
return {"B": 1, "W": -1, None: 0}[player]
@property
def candidate_moves(self) -> List[Dict]:
if not self.analysis_exists:
return []
if not self.analysis["moves"]:
polmoves = self.policy_ranking
top_polmove = polmoves[0][1] if polmoves else Move(None) # if no info at all, pass
return [
{
**self.analysis["root"],
"pointsLost": 0,
"winrateLost": 0,
"order": 0,
"move": top_polmove.gtp(),
"pv": [top_polmove.gtp()],
}
] # single visit -> go by policy/root
root_score = self.analysis["root"]["scoreLead"]
root_winrate = self.analysis["root"]["winrate"]
move_dicts = list(self.analysis["moves"].values()) # prevent incoming analysis from causing crash
top_move = [d for d in move_dicts if d["order"] == 0]
top_score_lead = top_move[0]["scoreLead"] if top_move else root_score
return sorted(
[
{
"pointsLost": self.player_sign(self.next_player) * (root_score - d["scoreLead"]),
"relativePointsLost": self.player_sign(self.next_player) * (top_score_lead - d["scoreLead"]),
"winrateLost": self.player_sign(self.next_player) * (root_winrate - d["winrate"]),
**d,
}
for d in move_dicts
],
key=lambda d: (d["order"], d["pointsLost"]),
)
@property
def policy_ranking(self) -> Optional[List[Tuple[float, Move]]]: # return moves from highest policy value to lowest
if self.policy:
szx, szy = self.board_size
policy_grid = var_to_grid(self.policy, size=(szx, szy))
moves = [(policy_grid[y][x], Move((x, y), player=self.next_player)) for x in range(szx) for y in range(szy)]
moves.append((self.policy[-1], Move(None, player=self.next_player)))
return sorted(moves, key=lambda mp: -mp[0])
| import base64
import copy
import gzip
import json
import random
from typing import Dict, List, Optional, Tuple
from katrain.core.constants import (
ANALYSIS_FORMAT_VERSION,
PROGRAM_NAME,
REPORT_DT,
SGF_INTERNAL_COMMENTS_MARKER,
SGF_SEPARATOR_MARKER,
VERSION,
PRIORITY_DEFAULT,
ADDITIONAL_MOVE_ORDER,
)
from katrain.core.lang import i18n
from katrain.core.sgf_parser import Move, SGFNode
from katrain.core.utils import evaluation_class, pack_floats, unpack_floats, var_to_grid
from katrain.gui.theme import Theme
def analysis_dumps(analysis):
analysis = copy.deepcopy(analysis)
for movedict in analysis["moves"].values():
if "ownership" in movedict: # per-move ownership rarely used
del movedict["ownership"]
ownership_data = pack_floats(analysis.pop("ownership"))
policy_data = pack_floats(analysis.pop("policy"))
main_data = json.dumps(analysis).encode("utf-8")
return [
base64.standard_b64encode(gzip.compress(data)).decode("utf-8")
for data in [ownership_data, policy_data, main_data]
]
class GameNode(SGFNode):
"""Represents a single game node, with one or more moves and placements."""
def __init__(self, parent=None, properties=None, move=None):
super().__init__(parent=parent, properties=properties, move=move)
self.auto_undo = None # None = not analyzed. False: not undone (good move). True: undone (bad move)
self.played_sound = None
self.ai_thoughts = ""
self.note = ""
self.move_number = 0
self.time_used = 0
self.undo_threshold = random.random() # for fractional undos
self.end_state = None
self.shortcuts_to = []
self.shortcut_from = None
self.analysis_from_sgf = None
self.clear_analysis()
def add_shortcut(self, to_node): # collapses the branch between them
nodes = [to_node]
while nodes[-1].parent and nodes[-1] != self: # ensure on path
nodes.append(nodes[-1].parent)
if nodes[-1] == self and len(nodes) > 2:
via = nodes[-2]
self.shortcuts_to.append((to_node, via)) # and first child
to_node.shortcut_from = self
def remove_shortcut(self):
from_node = self.shortcut_from
if from_node:
from_node.shortcuts_to = [(m, v) for m, v in from_node.shortcuts_to if m != self]
self.shortcut_from = None
def load_analysis(self):
if not self.analysis_from_sgf:
return False
try:
szx, szy = self.root.board_size
board_squares = szx * szy
version = self.root.get_property("KTV", ANALYSIS_FORMAT_VERSION)
if version > ANALYSIS_FORMAT_VERSION:
raise ValueError(f"Can not decode analysis data with version {version}, please update {PROGRAM_NAME}")
ownership_data, policy_data, main_data, *_ = [
gzip.decompress(base64.standard_b64decode(data)) for data in self.analysis_from_sgf
]
self.analysis = {
**json.loads(main_data),
"policy": unpack_floats(policy_data, board_squares + 1),
"ownership": unpack_floats(ownership_data, board_squares),
}
return True
except Exception as e:
print(f"Error in loading analysis: {e}")
return False
def add_list_property(self, property: str, values: List):
if property == "KT":
self.analysis_from_sgf = values
elif property == "C":
comments = [ # strip out all previously auto generated comments
c
for v in values
for c in v.split(SGF_SEPARATOR_MARKER)
if c.strip() and SGF_INTERNAL_COMMENTS_MARKER not in c
]
self.note = "".join(comments).strip() # no super call intended, just save as note to be editable
else:
return super().add_list_property(property, values)
def clear_analysis(self):
self.analysis_visits_requested = 0
self.analysis = {"moves": {}, "root": None, "ownership": None, "policy": None, "completed": False}
def sgf_properties(
self,
save_comments_player=None,
save_comments_class=None,
eval_thresholds=None,
save_analysis=False,
save_marks=False,
):
properties = copy.copy(super().sgf_properties())
note = self.note.strip()
if save_analysis and self.analysis_complete:
try:
properties["KT"] = analysis_dumps(self.analysis)
except Exception as e:
print(f"Error in saving analysis: {e}")
if self.points_lost and save_comments_class is not None and eval_thresholds is not None:
show_class = save_comments_class[evaluation_class(self.points_lost, eval_thresholds)]
else:
show_class = False
comments = properties.get("C", [])
if (
self.parent
and self.parent.analysis_exists
and self.analysis_exists
and (note or ((save_comments_player or {}).get(self.player, False) and show_class))
):
if save_marks:
candidate_moves = self.parent.candidate_moves
top_x = Move.from_gtp(candidate_moves[0]["move"]).sgf(self.board_size)
best_sq = [
Move.from_gtp(d["move"]).sgf(self.board_size)
for d in candidate_moves
if d["pointsLost"] <= 0.5 and d["move"] != "pass" and d["order"] != 0
]
if best_sq and "SQ" not in properties:
properties["SQ"] = best_sq
if top_x and "MA" not in properties:
properties["MA"] = [top_x]
comments.append("\n" + self.comment(sgf=True, interactive=False) + SGF_INTERNAL_COMMENTS_MARKER)
if self.is_root:
if save_marks:
comments = [i18n._("SGF start message") + SGF_INTERNAL_COMMENTS_MARKER + "\n"]
else:
comments = []
comments += [
*comments,
f"\nSGF generated by {PROGRAM_NAME} {VERSION}{SGF_INTERNAL_COMMENTS_MARKER}\n",
]
properties["CA"] = ["UTF-8"]
properties["AP"] = [f"{PROGRAM_NAME}:{VERSION}"]
properties["KTV"] = [ANALYSIS_FORMAT_VERSION]
if self.shortcut_from:
properties["KTSF"] = [id(self.shortcut_from)]
elif "KTSF" in properties:
del properties["KTSF"]
if self.shortcuts_to:
properties["KTSID"] = [id(self)]
elif "KTSID" in properties:
del properties["KTSID"]
if note:
comments.insert(0, f"{self.note}\n") # user notes at top!
if comments:
properties["C"] = [SGF_SEPARATOR_MARKER.join(comments).strip("\n")]
elif "C" in properties:
del properties["C"]
return properties
@staticmethod
def order_children(children):
return sorted(
children, key=lambda c: 0.5 if c.auto_undo is None else int(c.auto_undo)
) # analyzed/not undone main, non-teach second, undone last
# various analysis functions
def analyze(
self,
engine,
priority=PRIORITY_DEFAULT,
visits=None,
time_limit=True,
refine_move=None,
analyze_fast=False,
find_alternatives=False,
region_of_interest=None,
report_every=REPORT_DT,
):
engine.request_analysis(
self,
callback=lambda result, partial_result: self.set_analysis(
result, refine_move, find_alternatives, region_of_interest, partial_result
),
priority=priority,
visits=visits,
analyze_fast=analyze_fast,
time_limit=time_limit,
next_move=refine_move,
find_alternatives=find_alternatives,
region_of_interest=region_of_interest,
report_every=report_every,
)
def update_move_analysis(self, move_analysis, move_gtp):
cur = self.analysis["moves"].get(move_gtp)
if cur is None:
self.analysis["moves"][move_gtp] = {
"move": move_gtp,
"order": ADDITIONAL_MOVE_ORDER,
**move_analysis,
} # some default values for keys missing in rootInfo
else:
cur["order"] = min(
cur["order"], move_analysis.get("order", ADDITIONAL_MOVE_ORDER)
) # parent arriving after child
if cur["visits"] < move_analysis["visits"]:
cur.update(move_analysis)
else: # prior etc only
cur.update({k: v for k, v in move_analysis.items() if k not in cur})
def set_analysis(
self,
analysis_json: Dict,
refine_move: Optional[Move] = None,
additional_moves: bool = False,
region_of_interest=None,
partial_result: bool = False,
):
if refine_move:
pvtail = analysis_json["moveInfos"][0]["pv"] if analysis_json["moveInfos"] else []
self.update_move_analysis(
{"pv": [refine_move.gtp()] + pvtail, **analysis_json["rootInfo"]}, refine_move.gtp()
)
else:
if additional_moves: # additional moves: old order matters, ignore new order
for m in analysis_json["moveInfos"]:
del m["order"]
elif refine_move is None: # normal update: old moves to end, new order matters. also for region?
for move_dict in self.analysis["moves"].values():
move_dict["order"] = ADDITIONAL_MOVE_ORDER # old moves to end
for move_analysis in analysis_json["moveInfos"]:
self.update_move_analysis(move_analysis, move_analysis["move"])
self.analysis["ownership"] = analysis_json.get("ownership")
self.analysis["policy"] = analysis_json.get("policy")
if not additional_moves and not region_of_interest:
self.analysis["root"] = analysis_json["rootInfo"]
if self.parent and self.move:
analysis_json["rootInfo"]["pv"] = [self.move.gtp()] + (
analysis_json["moveInfos"][0]["pv"] if analysis_json["moveInfos"] else []
)
self.parent.update_move_analysis(
analysis_json["rootInfo"], self.move.gtp()
) # update analysis in parent for consistency
is_normal_query = refine_move is None and not additional_moves
self.analysis["completed"] = self.analysis["completed"] or (is_normal_query and not partial_result)
@property
def ownership(self):
return self.analysis.get("ownership")
@property
def policy(self):
return self.analysis.get("policy")
@property
def analysis_exists(self):
return self.analysis["root"] is not None
@property
def analysis_complete(self):
return self.analysis["completed"] and self.analysis["root"] is not None
@property
def score(self) -> Optional[float]:
if self.analysis_exists:
return self.analysis["root"].get("scoreLead")
def format_score(self, score=None):
score = score or self.score
if score is not None:
return f"{'B' if score >= 0 else 'W'}+{abs(score):.1f}"
@property
def winrate(self) -> Optional[float]:
if self.analysis_exists:
return self.analysis["root"].get("winrate")
def format_winrate(self, win_rate=None):
win_rate = win_rate or self.winrate
if win_rate is not None:
return f"{'B' if win_rate > 0.5 else 'W'} {max(win_rate,1-win_rate):.1%}"
def move_policy_stats(self) -> Tuple[Optional[int], float, List]:
single_move = self.move
if single_move and self.parent:
policy_ranking = self.parent.policy_ranking
if policy_ranking:
for ix, (p, m) in enumerate(policy_ranking):
if m == single_move:
return ix + 1, p, policy_ranking
return None, 0.0, []
def make_pv(self, player, pv, interactive):
pvtext = f"{player}{' '.join(pv)}"
if interactive:
pvtext = f"[u][ref={pvtext}][color={Theme.INFO_PV_COLOR}]{pvtext}[/color][/ref][/u]"
return pvtext
def comment(self, sgf=False, teach=False, details=False, interactive=True):
single_move = self.move
if not self.parent or not single_move: # root
if self.root:
rules = self.get_property("RU", "Japanese")
if isinstance(rules, str): # else katago dict
rules = i18n._(rules.lower())
return f"{i18n._('komi')}: {self.komi:.1f}\n{i18n._('ruleset')}: {rules}\n"
return ""
text = i18n._("move").format(number=self.depth) + f": {single_move.player} {single_move.gtp()}\n"
if self.analysis_exists:
score = self.score
if sgf:
text += i18n._("Info:score").format(score=self.format_score(score)) + "\n"
text += i18n._("Info:winrate").format(winrate=self.format_winrate()) + "\n"
if self.parent and self.parent.analysis_exists:
previous_top_move = self.parent.candidate_moves[0]
if sgf or details:
if previous_top_move["move"] != single_move.gtp():
points_lost = self.points_lost
if sgf and points_lost > 0.5:
text += i18n._("Info:point loss").format(points_lost=points_lost) + "\n"
top_move = previous_top_move["move"]
score = self.format_score(previous_top_move["scoreLead"])
text += (
i18n._("Info:top move").format(
top_move=top_move,
score=score,
)
+ "\n"
)
else:
text += i18n._("Info:best move") + "\n"
if previous_top_move.get("pv") and (sgf or details):
pv = self.make_pv(single_move.player, previous_top_move["pv"], interactive)
text += i18n._("Info:PV").format(pv=pv) + "\n"
if sgf or details or teach:
currmove_pol_rank, currmove_pol_prob, policy_ranking = self.move_policy_stats()
if currmove_pol_rank is not None:
policy_rank_msg = i18n._("Info:policy rank")
text += policy_rank_msg.format(rank=currmove_pol_rank, probability=currmove_pol_prob) + "\n"
if currmove_pol_rank != 1 and policy_ranking and (sgf or details):
policy_best_msg = i18n._("Info:policy best")
pol_move, pol_prob = policy_ranking[0][1].gtp(), policy_ranking[0][0]
text += policy_best_msg.format(move=pol_move, probability=pol_prob) + "\n"
if self.auto_undo and sgf:
text += i18n._("Info:teaching undo") + "\n"
top_pv = self.analysis_exists and self.candidate_moves[0].get("pv")
if top_pv:
text += i18n._("Info:undo predicted PV").format(pv=f"{self.next_player}{' '.join(top_pv)}") + "\n"
else:
text = i18n._("No analysis available") if sgf else i18n._("Analyzing move...")
if self.ai_thoughts and (sgf or details):
text += "\n" + i18n._("Info:AI thoughts").format(thoughts=self.ai_thoughts)
if "C" in self.properties:
text += "\n[u]SGF Comments:[/u]\n" + "\n".join(self.properties["C"])
return text
@property
def points_lost(self) -> Optional[float]:
single_move = self.move
if single_move and self.parent and self.analysis_exists and self.parent.analysis_exists:
parent_score = self.parent.score
score = self.score
return self.player_sign(single_move.player) * (parent_score - score)
@property
def parent_realized_points_lost(self) -> Optional[float]:
single_move = self.move
if (
single_move
and self.parent
and self.parent.parent
and self.analysis_exists
and self.parent.parent.analysis_exists
):
parent_parent_score = self.parent.parent.score
score = self.score
return self.player_sign(single_move.player) * (score - parent_parent_score)
@staticmethod
def player_sign(player):
return {"B": 1, "W": -1, None: 0}[player]
@property
def candidate_moves(self) -> List[Dict]:
if not self.analysis_exists:
return []
if not self.analysis["moves"]:
polmoves = self.policy_ranking
top_polmove = polmoves[0][1] if polmoves else Move(None) # if no info at all, pass
return [
{
**self.analysis["root"],
"pointsLost": 0,
"winrateLost": 0,
"order": 0,
"move": top_polmove.gtp(),
"pv": [top_polmove.gtp()],
}
] # single visit -> go by policy/root
root_score = self.analysis["root"]["scoreLead"]
root_winrate = self.analysis["root"]["winrate"]
move_dicts = list(self.analysis["moves"].values()) # prevent incoming analysis from causing crash
top_move = [d for d in move_dicts if d["order"] == 0]
top_score_lead = top_move[0]["scoreLead"] if top_move else root_score
return sorted(
[
{
"pointsLost": self.player_sign(self.next_player) * (root_score - d["scoreLead"]),
"relativePointsLost": self.player_sign(self.next_player) * (top_score_lead - d["scoreLead"]),
"winrateLost": self.player_sign(self.next_player) * (root_winrate - d["winrate"]),
**d,
}
for d in move_dicts
],
key=lambda d: (d["order"], d["pointsLost"]),
)
@property
def policy_ranking(self) -> Optional[List[Tuple[float, Move]]]: # return moves from highest policy value to lowest
if self.policy:
szx, szy = self.board_size
policy_grid = var_to_grid(self.policy, size=(szx, szy))
moves = [(policy_grid[y][x], Move((x, y), player=self.next_player)) for x in range(szx) for y in range(szy)]
moves.append((self.policy[-1], Move(None, player=self.next_player)))
return sorted(moves, key=lambda mp: -mp[0])
|
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#
from abc import ABC, abstractmethod
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional
from urllib.parse import parse_qsl, urlparse
import pendulum
import requests
from airbyte_cdk.models import SyncMode
from airbyte_cdk.sources.streams import IncrementalMixin
from airbyte_cdk.sources.streams.http import HttpStream
from airbyte_cdk.sources.utils.transform import TransformConfig, TypeTransformer
TWILIO_API_URL_BASE = "https://api.twilio.com"
TWILIO_API_URL_BASE_VERSIONED = f"{TWILIO_API_URL_BASE}/2010-04-01/"
TWILIO_MONITOR_URL_BASE = "https://monitor.twilio.com/v1/"
class TwilioStream(HttpStream, ABC):
url_base = TWILIO_API_URL_BASE
primary_key = "sid"
page_size = 1000
transformer: TypeTransformer = TypeTransformer(TransformConfig.DefaultSchemaNormalization | TransformConfig.CustomSchemaNormalization)
def __init__(self, **kwargs):
super().__init__(**kwargs)
@property
def data_field(self):
return self.name
@property
def changeable_fields(self):
"""
:return list of changeable fields that should be removed from the records
"""
return []
def path(self, **kwargs):
return f"{self.name.title()}.json"
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
stream_data = response.json()
next_page_uri = stream_data.get("next_page_uri")
if next_page_uri:
next_url = urlparse(next_page_uri)
next_page_params = dict(parse_qsl(next_url.query))
return next_page_params
def parse_response(self, response: requests.Response, stream_state: Mapping[str, Any], **kwargs) -> Iterable[Mapping]:
"""
:return an iterable containing each record in the response
"""
records = response.json().get(self.data_field, [])
if self.changeable_fields:
for record in records:
for field in self.changeable_fields:
record.pop(field, None)
yield record
yield from records
def backoff_time(self, response: requests.Response) -> Optional[float]:
"""This method is called if we run into the rate limit.
Twilio puts the retry time in the `Retry-After` response header so we
we return that value. If the response is anything other than a 429 (e.g: 5XX)
fall back on default retry behavior.
Rate Limits Docs: https://support.twilio.com/hc/en-us/articles/360032845014-Verify-V2-Rate-Limiting"""
backoff_time = response.headers.get("Retry-After")
if backoff_time is not None:
return float(backoff_time)
def request_params(
self, stream_state: Mapping[str, Any], next_page_token: Mapping[str, Any] = None, **kwargs
) -> MutableMapping[str, Any]:
params = super().request_params(stream_state=stream_state, next_page_token=next_page_token, **kwargs)
params["PageSize"] = self.page_size
if next_page_token:
params.update(**next_page_token)
return params
@transformer.registerCustomTransform
def custom_transform_function(original_value: Any, field_schema: Mapping[str, Any]) -> Any:
if original_value and field_schema.get("format") == "date-time":
try:
return pendulum.from_format(original_value, "ddd, D MMM YYYY HH:mm:ss ZZ").in_timezone("UTC").to_iso8601_string()
except ValueError:
# Twilio API returns datetime in two formats:
# - RFC2822, like "Fri, 11 Dec 2020 04:28:40 +0000";
# - ISO8601, like "2020-12-11T04:29:09Z".
# If `ValueError` exception was raised this means that datetime was already in ISO8601 format and there
# is no need in transforming anything.
pass
return original_value
class IncrementalTwilioStream(TwilioStream, IncrementalMixin):
time_filter_template = "YYYY-MM-DD HH:mm:ss[Z]"
def __init__(self, start_date: str = None, lookback_window: int = 0, **kwargs):
super().__init__(**kwargs)
self._start_date = start_date if start_date is not None else "1970-01-01T00:00:00Z"
self._lookback_window = lookback_window
self._cursor_value = None
@property
@abstractmethod
def incremental_filter_field(self) -> str:
"""
return: date filter query parameter name
"""
@property
def state(self) -> Mapping[str, Any]:
if self._cursor_value:
return {
self.cursor_field: self._cursor_value,
}
return {}
@state.setter
def state(self, value: Mapping[str, Any]):
if self._lookback_window and value.get(self.cursor_field):
new_start_date = (
pendulum.parse(value[self.cursor_field]) - pendulum.duration(minutes=self._lookback_window)
).to_iso8601_string()
if new_start_date > self._start_date:
value[self.cursor_field] = new_start_date
self._cursor_value = value.get(self.cursor_field)
def request_params(
self, stream_state: Mapping[str, Any], next_page_token: Mapping[str, Any] = None, **kwargs
) -> MutableMapping[str, Any]:
params = super().request_params(stream_state=stream_state, next_page_token=next_page_token, **kwargs)
start_date = self.state.get(self.cursor_field, self._start_date)
params[self.incremental_filter_field] = pendulum.parse(start_date).format(self.time_filter_template)
return params
def read_records(
self,
sync_mode: SyncMode,
cursor_field: List[str] = None,
stream_slice: Mapping[str, Any] = None,
stream_state: Mapping[str, Any] = None,
) -> Iterable[Mapping[str, Any]]:
unsorted_records = []
for record in super().read_records(sync_mode, cursor_field, stream_slice, stream_state):
record[self.cursor_field] = pendulum.parse(record[self.cursor_field], strict=False).to_iso8601_string()
unsorted_records.append(record)
sorted_records = sorted(unsorted_records, key=lambda x: x[self.cursor_field])
for record in sorted_records:
if record[self.cursor_field] >= self.state.get(self.cursor_field, self._start_date):
self._cursor_value = record[self.cursor_field]
yield record
class TwilioNestedStream(TwilioStream):
"""
Basic class for the streams that are dependant on the results of another stream output (parent-child relations).
Parent class read is always full refresh, even if it supports incremental read.
"""
media_exist_validation = {}
def path(self, stream_slice: Mapping[str, Any], **kwargs):
return stream_slice["subresource_uri"]
@property
def subresource_uri_key(self):
return self.data_field
@property
@abstractmethod
def parent_stream(self) -> TwilioStream:
"""
:return: parent stream class
"""
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, any]]]:
stream_instance = self.parent_stream(authenticator=self.authenticator)
stream_slices = stream_instance.stream_slices(sync_mode=SyncMode.full_refresh, cursor_field=stream_instance.cursor_field)
for stream_slice in stream_slices:
for item in stream_instance.read_records(
sync_mode=SyncMode.full_refresh, stream_slice=stream_slice, cursor_field=stream_instance.cursor_field
):
if item.get("subresource_uris", {}).get(self.subresource_uri_key):
validated = True
for key, value in self.media_exist_validation.items():
validated = item.get(key) and item.get(key) != value
if not validated:
break
if validated:
yield {"subresource_uri": item["subresource_uris"][self.subresource_uri_key]}
class Accounts(TwilioStream):
"""https://www.twilio.com/docs/usage/api/account#read-multiple-account-resources"""
url_base = TWILIO_API_URL_BASE_VERSIONED
class Addresses(TwilioNestedStream):
"""https://www.twilio.com/docs/usage/api/address#read-multiple-address-resources"""
parent_stream = Accounts
class DependentPhoneNumbers(TwilioNestedStream):
"""https://www.twilio.com/docs/usage/api/address?code-sample=code-list-dependent-pns-subresources&code-language=curl&code-sdk-version=json#instance-subresources"""
parent_stream = Addresses
url_base = TWILIO_API_URL_BASE_VERSIONED
def path(self, stream_slice: Mapping[str, Any], **kwargs):
return f"Accounts/{stream_slice["account_sid"]}/Addresses/{stream_slice["sid"]}/DependentPhoneNumbers.json"
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, any]]]:
stream_instance = self.parent_stream(authenticator=self.authenticator)
stream_slices = stream_instance.stream_slices(sync_mode=SyncMode.full_refresh, cursor_field=stream_instance.cursor_field)
for stream_slice in stream_slices:
for item in stream_instance.read_records(
sync_mode=SyncMode.full_refresh, stream_slice=stream_slice, cursor_field=stream_instance.cursor_field
):
yield {"sid": item["sid"], "account_sid": item["account_sid"]}
class Applications(TwilioNestedStream):
"""https://www.twilio.com/docs/usage/api/applications#read-multiple-application-resources"""
parent_stream = Accounts
class AvailablePhoneNumberCountries(TwilioNestedStream):
"""
https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#read-a-list-of-countries
List of available phone number countries, as well as local, mobile and toll free numbers
may be different on each request, so could not pass the full refresh tests.
"""
parent_stream = Accounts
data_field = "countries"
subresource_uri_key = "available_phone_numbers"
primary_key = None
class AvailablePhoneNumbersLocal(TwilioNestedStream):
"""https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource#read-multiple-availablephonenumberlocal-resources"""
parent_stream = AvailablePhoneNumberCountries
data_field = "available_phone_numbers"
subresource_uri_key = "local"
primary_key = None
class AvailablePhoneNumbersMobile(TwilioNestedStream):
"""https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-mobile-resource#read-multiple-availablephonenumbermobile-resources"""
parent_stream = AvailablePhoneNumberCountries
data_field = "available_phone_numbers"
subresource_uri_key = "mobile"
primary_key = None
class AvailablePhoneNumbersTollFree(TwilioNestedStream):
"""https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-tollfree-resource#read-multiple-availablephonenumbertollfree-resources"""
parent_stream = AvailablePhoneNumberCountries
data_field = "available_phone_numbers"
subresource_uri_key = "toll_free"
primary_key = None
class IncomingPhoneNumbers(TwilioNestedStream):
"""https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource#read-multiple-incomingphonenumber-resources"""
parent_stream = Accounts
class Keys(TwilioNestedStream):
"""https://www.twilio.com/docs/usage/api/keys#read-a-key-resource"""
parent_stream = Accounts
class Calls(TwilioNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/voice/api/call-resource#create-a-call-resource"""
parent_stream = Accounts
incremental_filter_field = "EndTime>"
cursor_field = "end_time"
time_filter_template = "YYYY-MM-DD"
class Conferences(TwilioNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/voice/api/conference-resource#read-multiple-conference-resources"""
parent_stream = Accounts
incremental_filter_field = "DateCreated>"
cursor_field = "date_created"
time_filter_template = "YYYY-MM-DD"
class ConferenceParticipants(TwilioNestedStream):
"""
https://www.twilio.com/docs/voice/api/conference-participant-resource#read-multiple-participant-resources
This streams has records only if there are active conference participants (participants,
which are on conference call at the moment request is made).
"""
primary_key = ["account_sid", "conference_sid"]
parent_stream = Conferences
data_field = "participants"
class OutgoingCallerIds(TwilioNestedStream):
"""https://www.twilio.com/docs/voice/api/outgoing-caller-ids#outgoingcallerids-list-resource"""
parent_stream = Accounts
class Recordings(TwilioNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/voice/api/recording#read-multiple-recording-resources"""
parent_stream = Accounts
incremental_filter_field = "DateCreated>"
cursor_field = "date_created"
class Transcriptions(TwilioNestedStream):
"""https://www.twilio.com/docs/voice/api/recording-transcription?code-sample=code-read-list-all-transcriptions&code-language=curl&code-sdk-version=json#read-multiple-transcription-resources"""
parent_stream = Accounts
class Queues(TwilioNestedStream):
"""https://www.twilio.com/docs/voice/api/queue-resource#read-multiple-queue-resources"""
parent_stream = Accounts
class Messages(TwilioNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/sms/api/message-resource#read-multiple-message-resources"""
parent_stream = Accounts
incremental_filter_field = "DateSent>"
cursor_field = "date_sent"
class MessageMedia(TwilioNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/sms/api/media-resource#read-multiple-media-resources"""
parent_stream = Messages
data_field = "media_list"
subresource_uri_key = "media"
media_exist_validation = {"num_media": "0"}
incremental_filter_field = "DateCreated>"
cursor_field = "date_created"
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, any]]]:
stream_instance = self.parent_stream(
authenticator=self.authenticator, start_date=self._start_date, lookback_window=self._lookback_window
)
stream_slices = stream_instance.stream_slices(sync_mode=SyncMode.full_refresh, cursor_field=stream_instance.cursor_field)
for stream_slice in stream_slices:
for item in stream_instance.read_records(
sync_mode=SyncMode.full_refresh, stream_slice=stream_slice, cursor_field=stream_instance.cursor_field
):
if item.get("subresource_uris", {}).get(self.subresource_uri_key):
validated = True
for key, value in self.media_exist_validation.items():
validated = item.get(key) and item.get(key) != value
if not validated:
break
if validated:
yield {"subresource_uri": item["subresource_uris"][self.subresource_uri_key]}
class UsageNestedStream(TwilioNestedStream):
url_base = TWILIO_API_URL_BASE_VERSIONED
@property
@abstractmethod
def path_name(self) -> str:
"""
return: name of the end of the usage paths
"""
def path(self, stream_slice: Mapping[str, Any], **kwargs):
return f"Accounts/{stream_slice["account_sid"]}/Usage/{self.path_name}.json"
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, any]]]:
stream_instance = self.parent_stream(authenticator=self.authenticator)
stream_slices = stream_instance.stream_slices(sync_mode=SyncMode.full_refresh, cursor_field=stream_instance.cursor_field)
for stream_slice in stream_slices:
for item in stream_instance.read_records(
sync_mode=SyncMode.full_refresh, stream_slice=stream_slice, cursor_field=stream_instance.cursor_field
):
yield {"account_sid": item["sid"]}
class UsageRecords(UsageNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/usage/api/usage-record#read-multiple-usagerecord-resources"""
parent_stream = Accounts
incremental_filter_field = "StartDate"
cursor_field = "start_date"
time_filter_template = "YYYY-MM-DD"
path_name = "Records"
primary_key = [["account_sid"], ["category"]]
changeable_fields = ["as_of"]
class UsageTriggers(UsageNestedStream):
"""https://www.twilio.com/docs/usage/api/usage-trigger#read-multiple-usagetrigger-resources"""
parent_stream = Accounts
subresource_uri_key = "triggers"
path_name = "Triggers"
class Alerts(IncrementalTwilioStream):
"""https://www.twilio.com/docs/usage/monitor-alert#read-multiple-alert-resources"""
url_base = TWILIO_MONITOR_URL_BASE
incremental_filter_field = "StartDate"
cursor_field = "date_generated"
def path(self, **kwargs):
return self.name.title()
| #
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#
from abc import ABC, abstractmethod
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional
from urllib.parse import parse_qsl, urlparse
import pendulum
import requests
from airbyte_cdk.models import SyncMode
from airbyte_cdk.sources.streams import IncrementalMixin
from airbyte_cdk.sources.streams.http import HttpStream
from airbyte_cdk.sources.utils.transform import TransformConfig, TypeTransformer
TWILIO_API_URL_BASE = "https://api.twilio.com"
TWILIO_API_URL_BASE_VERSIONED = f"{TWILIO_API_URL_BASE}/2010-04-01/"
TWILIO_MONITOR_URL_BASE = "https://monitor.twilio.com/v1/"
class TwilioStream(HttpStream, ABC):
url_base = TWILIO_API_URL_BASE
primary_key = "sid"
page_size = 1000
transformer: TypeTransformer = TypeTransformer(TransformConfig.DefaultSchemaNormalization | TransformConfig.CustomSchemaNormalization)
def __init__(self, **kwargs):
super().__init__(**kwargs)
@property
def data_field(self):
return self.name
@property
def changeable_fields(self):
"""
:return list of changeable fields that should be removed from the records
"""
return []
def path(self, **kwargs):
return f"{self.name.title()}.json"
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
stream_data = response.json()
next_page_uri = stream_data.get("next_page_uri")
if next_page_uri:
next_url = urlparse(next_page_uri)
next_page_params = dict(parse_qsl(next_url.query))
return next_page_params
def parse_response(self, response: requests.Response, stream_state: Mapping[str, Any], **kwargs) -> Iterable[Mapping]:
"""
:return an iterable containing each record in the response
"""
records = response.json().get(self.data_field, [])
if self.changeable_fields:
for record in records:
for field in self.changeable_fields:
record.pop(field, None)
yield record
yield from records
def backoff_time(self, response: requests.Response) -> Optional[float]:
"""This method is called if we run into the rate limit.
Twilio puts the retry time in the `Retry-After` response header so we
we return that value. If the response is anything other than a 429 (e.g: 5XX)
fall back on default retry behavior.
Rate Limits Docs: https://support.twilio.com/hc/en-us/articles/360032845014-Verify-V2-Rate-Limiting"""
backoff_time = response.headers.get("Retry-After")
if backoff_time is not None:
return float(backoff_time)
def request_params(
self, stream_state: Mapping[str, Any], next_page_token: Mapping[str, Any] = None, **kwargs
) -> MutableMapping[str, Any]:
params = super().request_params(stream_state=stream_state, next_page_token=next_page_token, **kwargs)
params["PageSize"] = self.page_size
if next_page_token:
params.update(**next_page_token)
return params
@transformer.registerCustomTransform
def custom_transform_function(original_value: Any, field_schema: Mapping[str, Any]) -> Any:
if original_value and field_schema.get("format") == "date-time":
try:
return pendulum.from_format(original_value, "ddd, D MMM YYYY HH:mm:ss ZZ").in_timezone("UTC").to_iso8601_string()
except ValueError:
# Twilio API returns datetime in two formats:
# - RFC2822, like "Fri, 11 Dec 2020 04:28:40 +0000";
# - ISO8601, like "2020-12-11T04:29:09Z".
# If `ValueError` exception was raised this means that datetime was already in ISO8601 format and there
# is no need in transforming anything.
pass
return original_value
class IncrementalTwilioStream(TwilioStream, IncrementalMixin):
time_filter_template = "YYYY-MM-DD HH:mm:ss[Z]"
def __init__(self, start_date: str = None, lookback_window: int = 0, **kwargs):
super().__init__(**kwargs)
self._start_date = start_date if start_date is not None else "1970-01-01T00:00:00Z"
self._lookback_window = lookback_window
self._cursor_value = None
@property
@abstractmethod
def incremental_filter_field(self) -> str:
"""
return: date filter query parameter name
"""
@property
def state(self) -> Mapping[str, Any]:
if self._cursor_value:
return {
self.cursor_field: self._cursor_value,
}
return {}
@state.setter
def state(self, value: Mapping[str, Any]):
if self._lookback_window and value.get(self.cursor_field):
new_start_date = (
pendulum.parse(value[self.cursor_field]) - pendulum.duration(minutes=self._lookback_window)
).to_iso8601_string()
if new_start_date > self._start_date:
value[self.cursor_field] = new_start_date
self._cursor_value = value.get(self.cursor_field)
def request_params(
self, stream_state: Mapping[str, Any], next_page_token: Mapping[str, Any] = None, **kwargs
) -> MutableMapping[str, Any]:
params = super().request_params(stream_state=stream_state, next_page_token=next_page_token, **kwargs)
start_date = self.state.get(self.cursor_field, self._start_date)
params[self.incremental_filter_field] = pendulum.parse(start_date).format(self.time_filter_template)
return params
def read_records(
self,
sync_mode: SyncMode,
cursor_field: List[str] = None,
stream_slice: Mapping[str, Any] = None,
stream_state: Mapping[str, Any] = None,
) -> Iterable[Mapping[str, Any]]:
unsorted_records = []
for record in super().read_records(sync_mode, cursor_field, stream_slice, stream_state):
record[self.cursor_field] = pendulum.parse(record[self.cursor_field], strict=False).to_iso8601_string()
unsorted_records.append(record)
sorted_records = sorted(unsorted_records, key=lambda x: x[self.cursor_field])
for record in sorted_records:
if record[self.cursor_field] >= self.state.get(self.cursor_field, self._start_date):
self._cursor_value = record[self.cursor_field]
yield record
class TwilioNestedStream(TwilioStream):
"""
Basic class for the streams that are dependant on the results of another stream output (parent-child relations).
Parent class read is always full refresh, even if it supports incremental read.
"""
media_exist_validation = {}
def path(self, stream_slice: Mapping[str, Any], **kwargs):
return stream_slice["subresource_uri"]
@property
def subresource_uri_key(self):
return self.data_field
@property
@abstractmethod
def parent_stream(self) -> TwilioStream:
"""
:return: parent stream class
"""
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, any]]]:
stream_instance = self.parent_stream(authenticator=self.authenticator)
stream_slices = stream_instance.stream_slices(sync_mode=SyncMode.full_refresh, cursor_field=stream_instance.cursor_field)
for stream_slice in stream_slices:
for item in stream_instance.read_records(
sync_mode=SyncMode.full_refresh, stream_slice=stream_slice, cursor_field=stream_instance.cursor_field
):
if item.get("subresource_uris", {}).get(self.subresource_uri_key):
validated = True
for key, value in self.media_exist_validation.items():
validated = item.get(key) and item.get(key) != value
if not validated:
break
if validated:
yield {"subresource_uri": item["subresource_uris"][self.subresource_uri_key]}
class Accounts(TwilioStream):
"""https://www.twilio.com/docs/usage/api/account#read-multiple-account-resources"""
url_base = TWILIO_API_URL_BASE_VERSIONED
class Addresses(TwilioNestedStream):
"""https://www.twilio.com/docs/usage/api/address#read-multiple-address-resources"""
parent_stream = Accounts
class DependentPhoneNumbers(TwilioNestedStream):
"""https://www.twilio.com/docs/usage/api/address?code-sample=code-list-dependent-pns-subresources&code-language=curl&code-sdk-version=json#instance-subresources"""
parent_stream = Addresses
url_base = TWILIO_API_URL_BASE_VERSIONED
def path(self, stream_slice: Mapping[str, Any], **kwargs):
return f"Accounts/{stream_slice['account_sid']}/Addresses/{stream_slice['sid']}/DependentPhoneNumbers.json"
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, any]]]:
stream_instance = self.parent_stream(authenticator=self.authenticator)
stream_slices = stream_instance.stream_slices(sync_mode=SyncMode.full_refresh, cursor_field=stream_instance.cursor_field)
for stream_slice in stream_slices:
for item in stream_instance.read_records(
sync_mode=SyncMode.full_refresh, stream_slice=stream_slice, cursor_field=stream_instance.cursor_field
):
yield {"sid": item["sid"], "account_sid": item["account_sid"]}
class Applications(TwilioNestedStream):
"""https://www.twilio.com/docs/usage/api/applications#read-multiple-application-resources"""
parent_stream = Accounts
class AvailablePhoneNumberCountries(TwilioNestedStream):
"""
https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#read-a-list-of-countries
List of available phone number countries, as well as local, mobile and toll free numbers
may be different on each request, so could not pass the full refresh tests.
"""
parent_stream = Accounts
data_field = "countries"
subresource_uri_key = "available_phone_numbers"
primary_key = None
class AvailablePhoneNumbersLocal(TwilioNestedStream):
"""https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource#read-multiple-availablephonenumberlocal-resources"""
parent_stream = AvailablePhoneNumberCountries
data_field = "available_phone_numbers"
subresource_uri_key = "local"
primary_key = None
class AvailablePhoneNumbersMobile(TwilioNestedStream):
"""https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-mobile-resource#read-multiple-availablephonenumbermobile-resources"""
parent_stream = AvailablePhoneNumberCountries
data_field = "available_phone_numbers"
subresource_uri_key = "mobile"
primary_key = None
class AvailablePhoneNumbersTollFree(TwilioNestedStream):
"""https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-tollfree-resource#read-multiple-availablephonenumbertollfree-resources"""
parent_stream = AvailablePhoneNumberCountries
data_field = "available_phone_numbers"
subresource_uri_key = "toll_free"
primary_key = None
class IncomingPhoneNumbers(TwilioNestedStream):
"""https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource#read-multiple-incomingphonenumber-resources"""
parent_stream = Accounts
class Keys(TwilioNestedStream):
"""https://www.twilio.com/docs/usage/api/keys#read-a-key-resource"""
parent_stream = Accounts
class Calls(TwilioNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/voice/api/call-resource#create-a-call-resource"""
parent_stream = Accounts
incremental_filter_field = "EndTime>"
cursor_field = "end_time"
time_filter_template = "YYYY-MM-DD"
class Conferences(TwilioNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/voice/api/conference-resource#read-multiple-conference-resources"""
parent_stream = Accounts
incremental_filter_field = "DateCreated>"
cursor_field = "date_created"
time_filter_template = "YYYY-MM-DD"
class ConferenceParticipants(TwilioNestedStream):
"""
https://www.twilio.com/docs/voice/api/conference-participant-resource#read-multiple-participant-resources
This streams has records only if there are active conference participants (participants,
which are on conference call at the moment request is made).
"""
primary_key = ["account_sid", "conference_sid"]
parent_stream = Conferences
data_field = "participants"
class OutgoingCallerIds(TwilioNestedStream):
"""https://www.twilio.com/docs/voice/api/outgoing-caller-ids#outgoingcallerids-list-resource"""
parent_stream = Accounts
class Recordings(TwilioNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/voice/api/recording#read-multiple-recording-resources"""
parent_stream = Accounts
incremental_filter_field = "DateCreated>"
cursor_field = "date_created"
class Transcriptions(TwilioNestedStream):
"""https://www.twilio.com/docs/voice/api/recording-transcription?code-sample=code-read-list-all-transcriptions&code-language=curl&code-sdk-version=json#read-multiple-transcription-resources"""
parent_stream = Accounts
class Queues(TwilioNestedStream):
"""https://www.twilio.com/docs/voice/api/queue-resource#read-multiple-queue-resources"""
parent_stream = Accounts
class Messages(TwilioNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/sms/api/message-resource#read-multiple-message-resources"""
parent_stream = Accounts
incremental_filter_field = "DateSent>"
cursor_field = "date_sent"
class MessageMedia(TwilioNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/sms/api/media-resource#read-multiple-media-resources"""
parent_stream = Messages
data_field = "media_list"
subresource_uri_key = "media"
media_exist_validation = {"num_media": "0"}
incremental_filter_field = "DateCreated>"
cursor_field = "date_created"
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, any]]]:
stream_instance = self.parent_stream(
authenticator=self.authenticator, start_date=self._start_date, lookback_window=self._lookback_window
)
stream_slices = stream_instance.stream_slices(sync_mode=SyncMode.full_refresh, cursor_field=stream_instance.cursor_field)
for stream_slice in stream_slices:
for item in stream_instance.read_records(
sync_mode=SyncMode.full_refresh, stream_slice=stream_slice, cursor_field=stream_instance.cursor_field
):
if item.get("subresource_uris", {}).get(self.subresource_uri_key):
validated = True
for key, value in self.media_exist_validation.items():
validated = item.get(key) and item.get(key) != value
if not validated:
break
if validated:
yield {"subresource_uri": item["subresource_uris"][self.subresource_uri_key]}
class UsageNestedStream(TwilioNestedStream):
url_base = TWILIO_API_URL_BASE_VERSIONED
@property
@abstractmethod
def path_name(self) -> str:
"""
return: name of the end of the usage paths
"""
def path(self, stream_slice: Mapping[str, Any], **kwargs):
return f"Accounts/{stream_slice['account_sid']}/Usage/{self.path_name}.json"
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, any]]]:
stream_instance = self.parent_stream(authenticator=self.authenticator)
stream_slices = stream_instance.stream_slices(sync_mode=SyncMode.full_refresh, cursor_field=stream_instance.cursor_field)
for stream_slice in stream_slices:
for item in stream_instance.read_records(
sync_mode=SyncMode.full_refresh, stream_slice=stream_slice, cursor_field=stream_instance.cursor_field
):
yield {"account_sid": item["sid"]}
class UsageRecords(UsageNestedStream, IncrementalTwilioStream):
"""https://www.twilio.com/docs/usage/api/usage-record#read-multiple-usagerecord-resources"""
parent_stream = Accounts
incremental_filter_field = "StartDate"
cursor_field = "start_date"
time_filter_template = "YYYY-MM-DD"
path_name = "Records"
primary_key = [["account_sid"], ["category"]]
changeable_fields = ["as_of"]
class UsageTriggers(UsageNestedStream):
"""https://www.twilio.com/docs/usage/api/usage-trigger#read-multiple-usagetrigger-resources"""
parent_stream = Accounts
subresource_uri_key = "triggers"
path_name = "Triggers"
class Alerts(IncrementalTwilioStream):
"""https://www.twilio.com/docs/usage/monitor-alert#read-multiple-alert-resources"""
url_base = TWILIO_MONITOR_URL_BASE
incremental_filter_field = "StartDate"
cursor_field = "date_generated"
def path(self, **kwargs):
return self.name.title()
|
from ProgressManager.RunTable.Models.RunProgress import RunProgress
from ConfigValidator.CustomErrors.ExperimentOutputErrors import ExperimentOutputFileDoesNotExistError
from ProgressManager.Output.OutputProcedure import OutputProcedure as output
from ProgressManager.Output.BaseOutputManager import BaseOutputManager
from tempfile import NamedTemporaryFile
import shutil
import csv
from typing import Dict, List
class CSVOutputManager(BaseOutputManager):
def read_run_table_from_csv(self) -> List[Dict]:
read_run_table = []
try:
with open(self._experiment_path + '/run_table.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# if value was integer, stored as string by CSV writer, then convert back to integer.
for key, value in row.items():
if value.isnumeric():
row[key] = int(value)
if key == '__done':
row[key] = RunProgress[value]
read_run_table.append(row)
return read_run_table
except:
raise ExperimentOutputFileDoesNotExistError
def write_run_table_to_csv(self, run_table: List[Dict]):
try:
with open(self._experiment_path + '/run_table.csv', 'w', newline='') as myfile:
writer = csv.DictWriter(myfile, fieldnames=list(run_table[0].keys()))
writer.writeheader()
for data in run_table:
data['__done'] = data['__done'].name
writer.writerow(data)
except:
raise ExperimentOutputFileDoesNotExistError
# TODO: Nice To have
def shuffle_experiment_run_table(self):
pass
def update_row_data(self, updated_row: dict):
tempfile = NamedTemporaryFile(mode='w', delete=False)
with open(self._experiment_path + '/run_table.csv', 'r') as csvfile, tempfile:
reader = csv.DictReader(csvfile, fieldnames=list(updated_row.keys()))
writer = csv.DictWriter(tempfile, fieldnames=list(updated_row.keys()))
for row in reader:
if row['__run_id'] == updated_row['__run_id']:
# When the row is updated, it is an ENUM value again.
# Write as human-readable: enum_value.name
updated_row['__done'] = updated_row['__done'].name
writer.writerow(updated_row)
else:
writer.writerow(row)
shutil.move(tempfile.name, self._experiment_path + '/run_table.csv')
output.console_log_WARNING(f"CSVManager: Updated row {updated_row["__run_id"]}")
# with open(self.experiment_path + '/run_table.csv', 'w', newline='') as myfile:
# wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
# wr.writerow(updated_row)
# for row in reader:
# if name == row['name']:
# row['name'] = input("enter new name for {}".format(name))
# # write the row either way
# writer.writerow({'name': row['name'], 'number': row['number'], 'address': row['address']}) | from ProgressManager.RunTable.Models.RunProgress import RunProgress
from ConfigValidator.CustomErrors.ExperimentOutputErrors import ExperimentOutputFileDoesNotExistError
from ProgressManager.Output.OutputProcedure import OutputProcedure as output
from ProgressManager.Output.BaseOutputManager import BaseOutputManager
from tempfile import NamedTemporaryFile
import shutil
import csv
from typing import Dict, List
class CSVOutputManager(BaseOutputManager):
def read_run_table_from_csv(self) -> List[Dict]:
read_run_table = []
try:
with open(self._experiment_path + '/run_table.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# if value was integer, stored as string by CSV writer, then convert back to integer.
for key, value in row.items():
if value.isnumeric():
row[key] = int(value)
if key == '__done':
row[key] = RunProgress[value]
read_run_table.append(row)
return read_run_table
except:
raise ExperimentOutputFileDoesNotExistError
def write_run_table_to_csv(self, run_table: List[Dict]):
try:
with open(self._experiment_path + '/run_table.csv', 'w', newline='') as myfile:
writer = csv.DictWriter(myfile, fieldnames=list(run_table[0].keys()))
writer.writeheader()
for data in run_table:
data['__done'] = data['__done'].name
writer.writerow(data)
except:
raise ExperimentOutputFileDoesNotExistError
# TODO: Nice To have
def shuffle_experiment_run_table(self):
pass
def update_row_data(self, updated_row: dict):
tempfile = NamedTemporaryFile(mode='w', delete=False)
with open(self._experiment_path + '/run_table.csv', 'r') as csvfile, tempfile:
reader = csv.DictReader(csvfile, fieldnames=list(updated_row.keys()))
writer = csv.DictWriter(tempfile, fieldnames=list(updated_row.keys()))
for row in reader:
if row['__run_id'] == updated_row['__run_id']:
# When the row is updated, it is an ENUM value again.
# Write as human-readable: enum_value.name
updated_row['__done'] = updated_row['__done'].name
writer.writerow(updated_row)
else:
writer.writerow(row)
shutil.move(tempfile.name, self._experiment_path + '/run_table.csv')
output.console_log_WARNING(f"CSVManager: Updated row {updated_row['__run_id']}")
# with open(self.experiment_path + '/run_table.csv', 'w', newline='') as myfile:
# wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
# wr.writerow(updated_row)
# for row in reader:
# if name == row['name']:
# row['name'] = input("enter new name for {}".format(name))
# # write the row either way
# writer.writerow({'name': row['name'], 'number': row['number'], 'address': row['address']}) |
#!/usr/bin/python
#
# 2019 Graham R Pugh
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""See docstring for LastRecipeRunChecker class"""
import json
import os.path
from autopkglib import Processor, ProcessorError # pylint: disable=import-error
__all__ = ["LastRecipeRunChecker"]
class LastRecipeRunChecker(Processor):
"""An AutoPkg pre-processor which reads the output from the LastRecipeRunResult processor from
a different AutoPkg recipe, so that they can be used in the foillowing processes."""
input_variables = {
"recipeoverride_identifier": {
"description": "The identifier of the recipe from which the information is required.",
"required": True,
},
"cache_dir": {
"description": "Path to the cache dir.",
"required": False,
"default": "~/Library/AutoPkg/Cache",
},
"info_file": {
"description": ("Name of input file."),
"required": False,
"default": "latest_version.json",
},
}
output_variables = {
"url": {"description": ("the download URL.")},
"version": {"description": ("The current package version.")},
"minimum_os_version": {
"description": ("The minimum OS version compatibility of a package.")
},
"license_key": {"description": ("The outputted value for license_key.")},
"pkg_path": {"description": ("the package path.")},
"pkg_name": {"description": ("the package name.")},
"pkg_uploaded": {
"description": ("whether a package was uploaded on the last run or not.")
},
"pkg_metadata_updated": {
"description": (
"whether package metadata was updated on the last run or not."
)
},
"PKG_CATEGORY": {"description": ("The package category.")},
"LAST_RUN_POLICY_NAME": {"description": ("The policy_name.")},
"LAST_RUN_SELFSERVICE_DESCRIPTION": {
"description": ("The self-service description.")
},
}
description = __doc__
def get_latest_recipe_run_info(self, cache_dir, identifier, info_file):
"""get information from the output files of a LastRecipeRunResult processor"""
try:
info_filepath = os.path.join(cache_dir, identifier, info_file)
with open(info_filepath, "r") as fp:
data = json.load(fp)
except (IOError, ValueError):
raise ProcessorError("No package or version information found")
else:
return data
def main(self):
identifier = self.env.get("recipeoverride_identifier")
cache_dir = os.path.expanduser(self.env.get("cache_dir"))
info_file = self.env.get("info_file")
# make sure all the values were obtained from the file
data = self.get_latest_recipe_run_info(cache_dir, identifier, info_file)
self.env["version"] = data.get("version")
self.env["minimum_os_version"] = data.get("minimum_os_version")
self.env["license_key"] = data.get("license_key")
self.env["pkg_name"] = data.get("pkg_name")
self.env["pkg_uploaded"] = data.get("pkg_uploaded")
self.env["pkg_metadata_updated"] = data.get("pkg_metadata_updated")
if not self.env["version"] or not self.env["pkg_name"]:
raise ProcessorError("No package or version information found")
self.env["pkg_path"] = data["pkg_path"]
self.env["url"] = data.get("url")
self.env["PKG_CATEGORY"] = data.get("category")
self.env["LAST_RUN_POLICY_NAME"] = data.get("policy_name")
self.env["LAST_RUN_SELFSERVICE_DESCRIPTION"] = data.get(
"self_service_description"
)
# make sure the package actually exists
if not os.path.exists(self.env["pkg_path"]):
raise ProcessorError(
"Package does not exist: {}".format(self.env["pkg_path"])
)
self.output(f"Package name: {self.env["pkg_name"]}")
self.output(f"Package path: {self.env["pkg_path"]}")
self.output(f"Version: {self.env["version"]}")
self.output(f"Minimum OS version: {self.env["minimum_os_version"]}")
self.output(f"URL: {self.env["url"]}")
self.output(f"Pkg category: {self.env["PKG_CATEGORY"]}")
self.output(f"Policy name: {self.env["LAST_RUN_POLICY_NAME"]}")
self.output(
f"Self Service Description: {self.env["LAST_RUN_SELFSERVICE_DESCRIPTION"]}"
)
self.output(f"License Key: {self.env["license_key"]}")
self.output(f"Package uploaded: {self.env["pkg_uploaded"]}")
self.output(f"Package metadata updated: {self.env["pkg_metadata_updated"]}")
if __name__ == "__main__":
PROCESSOR = LastRecipeRunChecker()
PROCESSOR.execute_shell()
| #!/usr/bin/python
#
# 2019 Graham R Pugh
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""See docstring for LastRecipeRunChecker class"""
import json
import os.path
from autopkglib import Processor, ProcessorError # pylint: disable=import-error
__all__ = ["LastRecipeRunChecker"]
class LastRecipeRunChecker(Processor):
"""An AutoPkg pre-processor which reads the output from the LastRecipeRunResult processor from
a different AutoPkg recipe, so that they can be used in the foillowing processes."""
input_variables = {
"recipeoverride_identifier": {
"description": "The identifier of the recipe from which the information is required.",
"required": True,
},
"cache_dir": {
"description": "Path to the cache dir.",
"required": False,
"default": "~/Library/AutoPkg/Cache",
},
"info_file": {
"description": ("Name of input file."),
"required": False,
"default": "latest_version.json",
},
}
output_variables = {
"url": {"description": ("the download URL.")},
"version": {"description": ("The current package version.")},
"minimum_os_version": {
"description": ("The minimum OS version compatibility of a package.")
},
"license_key": {"description": ("The outputted value for license_key.")},
"pkg_path": {"description": ("the package path.")},
"pkg_name": {"description": ("the package name.")},
"pkg_uploaded": {
"description": ("whether a package was uploaded on the last run or not.")
},
"pkg_metadata_updated": {
"description": (
"whether package metadata was updated on the last run or not."
)
},
"PKG_CATEGORY": {"description": ("The package category.")},
"LAST_RUN_POLICY_NAME": {"description": ("The policy_name.")},
"LAST_RUN_SELFSERVICE_DESCRIPTION": {
"description": ("The self-service description.")
},
}
description = __doc__
def get_latest_recipe_run_info(self, cache_dir, identifier, info_file):
"""get information from the output files of a LastRecipeRunResult processor"""
try:
info_filepath = os.path.join(cache_dir, identifier, info_file)
with open(info_filepath, "r") as fp:
data = json.load(fp)
except (IOError, ValueError):
raise ProcessorError("No package or version information found")
else:
return data
def main(self):
identifier = self.env.get("recipeoverride_identifier")
cache_dir = os.path.expanduser(self.env.get("cache_dir"))
info_file = self.env.get("info_file")
# make sure all the values were obtained from the file
data = self.get_latest_recipe_run_info(cache_dir, identifier, info_file)
self.env["version"] = data.get("version")
self.env["minimum_os_version"] = data.get("minimum_os_version")
self.env["license_key"] = data.get("license_key")
self.env["pkg_name"] = data.get("pkg_name")
self.env["pkg_uploaded"] = data.get("pkg_uploaded")
self.env["pkg_metadata_updated"] = data.get("pkg_metadata_updated")
if not self.env["version"] or not self.env["pkg_name"]:
raise ProcessorError("No package or version information found")
self.env["pkg_path"] = data["pkg_path"]
self.env["url"] = data.get("url")
self.env["PKG_CATEGORY"] = data.get("category")
self.env["LAST_RUN_POLICY_NAME"] = data.get("policy_name")
self.env["LAST_RUN_SELFSERVICE_DESCRIPTION"] = data.get(
"self_service_description"
)
# make sure the package actually exists
if not os.path.exists(self.env["pkg_path"]):
raise ProcessorError(
"Package does not exist: {}".format(self.env["pkg_path"])
)
self.output(f"Package name: {self.env['pkg_name']}")
self.output(f"Package path: {self.env['pkg_path']}")
self.output(f"Version: {self.env['version']}")
self.output(f"Minimum OS version: {self.env['minimum_os_version']}")
self.output(f"URL: {self.env['url']}")
self.output(f"Pkg category: {self.env['PKG_CATEGORY']}")
self.output(f"Policy name: {self.env['LAST_RUN_POLICY_NAME']}")
self.output(
f"Self Service Description: {self.env['LAST_RUN_SELFSERVICE_DESCRIPTION']}"
)
self.output(f"License Key: {self.env['license_key']}")
self.output(f"Package uploaded: {self.env['pkg_uploaded']}")
self.output(f"Package metadata updated: {self.env['pkg_metadata_updated']}")
if __name__ == "__main__":
PROCESSOR = LastRecipeRunChecker()
PROCESSOR.execute_shell()
|
from selenium import webdriver
from time import sleep
import json
import Client
t = Client.get_servers_raw()
if t == None:
print('Failed to get the list of servers')
raise SystemExit
if len(t) == 0:
print('The list of servers is empty')
raise SystemExit
print(f'Added {len(t)} servers to the queue')
with open('res\\GetMembers.js', 'r') as f:
uscan = f.read()
users = set()
total_expected = 0
total = 0
driver = webdriver.Edge('res\\msedgedriver.exe')
driver.get('https://discord.com/login')
print('Login to continue')
while not driver.current_url == 'https://discord.com/channels/@me':
sleep(1)
print('Login successful!')
for srv in t:
print(f'Processing [{srv['id']}] {srv['name']}')
count = Client.get_member_count(srv['id'])
print(f'Expected member count:', count)
total_expected += count
driver.get('https://discord.com/channels/' + srv['id'])
wait = True
while wait:
sleep(0.5)
wait = False
try:
driver.find_element_by_xpath('//div[@aria-label="Members"]')
except:
wait = True
sleep(0.5)
driver.execute_script(uscan)
done = False
while not done:
done = driver.execute_script('return done;')
sleep(1)
tmp = json.loads(driver.execute_script('return JSON.stringify(users);'))
total += len(tmp)
users = users.union(tmp)
print(f'Discovered {len(tmp)} members ~{len(tmp)*100//count}%.\n')
driver.close()
with open('Users.json', 'w') as f:
json.dump(list(users), f)
print(f'Exported {total} users as Users.json')
print(f'Final discovery rate: ~{total*100//total_expected}%') | from selenium import webdriver
from time import sleep
import json
import Client
t = Client.get_servers_raw()
if t == None:
print('Failed to get the list of servers')
raise SystemExit
if len(t) == 0:
print('The list of servers is empty')
raise SystemExit
print(f'Added {len(t)} servers to the queue')
with open('res\\GetMembers.js', 'r') as f:
uscan = f.read()
users = set()
total_expected = 0
total = 0
driver = webdriver.Edge('res\\msedgedriver.exe')
driver.get('https://discord.com/login')
print('Login to continue')
while not driver.current_url == 'https://discord.com/channels/@me':
sleep(1)
print('Login successful!')
for srv in t:
print(f'Processing [{srv["id"]}] {srv["name"]}')
count = Client.get_member_count(srv['id'])
print(f'Expected member count:', count)
total_expected += count
driver.get('https://discord.com/channels/' + srv['id'])
wait = True
while wait:
sleep(0.5)
wait = False
try:
driver.find_element_by_xpath('//div[@aria-label="Members"]')
except:
wait = True
sleep(0.5)
driver.execute_script(uscan)
done = False
while not done:
done = driver.execute_script('return done;')
sleep(1)
tmp = json.loads(driver.execute_script('return JSON.stringify(users);'))
total += len(tmp)
users = users.union(tmp)
print(f'Discovered {len(tmp)} members ~{len(tmp)*100//count}%.\n')
driver.close()
with open('Users.json', 'w') as f:
json.dump(list(users), f)
print(f'Exported {total} users as Users.json')
print(f'Final discovery rate: ~{total*100//total_expected}%') |
import pytest
from os import path as osp
from glob import glob
from shutil import which
from subprocess import Popen, PIPE, TimeoutExpired
import time
RANKS = 1
TEST_PATH = osp.dirname(osp.abspath(__file__))
def get_test_names():
"""Obtain test names by globbing for client_test
Add tests manually if necessary
"""
glob_path = osp.join(TEST_PATH, "build/cpp_unit_tests")
test_names = glob(glob_path)
test_names = [(pytest.param(test,
id=osp.basename(test))) for test in test_names]
print(test_names)
#test_names = [("build/test", "unit_tests")]
return test_names
@pytest.mark.parametrize("test", get_test_names())
def test_unit_cpp_client(test, use_cluster):
cmd = []
cmd.append(test)
print(f"Running test: {osp.basename(test)}")
print(f"Test command {" ".join(cmd)}")
print(f"Using cluster: {use_cluster}")
execute_cmd(cmd)
time.sleep(1)
def execute_cmd(cmd_list):
"""Execute a command """
# spawning the subprocess and connecting to its output
run_path = osp.join(TEST_PATH, "build/")
proc = Popen(
cmd_list, stderr=PIPE, stdout=PIPE, stdin=PIPE, cwd=run_path)
try:
out, err = proc.communicate(timeout=120)
assert(proc.returncode == 0)
if out:
print("OUTPUT:", out.decode("utf-8"))
if err:
print("ERROR:", err.decode("utf-8"))
except UnicodeDecodeError:
output, errs = proc.communicate()
print("ERROR:", errs.decode("utf-8"))
assert(False)
except TimeoutExpired:
proc.kill()
output, errs = proc.communicate()
print("TIMEOUT: test timed out after test timeout limit of 120 seconds")
print("OUTPUT:", output.decode("utf-8"))
print("ERROR:", errs.decode("utf-8"))
assert(False)
except Exception:
proc.kill()
output, errs = proc.communicate()
print("OUTPUT:", output.decode("utf-8"))
print("ERROR:", errs.decode("utf-8"))
assert(False)
| import pytest
from os import path as osp
from glob import glob
from shutil import which
from subprocess import Popen, PIPE, TimeoutExpired
import time
RANKS = 1
TEST_PATH = osp.dirname(osp.abspath(__file__))
def get_test_names():
"""Obtain test names by globbing for client_test
Add tests manually if necessary
"""
glob_path = osp.join(TEST_PATH, "build/cpp_unit_tests")
test_names = glob(glob_path)
test_names = [(pytest.param(test,
id=osp.basename(test))) for test in test_names]
print(test_names)
#test_names = [("build/test", "unit_tests")]
return test_names
@pytest.mark.parametrize("test", get_test_names())
def test_unit_cpp_client(test, use_cluster):
cmd = []
cmd.append(test)
print(f"Running test: {osp.basename(test)}")
print(f"Test command {' '.join(cmd)}")
print(f"Using cluster: {use_cluster}")
execute_cmd(cmd)
time.sleep(1)
def execute_cmd(cmd_list):
"""Execute a command """
# spawning the subprocess and connecting to its output
run_path = osp.join(TEST_PATH, "build/")
proc = Popen(
cmd_list, stderr=PIPE, stdout=PIPE, stdin=PIPE, cwd=run_path)
try:
out, err = proc.communicate(timeout=120)
assert(proc.returncode == 0)
if out:
print("OUTPUT:", out.decode("utf-8"))
if err:
print("ERROR:", err.decode("utf-8"))
except UnicodeDecodeError:
output, errs = proc.communicate()
print("ERROR:", errs.decode("utf-8"))
assert(False)
except TimeoutExpired:
proc.kill()
output, errs = proc.communicate()
print("TIMEOUT: test timed out after test timeout limit of 120 seconds")
print("OUTPUT:", output.decode("utf-8"))
print("ERROR:", errs.decode("utf-8"))
assert(False)
except Exception:
proc.kill()
output, errs = proc.communicate()
print("OUTPUT:", output.decode("utf-8"))
print("ERROR:", errs.decode("utf-8"))
assert(False)
|
# Copyright 2008-2018 pydicom authors. See LICENSE file for details.
"""Define the Dataset and FileDataset classes.
The Dataset class represents the DICOM Dataset while the FileDataset class
adds extra functionality to Dataset when data is read from or written to file.
Overview of DICOM object model
------------------------------
Dataset (dict subclass)
Contains DataElement instances, each of which has a tag, VR, VM and value.
The DataElement value can be:
* A single value, such as a number, string, etc. (i.e. VM = 1)
* A list of numbers, strings, etc. (i.e. VM > 1)
* A Sequence (list subclass), where each item is a Dataset which
contains its own DataElements, and so on in a recursive manner.
"""
import copy
from bisect import bisect_left
import io
from importlib.util import find_spec as have_package
import inspect # for __dir__
from itertools import takewhile
import json
import os
import os.path
import re
from types import TracebackType
from typing import (
TYPE_CHECKING, Optional, Tuple, Union, List, Any, cast, Dict, ValuesView,
Iterator, BinaryIO, AnyStr, Callable, TypeVar, Type, overload,
MutableSequence, MutableMapping, AbstractSet
)
import warnings
import weakref
try:
import numpy
except ImportError:
pass
import pydicom # for dcmwrite
import pydicom.charset
import pydicom.config
from pydicom import jsonrep, config
from pydicom._version import __version_info__
from pydicom.charset import default_encoding, convert_encodings
from pydicom.config import logger
from pydicom.datadict import (
dictionary_VR, tag_for_keyword, keyword_for_tag, repeater_has_keyword
)
from pydicom.dataelem import DataElement, DataElement_from_raw, RawDataElement
from pydicom.encaps import encapsulate, encapsulate_extended
from pydicom.fileutil import path_from_pathlike
from pydicom.pixel_data_handlers.util import (
convert_color_space, reshape_pixel_array, get_image_pixel_ids
)
from pydicom.tag import Tag, BaseTag, tag_in_exception, TagType
from pydicom.uid import (
ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian,
RLELossless, PYDICOM_IMPLEMENTATION_UID, UID
)
from pydicom.waveforms import numpy_handler as wave_handler
class PrivateBlock:
"""Helper class for a private block in the :class:`Dataset`.
.. versionadded:: 1.3
See the DICOM Standard, Part 5,
:dcm:`Section 7.8.1<part05/sect_7.8.html#sect_7.8.1>` - Private Data
Element Tags
Attributes
----------
group : int
The private group where the private block is located as a 32-bit
:class:`int`.
private_creator : str
The private creator string related to the block.
dataset : Dataset
The parent dataset.
block_start : int
The start element of the private block as a 32-bit :class:`int`. Note
that the 2 low order hex digits of the element are always 0.
"""
def __init__(
self,
key: Tuple[int, str],
dataset: "Dataset",
private_creator_element: int
) -> None:
"""Initializes an object corresponding to a private tag block.
Parameters
----------
key : tuple
The private (tag group, creator) as ``(int, str)``. The group
must be an odd number.
dataset : Dataset
The parent :class:`Dataset`.
private_creator_element : int
The element of the private creator tag as a 32-bit :class:`int`.
"""
self.group = key[0]
self.private_creator = key[1]
self.dataset = dataset
self.block_start = private_creator_element << 8
def get_tag(self, element_offset: int) -> BaseTag:
"""Return the private tag ID for the given `element_offset`.
Parameters
----------
element_offset : int
The lower 16 bits (e.g. 2 hex numbers) of the element tag.
Returns
-------
The tag ID defined by the private block location and the
given element offset.
Raises
------
ValueError
If `element_offset` is too large.
"""
if element_offset > 0xff:
raise ValueError('Element offset must be less than 256')
return Tag(self.group, self.block_start + element_offset)
def __contains__(self, element_offset: int) -> bool:
"""Return ``True`` if the tag with given `element_offset` is in
the parent :class:`Dataset`.
"""
return self.get_tag(element_offset) in self.dataset
def __getitem__(self, element_offset: int) -> DataElement:
"""Return the data element in the parent dataset for the given element
offset.
Parameters
----------
element_offset : int
The lower 16 bits (e.g. 2 hex numbers) of the element tag.
Returns
-------
The data element of the tag in the parent dataset defined by the
private block location and the given element offset.
Raises
------
ValueError
If `element_offset` is too large.
KeyError
If no data element exists at that offset.
"""
return self.dataset.__getitem__(self.get_tag(element_offset))
def __delitem__(self, element_offset: int) -> None:
"""Delete the tag with the given `element_offset` from the dataset.
Parameters
----------
element_offset : int
The lower 16 bits (e.g. 2 hex numbers) of the element tag
to be deleted.
Raises
------
ValueError
If `element_offset` is too large.
KeyError
If no data element exists at that offset.
"""
del self.dataset[self.get_tag(element_offset)]
def add_new(self, element_offset: int, VR: str, value: object) -> None:
"""Add a private element to the parent :class:`Dataset`.
Adds the private tag with the given `VR` and `value` to the parent
:class:`Dataset` at the tag ID defined by the private block and the
given `element_offset`.
Parameters
----------
element_offset : int
The lower 16 bits (e.g. 2 hex numbers) of the element tag
to be added.
VR : str
The 2 character DICOM value representation.
value
The value of the data element. See :meth:`Dataset.add_new()`
for a description.
"""
tag = self.get_tag(element_offset)
self.dataset.add_new(tag, VR, value)
self.dataset[tag].private_creator = self.private_creator
def _dict_equal(
a: "Dataset", b: Any, exclude: Optional[List[str]] = None
) -> bool:
"""Common method for Dataset.__eq__ and FileDataset.__eq__
Uses .keys() as needed because Dataset iter return items not keys
`exclude` is used in FileDataset__eq__ ds.__dict__ compare, which
would also compare the wrapped _dict member (entire dataset) again.
"""
return (len(a) == len(b) and
all(key in b for key in a.keys()) and
all(a[key] == b[key] for key in a.keys()
if exclude is None or key not in exclude)
)
_DatasetValue = Union[DataElement, RawDataElement]
_DatasetType = Union["Dataset", MutableMapping[BaseTag, _DatasetValue]]
class Dataset:
"""A DICOM dataset as a mutable mapping of DICOM Data Elements.
Examples
--------
Add an element to the :class:`Dataset` (for elements in the DICOM
dictionary):
>>> ds = Dataset()
>>> ds.PatientName = "CITIZEN^Joan"
>>> ds.add_new(0x00100020, 'LO', '12345')
>>> ds[0x0010, 0x0030] = DataElement(0x00100030, 'DA', '20010101')
Add a sequence element to the :class:`Dataset`
>>> ds.BeamSequence = [Dataset(), Dataset(), Dataset()]
>>> ds.BeamSequence[0].Manufacturer = "Linac, co."
>>> ds.BeamSequence[1].Manufacturer = "Linac and Sons, co."
>>> ds.BeamSequence[2].Manufacturer = "Linac and Daughters, co."
Add private elements to the :class:`Dataset`
>>> block = ds.private_block(0x0041, 'My Creator', create=True)
>>> block.add_new(0x01, 'LO', '12345')
Updating and retrieving element values:
>>> ds.PatientName = "CITIZEN^Joan"
>>> ds.PatientName
'CITIZEN^Joan'
>>> ds.PatientName = "CITIZEN^John"
>>> ds.PatientName
'CITIZEN^John'
Retrieving an element's value from a Sequence:
>>> ds.BeamSequence[0].Manufacturer
'Linac, co.'
>>> ds.BeamSequence[1].Manufacturer
'Linac and Sons, co.'
Accessing the :class:`~pydicom.dataelem.DataElement` items:
>>> elem = ds['PatientName']
>>> elem
(0010, 0010) Patient's Name PN: 'CITIZEN^John'
>>> elem = ds[0x00100010]
>>> elem
(0010, 0010) Patient's Name PN: 'CITIZEN^John'
>>> elem = ds.data_element('PatientName')
>>> elem
(0010, 0010) Patient's Name PN: 'CITIZEN^John'
Accessing a private :class:`~pydicom.dataelem.DataElement`
item:
>>> block = ds.private_block(0x0041, 'My Creator')
>>> elem = block[0x01]
>>> elem
(0041, 1001) Private tag data LO: '12345'
>>> elem.value
'12345'
Alternatively:
>>> ds.get_private_item(0x0041, 0x01, 'My Creator').value
'12345'
Deleting an element from the :class:`Dataset`
>>> del ds.PatientID
>>> del ds.BeamSequence[1].Manufacturer
>>> del ds.BeamSequence[2]
Deleting a private element from the :class:`Dataset`
>>> block = ds.private_block(0x0041, 'My Creator')
>>> if 0x01 in block:
... del block[0x01]
Determining if an element is present in the :class:`Dataset`
>>> 'PatientName' in ds
True
>>> 'PatientID' in ds
False
>>> (0x0010, 0x0030) in ds
True
>>> 'Manufacturer' in ds.BeamSequence[0]
True
Iterating through the top level of a :class:`Dataset` only (excluding
Sequences):
>>> for elem in ds:
... print(elem)
(0010, 0010) Patient's Name PN: 'CITIZEN^John'
Iterating through the entire :class:`Dataset` (including Sequences):
>>> for elem in ds.iterall():
... print(elem)
(0010, 0010) Patient's Name PN: 'CITIZEN^John'
Recursively iterate through a :class:`Dataset` (including Sequences):
>>> def recurse(ds):
... for elem in ds:
... if elem.VR == 'SQ':
... [recurse(item) for item in elem]
... else:
... # Do something useful with each DataElement
Converting the :class:`Dataset` to and from JSON:
>>> ds = Dataset()
>>> ds.PatientName = "Some^Name"
>>> jsonmodel = ds.to_json()
>>> ds2 = Dataset()
>>> ds2.from_json(jsonmodel)
(0010, 0010) Patient's Name PN: 'Some^Name'
Attributes
----------
default_element_format : str
The default formatting for string display.
default_sequence_element_format : str
The default formatting for string display of sequences.
indent_chars : str
For string display, the characters used to indent nested Sequences.
Default is ``" "``.
is_little_endian : bool
Shall be set before writing with ``write_like_original=False``.
The :class:`Dataset` (excluding the pixel data) will be written using
the given endianess.
is_implicit_VR : bool
Shall be set before writing with ``write_like_original=False``.
The :class:`Dataset` will be written using the transfer syntax with
the given VR handling, e.g *Little Endian Implicit VR* if ``True``,
and *Little Endian Explicit VR* or *Big Endian Explicit VR* (depending
on ``Dataset.is_little_endian``) if ``False``.
"""
indent_chars = " "
def __init__(self, *args: _DatasetType, **kwargs: Any) -> None:
"""Create a new :class:`Dataset` instance."""
self._parent_encoding: List[str] = kwargs.get(
'parent_encoding', default_encoding
)
self._dict: MutableMapping[BaseTag, _DatasetValue]
if not args:
self._dict = {}
elif isinstance(args[0], Dataset):
self._dict = args[0]._dict
else:
self._dict = args[0]
self.is_decompressed = False
# the following read_XXX attributes are used internally to store
# the properties of the dataset after read from a file
# set depending on the endianess of the read dataset
self.read_little_endian: Optional[bool] = None
# set depending on the VR handling of the read dataset
self.read_implicit_vr: Optional[bool] = None
# The dataset's original character set encoding
self.read_encoding: Union[None, str, MutableSequence[str]] = None
self.is_little_endian: Optional[bool] = None
self.is_implicit_VR: Optional[bool] = None
# the parent data set, if this dataset is a sequence item
self.parent: "Optional[weakref.ReferenceType[Dataset]]" = None
# known private creator blocks
self._private_blocks: Dict[Tuple[int, str], PrivateBlock] = {}
self._pixel_array: Optional["numpy.ndarray"] = None
self._pixel_id: Dict[str, int] = {}
self.file_meta: FileMetaDataset
def __enter__(self) -> "Dataset":
"""Method invoked on entry to a with statement."""
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType]
) -> Optional[bool]:
"""Method invoked on exit from a with statement."""
# Returning anything other than True will re-raise any exceptions
return None
def add(self, data_element: DataElement) -> None:
"""Add an element to the :class:`Dataset`.
Equivalent to ``ds[data_element.tag] = data_element``
Parameters
----------
data_element : dataelem.DataElement
The :class:`~pydicom.dataelem.DataElement` to add.
"""
self[data_element.tag] = data_element
def add_new(self, tag: TagType, VR: str, value: Any) -> None:
"""Create a new element and add it to the :class:`Dataset`.
Parameters
----------
tag
The DICOM (group, element) tag in any form accepted by
:func:`~pydicom.tag.Tag` such as ``[0x0010, 0x0010]``,
``(0x10, 0x10)``, ``0x00100010``, etc.
VR : str
The 2 character DICOM value representation (see DICOM Standard,
Part 5, :dcm:`Section 6.2<part05/sect_6.2.html>`).
value
The value of the data element. One of the following:
* a single string or number
* a :class:`list` or :class:`tuple` with all strings or all numbers
* a multi-value string with backslash separator
* for a sequence element, an empty :class:`list` or ``list`` of
:class:`Dataset`
"""
data_element = DataElement(tag, VR, value)
# use data_element.tag since DataElement verified it
self._dict[data_element.tag] = data_element
def __array__(self) -> "numpy.ndarray":
"""Support accessing the dataset from a numpy array."""
return numpy.asarray(self._dict)
def data_element(self, name: str) -> Optional[DataElement]:
"""Return the element corresponding to the element keyword `name`.
Parameters
----------
name : str
A DICOM element keyword.
Returns
-------
dataelem.DataElement or None
For the given DICOM element `keyword`, return the corresponding
:class:`~pydicom.dataelem.DataElement` if present, ``None``
otherwise.
"""
tag = tag_for_keyword(name)
# Test against None as (0000,0000) is a possible tag
if tag is not None:
return self[tag]
return None
def __contains__(self, name: TagType) -> bool:
"""Simulate dict.__contains__() to handle DICOM keywords.
Examples
--------
>>> ds = Dataset()
>>> ds.SliceLocation = '2'
>>> 'SliceLocation' in ds
True
Parameters
----------
name : str or int or 2-tuple
The element keyword or tag to search for.
Returns
-------
bool
``True`` if the corresponding element is in the :class:`Dataset`,
``False`` otherwise.
"""
try:
return Tag(name) in self._dict
except Exception as exc:
msg = (
f"Invalid value '{name}' used with the 'in' operator: must be "
"an element tag as a 2-tuple or int, or an element keyword"
)
if isinstance(exc, OverflowError):
msg = (
"Invalid element tag value used with the 'in' operator: "
"tags have a maximum value of (0xFFFF, 0xFFFF)"
)
if config.INVALID_KEY_BEHAVIOR == "WARN":
warnings.warn(msg)
elif config.INVALID_KEY_BEHAVIOR == "RAISE":
raise ValueError(msg) from exc
return False
def decode(self) -> None:
"""Apply character set decoding to the elements in the
:class:`Dataset`.
See DICOM Standard, Part 5,
:dcm:`Section 6.1.1<part05/chapter_6.html#sect_6.1.1>`.
"""
# Find specific character set. 'ISO_IR 6' is default
# May be multi-valued, but let pydicom.charset handle all logic on that
dicom_character_set = self._character_set
# Shortcut to the decode function in pydicom.charset
decode_data_element = pydicom.charset.decode_element
# Callback for walk(), to decode the chr strings if necessary
# This simply calls the pydicom.charset.decode_element function
def decode_callback(ds: "Dataset", data_element: DataElement) -> None:
"""Callback to decode `data_element`."""
if data_element.VR == 'SQ':
for dset in data_element.value:
dset._parent_encoding = dicom_character_set
dset.decode()
else:
decode_data_element(data_element, dicom_character_set)
self.walk(decode_callback, recursive=False)
def copy(self) -> "Dataset":
"""Return a shallow copy of the dataset."""
return copy.copy(self)
def __delattr__(self, name: str) -> None:
"""Intercept requests to delete an attribute by `name`.
Examples
--------
>>> ds = Dataset()
>>> ds.PatientName = 'foo'
>>> ds.some_attribute = True
If `name` is a DICOM keyword - delete the corresponding
:class:`~pydicom.dataelem.DataElement`
>>> del ds.PatientName
>>> 'PatientName' in ds
False
If `name` is another attribute - delete it
>>> del ds.some_attribute
>>> hasattr(ds, 'some_attribute')
False
Parameters
----------
name : str
The keyword for the DICOM element or the class attribute to delete.
"""
# First check if a valid DICOM keyword and if we have that data element
tag = cast(BaseTag, tag_for_keyword(name))
if tag is not None and tag in self._dict:
del self._dict[tag]
# If not a DICOM name in this dataset, check for regular instance name
# can't do delete directly, that will call __delattr__ again
elif name in self.__dict__:
del self.__dict__[name]
# Not found, raise an error in same style as python does
else:
raise AttributeError(name)
def __delitem__(self, key: Union[slice, BaseTag, TagType]) -> None:
"""Intercept requests to delete an attribute by key.
Examples
--------
Indexing using :class:`~pydicom.dataelem.DataElement` tag
>>> ds = Dataset()
>>> ds.CommandGroupLength = 100
>>> ds.PatientName = 'CITIZEN^Jan'
>>> del ds[0x00000000]
>>> ds
(0010, 0010) Patient's Name PN: 'CITIZEN^Jan'
Slicing using :class:`~pydicom.dataelem.DataElement` tag
>>> ds = Dataset()
>>> ds.CommandGroupLength = 100
>>> ds.SOPInstanceUID = '1.2.3'
>>> ds.PatientName = 'CITIZEN^Jan'
>>> del ds[:0x00100000]
>>> ds
(0010, 0010) Patient's Name PN: 'CITIZEN^Jan'
Parameters
----------
key
The key for the attribute to be deleted. If a ``slice`` is used
then the tags matching the slice conditions will be deleted.
"""
# If passed a slice, delete the corresponding DataElements
if isinstance(key, slice):
for tag in self._slice_dataset(key.start, key.stop, key.step):
del self._dict[tag]
# invalidate private blocks in case a private creator is
# deleted - will be re-created on next access
if self._private_blocks and BaseTag(tag).is_private_creator:
self._private_blocks = {}
elif isinstance(key, BaseTag):
del self._dict[key]
if self._private_blocks and key.is_private_creator:
self._private_blocks = {}
else:
# If not a standard tag, than convert to Tag and try again
tag = Tag(key)
del self._dict[tag]
if self._private_blocks and tag.is_private_creator:
self._private_blocks = {}
def __dir__(self) -> List[str]:
"""Give a list of attributes available in the :class:`Dataset`.
List of attributes is used, for example, in auto-completion in editors
or command-line environments.
"""
# Force zip object into a list
meths = set(list(zip(
*inspect.getmembers(self.__class__, inspect.isroutine)))[0])
props = set(list(zip(
*inspect.getmembers(self.__class__, inspect.isdatadescriptor)))[0])
dicom_names = set(self.dir())
alldir = sorted(props | meths | dicom_names)
return alldir
def dir(self, *filters: str) -> List[str]:
"""Return an alphabetical list of element keywords in the
:class:`Dataset`.
Intended mainly for use in interactive Python sessions. Only lists the
element keywords in the current level of the :class:`Dataset` (i.e.
the contents of any sequence elements are ignored).
Parameters
----------
filters : str
Zero or more string arguments to the function. Used for
case-insensitive match to any part of the DICOM keyword.
Returns
-------
list of str
The matching element keywords in the dataset. If no
filters are used then all element keywords are returned.
"""
allnames = [keyword_for_tag(tag) for tag in self._dict.keys()]
# remove blanks - tags without valid names (e.g. private tags)
allnames = [x for x in allnames if x]
# Store found names in a dict, so duplicate names appear only once
matches = {}
for filter_ in filters:
filter_ = filter_.lower()
match = [x for x in allnames if x.lower().find(filter_) != -1]
matches.update({x: 1 for x in match})
if filters:
return sorted(matches.keys())
return sorted(allnames)
def __eq__(self, other: Any) -> bool:
"""Compare `self` and `other` for equality.
Returns
-------
bool
The result if `self` and `other` are the same class
NotImplemented
If `other` is not the same class as `self` then returning
:class:`NotImplemented` delegates the result to
``superclass.__eq__(subclass)``.
"""
# When comparing against self this will be faster
if other is self:
return True
if isinstance(other, self.__class__):
return _dict_equal(self, other)
return NotImplemented
@overload
def get(self, key: str, default: Optional[Any] = None) -> Any:
pass # pragma: no cover
@overload
def get(
self,
key: Union[int, Tuple[int, int], BaseTag],
default: Optional[Any] = None
) -> DataElement:
pass # pragma: no cover
def get(
self,
key: Union[str, Union[int, Tuple[int, int], BaseTag]],
default: Optional[Any] = None
) -> Union[Any, DataElement]:
"""Simulate ``dict.get()`` to handle element tags and keywords.
Parameters
----------
key : str or int or Tuple[int, int] or BaseTag
The element keyword or tag or the class attribute name to get.
default : obj or None, optional
If the element or class attribute is not present, return
`default` (default ``None``).
Returns
-------
value
If `key` is the keyword for an element in the :class:`Dataset`
then return the element's value.
dataelem.DataElement
If `key` is a tag for a element in the :class:`Dataset` then
return the :class:`~pydicom.dataelem.DataElement`
instance.
value
If `key` is a class attribute then return its value.
"""
if isinstance(key, str):
try:
return getattr(self, key)
except AttributeError:
return default
# is not a string, try to make it into a tag and then hand it
# off to the underlying dict
try:
key = Tag(key)
except Exception as exc:
raise TypeError("Dataset.get key must be a string or tag") from exc
try:
return self.__getitem__(key)
except KeyError:
return default
def items(self) -> AbstractSet[Tuple[BaseTag, _DatasetValue]]:
"""Return the :class:`Dataset` items to simulate :meth:`dict.items`.
Returns
-------
dict_items
The top-level (:class:`~pydicom.tag.BaseTag`,
:class:`~pydicom.dataelem.DataElement`) items for the
:class:`Dataset`.
"""
return self._dict.items()
def keys(self) -> AbstractSet[BaseTag]:
"""Return the :class:`Dataset` keys to simulate :meth:`dict.keys`.
Returns
-------
dict_keys
The :class:`~pydicom.tag.BaseTag` of all the elements in
the :class:`Dataset`.
"""
return self._dict.keys()
def values(self) -> ValuesView[_DatasetValue]:
"""Return the :class:`Dataset` values to simulate :meth:`dict.values`.
Returns
-------
dict_keys
The :class:`DataElements<pydicom.dataelem.DataElement>` that make
up the values of the :class:`Dataset`.
"""
return self._dict.values()
def __getattr__(self, name: str) -> Any:
"""Intercept requests for :class:`Dataset` attribute names.
If `name` matches a DICOM keyword, return the value for the
element with the corresponding tag.
Parameters
----------
name : str
An element keyword or a class attribute name.
Returns
-------
value
If `name` matches a DICOM keyword, returns the corresponding
element's value. Otherwise returns the class attribute's
value (if present).
"""
tag = tag_for_keyword(name)
if tag is not None: # `name` isn't a DICOM element keyword
tag = Tag(tag)
if tag in self._dict: # DICOM DataElement not in the Dataset
return self[tag].value
# no tag or tag not contained in the dataset
if name == '_dict':
# special handling for contained dict, needed for pickle
return {}
# Try the base class attribute getter (fix for issue 332)
return object.__getattribute__(self, name)
@property
def _character_set(self) -> List[str]:
"""The character set used to encode text values."""
char_set = self.get(BaseTag(0x00080005), None)
if not char_set:
return self._parent_encoding
return convert_encodings(char_set.value)
@overload
def __getitem__(self, key: slice) -> "Dataset":
pass # pragma: no cover
@overload
def __getitem__(self, key: TagType) -> DataElement:
pass # pragma: no cover
def __getitem__(
self, key: Union[slice, TagType]
) -> Union["Dataset", DataElement]:
"""Operator for ``Dataset[key]`` request.
Any deferred data elements will be read in and an attempt will be made
to correct any elements with ambiguous VRs.
Examples
--------
Indexing using :class:`~pydicom.dataelem.DataElement` tag
>>> ds = Dataset()
>>> ds.SOPInstanceUID = '1.2.3'
>>> ds.PatientName = 'CITIZEN^Jan'
>>> ds.PatientID = '12345'
>>> ds[0x00100010].value
'CITIZEN^Jan'
Slicing using element tags; all group ``0x0010`` elements in
the dataset
>>> ds[0x00100000:0x00110000]
(0010, 0010) Patient's Name PN: 'CITIZEN^Jan'
(0010, 0020) Patient ID LO: '12345'
All group ``0x0002`` elements in the dataset
>>> ds[(0x0002, 0x0000):(0x0003, 0x0000)]
<BLANKLINE>
Parameters
----------
key
The DICOM (group, element) tag in any form accepted by
:func:`~pydicom.tag.Tag` such as ``[0x0010, 0x0010]``,
``(0x10, 0x10)``, ``0x00100010``, etc. May also be a :class:`slice`
made up of DICOM tags.
Returns
-------
dataelem.DataElement or Dataset
If a single DICOM element tag is used then returns the
corresponding :class:`~pydicom.dataelem.DataElement`.
If a :class:`slice` is used then returns a :class:`Dataset` object
containing the corresponding
:class:`DataElements<pydicom.dataelem.DataElement>`.
"""
# If passed a slice, return a Dataset containing the corresponding
# DataElements
if isinstance(key, slice):
return self._dataset_slice(key)
if isinstance(key, BaseTag):
tag = key
else:
try:
tag = Tag(key)
except Exception as exc:
raise KeyError(f"'{key}'") from exc
elem = self._dict[tag]
if isinstance(elem, DataElement):
if elem.VR == 'SQ' and elem.value:
# let a sequence know its parent dataset, as sequence items
# may need parent dataset tags to resolve ambiguous tags
elem.value.parent = self
return elem
if isinstance(elem, RawDataElement):
# If a deferred read, then go get the value now
if elem.value is None and elem.length != 0:
from pydicom.filereader import read_deferred_data_element
elem = read_deferred_data_element(
self.fileobj_type,
self.filename,
self.timestamp,
elem
)
if tag != BaseTag(0x00080005):
character_set = self.read_encoding or self._character_set
else:
character_set = default_encoding
# Not converted from raw form read from file yet; do so now
self[tag] = DataElement_from_raw(elem, character_set, self)
# If the Element has an ambiguous VR, try to correct it
if 'or' in self[tag].VR:
from pydicom.filewriter import correct_ambiguous_vr_element
self[tag] = correct_ambiguous_vr_element(
self[tag], self, elem[6]
)
return cast(DataElement, self._dict.get(tag))
def private_block(
self, group: int, private_creator: str, create: bool = False
) -> PrivateBlock:
"""Return the block for the given tag `group` and `private_creator`.
.. versionadded:: 1.3
If `create` is ``True`` and the `private_creator` does not exist,
the private creator tag is added.
Notes
-----
We ignore the unrealistic case that no free block is available.
Parameters
----------
group : int
The group of the private tag to be found as a 32-bit :class:`int`.
Must be an odd number (e.g. a private group).
private_creator : str
The private creator string associated with the tag.
create : bool, optional
If ``True`` and `private_creator` does not exist, a new private
creator tag is added at the next free block. If ``False``
(the default) and `private_creator` does not exist,
:class:`KeyError` is raised instead.
Returns
-------
PrivateBlock
The existing or newly created private block.
Raises
------
ValueError
If `group` doesn't belong to a private tag or `private_creator`
is empty.
KeyError
If the private creator tag is not found in the given group and
the `create` parameter is ``False``.
"""
def new_block(element: int) -> PrivateBlock:
block = PrivateBlock(key, self, element)
self._private_blocks[key] = block
return block
key = (group, private_creator)
if key in self._private_blocks:
return self._private_blocks[key]
if not private_creator:
raise ValueError('Private creator must have a value')
if group % 2 == 0:
raise ValueError(
'Tag must be private if private creator is given')
# find block with matching private creator
block = self[(group, 0x10):(group, 0x100)] # type: ignore[misc]
data_el = next(
(
elem for elem in block if elem.value == private_creator
),
None
)
if data_el is not None:
return new_block(data_el.tag.element)
if not create:
# not found and shall not be created - raise
raise KeyError(
"Private creator '{}' not found".format(private_creator))
# private creator not existing - find first unused private block
# and add the private creator
first_free_el = next(
el for el in range(0x10, 0x100)
if Tag(group, el) not in self._dict
)
self.add_new(Tag(group, first_free_el), 'LO', private_creator)
return new_block(first_free_el)
def private_creators(self, group: int) -> List[str]:
"""Return a list of private creator names in the given group.
.. versionadded:: 1.3
Examples
--------
This can be used to check if a given private creator exists in
the group of the dataset:
>>> ds = Dataset()
>>> if 'My Creator' in ds.private_creators(0x0041):
... block = ds.private_block(0x0041, 'My Creator')
Parameters
----------
group : int
The private group as a 32-bit :class:`int`. Must be an odd number.
Returns
-------
list of str
All private creator names for private blocks in the group.
Raises
------
ValueError
If `group` is not a private group.
"""
if group % 2 == 0:
raise ValueError('Group must be an odd number')
block = self[(group, 0x10):(group, 0x100)] # type: ignore[misc]
return [x.value for x in block]
def get_private_item(
self, group: int, element_offset: int, private_creator: str
) -> DataElement:
"""Return the data element for the given private tag `group`.
.. versionadded:: 1.3
This is analogous to ``Dataset.__getitem__()``, but only for private
tags. This allows to find the private tag for the correct private
creator without the need to add the tag to the private dictionary
first.
Parameters
----------
group : int
The private tag group where the item is located as a 32-bit int.
element_offset : int
The lower 16 bits (e.g. 2 hex numbers) of the element tag.
private_creator : str
The private creator for the tag. Must match the private creator
for the tag to be returned.
Returns
-------
dataelem.DataElement
The corresponding element.
Raises
------
ValueError
If `group` is not part of a private tag or `private_creator` is
empty.
KeyError
If the private creator tag is not found in the given group.
If the private tag is not found.
"""
block = self.private_block(group, private_creator)
return self.__getitem__(block.get_tag(element_offset))
@overload
def get_item(self, key: slice) -> "Dataset":
pass # pragma: no cover
@overload
def get_item(self, key: TagType) -> DataElement:
pass # pragma: no cover
def get_item(
self, key: Union[slice, TagType]
) -> Union["Dataset", DataElement, RawDataElement, None]:
"""Return the raw data element if possible.
It will be raw if the user has never accessed the value, or set their
own value. Note if the data element is a deferred-read element,
then it is read and converted before being returned.
Parameters
----------
key
The DICOM (group, element) tag in any form accepted by
:func:`~pydicom.tag.Tag` such as ``[0x0010, 0x0010]``,
``(0x10, 0x10)``, ``0x00100010``, etc. May also be a :class:`slice`
made up of DICOM tags.
Returns
-------
dataelem.DataElement
The corresponding element.
"""
if isinstance(key, slice):
return self._dataset_slice(key)
elem = self._dict.get(Tag(key))
# If a deferred read, return using __getitem__ to read and convert it
if isinstance(elem, RawDataElement) and elem.value is None:
return self[key]
return elem
def _dataset_slice(self, slce: slice) -> "Dataset":
"""Return a slice that has the same properties as the original dataset.
That includes properties related to endianess and VR handling,
and the specific character set. No element conversion is done, e.g.
elements of type ``RawDataElement`` are kept.
"""
tags = self._slice_dataset(slce.start, slce.stop, slce.step)
ds = Dataset({tag: self.get_item(tag) for tag in tags})
ds.is_little_endian = self.is_little_endian
ds.is_implicit_VR = self.is_implicit_VR
ds.set_original_encoding(
self.read_implicit_vr, self.read_little_endian, self.read_encoding
)
return ds
@property
def is_original_encoding(self) -> bool:
"""Return ``True`` if the encoding to be used for writing is set and
is the same as that used to originally encode the :class:`Dataset`.
.. versionadded:: 1.1
This includes properties related to endianess, VR handling and the
(0008,0005) *Specific Character Set*.
"""
return (
self.is_implicit_VR is not None
and self.is_little_endian is not None
and self.read_implicit_vr == self.is_implicit_VR
and self.read_little_endian == self.is_little_endian
and self.read_encoding == self._character_set
)
def set_original_encoding(
self,
is_implicit_vr: Optional[bool],
is_little_endian: Optional[bool],
character_encoding: Union[None, str, MutableSequence[str]]
) -> None:
"""Set the values for the original transfer syntax and encoding.
.. versionadded:: 1.2
Can be used for a :class:`Dataset` with raw data elements to enable
optimized writing (e.g. without decoding the data elements).
"""
self.read_implicit_vr = is_implicit_vr
self.read_little_endian = is_little_endian
self.read_encoding = character_encoding
def group_dataset(self, group: int) -> "Dataset":
"""Return a :class:`Dataset` containing only elements of a certain
group.
Parameters
----------
group : int
The group part of a DICOM (group, element) tag.
Returns
-------
Dataset
A :class:`Dataset` containing elements of the group specified.
"""
return self[(group, 0x0000):(group + 1, 0x0000)] # type: ignore[misc]
def __iter__(self) -> Iterator[DataElement]:
"""Iterate through the top-level of the Dataset, yielding DataElements.
Examples
--------
>>> ds = Dataset()
>>> for elem in ds:
... print(elem)
The :class:`DataElements<pydicom.dataelem.DataElement>` are returned in
increasing tag value order. Sequence items are returned as a single
:class:`~pydicom.dataelem.DataElement`, so it is up
to the calling code to recurse into the Sequence items if desired.
Yields
------
dataelem.DataElement
The :class:`Dataset`'s
:class:`DataElements<pydicom.dataelem.DataElement>`, sorted by
increasing tag order.
"""
# Note this is different than the underlying dict class,
# which returns the key of the key:value mapping.
# Here the value is returned (but data_element.tag has the key)
taglist = sorted(self._dict.keys())
for tag in taglist:
yield self[tag]
def elements(self) -> Iterator[DataElement]:
"""Yield the top-level elements of the :class:`Dataset`.
.. versionadded:: 1.1
Examples
--------
>>> ds = Dataset()
>>> for elem in ds.elements():
... print(elem)
The elements are returned in the same way as in
``Dataset.__getitem__()``.
Yields
------
dataelem.DataElement or dataelem.RawDataElement
The unconverted elements sorted by increasing tag order.
"""
taglist = sorted(self._dict.keys())
for tag in taglist:
yield self.get_item(tag)
def __len__(self) -> int:
"""Return the number of elements in the top level of the dataset."""
return len(self._dict)
def __ne__(self, other: Any) -> bool:
"""Compare `self` and `other` for inequality."""
return not self == other
def clear(self) -> None:
"""Delete all the elements from the :class:`Dataset`."""
self._dict.clear()
def pop(self, key: Union[BaseTag, TagType], *args: Any) -> _DatasetValue:
"""Emulate :meth:`dict.pop` with support for tags and keywords.
Removes the element for `key` if it exists and returns it,
otherwise returns a default value if given or raises :class:`KeyError`.
Parameters
----------
key : int or str or 2-tuple
* If :class:`tuple` - the group and element number of the DICOM tag
* If :class:`int` - the combined group/element number
* If :class:`str` - the DICOM keyword of the tag
*args : zero or one argument
Defines the behavior if no tag exists for `key`: if given,
it defines the return value, if not given, :class:`KeyError` is
raised
Returns
-------
RawDataElement or DataElement
The element for `key` if it exists, or the default value if given.
Raises
------
KeyError
If the `key` is not a valid tag or keyword.
If the tag does not exist and no default is given.
"""
try:
key = Tag(key)
except Exception:
pass
return self._dict.pop(cast(BaseTag, key), *args)
def popitem(self) -> Tuple[BaseTag, _DatasetValue]:
"""Emulate :meth:`dict.popitem`.
Returns
-------
tuple of (BaseTag, DataElement)
"""
return self._dict.popitem()
def setdefault(
self, key: TagType, default: Optional[Any] = None
) -> DataElement:
"""Emulate :meth:`dict.setdefault` with support for tags and keywords.
Examples
--------
>>> ds = Dataset()
>>> elem = ds.setdefault((0x0010, 0x0010), "Test")
>>> elem
(0010, 0010) Patient's Name PN: 'Test'
>>> elem.value
'Test'
>>> elem = ds.setdefault('PatientSex',
... DataElement(0x00100040, 'CS', 'F'))
>>> elem.value
'F'
Parameters
----------
key : int, str or 2-tuple of int
* If :class:`tuple` - the group and element number of the DICOM tag
* If :class:`int` - the combined group/element number
* If :class:`str` - the DICOM keyword of the tag
default : pydicom.dataelem.DataElement or object, optional
The :class:`~pydicom.dataelem.DataElement` to use with `key`, or
the value of the :class:`~pydicom.dataelem.DataElement` to use with
`key` (default ``None``).
Returns
-------
pydicom.dataelem.DataElement or object
The :class:`~pydicom.dataelem.DataElement` for `key`.
Raises
------
ValueError
If `key` is not convertible to a valid tag or a known element
keyword.
KeyError
If :attr:`~pydicom.config.enforce_valid_values` is ``True`` and
`key` is an unknown non-private tag.
"""
tag = Tag(key)
if tag in self:
return self[tag]
if not isinstance(default, DataElement):
if tag.is_private:
vr = 'UN'
else:
try:
vr = dictionary_VR(tag)
except KeyError:
if config.enforce_valid_values:
raise KeyError(f"Unknown DICOM tag {tag}")
else:
vr = 'UN'
warnings.warn(
f"Unknown DICOM tag {tag} - setting VR to 'UN'"
)
default = DataElement(tag, vr, default)
self[key] = default
return default
def convert_pixel_data(self, handler_name: str = '') -> None:
"""Convert pixel data to a :class:`numpy.ndarray` internally.
Parameters
----------
handler_name : str, optional
The name of the pixel handler that shall be used to
decode the data. Supported names are: ``'gdcm'``,
``'pillow'``, ``'jpeg_ls'``, ``'rle'``, ``'numpy'`` and
``'pylibjpeg'``. If not used (the default), a matching handler is
used from the handlers configured in
:attr:`~pydicom.config.pixel_data_handlers`.
Returns
-------
None
Converted pixel data is stored internally in the dataset.
Raises
------
ValueError
If `handler_name` is not a valid handler name.
NotImplementedError
If the given handler or any handler, if none given, is unable to
decompress pixel data with the current transfer syntax
RuntimeError
If the given handler, or the handler that has been selected if
none given, is not available.
Notes
-----
If the pixel data is in a compressed image format, the data is
decompressed and any related data elements are changed accordingly.
"""
# Check if already have converted to a NumPy array
# Also check if pixel data has changed. If so, get new NumPy array
already_have = True
if not hasattr(self, "_pixel_array"):
already_have = False
elif self._pixel_id != get_image_pixel_ids(self):
already_have = False
if already_have:
return
if handler_name:
self._convert_pixel_data_using_handler(handler_name)
else:
self._convert_pixel_data_without_handler()
def _convert_pixel_data_using_handler(self, name: str) -> None:
"""Convert the pixel data using handler with the given name.
See :meth:`~Dataset.convert_pixel_data` for more information.
"""
# handle some variations in name
handler_name = name.lower()
if not handler_name.endswith('_handler'):
handler_name += '_handler'
if handler_name == 'numpy_handler':
handler_name = 'np_handler'
if handler_name == 'jpeg_ls_handler':
# the name in config differs from the actual handler name
# we allow both
handler_name = 'jpegls_handler'
if not hasattr(pydicom.config, handler_name):
raise ValueError(f"'{name}' is not a known handler name")
handler = getattr(pydicom.config, handler_name)
tsyntax = self.file_meta.TransferSyntaxUID
if not handler.supports_transfer_syntax(tsyntax):
raise NotImplementedError(
"Unable to decode pixel data with a transfer syntax UID"
f" of '{tsyntax}' ({tsyntax.name}) using the pixel data "
f"handler '{name}'. Please see the pydicom documentation for "
"information on supported transfer syntaxes."
)
if not handler.is_available():
raise RuntimeError(
f"The pixel data handler '{name}' is not available on your "
"system. Please refer to the pydicom documentation for "
"information on installing needed packages."
)
# if the conversion fails, the exception is propagated up
self._do_pixel_data_conversion(handler)
def _convert_pixel_data_without_handler(self) -> None:
"""Convert the pixel data using the first matching handler.
See :meth:`~Dataset.convert_pixel_data` for more information.
"""
# Find all possible handlers that support the transfer syntax
ts = self.file_meta.TransferSyntaxUID
possible_handlers = [
hh for hh in pydicom.config.pixel_data_handlers
if hh is not None
and hh.supports_transfer_syntax(ts) # type: ignore[attr-defined]
]
# No handlers support the transfer syntax
if not possible_handlers:
raise NotImplementedError(
"Unable to decode pixel data with a transfer syntax UID of "
f"'{ts}' ({ts.name}) as there are no pixel data "
"handlers available that support it. Please see the pydicom "
"documentation for information on supported transfer syntaxes "
)
# Handlers that both support the transfer syntax and have their
# dependencies met
available_handlers = [
hh for hh in possible_handlers
if hh.is_available() # type: ignore[attr-defined]
]
# There are handlers that support the transfer syntax but none of them
# can be used as missing dependencies
if not available_handlers:
# For each of the possible handlers we want to find which
# dependencies are missing
msg = (
"The following handlers are available to decode the pixel "
"data however they are missing required dependencies: "
)
pkg_msg = []
for hh in possible_handlers:
hh_deps = hh.DEPENDENCIES # type: ignore[attr-defined]
# Missing packages
missing = [dd for dd in hh_deps if have_package(dd) is None]
# Package names
names = [hh_deps[name][1] for name in missing]
pkg_msg.append(
f"{hh.HANDLER_NAME} " # type: ignore[attr-defined]
f"(req. {", ".join(names)})"
)
raise RuntimeError(msg + ', '.join(pkg_msg))
last_exception = None
for handler in available_handlers:
try:
self._do_pixel_data_conversion(handler)
return
except Exception as exc:
logger.debug(
"Exception raised by pixel data handler", exc_info=exc
)
last_exception = exc
# The only way to get to this point is if we failed to get the pixel
# array because all suitable handlers raised exceptions
self._pixel_array = None
self._pixel_id = {}
logger.info(
"Unable to decode the pixel data using the following handlers: {}."
"Please see the list of supported Transfer Syntaxes in the "
"pydicom documentation for alternative packages that might "
"be able to decode the data"
.format(", ".join([str(hh) for hh in available_handlers]))
)
raise last_exception # type: ignore[misc]
def _do_pixel_data_conversion(self, handler: Any) -> None:
"""Do the actual data conversion using the given handler."""
# Use the handler to get a 1D numpy array of the pixel data
# Will raise an exception if no pixel data element
arr = handler.get_pixeldata(self)
self._pixel_array = reshape_pixel_array(self, arr)
# Some handler/transfer syntax combinations may need to
# convert the color space from YCbCr to RGB
if handler.needs_to_convert_to_RGB(self):
self._pixel_array = convert_color_space(
self._pixel_array, 'YBR_FULL', 'RGB'
)
self._pixel_id = get_image_pixel_ids(self)
def compress(
self,
transfer_syntax_uid: str,
arr: Optional["numpy.ndarray"] = None,
encoding_plugin: str = '',
decoding_plugin: str = '',
encapsulate_ext: bool = False,
**kwargs: Any,
) -> None:
"""Compress and update an uncompressed dataset in-place with the
resulting :dcm:`encapsulated<part05/sect_A.4.html>` pixel data.
.. versionadded:: 2.2
The dataset must already have the following
:dcm:`Image Pixel<part03/sect_C.7.6.3.html>` module elements present
with correct values that correspond to the resulting compressed
pixel data:
* (0028,0002) *Samples per Pixel*
* (0028,0004) *Photometric Interpretation*
* (0028,0008) *Number of Frames* (if more than 1 frame will be present)
* (0028,0010) *Rows*
* (0028,0011) *Columns*
* (0028,0100) *Bits Allocated*
* (0028,0101) *Bits Stored*
* (0028,0103) *Pixel Representation*
This method will add the file meta dataset if none is present and add
or modify the following elements:
* (0002,0010) *Transfer Syntax UID*
* (7FE0,0010) *Pixel Data*
If *Samples per Pixel* is greater than 1 then the following element
will also be added:
* (0028,0006) *Planar Configuration*
If the compressed pixel data is too large for encapsulation using a
basic offset table then an :dcm:`extended offset table
<part03/sect_C.7.6.3.html>` will also be used, in which case the
following elements will also be added:
* (7FE0,0001) *Extended Offset Table*
* (7FE0,0002) *Extended Offset Table Lengths*
**Supported Transfer Syntax UIDs**
+----------------------+----------+----------------------------------+
| UID | Plugins | Encoding Guide |
+======================+==========+==================================+
| *RLE Lossless* - |pydicom, | :doc:`RLE Lossless |
| 1.2.840.10008.1.2.5 |pylibjpeg,| </guides/encoding/rle_lossless>` |
| |gdcm | |
+----------------------+----------+----------------------------------+
Examples
--------
Compress the existing uncompressed *Pixel Data* in place:
>>> from pydicom.data import get_testdata_file
>>> from pydicom.uid import RLELossless
>>> ds = get_testdata_file("CT_small.dcm", read=True)
>>> ds.compress(RLELossless)
>>> ds.save_as("CT_small_rle.dcm")
Parameters
----------
transfer_syntax_uid : pydicom.uid.UID
The UID of the :dcm:`transfer syntax<part05/chapter_10.html>` to
use when compressing the pixel data.
arr : numpy.ndarray, optional
Compress the uncompressed pixel data in `arr` and use it
to set the *Pixel Data*. If `arr` is not used then the
existing *Pixel Data* in the dataset will be compressed instead.
The :attr:`~numpy.ndarray.shape`, :class:`~numpy.dtype` and
contents of the array should match the dataset.
encoding_plugin : str, optional
Use the `encoding_plugin` to compress the pixel data. See the
:doc:`user guide </old/image_data_compression>` for a list of
plugins available for each UID and their dependencies. If not
specified then all available plugins will be tried (default).
decoding_plugin : str, optional
Placeholder for future functionality.
encapsulate_ext : bool, optional
If ``True`` then force the addition of an extended offset table.
If ``False`` (default) then an extended offset table
will be added if needed for large amounts of compressed *Pixel
Data*, otherwise just the basic offset table will be used.
**kwargs
Optional keyword parameters for the encoding plugin may also be
present. See the :doc:`encoding plugins options
</guides/encoding/encoder_plugin_options>` for more information.
"""
from pydicom.encoders import get_encoder
uid = UID(transfer_syntax_uid)
# Raises NotImplementedError if `uid` is not supported
encoder = get_encoder(uid)
if not encoder.is_available:
missing = "\n".join(
[f" {s}" for s in encoder.missing_dependencies]
)
raise RuntimeError(
f"The '{uid.name}' encoder is unavailable because its "
f"encoding plugins are missing dependencies:\n"
f"{missing}"
)
if arr is None:
# Encode the current *Pixel Data*
frame_iterator = encoder.iter_encode(
self,
encoding_plugin=encoding_plugin,
decoding_plugin=decoding_plugin,
**kwargs
)
else:
# Encode from an uncompressed pixel data array
kwargs.update(encoder.kwargs_from_ds(self))
frame_iterator = encoder.iter_encode(
arr,
encoding_plugin=encoding_plugin,
**kwargs
)
# Encode!
encoded = [f for f in frame_iterator]
# Encapsulate the encoded *Pixel Data*
nr_frames = getattr(self, "NumberOfFrames", 1) or 1
total = (nr_frames - 1) * 8 + sum([len(f) for f in encoded[:-1]])
if encapsulate_ext or total > 2**32 - 1:
(self.PixelData,
self.ExtendedOffsetTable,
self.ExtendedOffsetTableLengths) = encapsulate_extended(encoded)
else:
self.PixelData = encapsulate(encoded)
self['PixelData'].is_undefined_length = True
# Set the correct *Transfer Syntax UID*
if not hasattr(self, 'file_meta'):
self.file_meta = FileMetaDataset()
self.file_meta.TransferSyntaxUID = uid
# Add or update any other required elements
if self.SamplesPerPixel > 1:
self.PlanarConfiguration: int = 1 if uid == RLELossless else 0
def decompress(self, handler_name: str = '') -> None:
"""Decompresses *Pixel Data* and modifies the :class:`Dataset`
in-place.
.. versionadded:: 1.4
The `handler_name` keyword argument was added
If not a compressed transfer syntax, then pixel data is converted
to a :class:`numpy.ndarray` internally, but not returned.
If compressed pixel data, then is decompressed using an image handler,
and internal state is updated appropriately:
- ``Dataset.file_meta.TransferSyntaxUID`` is updated to non-compressed
form
- :attr:`~pydicom.dataelem.DataElement.is_undefined_length`
is ``False`` for the (7FE0,0010) *Pixel Data* element.
.. versionchanged:: 1.4
The `handler_name` keyword argument was added
Parameters
----------
handler_name : str, optional
The name of the pixel handler that shall be used to
decode the data. Supported names are: ``'gdcm'``,
``'pillow'``, ``'jpeg_ls'``, ``'rle'``, ``'numpy'`` and
``'pylibjpeg'``.
If not used (the default), a matching handler is used from the
handlers configured in :attr:`~pydicom.config.pixel_data_handlers`.
Returns
-------
None
Raises
------
NotImplementedError
If the pixel data was originally compressed but file is not
*Explicit VR Little Endian* as required by the DICOM Standard.
"""
self.convert_pixel_data(handler_name)
self.is_decompressed = True
# May have been undefined length pixel data, but won't be now
if 'PixelData' in self:
self[0x7fe00010].is_undefined_length = False
# Make sure correct Transfer Syntax is set
# According to the dicom standard PS3.5 section A.4,
# all compressed files must have been explicit VR, little endian
# First check if was a compressed file
if (
hasattr(self, 'file_meta')
and self.file_meta.TransferSyntaxUID.is_compressed
):
# Check that current file as read does match expected
if not self.is_little_endian or self.is_implicit_VR:
msg = ("Current dataset does not match expected ExplicitVR "
"LittleEndian transfer syntax from a compressed "
"transfer syntax")
raise NotImplementedError(msg)
# All is as expected, updated the Transfer Syntax
self.file_meta.TransferSyntaxUID = ExplicitVRLittleEndian
def overlay_array(self, group: int) -> "numpy.ndarray":
"""Return the *Overlay Data* in `group` as a :class:`numpy.ndarray`.
.. versionadded:: 1.4
Parameters
----------
group : int
The group number of the overlay data.
Returns
-------
numpy.ndarray
The (`group`,3000) *Overlay Data* converted to a
:class:`numpy.ndarray`.
"""
if group < 0x6000 or group > 0x60FF:
raise ValueError(
"The group part of the 'Overlay Data' element tag must be "
"between 0x6000 and 0x60FF (inclusive)"
)
from pydicom.config import overlay_data_handlers
available_handlers = [
hh for hh in overlay_data_handlers
if hh.is_available() # type: ignore[attr-defined]
]
if not available_handlers:
# For each of the handlers we want to find which
# dependencies are missing
msg = (
"The following handlers are available to decode the overlay "
"data however they are missing required dependencies: "
)
pkg_msg = []
for hh in overlay_data_handlers:
hh_deps = hh.DEPENDENCIES # type: ignore[attr-defined]
# Missing packages
missing = [dd for dd in hh_deps if have_package(dd) is None]
# Package names
names = [hh_deps[name][1] for name in missing]
pkg_msg.append(
f"{hh.HANDLER_NAME} " # type: ignore[attr-defined]
f"(req. {", ".join(names)})"
)
raise RuntimeError(msg + ', '.join(pkg_msg))
last_exception = None
for handler in available_handlers:
try:
# Use the handler to get an ndarray of the pixel data
func = handler.get_overlay_array # type: ignore[attr-defined]
return cast("numpy.ndarray", func(self, group))
except Exception as exc:
logger.debug(
"Exception raised by overlay data handler", exc_info=exc
)
last_exception = exc
logger.info(
"Unable to decode the overlay data using the following handlers: "
"{}. Please see the list of supported Transfer Syntaxes in the "
"pydicom documentation for alternative packages that might "
"be able to decode the data"
.format(", ".join([str(hh) for hh in available_handlers]))
)
raise last_exception # type: ignore[misc]
@property
def pixel_array(self) -> "numpy.ndarray":
"""Return the pixel data as a :class:`numpy.ndarray`.
.. versionchanged:: 1.4
Added support for *Float Pixel Data* and *Double Float Pixel Data*
Returns
-------
numpy.ndarray
The (7FE0,0008) *Float Pixel Data*, (7FE0,0009) *Double Float
Pixel Data* or (7FE0,0010) *Pixel Data* converted to a
:class:`numpy.ndarray`.
"""
self.convert_pixel_data()
return cast("numpy.ndarray", self._pixel_array)
def waveform_array(self, index: int) -> "numpy.ndarray":
"""Return an :class:`~numpy.ndarray` for the multiplex group at
`index` in the (5400,0100) *Waveform Sequence*.
.. versionadded:: 2.1
Parameters
----------
index : int
The index of the multiplex group to return the array for.
Returns
------
numpy.ndarray
The *Waveform Data* for the multiplex group as an
:class:`~numpy.ndarray` with shape (samples, channels). If
(003A,0210) *Channel Sensitivity* is present
then the values will be in the units specified by the (003A,0211)
*Channel Sensitivity Units Sequence*.
See Also
--------
:func:`~pydicom.waveforms.numpy_handler.generate_multiplex`
:func:`~pydicom.waveforms.numpy_handler.multiplex_array`
"""
if not wave_handler.is_available():
raise RuntimeError("The waveform data handler requires numpy")
return wave_handler.multiplex_array(self, index, as_raw=False)
# Format strings spec'd according to python string formatting options
# See http://docs.python.org/library/stdtypes.html#string-formatting-operations # noqa
default_element_format = "%(tag)s %(name)-35.35s %(VR)s: %(repval)s"
default_sequence_element_format = "%(tag)s %(name)-35.35s %(VR)s: %(repval)s" # noqa
def formatted_lines(
self,
element_format: str = default_element_format,
sequence_element_format: str = default_sequence_element_format,
indent_format: Optional[str] = None
) -> Iterator[str]:
"""Iterate through the :class:`Dataset` yielding formatted :class:`str`
for each element.
Parameters
----------
element_format : str
The string format to use for non-sequence elements. Formatting uses
the attributes of
:class:`~pydicom.dataelem.DataElement`. Default is
``"%(tag)s %(name)-35.35s %(VR)s: %(repval)s"``.
sequence_element_format : str
The string format to use for sequence elements. Formatting uses
the attributes of
:class:`~pydicom.dataelem.DataElement`. Default is
``"%(tag)s %(name)-35.35s %(VR)s: %(repval)s"``
indent_format : str or None
Placeholder for future functionality.
Yields
------
str
A string representation of an element.
"""
exclusion = ('from_json', 'to_json', 'to_json_dict', 'clear')
for elem in self.iterall():
# Get all the attributes possible for this data element (e.g.
# gets descriptive text name too)
# This is the dictionary of names that can be used in the format
# string
elem_dict = {
attr: (
getattr(elem, attr)() if callable(getattr(elem, attr))
else getattr(elem, attr)
)
for attr in dir(elem) if not attr.startswith("_")
and attr not in exclusion
}
if elem.VR == "SQ":
yield sequence_element_format % elem_dict
else:
yield element_format % elem_dict
def _pretty_str(
self, indent: int = 0, top_level_only: bool = False
) -> str:
"""Return a string of the DataElements in the Dataset, with indented
levels.
This private method is called by the ``__str__()`` method for handling
print statements or ``str(dataset)``, and the ``__repr__()`` method.
It is also used by ``top()``, therefore the `top_level_only` flag.
This function recurses, with increasing indentation levels.
..versionchanged:: 2.0
The file meta information is returned in its own section,
if :data:`~pydicom.config.show_file_meta` is ``True`` (default)
Parameters
----------
indent : int, optional
The indent level offset (default ``0``).
top_level_only : bool, optional
When True, only create a string for the top level elements, i.e.
exclude elements within any Sequences (default ``False``).
Returns
-------
str
A string representation of the Dataset.
"""
strings = []
indent_str = self.indent_chars * indent
nextindent_str = self.indent_chars * (indent + 1)
# Display file meta, if configured to do so, and have a non-empty one
if (
hasattr(self, "file_meta") and self.file_meta
and pydicom.config.show_file_meta
):
strings.append(f"{"Dataset.file_meta ":-<49}")
for elem in self.file_meta:
with tag_in_exception(elem.tag):
strings.append(indent_str + repr(elem))
strings.append(f"{"":-<49}")
for elem in self:
with tag_in_exception(elem.tag):
if elem.VR == "SQ": # a sequence
strings.append(
f"{indent_str}{str(elem.tag)} {elem.description()} "
f"{len(elem.value)} item(s) ---- "
)
if not top_level_only:
for dataset in elem.value:
strings.append(dataset._pretty_str(indent + 1))
strings.append(nextindent_str + "---------")
else:
strings.append(indent_str + repr(elem))
return "\n".join(strings)
def remove_private_tags(self) -> None:
"""Remove all private elements from the :class:`Dataset`."""
def remove_callback(dataset: "Dataset", elem: DataElement) -> None:
"""Internal method to use as callback to walk() method."""
if elem.tag.is_private:
# can't del self[tag] - won't be right dataset on recursion
del dataset[elem.tag]
self.walk(remove_callback)
def save_as(
self,
filename: Union[str, "os.PathLike[AnyStr]", BinaryIO],
write_like_original: bool = True
) -> None:
"""Write the :class:`Dataset` to `filename`.
Wrapper for pydicom.filewriter.dcmwrite, passing this dataset to it.
See documentation for that function for details.
See Also
--------
pydicom.filewriter.dcmwrite
Write a DICOM file from a :class:`FileDataset` instance.
"""
pydicom.dcmwrite(filename, self, write_like_original)
def ensure_file_meta(self) -> None:
"""Create an empty ``Dataset.file_meta`` if none exists.
.. versionadded:: 1.2
"""
# Changed in v2.0 so does not re-assign self.file_meta with getattr()
if not hasattr(self, "file_meta"):
self.file_meta = FileMetaDataset()
def fix_meta_info(self, enforce_standard: bool = True) -> None:
"""Ensure the file meta info exists and has the correct values
for transfer syntax and media storage UIDs.
.. versionadded:: 1.2
.. warning::
The transfer syntax for ``is_implicit_VR = False`` and
``is_little_endian = True`` is ambiguous and will therefore not
be set.
Parameters
----------
enforce_standard : bool, optional
If ``True``, a check for incorrect and missing elements is
performed (see :func:`~validate_file_meta`).
"""
self.ensure_file_meta()
if self.is_little_endian and self.is_implicit_VR:
self.file_meta.TransferSyntaxUID = ImplicitVRLittleEndian
elif not self.is_little_endian and not self.is_implicit_VR:
self.file_meta.TransferSyntaxUID = ExplicitVRBigEndian
elif not self.is_little_endian and self.is_implicit_VR:
raise NotImplementedError("Implicit VR Big Endian is not a "
"supported Transfer Syntax.")
if 'SOPClassUID' in self:
self.file_meta.MediaStorageSOPClassUID = self.SOPClassUID
if 'SOPInstanceUID' in self:
self.file_meta.MediaStorageSOPInstanceUID = self.SOPInstanceUID
if enforce_standard:
validate_file_meta(self.file_meta, enforce_standard=True)
def __setattr__(self, name: str, value: Any) -> None:
"""Intercept any attempts to set a value for an instance attribute.
If name is a DICOM keyword, set the corresponding tag and DataElement.
Else, set an instance (python) attribute as any other class would do.
Parameters
----------
name : str
The keyword for the element you wish to add/change. If
`name` is not a DICOM element keyword then this will be the
name of the attribute to be added/changed.
value
The value for the attribute to be added/changed.
"""
tag = tag_for_keyword(name)
if tag is not None: # successfully mapped name to a tag
if tag not in self:
# don't have this tag yet->create the data_element instance
VR = dictionary_VR(tag)
data_element = DataElement(tag, VR, value)
if VR == 'SQ':
# let a sequence know its parent dataset to pass it
# to its items, who may need parent dataset tags
# to resolve ambiguous tags
data_element.parent = self
else:
# already have this data_element, just changing its value
data_element = self[tag]
data_element.value = value
# Now have data_element - store it in this dict
self[tag] = data_element
elif repeater_has_keyword(name):
# Check if `name` is repeaters element
raise ValueError(
f"'{name}' is a DICOM repeating group element and must be "
"added using the add() or add_new() methods."
)
elif name == "file_meta":
self._set_file_meta(value)
else:
# Warn if `name` is camel case but not a keyword
if _RE_CAMEL_CASE.match(name):
msg = (
f"Camel case attribute '{name}' used which is not in the "
"element keyword data dictionary"
)
if config.INVALID_KEYWORD_BEHAVIOR == "WARN":
warnings.warn(msg)
elif config.INVALID_KEYWORD_BEHAVIOR == "RAISE":
raise ValueError(msg)
# name not in dicom dictionary - setting a non-dicom instance
# attribute
# XXX note if user mis-spells a dicom data_element - no error!!!
object.__setattr__(self, name, value)
def _set_file_meta(self, value: Optional["Dataset"]) -> None:
if value is not None and not isinstance(value, FileMetaDataset):
if config._use_future:
raise TypeError(
"Pydicom Future: Dataset.file_meta must be an instance "
"of FileMetaDataset"
)
FileMetaDataset.validate(value)
warnings.warn(
"Starting in pydicom 3.0, Dataset.file_meta must be a "
"FileMetaDataset class instance",
DeprecationWarning
)
self.__dict__["file_meta"] = value
def __setitem__(
self, key: Union[slice, TagType], elem: _DatasetValue
) -> None:
"""Operator for ``Dataset[key] = elem``.
Parameters
----------
key : int or Tuple[int, int] or str
The tag for the element to be added to the :class:`Dataset`.
elem : dataelem.DataElement or dataelem.RawDataElement
The element to add to the :class:`Dataset`.
Raises
------
NotImplementedError
If `key` is a :class:`slice`.
ValueError
If the `key` value doesn't match the corresponding
:attr:`DataElement.tag<pydicom.dataelem.tag>`.
"""
if isinstance(key, slice):
raise NotImplementedError(
'Slicing is not supported when setting Dataset items'
)
try:
key = Tag(key)
except Exception as exc:
raise ValueError(
f"Unable to convert the key '{key}' to an element tag"
) from exc
if not isinstance(elem, (DataElement, RawDataElement)):
raise TypeError("Dataset items must be 'DataElement' instances")
if isinstance(elem.tag, BaseTag):
elem_tag = elem.tag
else:
elem_tag = Tag(elem.tag)
if key != elem_tag:
raise ValueError(
f"The key '{key}' doesn't match the 'DataElement' tag "
f"'{elem_tag}'"
)
if elem_tag.is_private:
# See PS 3.5-2008 section 7.8.1 (p. 44) for how blocks are reserved
logger.debug(f"Setting private tag {elem_tag}")
private_block = elem_tag.element >> 8
private_creator_tag = Tag(elem_tag.group, private_block)
if private_creator_tag in self and elem_tag != private_creator_tag:
if isinstance(elem, RawDataElement):
elem = DataElement_from_raw(
elem, self._character_set, self
)
elem.private_creator = self[private_creator_tag].value
self._dict[elem_tag] = elem
def _slice_dataset(
self,
start: Optional[TagType],
stop: Optional[TagType],
step: Optional[int]
) -> List[BaseTag]:
"""Return the element tags in the Dataset that match the slice.
Parameters
----------
start : int or 2-tuple of int or None
The slice's starting element tag value, in any format accepted by
:func:`~pydicom.tag.Tag`.
stop : int or 2-tuple of int or None
The slice's stopping element tag value, in any format accepted by
:func:`~pydicom.tag.Tag`.
step : int or None
The slice's step size.
Returns
------
list of BaseTag
The tags in the :class:`Dataset` that meet the conditions of the
slice.
"""
# Check the starting/stopping Tags are valid when used
if start is not None:
start = Tag(start)
if stop is not None:
stop = Tag(stop)
all_tags = sorted(self._dict.keys())
# If the Dataset is empty, return an empty list
if not all_tags:
return []
# Special case the common situations:
# - start and/or stop are None
# - step is 1
if start is None:
if stop is None:
# For step=1 avoid copying the list
return all_tags if step == 1 else all_tags[::step]
else: # Have a stop value, get values until that point
step1_list = list(takewhile(lambda x: x < stop, all_tags))
return step1_list if step == 1 else step1_list[::step]
# Have a non-None start value. Find its index
i_start = bisect_left(all_tags, start)
if stop is None:
return all_tags[i_start::step]
i_stop = bisect_left(all_tags, stop)
return all_tags[i_start:i_stop:step]
def __str__(self) -> str:
"""Handle str(dataset).
..versionchanged:: 2.0
The file meta information was added in its own section,
if :data:`pydicom.config.show_file_meta` is ``True``
"""
return self._pretty_str()
def top(self) -> str:
"""Return a :class:`str` representation of the top level elements. """
return self._pretty_str(top_level_only=True)
def trait_names(self) -> List[str]:
"""Return a :class:`list` of valid names for auto-completion code.
Used in IPython, so that data element names can be found and offered
for autocompletion on the IPython command line.
"""
return dir(self)
def update(self, d: _DatasetType) -> None:
"""Extend :meth:`dict.update` to handle DICOM tags and keywords.
Parameters
----------
dictionary : dict or Dataset
The :class:`dict` or :class:`Dataset` to use when updating the
current object.
"""
for key, value in list(d.items()):
if isinstance(key, str):
setattr(self, key, value)
else:
self[Tag(cast(int, key))] = value
def iterall(self) -> Iterator[DataElement]:
"""Iterate through the :class:`Dataset`, yielding all the elements.
Unlike ``iter(Dataset)``, this *does* recurse into sequences,
and so yields all elements as if dataset were "flattened".
Yields
------
dataelem.DataElement
"""
for elem in self:
yield elem
if elem.VR == "SQ":
for ds in elem.value:
yield from ds.iterall()
def walk(
self,
callback: Callable[["Dataset", DataElement], None],
recursive: bool = True
) -> None:
"""Iterate through the :class:`Dataset's<Dataset>` elements and run
`callback` on each.
Visit all elements in the :class:`Dataset`, possibly recursing into
sequences and their items. The `callback` function is called for each
:class:`~pydicom.dataelem.DataElement` (including elements
with a VR of 'SQ'). Can be used to perform an operation on certain
types of elements.
For example,
:meth:`~Dataset.remove_private_tags` finds all elements with private
tags and deletes them.
The elements will be returned in order of increasing tag number within
their current :class:`Dataset`.
Parameters
----------
callback
A callable function that takes two arguments:
* a :class:`Dataset`
* a :class:`~pydicom.dataelem.DataElement` belonging
to that :class:`Dataset`
recursive : bool, optional
Flag to indicate whether to recurse into sequences (default
``True``).
"""
taglist = sorted(self._dict.keys())
for tag in taglist:
with tag_in_exception(tag):
data_element = self[tag]
callback(self, data_element) # self = this Dataset
# 'tag in self' below needed in case callback deleted
# data_element
if recursive and tag in self and data_element.VR == "SQ":
sequence = data_element.value
for dataset in sequence:
dataset.walk(callback)
@classmethod
def from_json(
cls: Type["Dataset"],
json_dataset: Union[Dict[str, Any], str, bytes, bytearray],
bulk_data_uri_handler: Optional[
Union[
Callable[[str, str, str], Union[None, str, int, float, bytes]],
Callable[[str], Union[None, str, int, float, bytes]]
]
] = None
) -> "Dataset":
"""Return a :class:`Dataset` from a DICOM JSON Model object.
.. versionadded:: 1.3
See the DICOM Standard, Part 18, :dcm:`Annex F<part18/chapter_F.html>`.
Parameters
----------
json_dataset : dict, str, bytes or bytearray
:class:`dict`, :class:`str`, :class:`bytes` or :class:`bytearray`
representing a DICOM Data Set formatted based on the :dcm:`DICOM
JSON Model<part18/chapter_F.html>`.
bulk_data_uri_handler : callable, optional
Callable function that accepts either the tag, vr and
"BulkDataURI" value or just the "BulkDataURI" value of the JSON
representation of a data element and returns the actual value of
that data element (retrieved via DICOMweb WADO-RS). If no
`bulk_data_uri_handler` is specified (default) then the
corresponding element will have an "empty" value such as
``""``, ``b""`` or ``None`` depending on the `vr` (i.e. the
Value Multiplicity will be 0).
Returns
-------
Dataset
"""
if isinstance(json_dataset, (str, bytes, bytearray)):
json_dataset = cast(Dict[str, Any], json.loads(json_dataset))
dataset = cls()
for tag, mapping in json_dataset.items():
# `tag` is an element tag in uppercase hex format as a str
# `mapping` is Dict[str, Any] and should have keys 'vr' and at most
# one of ('Value', 'BulkDataURI', 'InlineBinary') but may have
# none of those if the element's VM is 0
vr = mapping['vr']
unique_value_keys = tuple(
set(mapping.keys()) & set(jsonrep.JSON_VALUE_KEYS)
)
if len(unique_value_keys) == 0:
value_key = None
value = ['']
else:
value_key = unique_value_keys[0]
value = mapping[value_key]
data_element = DataElement.from_json(
cls, tag, vr, value, value_key, bulk_data_uri_handler
)
dataset.add(data_element)
return dataset
def to_json_dict(
self,
bulk_data_threshold: int = 1024,
bulk_data_element_handler: Optional[Callable[[DataElement], str]] = None, # noqa
suppress_invalid_tags: bool = False,
) -> Dict[str, Any]:
"""Return a dictionary representation of the :class:`Dataset`
conforming to the DICOM JSON Model as described in the DICOM
Standard, Part 18, :dcm:`Annex F<part18/chapter_F.html>`.
.. versionadded:: 1.4
Parameters
----------
bulk_data_threshold : int, optional
Threshold for the length of a base64-encoded binary data element
above which the element should be considered bulk data and the
value provided as a URI rather than included inline (default:
``1024``). Ignored if no bulk data handler is given.
bulk_data_element_handler : callable, optional
Callable function that accepts a bulk data element and returns a
JSON representation of the data element (dictionary including the
"vr" key and either the "InlineBinary" or the "BulkDataURI" key).
suppress_invalid_tags : bool, optional
Flag to specify if errors while serializing tags should be logged
and the tag dropped or if the error should be bubbled up.
Returns
-------
dict
:class:`Dataset` representation based on the DICOM JSON Model.
"""
json_dataset = {}
for key in self.keys():
json_key = '{:08X}'.format(key)
data_element = self[key]
try:
json_dataset[json_key] = data_element.to_json_dict(
bulk_data_element_handler=bulk_data_element_handler,
bulk_data_threshold=bulk_data_threshold
)
except Exception as exc:
logger.error(f"Error while processing tag {json_key}")
if not suppress_invalid_tags:
raise exc
return json_dataset
def to_json(
self,
bulk_data_threshold: int = 1024,
bulk_data_element_handler: Optional[Callable[[DataElement], str]] = None, # noqa
dump_handler: Optional[Callable[[Dict[str, Any]], str]] = None,
suppress_invalid_tags: bool = False,
) -> str:
"""Return a JSON representation of the :class:`Dataset`.
.. versionadded:: 1.3
See the DICOM Standard, Part 18, :dcm:`Annex F<part18/chapter_F.html>`.
Parameters
----------
bulk_data_threshold : int, optional
Threshold for the length of a base64-encoded binary data element
above which the element should be considered bulk data and the
value provided as a URI rather than included inline (default:
``1024``). Ignored if no bulk data handler is given.
bulk_data_element_handler : callable, optional
Callable function that accepts a bulk data element and returns a
JSON representation of the data element (dictionary including the
"vr" key and either the "InlineBinary" or the "BulkDataURI" key).
dump_handler : callable, optional
Callable function that accepts a :class:`dict` and returns the
serialized (dumped) JSON string (by default uses
:func:`json.dumps`).
.. note:
Make sure to use a dump handler that sorts the keys (see
example below) to create DICOM-conformant JSON.
suppress_invalid_tags : bool, optional
Flag to specify if errors while serializing tags should be logged
and the tag dropped or if the error should be bubbled up.
Returns
-------
str
:class:`Dataset` serialized into a string based on the DICOM JSON
Model.
Examples
--------
>>> def my_json_dumps(data):
... return json.dumps(data, indent=4, sort_keys=True)
>>> ds.to_json(dump_handler=my_json_dumps)
"""
if dump_handler is None:
def json_dump(d: Any) -> str:
return json.dumps(d, sort_keys=True)
dump_handler = json_dump
return dump_handler(
self.to_json_dict(
bulk_data_threshold,
bulk_data_element_handler,
suppress_invalid_tags=suppress_invalid_tags
)
)
def __getstate__(self) -> Dict[str, Any]:
# pickle cannot handle weakref - remove parent
d = self.__dict__.copy()
del d['parent']
return d
def __setstate__(self, state: Dict[str, Any]) -> None:
self.__dict__.update(state)
# re-add parent - it will be set to the parent dataset on demand
# if the dataset is in a sequence
self.__dict__['parent'] = None
__repr__ = __str__
_FileDataset = TypeVar("_FileDataset", bound="FileDataset")
class FileDataset(Dataset):
"""An extension of :class:`Dataset` to make reading and writing to
file-like easier.
Attributes
----------
preamble : str or bytes or None
The optional DICOM preamble prepended to the :class:`FileDataset`, if
available.
file_meta : FileMetaDataset or None
The Dataset's file meta information as a :class:`FileMetaDataset`,
if available (``None`` if not present).
Consists of group ``0x0002`` elements.
filename : str or None
The filename that the :class:`FileDataset` was read from (if read from
file) or ``None`` if the filename is not available (if read from a
:class:`io.BytesIO` or similar).
fileobj_type
The object type of the file-like the :class:`FileDataset` was read
from.
is_implicit_VR : bool
``True`` if the dataset encoding is implicit VR, ``False`` otherwise.
is_little_endian : bool
``True`` if the dataset encoding is little endian byte ordering,
``False`` otherwise.
timestamp : float or None
The modification time of the file the :class:`FileDataset` was read
from, ``None`` if the modification time is not available.
"""
def __init__(
self,
filename_or_obj: Union[str, "os.PathLike[AnyStr]", BinaryIO],
dataset: _DatasetType,
preamble: Optional[bytes] = None,
file_meta: Optional["FileMetaDataset"] = None,
is_implicit_VR: bool = True,
is_little_endian: bool = True
) -> None:
"""Initialize a :class:`FileDataset` read from a DICOM file.
Parameters
----------
filename_or_obj : str or PathLike or BytesIO or None
Full path and filename to the file, memory buffer object, or
``None`` if is a :class:`io.BytesIO`.
dataset : Dataset or dict
Some form of dictionary, usually a :class:`Dataset` returned from
:func:`~pydicom.filereader.dcmread`.
preamble : bytes or str, optional
The 128-byte DICOM preamble.
file_meta : FileMetaDataset, optional
The file meta :class:`FileMetaDataset`, such as the one returned by
:func:`~pydicom.filereader.read_file_meta_info`, or an empty
:class:`FileMetaDataset` if no file meta information is in the
file.
is_implicit_VR : bool, optional
``True`` (default) if implicit VR transfer syntax used; ``False``
if explicit VR.
is_little_endian : bool
``True`` (default) if little-endian transfer syntax used; ``False``
if big-endian.
"""
Dataset.__init__(self, dataset)
self.preamble = preamble
self.file_meta: "FileMetaDataset" = (
file_meta if file_meta is not None else FileMetaDataset()
)
self.is_implicit_VR: bool = is_implicit_VR
self.is_little_endian: bool = is_little_endian
filename: Optional[str] = None
filename_or_obj = path_from_pathlike(filename_or_obj)
self.fileobj_type: Any
self.filename: Union[str, BinaryIO]
if isinstance(filename_or_obj, str):
filename = filename_or_obj
self.fileobj_type = open
elif isinstance(filename_or_obj, io.BufferedReader):
filename = filename_or_obj.name
# This is the appropriate constructor for io.BufferedReader
self.fileobj_type = open
else:
# use __class__ python <2.7?;
# http://docs.python.org/reference/datamodel.html
self.fileobj_type = filename_or_obj.__class__
if hasattr(filename_or_obj, "name"):
filename = filename_or_obj.name
elif hasattr(filename_or_obj, "filename"):
filename = (
filename_or_obj.filename # type: ignore[attr-defined]
)
else:
# e.g. came from BytesIO or something file-like
self.filename = filename_or_obj
self.timestamp = None
if filename:
self.filename = filename
if os.path.exists(filename):
statinfo = os.stat(filename)
self.timestamp = statinfo.st_mtime
def _copy_implementation(self, copy_function: Callable) -> "FileDataset":
"""Implementation of ``__copy__`` and ``__deepcopy__``.
Sets the filename to ``None`` if it isn't a string,
and copies all other attributes using `copy_function`.
"""
copied = self.__class__(
self.filename, self, self.preamble, self.file_meta,
self.is_implicit_VR, self.is_little_endian
)
filename = self.filename
if filename is not None and not isinstance(filename, str):
warnings.warn("The 'filename' attribute of the dataset is a "
"file-like object and will be set to None "
"in the copied object")
self.filename = None # type: ignore[assignment]
for (k, v) in self.__dict__.items():
copied.__dict__[k] = copy_function(v)
self.filename = filename
return copied
def __copy__(self) -> "FileDataset":
"""Return a shallow copy of the file dataset.
Make sure that the filename is not copied in case it is a file-like
object.
Returns
-------
FileDataset
A shallow copy of the file data set.
"""
return self._copy_implementation(copy.copy)
def __deepcopy__(self, _: Optional[Dict[int, Any]]) -> "FileDataset":
"""Return a deep copy of the file dataset.
Make sure that the filename is not copied in case it is a file-like
object.
Returns
-------
FileDataset
A deep copy of the file data set.
"""
return self._copy_implementation(copy.deepcopy)
def validate_file_meta(
file_meta: "FileMetaDataset", enforce_standard: bool = True
) -> None:
"""Validate the *File Meta Information* elements in `file_meta`.
.. versionchanged:: 1.2
Moved from :mod:`pydicom.filewriter`.
Parameters
----------
file_meta : Dataset
The *File Meta Information* data elements.
enforce_standard : bool, optional
If ``False``, then only a check for invalid elements is performed.
If ``True`` (default), the following elements will be added if not
already present:
* (0002,0001) *File Meta Information Version*
* (0002,0012) *Implementation Class UID*
* (0002,0013) *Implementation Version Name*
and the following elements will be checked:
* (0002,0002) *Media Storage SOP Class UID*
* (0002,0003) *Media Storage SOP Instance UID*
* (0002,0010) *Transfer Syntax UID*
Raises
------
ValueError
If `enforce_standard` is ``True`` and any of the checked *File Meta
Information* elements are missing from `file_meta`.
ValueError
If any non-Group 2 Elements are present in `file_meta`.
"""
# Check that no non-Group 2 Elements are present
for elem in file_meta.elements():
if elem.tag.group != 0x0002:
raise ValueError("Only File Meta Information Group (0002,eeee) "
"elements must be present in 'file_meta'.")
if enforce_standard:
if 'FileMetaInformationVersion' not in file_meta:
file_meta.FileMetaInformationVersion = b'\x00\x01'
if 'ImplementationClassUID' not in file_meta:
file_meta.ImplementationClassUID = UID(PYDICOM_IMPLEMENTATION_UID)
if 'ImplementationVersionName' not in file_meta:
file_meta.ImplementationVersionName = (
'PYDICOM ' + ".".join(str(x) for x in __version_info__))
# Check that required File Meta Information elements are present
missing = []
for element in [0x0002, 0x0003, 0x0010]:
if Tag(0x0002, element) not in file_meta:
missing.append(Tag(0x0002, element))
if missing:
msg = ("Missing required File Meta Information elements from "
"'file_meta':\n")
for tag in missing:
msg += '\t{0} {1}\n'.format(tag, keyword_for_tag(tag))
raise ValueError(msg[:-1]) # Remove final newline
class FileMetaDataset(Dataset):
"""Contains a collection (dictionary) of group 2 DICOM Data Elements.
.. versionadded:: 2.0
Derived from :class:`~pydicom.dataset.Dataset`, but only allows
Group 2 (File Meta Information) data elements
"""
def __init__(self, *args: _DatasetType, **kwargs: Any) -> None:
"""Initialize a FileMetaDataset
Parameters are as per :class:`Dataset`; this overrides the super class
only to check that all are group 2 data elements
Raises
------
ValueError
If any data elements are not group 2.
TypeError
If the passed argument is not a :class:`dict` or :class:`Dataset`
"""
super().__init__(*args, **kwargs)
FileMetaDataset.validate(self._dict)
# Set type hints for the possible contents - VR, Type (1|1C|3)
self.FileMetaInformationGroupLength: int # UL, 1
self.FileMetaInformationVersion: bytes # OB, 1
self.MediaStorageSOPClassUID: UID # UI, 1
self.MediaStorageSOPInstanceUID: UID # UI, 1
self.TransferSyntaxUID: UID # UI, 1
self.ImplementationClassUID: UID # UI, 1
self.ImplementationVersionName: Optional[str] # SH, 3
self.SourceApplicationEntityTitle: Optional[str] # AE, 3
self.SendingApplicationEntityTitle: Optional[str] # AE, 3
self.ReceivingApplicationEntityTitle: Optional[str] # AE, 3
self.SourcePresentationAddress: Optional[str] # UR, 3
self.ReceivingPresentationAddress: Optional[str] # UR, 3
self.PrivateInformationCreatorUID: Optional[UID] # UI, 3
self.PrivateInformation: bytes # OB, 1C
@staticmethod
def validate(init_value: _DatasetType) -> None:
"""Raise errors if initialization value is not acceptable for file_meta
Parameters
----------
init_value: dict or Dataset
The tag:data element pairs to initialize a file meta dataset
Raises
------
TypeError
If the passed argument is not a :class:`dict` or :class:`Dataset`
ValueError
If any data elements passed are not group 2.
"""
if init_value is None:
return
if not isinstance(init_value, (Dataset, dict)):
raise TypeError(
"Argument must be a dict or Dataset, not {}".format(
type(init_value)
)
)
non_group2 = [
Tag(tag) for tag in init_value.keys() if Tag(tag).group != 2
]
if non_group2:
msg = "Attempted to set non-group 2 elements: {}"
raise ValueError(msg.format(non_group2))
def __setitem__(
self, key: Union[slice, TagType], value: _DatasetValue
) -> None:
"""Override parent class to only allow setting of group 2 elements.
Parameters
----------
key : int or Tuple[int, int] or str
The tag for the element to be added to the Dataset.
value : dataelem.DataElement or dataelem.RawDataElement
The element to add to the :class:`FileMetaDataset`.
Raises
------
ValueError
If `key` is not a DICOM Group 2 tag.
"""
if isinstance(value.tag, BaseTag):
tag = value.tag
else:
tag = Tag(value.tag)
if tag.group != 2:
raise ValueError(
"Only group 2 data elements are allowed in a FileMetaDataset"
)
super().__setitem__(key, value)
_RE_CAMEL_CASE = re.compile(
# Ensure mix of upper and lowercase and digits, no underscores
# If first character is lowercase ensure at least one uppercase char
"(?P<start>(^[A-Za-z])((?=.+?[A-Z])[A-Za-z0-9]+)|(^[A-Z])([A-Za-z0-9]+))"
"(?P<last>[A-za-z0-9][^_]$)" # Last character is alphanumeric
)
| # Copyright 2008-2018 pydicom authors. See LICENSE file for details.
"""Define the Dataset and FileDataset classes.
The Dataset class represents the DICOM Dataset while the FileDataset class
adds extra functionality to Dataset when data is read from or written to file.
Overview of DICOM object model
------------------------------
Dataset (dict subclass)
Contains DataElement instances, each of which has a tag, VR, VM and value.
The DataElement value can be:
* A single value, such as a number, string, etc. (i.e. VM = 1)
* A list of numbers, strings, etc. (i.e. VM > 1)
* A Sequence (list subclass), where each item is a Dataset which
contains its own DataElements, and so on in a recursive manner.
"""
import copy
from bisect import bisect_left
import io
from importlib.util import find_spec as have_package
import inspect # for __dir__
from itertools import takewhile
import json
import os
import os.path
import re
from types import TracebackType
from typing import (
TYPE_CHECKING, Optional, Tuple, Union, List, Any, cast, Dict, ValuesView,
Iterator, BinaryIO, AnyStr, Callable, TypeVar, Type, overload,
MutableSequence, MutableMapping, AbstractSet
)
import warnings
import weakref
try:
import numpy
except ImportError:
pass
import pydicom # for dcmwrite
import pydicom.charset
import pydicom.config
from pydicom import jsonrep, config
from pydicom._version import __version_info__
from pydicom.charset import default_encoding, convert_encodings
from pydicom.config import logger
from pydicom.datadict import (
dictionary_VR, tag_for_keyword, keyword_for_tag, repeater_has_keyword
)
from pydicom.dataelem import DataElement, DataElement_from_raw, RawDataElement
from pydicom.encaps import encapsulate, encapsulate_extended
from pydicom.fileutil import path_from_pathlike
from pydicom.pixel_data_handlers.util import (
convert_color_space, reshape_pixel_array, get_image_pixel_ids
)
from pydicom.tag import Tag, BaseTag, tag_in_exception, TagType
from pydicom.uid import (
ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian,
RLELossless, PYDICOM_IMPLEMENTATION_UID, UID
)
from pydicom.waveforms import numpy_handler as wave_handler
class PrivateBlock:
"""Helper class for a private block in the :class:`Dataset`.
.. versionadded:: 1.3
See the DICOM Standard, Part 5,
:dcm:`Section 7.8.1<part05/sect_7.8.html#sect_7.8.1>` - Private Data
Element Tags
Attributes
----------
group : int
The private group where the private block is located as a 32-bit
:class:`int`.
private_creator : str
The private creator string related to the block.
dataset : Dataset
The parent dataset.
block_start : int
The start element of the private block as a 32-bit :class:`int`. Note
that the 2 low order hex digits of the element are always 0.
"""
def __init__(
self,
key: Tuple[int, str],
dataset: "Dataset",
private_creator_element: int
) -> None:
"""Initializes an object corresponding to a private tag block.
Parameters
----------
key : tuple
The private (tag group, creator) as ``(int, str)``. The group
must be an odd number.
dataset : Dataset
The parent :class:`Dataset`.
private_creator_element : int
The element of the private creator tag as a 32-bit :class:`int`.
"""
self.group = key[0]
self.private_creator = key[1]
self.dataset = dataset
self.block_start = private_creator_element << 8
def get_tag(self, element_offset: int) -> BaseTag:
"""Return the private tag ID for the given `element_offset`.
Parameters
----------
element_offset : int
The lower 16 bits (e.g. 2 hex numbers) of the element tag.
Returns
-------
The tag ID defined by the private block location and the
given element offset.
Raises
------
ValueError
If `element_offset` is too large.
"""
if element_offset > 0xff:
raise ValueError('Element offset must be less than 256')
return Tag(self.group, self.block_start + element_offset)
def __contains__(self, element_offset: int) -> bool:
"""Return ``True`` if the tag with given `element_offset` is in
the parent :class:`Dataset`.
"""
return self.get_tag(element_offset) in self.dataset
def __getitem__(self, element_offset: int) -> DataElement:
"""Return the data element in the parent dataset for the given element
offset.
Parameters
----------
element_offset : int
The lower 16 bits (e.g. 2 hex numbers) of the element tag.
Returns
-------
The data element of the tag in the parent dataset defined by the
private block location and the given element offset.
Raises
------
ValueError
If `element_offset` is too large.
KeyError
If no data element exists at that offset.
"""
return self.dataset.__getitem__(self.get_tag(element_offset))
def __delitem__(self, element_offset: int) -> None:
"""Delete the tag with the given `element_offset` from the dataset.
Parameters
----------
element_offset : int
The lower 16 bits (e.g. 2 hex numbers) of the element tag
to be deleted.
Raises
------
ValueError
If `element_offset` is too large.
KeyError
If no data element exists at that offset.
"""
del self.dataset[self.get_tag(element_offset)]
def add_new(self, element_offset: int, VR: str, value: object) -> None:
"""Add a private element to the parent :class:`Dataset`.
Adds the private tag with the given `VR` and `value` to the parent
:class:`Dataset` at the tag ID defined by the private block and the
given `element_offset`.
Parameters
----------
element_offset : int
The lower 16 bits (e.g. 2 hex numbers) of the element tag
to be added.
VR : str
The 2 character DICOM value representation.
value
The value of the data element. See :meth:`Dataset.add_new()`
for a description.
"""
tag = self.get_tag(element_offset)
self.dataset.add_new(tag, VR, value)
self.dataset[tag].private_creator = self.private_creator
def _dict_equal(
a: "Dataset", b: Any, exclude: Optional[List[str]] = None
) -> bool:
"""Common method for Dataset.__eq__ and FileDataset.__eq__
Uses .keys() as needed because Dataset iter return items not keys
`exclude` is used in FileDataset__eq__ ds.__dict__ compare, which
would also compare the wrapped _dict member (entire dataset) again.
"""
return (len(a) == len(b) and
all(key in b for key in a.keys()) and
all(a[key] == b[key] for key in a.keys()
if exclude is None or key not in exclude)
)
_DatasetValue = Union[DataElement, RawDataElement]
_DatasetType = Union["Dataset", MutableMapping[BaseTag, _DatasetValue]]
class Dataset:
"""A DICOM dataset as a mutable mapping of DICOM Data Elements.
Examples
--------
Add an element to the :class:`Dataset` (for elements in the DICOM
dictionary):
>>> ds = Dataset()
>>> ds.PatientName = "CITIZEN^Joan"
>>> ds.add_new(0x00100020, 'LO', '12345')
>>> ds[0x0010, 0x0030] = DataElement(0x00100030, 'DA', '20010101')
Add a sequence element to the :class:`Dataset`
>>> ds.BeamSequence = [Dataset(), Dataset(), Dataset()]
>>> ds.BeamSequence[0].Manufacturer = "Linac, co."
>>> ds.BeamSequence[1].Manufacturer = "Linac and Sons, co."
>>> ds.BeamSequence[2].Manufacturer = "Linac and Daughters, co."
Add private elements to the :class:`Dataset`
>>> block = ds.private_block(0x0041, 'My Creator', create=True)
>>> block.add_new(0x01, 'LO', '12345')
Updating and retrieving element values:
>>> ds.PatientName = "CITIZEN^Joan"
>>> ds.PatientName
'CITIZEN^Joan'
>>> ds.PatientName = "CITIZEN^John"
>>> ds.PatientName
'CITIZEN^John'
Retrieving an element's value from a Sequence:
>>> ds.BeamSequence[0].Manufacturer
'Linac, co.'
>>> ds.BeamSequence[1].Manufacturer
'Linac and Sons, co.'
Accessing the :class:`~pydicom.dataelem.DataElement` items:
>>> elem = ds['PatientName']
>>> elem
(0010, 0010) Patient's Name PN: 'CITIZEN^John'
>>> elem = ds[0x00100010]
>>> elem
(0010, 0010) Patient's Name PN: 'CITIZEN^John'
>>> elem = ds.data_element('PatientName')
>>> elem
(0010, 0010) Patient's Name PN: 'CITIZEN^John'
Accessing a private :class:`~pydicom.dataelem.DataElement`
item:
>>> block = ds.private_block(0x0041, 'My Creator')
>>> elem = block[0x01]
>>> elem
(0041, 1001) Private tag data LO: '12345'
>>> elem.value
'12345'
Alternatively:
>>> ds.get_private_item(0x0041, 0x01, 'My Creator').value
'12345'
Deleting an element from the :class:`Dataset`
>>> del ds.PatientID
>>> del ds.BeamSequence[1].Manufacturer
>>> del ds.BeamSequence[2]
Deleting a private element from the :class:`Dataset`
>>> block = ds.private_block(0x0041, 'My Creator')
>>> if 0x01 in block:
... del block[0x01]
Determining if an element is present in the :class:`Dataset`
>>> 'PatientName' in ds
True
>>> 'PatientID' in ds
False
>>> (0x0010, 0x0030) in ds
True
>>> 'Manufacturer' in ds.BeamSequence[0]
True
Iterating through the top level of a :class:`Dataset` only (excluding
Sequences):
>>> for elem in ds:
... print(elem)
(0010, 0010) Patient's Name PN: 'CITIZEN^John'
Iterating through the entire :class:`Dataset` (including Sequences):
>>> for elem in ds.iterall():
... print(elem)
(0010, 0010) Patient's Name PN: 'CITIZEN^John'
Recursively iterate through a :class:`Dataset` (including Sequences):
>>> def recurse(ds):
... for elem in ds:
... if elem.VR == 'SQ':
... [recurse(item) for item in elem]
... else:
... # Do something useful with each DataElement
Converting the :class:`Dataset` to and from JSON:
>>> ds = Dataset()
>>> ds.PatientName = "Some^Name"
>>> jsonmodel = ds.to_json()
>>> ds2 = Dataset()
>>> ds2.from_json(jsonmodel)
(0010, 0010) Patient's Name PN: 'Some^Name'
Attributes
----------
default_element_format : str
The default formatting for string display.
default_sequence_element_format : str
The default formatting for string display of sequences.
indent_chars : str
For string display, the characters used to indent nested Sequences.
Default is ``" "``.
is_little_endian : bool
Shall be set before writing with ``write_like_original=False``.
The :class:`Dataset` (excluding the pixel data) will be written using
the given endianess.
is_implicit_VR : bool
Shall be set before writing with ``write_like_original=False``.
The :class:`Dataset` will be written using the transfer syntax with
the given VR handling, e.g *Little Endian Implicit VR* if ``True``,
and *Little Endian Explicit VR* or *Big Endian Explicit VR* (depending
on ``Dataset.is_little_endian``) if ``False``.
"""
indent_chars = " "
def __init__(self, *args: _DatasetType, **kwargs: Any) -> None:
"""Create a new :class:`Dataset` instance."""
self._parent_encoding: List[str] = kwargs.get(
'parent_encoding', default_encoding
)
self._dict: MutableMapping[BaseTag, _DatasetValue]
if not args:
self._dict = {}
elif isinstance(args[0], Dataset):
self._dict = args[0]._dict
else:
self._dict = args[0]
self.is_decompressed = False
# the following read_XXX attributes are used internally to store
# the properties of the dataset after read from a file
# set depending on the endianess of the read dataset
self.read_little_endian: Optional[bool] = None
# set depending on the VR handling of the read dataset
self.read_implicit_vr: Optional[bool] = None
# The dataset's original character set encoding
self.read_encoding: Union[None, str, MutableSequence[str]] = None
self.is_little_endian: Optional[bool] = None
self.is_implicit_VR: Optional[bool] = None
# the parent data set, if this dataset is a sequence item
self.parent: "Optional[weakref.ReferenceType[Dataset]]" = None
# known private creator blocks
self._private_blocks: Dict[Tuple[int, str], PrivateBlock] = {}
self._pixel_array: Optional["numpy.ndarray"] = None
self._pixel_id: Dict[str, int] = {}
self.file_meta: FileMetaDataset
def __enter__(self) -> "Dataset":
"""Method invoked on entry to a with statement."""
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType]
) -> Optional[bool]:
"""Method invoked on exit from a with statement."""
# Returning anything other than True will re-raise any exceptions
return None
def add(self, data_element: DataElement) -> None:
"""Add an element to the :class:`Dataset`.
Equivalent to ``ds[data_element.tag] = data_element``
Parameters
----------
data_element : dataelem.DataElement
The :class:`~pydicom.dataelem.DataElement` to add.
"""
self[data_element.tag] = data_element
def add_new(self, tag: TagType, VR: str, value: Any) -> None:
"""Create a new element and add it to the :class:`Dataset`.
Parameters
----------
tag
The DICOM (group, element) tag in any form accepted by
:func:`~pydicom.tag.Tag` such as ``[0x0010, 0x0010]``,
``(0x10, 0x10)``, ``0x00100010``, etc.
VR : str
The 2 character DICOM value representation (see DICOM Standard,
Part 5, :dcm:`Section 6.2<part05/sect_6.2.html>`).
value
The value of the data element. One of the following:
* a single string or number
* a :class:`list` or :class:`tuple` with all strings or all numbers
* a multi-value string with backslash separator
* for a sequence element, an empty :class:`list` or ``list`` of
:class:`Dataset`
"""
data_element = DataElement(tag, VR, value)
# use data_element.tag since DataElement verified it
self._dict[data_element.tag] = data_element
def __array__(self) -> "numpy.ndarray":
"""Support accessing the dataset from a numpy array."""
return numpy.asarray(self._dict)
def data_element(self, name: str) -> Optional[DataElement]:
"""Return the element corresponding to the element keyword `name`.
Parameters
----------
name : str
A DICOM element keyword.
Returns
-------
dataelem.DataElement or None
For the given DICOM element `keyword`, return the corresponding
:class:`~pydicom.dataelem.DataElement` if present, ``None``
otherwise.
"""
tag = tag_for_keyword(name)
# Test against None as (0000,0000) is a possible tag
if tag is not None:
return self[tag]
return None
def __contains__(self, name: TagType) -> bool:
"""Simulate dict.__contains__() to handle DICOM keywords.
Examples
--------
>>> ds = Dataset()
>>> ds.SliceLocation = '2'
>>> 'SliceLocation' in ds
True
Parameters
----------
name : str or int or 2-tuple
The element keyword or tag to search for.
Returns
-------
bool
``True`` if the corresponding element is in the :class:`Dataset`,
``False`` otherwise.
"""
try:
return Tag(name) in self._dict
except Exception as exc:
msg = (
f"Invalid value '{name}' used with the 'in' operator: must be "
"an element tag as a 2-tuple or int, or an element keyword"
)
if isinstance(exc, OverflowError):
msg = (
"Invalid element tag value used with the 'in' operator: "
"tags have a maximum value of (0xFFFF, 0xFFFF)"
)
if config.INVALID_KEY_BEHAVIOR == "WARN":
warnings.warn(msg)
elif config.INVALID_KEY_BEHAVIOR == "RAISE":
raise ValueError(msg) from exc
return False
def decode(self) -> None:
"""Apply character set decoding to the elements in the
:class:`Dataset`.
See DICOM Standard, Part 5,
:dcm:`Section 6.1.1<part05/chapter_6.html#sect_6.1.1>`.
"""
# Find specific character set. 'ISO_IR 6' is default
# May be multi-valued, but let pydicom.charset handle all logic on that
dicom_character_set = self._character_set
# Shortcut to the decode function in pydicom.charset
decode_data_element = pydicom.charset.decode_element
# Callback for walk(), to decode the chr strings if necessary
# This simply calls the pydicom.charset.decode_element function
def decode_callback(ds: "Dataset", data_element: DataElement) -> None:
"""Callback to decode `data_element`."""
if data_element.VR == 'SQ':
for dset in data_element.value:
dset._parent_encoding = dicom_character_set
dset.decode()
else:
decode_data_element(data_element, dicom_character_set)
self.walk(decode_callback, recursive=False)
def copy(self) -> "Dataset":
"""Return a shallow copy of the dataset."""
return copy.copy(self)
def __delattr__(self, name: str) -> None:
"""Intercept requests to delete an attribute by `name`.
Examples
--------
>>> ds = Dataset()
>>> ds.PatientName = 'foo'
>>> ds.some_attribute = True
If `name` is a DICOM keyword - delete the corresponding
:class:`~pydicom.dataelem.DataElement`
>>> del ds.PatientName
>>> 'PatientName' in ds
False
If `name` is another attribute - delete it
>>> del ds.some_attribute
>>> hasattr(ds, 'some_attribute')
False
Parameters
----------
name : str
The keyword for the DICOM element or the class attribute to delete.
"""
# First check if a valid DICOM keyword and if we have that data element
tag = cast(BaseTag, tag_for_keyword(name))
if tag is not None and tag in self._dict:
del self._dict[tag]
# If not a DICOM name in this dataset, check for regular instance name
# can't do delete directly, that will call __delattr__ again
elif name in self.__dict__:
del self.__dict__[name]
# Not found, raise an error in same style as python does
else:
raise AttributeError(name)
def __delitem__(self, key: Union[slice, BaseTag, TagType]) -> None:
"""Intercept requests to delete an attribute by key.
Examples
--------
Indexing using :class:`~pydicom.dataelem.DataElement` tag
>>> ds = Dataset()
>>> ds.CommandGroupLength = 100
>>> ds.PatientName = 'CITIZEN^Jan'
>>> del ds[0x00000000]
>>> ds
(0010, 0010) Patient's Name PN: 'CITIZEN^Jan'
Slicing using :class:`~pydicom.dataelem.DataElement` tag
>>> ds = Dataset()
>>> ds.CommandGroupLength = 100
>>> ds.SOPInstanceUID = '1.2.3'
>>> ds.PatientName = 'CITIZEN^Jan'
>>> del ds[:0x00100000]
>>> ds
(0010, 0010) Patient's Name PN: 'CITIZEN^Jan'
Parameters
----------
key
The key for the attribute to be deleted. If a ``slice`` is used
then the tags matching the slice conditions will be deleted.
"""
# If passed a slice, delete the corresponding DataElements
if isinstance(key, slice):
for tag in self._slice_dataset(key.start, key.stop, key.step):
del self._dict[tag]
# invalidate private blocks in case a private creator is
# deleted - will be re-created on next access
if self._private_blocks and BaseTag(tag).is_private_creator:
self._private_blocks = {}
elif isinstance(key, BaseTag):
del self._dict[key]
if self._private_blocks and key.is_private_creator:
self._private_blocks = {}
else:
# If not a standard tag, than convert to Tag and try again
tag = Tag(key)
del self._dict[tag]
if self._private_blocks and tag.is_private_creator:
self._private_blocks = {}
def __dir__(self) -> List[str]:
"""Give a list of attributes available in the :class:`Dataset`.
List of attributes is used, for example, in auto-completion in editors
or command-line environments.
"""
# Force zip object into a list
meths = set(list(zip(
*inspect.getmembers(self.__class__, inspect.isroutine)))[0])
props = set(list(zip(
*inspect.getmembers(self.__class__, inspect.isdatadescriptor)))[0])
dicom_names = set(self.dir())
alldir = sorted(props | meths | dicom_names)
return alldir
def dir(self, *filters: str) -> List[str]:
"""Return an alphabetical list of element keywords in the
:class:`Dataset`.
Intended mainly for use in interactive Python sessions. Only lists the
element keywords in the current level of the :class:`Dataset` (i.e.
the contents of any sequence elements are ignored).
Parameters
----------
filters : str
Zero or more string arguments to the function. Used for
case-insensitive match to any part of the DICOM keyword.
Returns
-------
list of str
The matching element keywords in the dataset. If no
filters are used then all element keywords are returned.
"""
allnames = [keyword_for_tag(tag) for tag in self._dict.keys()]
# remove blanks - tags without valid names (e.g. private tags)
allnames = [x for x in allnames if x]
# Store found names in a dict, so duplicate names appear only once
matches = {}
for filter_ in filters:
filter_ = filter_.lower()
match = [x for x in allnames if x.lower().find(filter_) != -1]
matches.update({x: 1 for x in match})
if filters:
return sorted(matches.keys())
return sorted(allnames)
def __eq__(self, other: Any) -> bool:
"""Compare `self` and `other` for equality.
Returns
-------
bool
The result if `self` and `other` are the same class
NotImplemented
If `other` is not the same class as `self` then returning
:class:`NotImplemented` delegates the result to
``superclass.__eq__(subclass)``.
"""
# When comparing against self this will be faster
if other is self:
return True
if isinstance(other, self.__class__):
return _dict_equal(self, other)
return NotImplemented
@overload
def get(self, key: str, default: Optional[Any] = None) -> Any:
pass # pragma: no cover
@overload
def get(
self,
key: Union[int, Tuple[int, int], BaseTag],
default: Optional[Any] = None
) -> DataElement:
pass # pragma: no cover
def get(
self,
key: Union[str, Union[int, Tuple[int, int], BaseTag]],
default: Optional[Any] = None
) -> Union[Any, DataElement]:
"""Simulate ``dict.get()`` to handle element tags and keywords.
Parameters
----------
key : str or int or Tuple[int, int] or BaseTag
The element keyword or tag or the class attribute name to get.
default : obj or None, optional
If the element or class attribute is not present, return
`default` (default ``None``).
Returns
-------
value
If `key` is the keyword for an element in the :class:`Dataset`
then return the element's value.
dataelem.DataElement
If `key` is a tag for a element in the :class:`Dataset` then
return the :class:`~pydicom.dataelem.DataElement`
instance.
value
If `key` is a class attribute then return its value.
"""
if isinstance(key, str):
try:
return getattr(self, key)
except AttributeError:
return default
# is not a string, try to make it into a tag and then hand it
# off to the underlying dict
try:
key = Tag(key)
except Exception as exc:
raise TypeError("Dataset.get key must be a string or tag") from exc
try:
return self.__getitem__(key)
except KeyError:
return default
def items(self) -> AbstractSet[Tuple[BaseTag, _DatasetValue]]:
"""Return the :class:`Dataset` items to simulate :meth:`dict.items`.
Returns
-------
dict_items
The top-level (:class:`~pydicom.tag.BaseTag`,
:class:`~pydicom.dataelem.DataElement`) items for the
:class:`Dataset`.
"""
return self._dict.items()
def keys(self) -> AbstractSet[BaseTag]:
"""Return the :class:`Dataset` keys to simulate :meth:`dict.keys`.
Returns
-------
dict_keys
The :class:`~pydicom.tag.BaseTag` of all the elements in
the :class:`Dataset`.
"""
return self._dict.keys()
def values(self) -> ValuesView[_DatasetValue]:
"""Return the :class:`Dataset` values to simulate :meth:`dict.values`.
Returns
-------
dict_keys
The :class:`DataElements<pydicom.dataelem.DataElement>` that make
up the values of the :class:`Dataset`.
"""
return self._dict.values()
def __getattr__(self, name: str) -> Any:
"""Intercept requests for :class:`Dataset` attribute names.
If `name` matches a DICOM keyword, return the value for the
element with the corresponding tag.
Parameters
----------
name : str
An element keyword or a class attribute name.
Returns
-------
value
If `name` matches a DICOM keyword, returns the corresponding
element's value. Otherwise returns the class attribute's
value (if present).
"""
tag = tag_for_keyword(name)
if tag is not None: # `name` isn't a DICOM element keyword
tag = Tag(tag)
if tag in self._dict: # DICOM DataElement not in the Dataset
return self[tag].value
# no tag or tag not contained in the dataset
if name == '_dict':
# special handling for contained dict, needed for pickle
return {}
# Try the base class attribute getter (fix for issue 332)
return object.__getattribute__(self, name)
@property
def _character_set(self) -> List[str]:
"""The character set used to encode text values."""
char_set = self.get(BaseTag(0x00080005), None)
if not char_set:
return self._parent_encoding
return convert_encodings(char_set.value)
@overload
def __getitem__(self, key: slice) -> "Dataset":
pass # pragma: no cover
@overload
def __getitem__(self, key: TagType) -> DataElement:
pass # pragma: no cover
def __getitem__(
self, key: Union[slice, TagType]
) -> Union["Dataset", DataElement]:
"""Operator for ``Dataset[key]`` request.
Any deferred data elements will be read in and an attempt will be made
to correct any elements with ambiguous VRs.
Examples
--------
Indexing using :class:`~pydicom.dataelem.DataElement` tag
>>> ds = Dataset()
>>> ds.SOPInstanceUID = '1.2.3'
>>> ds.PatientName = 'CITIZEN^Jan'
>>> ds.PatientID = '12345'
>>> ds[0x00100010].value
'CITIZEN^Jan'
Slicing using element tags; all group ``0x0010`` elements in
the dataset
>>> ds[0x00100000:0x00110000]
(0010, 0010) Patient's Name PN: 'CITIZEN^Jan'
(0010, 0020) Patient ID LO: '12345'
All group ``0x0002`` elements in the dataset
>>> ds[(0x0002, 0x0000):(0x0003, 0x0000)]
<BLANKLINE>
Parameters
----------
key
The DICOM (group, element) tag in any form accepted by
:func:`~pydicom.tag.Tag` such as ``[0x0010, 0x0010]``,
``(0x10, 0x10)``, ``0x00100010``, etc. May also be a :class:`slice`
made up of DICOM tags.
Returns
-------
dataelem.DataElement or Dataset
If a single DICOM element tag is used then returns the
corresponding :class:`~pydicom.dataelem.DataElement`.
If a :class:`slice` is used then returns a :class:`Dataset` object
containing the corresponding
:class:`DataElements<pydicom.dataelem.DataElement>`.
"""
# If passed a slice, return a Dataset containing the corresponding
# DataElements
if isinstance(key, slice):
return self._dataset_slice(key)
if isinstance(key, BaseTag):
tag = key
else:
try:
tag = Tag(key)
except Exception as exc:
raise KeyError(f"'{key}'") from exc
elem = self._dict[tag]
if isinstance(elem, DataElement):
if elem.VR == 'SQ' and elem.value:
# let a sequence know its parent dataset, as sequence items
# may need parent dataset tags to resolve ambiguous tags
elem.value.parent = self
return elem
if isinstance(elem, RawDataElement):
# If a deferred read, then go get the value now
if elem.value is None and elem.length != 0:
from pydicom.filereader import read_deferred_data_element
elem = read_deferred_data_element(
self.fileobj_type,
self.filename,
self.timestamp,
elem
)
if tag != BaseTag(0x00080005):
character_set = self.read_encoding or self._character_set
else:
character_set = default_encoding
# Not converted from raw form read from file yet; do so now
self[tag] = DataElement_from_raw(elem, character_set, self)
# If the Element has an ambiguous VR, try to correct it
if 'or' in self[tag].VR:
from pydicom.filewriter import correct_ambiguous_vr_element
self[tag] = correct_ambiguous_vr_element(
self[tag], self, elem[6]
)
return cast(DataElement, self._dict.get(tag))
def private_block(
self, group: int, private_creator: str, create: bool = False
) -> PrivateBlock:
"""Return the block for the given tag `group` and `private_creator`.
.. versionadded:: 1.3
If `create` is ``True`` and the `private_creator` does not exist,
the private creator tag is added.
Notes
-----
We ignore the unrealistic case that no free block is available.
Parameters
----------
group : int
The group of the private tag to be found as a 32-bit :class:`int`.
Must be an odd number (e.g. a private group).
private_creator : str
The private creator string associated with the tag.
create : bool, optional
If ``True`` and `private_creator` does not exist, a new private
creator tag is added at the next free block. If ``False``
(the default) and `private_creator` does not exist,
:class:`KeyError` is raised instead.
Returns
-------
PrivateBlock
The existing or newly created private block.
Raises
------
ValueError
If `group` doesn't belong to a private tag or `private_creator`
is empty.
KeyError
If the private creator tag is not found in the given group and
the `create` parameter is ``False``.
"""
def new_block(element: int) -> PrivateBlock:
block = PrivateBlock(key, self, element)
self._private_blocks[key] = block
return block
key = (group, private_creator)
if key in self._private_blocks:
return self._private_blocks[key]
if not private_creator:
raise ValueError('Private creator must have a value')
if group % 2 == 0:
raise ValueError(
'Tag must be private if private creator is given')
# find block with matching private creator
block = self[(group, 0x10):(group, 0x100)] # type: ignore[misc]
data_el = next(
(
elem for elem in block if elem.value == private_creator
),
None
)
if data_el is not None:
return new_block(data_el.tag.element)
if not create:
# not found and shall not be created - raise
raise KeyError(
"Private creator '{}' not found".format(private_creator))
# private creator not existing - find first unused private block
# and add the private creator
first_free_el = next(
el for el in range(0x10, 0x100)
if Tag(group, el) not in self._dict
)
self.add_new(Tag(group, first_free_el), 'LO', private_creator)
return new_block(first_free_el)
def private_creators(self, group: int) -> List[str]:
"""Return a list of private creator names in the given group.
.. versionadded:: 1.3
Examples
--------
This can be used to check if a given private creator exists in
the group of the dataset:
>>> ds = Dataset()
>>> if 'My Creator' in ds.private_creators(0x0041):
... block = ds.private_block(0x0041, 'My Creator')
Parameters
----------
group : int
The private group as a 32-bit :class:`int`. Must be an odd number.
Returns
-------
list of str
All private creator names for private blocks in the group.
Raises
------
ValueError
If `group` is not a private group.
"""
if group % 2 == 0:
raise ValueError('Group must be an odd number')
block = self[(group, 0x10):(group, 0x100)] # type: ignore[misc]
return [x.value for x in block]
def get_private_item(
self, group: int, element_offset: int, private_creator: str
) -> DataElement:
"""Return the data element for the given private tag `group`.
.. versionadded:: 1.3
This is analogous to ``Dataset.__getitem__()``, but only for private
tags. This allows to find the private tag for the correct private
creator without the need to add the tag to the private dictionary
first.
Parameters
----------
group : int
The private tag group where the item is located as a 32-bit int.
element_offset : int
The lower 16 bits (e.g. 2 hex numbers) of the element tag.
private_creator : str
The private creator for the tag. Must match the private creator
for the tag to be returned.
Returns
-------
dataelem.DataElement
The corresponding element.
Raises
------
ValueError
If `group` is not part of a private tag or `private_creator` is
empty.
KeyError
If the private creator tag is not found in the given group.
If the private tag is not found.
"""
block = self.private_block(group, private_creator)
return self.__getitem__(block.get_tag(element_offset))
@overload
def get_item(self, key: slice) -> "Dataset":
pass # pragma: no cover
@overload
def get_item(self, key: TagType) -> DataElement:
pass # pragma: no cover
def get_item(
self, key: Union[slice, TagType]
) -> Union["Dataset", DataElement, RawDataElement, None]:
"""Return the raw data element if possible.
It will be raw if the user has never accessed the value, or set their
own value. Note if the data element is a deferred-read element,
then it is read and converted before being returned.
Parameters
----------
key
The DICOM (group, element) tag in any form accepted by
:func:`~pydicom.tag.Tag` such as ``[0x0010, 0x0010]``,
``(0x10, 0x10)``, ``0x00100010``, etc. May also be a :class:`slice`
made up of DICOM tags.
Returns
-------
dataelem.DataElement
The corresponding element.
"""
if isinstance(key, slice):
return self._dataset_slice(key)
elem = self._dict.get(Tag(key))
# If a deferred read, return using __getitem__ to read and convert it
if isinstance(elem, RawDataElement) and elem.value is None:
return self[key]
return elem
def _dataset_slice(self, slce: slice) -> "Dataset":
"""Return a slice that has the same properties as the original dataset.
That includes properties related to endianess and VR handling,
and the specific character set. No element conversion is done, e.g.
elements of type ``RawDataElement`` are kept.
"""
tags = self._slice_dataset(slce.start, slce.stop, slce.step)
ds = Dataset({tag: self.get_item(tag) for tag in tags})
ds.is_little_endian = self.is_little_endian
ds.is_implicit_VR = self.is_implicit_VR
ds.set_original_encoding(
self.read_implicit_vr, self.read_little_endian, self.read_encoding
)
return ds
@property
def is_original_encoding(self) -> bool:
"""Return ``True`` if the encoding to be used for writing is set and
is the same as that used to originally encode the :class:`Dataset`.
.. versionadded:: 1.1
This includes properties related to endianess, VR handling and the
(0008,0005) *Specific Character Set*.
"""
return (
self.is_implicit_VR is not None
and self.is_little_endian is not None
and self.read_implicit_vr == self.is_implicit_VR
and self.read_little_endian == self.is_little_endian
and self.read_encoding == self._character_set
)
def set_original_encoding(
self,
is_implicit_vr: Optional[bool],
is_little_endian: Optional[bool],
character_encoding: Union[None, str, MutableSequence[str]]
) -> None:
"""Set the values for the original transfer syntax and encoding.
.. versionadded:: 1.2
Can be used for a :class:`Dataset` with raw data elements to enable
optimized writing (e.g. without decoding the data elements).
"""
self.read_implicit_vr = is_implicit_vr
self.read_little_endian = is_little_endian
self.read_encoding = character_encoding
def group_dataset(self, group: int) -> "Dataset":
"""Return a :class:`Dataset` containing only elements of a certain
group.
Parameters
----------
group : int
The group part of a DICOM (group, element) tag.
Returns
-------
Dataset
A :class:`Dataset` containing elements of the group specified.
"""
return self[(group, 0x0000):(group + 1, 0x0000)] # type: ignore[misc]
def __iter__(self) -> Iterator[DataElement]:
"""Iterate through the top-level of the Dataset, yielding DataElements.
Examples
--------
>>> ds = Dataset()
>>> for elem in ds:
... print(elem)
The :class:`DataElements<pydicom.dataelem.DataElement>` are returned in
increasing tag value order. Sequence items are returned as a single
:class:`~pydicom.dataelem.DataElement`, so it is up
to the calling code to recurse into the Sequence items if desired.
Yields
------
dataelem.DataElement
The :class:`Dataset`'s
:class:`DataElements<pydicom.dataelem.DataElement>`, sorted by
increasing tag order.
"""
# Note this is different than the underlying dict class,
# which returns the key of the key:value mapping.
# Here the value is returned (but data_element.tag has the key)
taglist = sorted(self._dict.keys())
for tag in taglist:
yield self[tag]
def elements(self) -> Iterator[DataElement]:
"""Yield the top-level elements of the :class:`Dataset`.
.. versionadded:: 1.1
Examples
--------
>>> ds = Dataset()
>>> for elem in ds.elements():
... print(elem)
The elements are returned in the same way as in
``Dataset.__getitem__()``.
Yields
------
dataelem.DataElement or dataelem.RawDataElement
The unconverted elements sorted by increasing tag order.
"""
taglist = sorted(self._dict.keys())
for tag in taglist:
yield self.get_item(tag)
def __len__(self) -> int:
"""Return the number of elements in the top level of the dataset."""
return len(self._dict)
def __ne__(self, other: Any) -> bool:
"""Compare `self` and `other` for inequality."""
return not self == other
def clear(self) -> None:
"""Delete all the elements from the :class:`Dataset`."""
self._dict.clear()
def pop(self, key: Union[BaseTag, TagType], *args: Any) -> _DatasetValue:
"""Emulate :meth:`dict.pop` with support for tags and keywords.
Removes the element for `key` if it exists and returns it,
otherwise returns a default value if given or raises :class:`KeyError`.
Parameters
----------
key : int or str or 2-tuple
* If :class:`tuple` - the group and element number of the DICOM tag
* If :class:`int` - the combined group/element number
* If :class:`str` - the DICOM keyword of the tag
*args : zero or one argument
Defines the behavior if no tag exists for `key`: if given,
it defines the return value, if not given, :class:`KeyError` is
raised
Returns
-------
RawDataElement or DataElement
The element for `key` if it exists, or the default value if given.
Raises
------
KeyError
If the `key` is not a valid tag or keyword.
If the tag does not exist and no default is given.
"""
try:
key = Tag(key)
except Exception:
pass
return self._dict.pop(cast(BaseTag, key), *args)
def popitem(self) -> Tuple[BaseTag, _DatasetValue]:
"""Emulate :meth:`dict.popitem`.
Returns
-------
tuple of (BaseTag, DataElement)
"""
return self._dict.popitem()
def setdefault(
self, key: TagType, default: Optional[Any] = None
) -> DataElement:
"""Emulate :meth:`dict.setdefault` with support for tags and keywords.
Examples
--------
>>> ds = Dataset()
>>> elem = ds.setdefault((0x0010, 0x0010), "Test")
>>> elem
(0010, 0010) Patient's Name PN: 'Test'
>>> elem.value
'Test'
>>> elem = ds.setdefault('PatientSex',
... DataElement(0x00100040, 'CS', 'F'))
>>> elem.value
'F'
Parameters
----------
key : int, str or 2-tuple of int
* If :class:`tuple` - the group and element number of the DICOM tag
* If :class:`int` - the combined group/element number
* If :class:`str` - the DICOM keyword of the tag
default : pydicom.dataelem.DataElement or object, optional
The :class:`~pydicom.dataelem.DataElement` to use with `key`, or
the value of the :class:`~pydicom.dataelem.DataElement` to use with
`key` (default ``None``).
Returns
-------
pydicom.dataelem.DataElement or object
The :class:`~pydicom.dataelem.DataElement` for `key`.
Raises
------
ValueError
If `key` is not convertible to a valid tag or a known element
keyword.
KeyError
If :attr:`~pydicom.config.enforce_valid_values` is ``True`` and
`key` is an unknown non-private tag.
"""
tag = Tag(key)
if tag in self:
return self[tag]
if not isinstance(default, DataElement):
if tag.is_private:
vr = 'UN'
else:
try:
vr = dictionary_VR(tag)
except KeyError:
if config.enforce_valid_values:
raise KeyError(f"Unknown DICOM tag {tag}")
else:
vr = 'UN'
warnings.warn(
f"Unknown DICOM tag {tag} - setting VR to 'UN'"
)
default = DataElement(tag, vr, default)
self[key] = default
return default
def convert_pixel_data(self, handler_name: str = '') -> None:
"""Convert pixel data to a :class:`numpy.ndarray` internally.
Parameters
----------
handler_name : str, optional
The name of the pixel handler that shall be used to
decode the data. Supported names are: ``'gdcm'``,
``'pillow'``, ``'jpeg_ls'``, ``'rle'``, ``'numpy'`` and
``'pylibjpeg'``. If not used (the default), a matching handler is
used from the handlers configured in
:attr:`~pydicom.config.pixel_data_handlers`.
Returns
-------
None
Converted pixel data is stored internally in the dataset.
Raises
------
ValueError
If `handler_name` is not a valid handler name.
NotImplementedError
If the given handler or any handler, if none given, is unable to
decompress pixel data with the current transfer syntax
RuntimeError
If the given handler, or the handler that has been selected if
none given, is not available.
Notes
-----
If the pixel data is in a compressed image format, the data is
decompressed and any related data elements are changed accordingly.
"""
# Check if already have converted to a NumPy array
# Also check if pixel data has changed. If so, get new NumPy array
already_have = True
if not hasattr(self, "_pixel_array"):
already_have = False
elif self._pixel_id != get_image_pixel_ids(self):
already_have = False
if already_have:
return
if handler_name:
self._convert_pixel_data_using_handler(handler_name)
else:
self._convert_pixel_data_without_handler()
def _convert_pixel_data_using_handler(self, name: str) -> None:
"""Convert the pixel data using handler with the given name.
See :meth:`~Dataset.convert_pixel_data` for more information.
"""
# handle some variations in name
handler_name = name.lower()
if not handler_name.endswith('_handler'):
handler_name += '_handler'
if handler_name == 'numpy_handler':
handler_name = 'np_handler'
if handler_name == 'jpeg_ls_handler':
# the name in config differs from the actual handler name
# we allow both
handler_name = 'jpegls_handler'
if not hasattr(pydicom.config, handler_name):
raise ValueError(f"'{name}' is not a known handler name")
handler = getattr(pydicom.config, handler_name)
tsyntax = self.file_meta.TransferSyntaxUID
if not handler.supports_transfer_syntax(tsyntax):
raise NotImplementedError(
"Unable to decode pixel data with a transfer syntax UID"
f" of '{tsyntax}' ({tsyntax.name}) using the pixel data "
f"handler '{name}'. Please see the pydicom documentation for "
"information on supported transfer syntaxes."
)
if not handler.is_available():
raise RuntimeError(
f"The pixel data handler '{name}' is not available on your "
"system. Please refer to the pydicom documentation for "
"information on installing needed packages."
)
# if the conversion fails, the exception is propagated up
self._do_pixel_data_conversion(handler)
def _convert_pixel_data_without_handler(self) -> None:
"""Convert the pixel data using the first matching handler.
See :meth:`~Dataset.convert_pixel_data` for more information.
"""
# Find all possible handlers that support the transfer syntax
ts = self.file_meta.TransferSyntaxUID
possible_handlers = [
hh for hh in pydicom.config.pixel_data_handlers
if hh is not None
and hh.supports_transfer_syntax(ts) # type: ignore[attr-defined]
]
# No handlers support the transfer syntax
if not possible_handlers:
raise NotImplementedError(
"Unable to decode pixel data with a transfer syntax UID of "
f"'{ts}' ({ts.name}) as there are no pixel data "
"handlers available that support it. Please see the pydicom "
"documentation for information on supported transfer syntaxes "
)
# Handlers that both support the transfer syntax and have their
# dependencies met
available_handlers = [
hh for hh in possible_handlers
if hh.is_available() # type: ignore[attr-defined]
]
# There are handlers that support the transfer syntax but none of them
# can be used as missing dependencies
if not available_handlers:
# For each of the possible handlers we want to find which
# dependencies are missing
msg = (
"The following handlers are available to decode the pixel "
"data however they are missing required dependencies: "
)
pkg_msg = []
for hh in possible_handlers:
hh_deps = hh.DEPENDENCIES # type: ignore[attr-defined]
# Missing packages
missing = [dd for dd in hh_deps if have_package(dd) is None]
# Package names
names = [hh_deps[name][1] for name in missing]
pkg_msg.append(
f"{hh.HANDLER_NAME} " # type: ignore[attr-defined]
f"(req. {', '.join(names)})"
)
raise RuntimeError(msg + ', '.join(pkg_msg))
last_exception = None
for handler in available_handlers:
try:
self._do_pixel_data_conversion(handler)
return
except Exception as exc:
logger.debug(
"Exception raised by pixel data handler", exc_info=exc
)
last_exception = exc
# The only way to get to this point is if we failed to get the pixel
# array because all suitable handlers raised exceptions
self._pixel_array = None
self._pixel_id = {}
logger.info(
"Unable to decode the pixel data using the following handlers: {}."
"Please see the list of supported Transfer Syntaxes in the "
"pydicom documentation for alternative packages that might "
"be able to decode the data"
.format(", ".join([str(hh) for hh in available_handlers]))
)
raise last_exception # type: ignore[misc]
def _do_pixel_data_conversion(self, handler: Any) -> None:
"""Do the actual data conversion using the given handler."""
# Use the handler to get a 1D numpy array of the pixel data
# Will raise an exception if no pixel data element
arr = handler.get_pixeldata(self)
self._pixel_array = reshape_pixel_array(self, arr)
# Some handler/transfer syntax combinations may need to
# convert the color space from YCbCr to RGB
if handler.needs_to_convert_to_RGB(self):
self._pixel_array = convert_color_space(
self._pixel_array, 'YBR_FULL', 'RGB'
)
self._pixel_id = get_image_pixel_ids(self)
def compress(
self,
transfer_syntax_uid: str,
arr: Optional["numpy.ndarray"] = None,
encoding_plugin: str = '',
decoding_plugin: str = '',
encapsulate_ext: bool = False,
**kwargs: Any,
) -> None:
"""Compress and update an uncompressed dataset in-place with the
resulting :dcm:`encapsulated<part05/sect_A.4.html>` pixel data.
.. versionadded:: 2.2
The dataset must already have the following
:dcm:`Image Pixel<part03/sect_C.7.6.3.html>` module elements present
with correct values that correspond to the resulting compressed
pixel data:
* (0028,0002) *Samples per Pixel*
* (0028,0004) *Photometric Interpretation*
* (0028,0008) *Number of Frames* (if more than 1 frame will be present)
* (0028,0010) *Rows*
* (0028,0011) *Columns*
* (0028,0100) *Bits Allocated*
* (0028,0101) *Bits Stored*
* (0028,0103) *Pixel Representation*
This method will add the file meta dataset if none is present and add
or modify the following elements:
* (0002,0010) *Transfer Syntax UID*
* (7FE0,0010) *Pixel Data*
If *Samples per Pixel* is greater than 1 then the following element
will also be added:
* (0028,0006) *Planar Configuration*
If the compressed pixel data is too large for encapsulation using a
basic offset table then an :dcm:`extended offset table
<part03/sect_C.7.6.3.html>` will also be used, in which case the
following elements will also be added:
* (7FE0,0001) *Extended Offset Table*
* (7FE0,0002) *Extended Offset Table Lengths*
**Supported Transfer Syntax UIDs**
+----------------------+----------+----------------------------------+
| UID | Plugins | Encoding Guide |
+======================+==========+==================================+
| *RLE Lossless* - |pydicom, | :doc:`RLE Lossless |
| 1.2.840.10008.1.2.5 |pylibjpeg,| </guides/encoding/rle_lossless>` |
| |gdcm | |
+----------------------+----------+----------------------------------+
Examples
--------
Compress the existing uncompressed *Pixel Data* in place:
>>> from pydicom.data import get_testdata_file
>>> from pydicom.uid import RLELossless
>>> ds = get_testdata_file("CT_small.dcm", read=True)
>>> ds.compress(RLELossless)
>>> ds.save_as("CT_small_rle.dcm")
Parameters
----------
transfer_syntax_uid : pydicom.uid.UID
The UID of the :dcm:`transfer syntax<part05/chapter_10.html>` to
use when compressing the pixel data.
arr : numpy.ndarray, optional
Compress the uncompressed pixel data in `arr` and use it
to set the *Pixel Data*. If `arr` is not used then the
existing *Pixel Data* in the dataset will be compressed instead.
The :attr:`~numpy.ndarray.shape`, :class:`~numpy.dtype` and
contents of the array should match the dataset.
encoding_plugin : str, optional
Use the `encoding_plugin` to compress the pixel data. See the
:doc:`user guide </old/image_data_compression>` for a list of
plugins available for each UID and their dependencies. If not
specified then all available plugins will be tried (default).
decoding_plugin : str, optional
Placeholder for future functionality.
encapsulate_ext : bool, optional
If ``True`` then force the addition of an extended offset table.
If ``False`` (default) then an extended offset table
will be added if needed for large amounts of compressed *Pixel
Data*, otherwise just the basic offset table will be used.
**kwargs
Optional keyword parameters for the encoding plugin may also be
present. See the :doc:`encoding plugins options
</guides/encoding/encoder_plugin_options>` for more information.
"""
from pydicom.encoders import get_encoder
uid = UID(transfer_syntax_uid)
# Raises NotImplementedError if `uid` is not supported
encoder = get_encoder(uid)
if not encoder.is_available:
missing = "\n".join(
[f" {s}" for s in encoder.missing_dependencies]
)
raise RuntimeError(
f"The '{uid.name}' encoder is unavailable because its "
f"encoding plugins are missing dependencies:\n"
f"{missing}"
)
if arr is None:
# Encode the current *Pixel Data*
frame_iterator = encoder.iter_encode(
self,
encoding_plugin=encoding_plugin,
decoding_plugin=decoding_plugin,
**kwargs
)
else:
# Encode from an uncompressed pixel data array
kwargs.update(encoder.kwargs_from_ds(self))
frame_iterator = encoder.iter_encode(
arr,
encoding_plugin=encoding_plugin,
**kwargs
)
# Encode!
encoded = [f for f in frame_iterator]
# Encapsulate the encoded *Pixel Data*
nr_frames = getattr(self, "NumberOfFrames", 1) or 1
total = (nr_frames - 1) * 8 + sum([len(f) for f in encoded[:-1]])
if encapsulate_ext or total > 2**32 - 1:
(self.PixelData,
self.ExtendedOffsetTable,
self.ExtendedOffsetTableLengths) = encapsulate_extended(encoded)
else:
self.PixelData = encapsulate(encoded)
self['PixelData'].is_undefined_length = True
# Set the correct *Transfer Syntax UID*
if not hasattr(self, 'file_meta'):
self.file_meta = FileMetaDataset()
self.file_meta.TransferSyntaxUID = uid
# Add or update any other required elements
if self.SamplesPerPixel > 1:
self.PlanarConfiguration: int = 1 if uid == RLELossless else 0
def decompress(self, handler_name: str = '') -> None:
"""Decompresses *Pixel Data* and modifies the :class:`Dataset`
in-place.
.. versionadded:: 1.4
The `handler_name` keyword argument was added
If not a compressed transfer syntax, then pixel data is converted
to a :class:`numpy.ndarray` internally, but not returned.
If compressed pixel data, then is decompressed using an image handler,
and internal state is updated appropriately:
- ``Dataset.file_meta.TransferSyntaxUID`` is updated to non-compressed
form
- :attr:`~pydicom.dataelem.DataElement.is_undefined_length`
is ``False`` for the (7FE0,0010) *Pixel Data* element.
.. versionchanged:: 1.4
The `handler_name` keyword argument was added
Parameters
----------
handler_name : str, optional
The name of the pixel handler that shall be used to
decode the data. Supported names are: ``'gdcm'``,
``'pillow'``, ``'jpeg_ls'``, ``'rle'``, ``'numpy'`` and
``'pylibjpeg'``.
If not used (the default), a matching handler is used from the
handlers configured in :attr:`~pydicom.config.pixel_data_handlers`.
Returns
-------
None
Raises
------
NotImplementedError
If the pixel data was originally compressed but file is not
*Explicit VR Little Endian* as required by the DICOM Standard.
"""
self.convert_pixel_data(handler_name)
self.is_decompressed = True
# May have been undefined length pixel data, but won't be now
if 'PixelData' in self:
self[0x7fe00010].is_undefined_length = False
# Make sure correct Transfer Syntax is set
# According to the dicom standard PS3.5 section A.4,
# all compressed files must have been explicit VR, little endian
# First check if was a compressed file
if (
hasattr(self, 'file_meta')
and self.file_meta.TransferSyntaxUID.is_compressed
):
# Check that current file as read does match expected
if not self.is_little_endian or self.is_implicit_VR:
msg = ("Current dataset does not match expected ExplicitVR "
"LittleEndian transfer syntax from a compressed "
"transfer syntax")
raise NotImplementedError(msg)
# All is as expected, updated the Transfer Syntax
self.file_meta.TransferSyntaxUID = ExplicitVRLittleEndian
def overlay_array(self, group: int) -> "numpy.ndarray":
"""Return the *Overlay Data* in `group` as a :class:`numpy.ndarray`.
.. versionadded:: 1.4
Parameters
----------
group : int
The group number of the overlay data.
Returns
-------
numpy.ndarray
The (`group`,3000) *Overlay Data* converted to a
:class:`numpy.ndarray`.
"""
if group < 0x6000 or group > 0x60FF:
raise ValueError(
"The group part of the 'Overlay Data' element tag must be "
"between 0x6000 and 0x60FF (inclusive)"
)
from pydicom.config import overlay_data_handlers
available_handlers = [
hh for hh in overlay_data_handlers
if hh.is_available() # type: ignore[attr-defined]
]
if not available_handlers:
# For each of the handlers we want to find which
# dependencies are missing
msg = (
"The following handlers are available to decode the overlay "
"data however they are missing required dependencies: "
)
pkg_msg = []
for hh in overlay_data_handlers:
hh_deps = hh.DEPENDENCIES # type: ignore[attr-defined]
# Missing packages
missing = [dd for dd in hh_deps if have_package(dd) is None]
# Package names
names = [hh_deps[name][1] for name in missing]
pkg_msg.append(
f"{hh.HANDLER_NAME} " # type: ignore[attr-defined]
f"(req. {', '.join(names)})"
)
raise RuntimeError(msg + ', '.join(pkg_msg))
last_exception = None
for handler in available_handlers:
try:
# Use the handler to get an ndarray of the pixel data
func = handler.get_overlay_array # type: ignore[attr-defined]
return cast("numpy.ndarray", func(self, group))
except Exception as exc:
logger.debug(
"Exception raised by overlay data handler", exc_info=exc
)
last_exception = exc
logger.info(
"Unable to decode the overlay data using the following handlers: "
"{}. Please see the list of supported Transfer Syntaxes in the "
"pydicom documentation for alternative packages that might "
"be able to decode the data"
.format(", ".join([str(hh) for hh in available_handlers]))
)
raise last_exception # type: ignore[misc]
@property
def pixel_array(self) -> "numpy.ndarray":
"""Return the pixel data as a :class:`numpy.ndarray`.
.. versionchanged:: 1.4
Added support for *Float Pixel Data* and *Double Float Pixel Data*
Returns
-------
numpy.ndarray
The (7FE0,0008) *Float Pixel Data*, (7FE0,0009) *Double Float
Pixel Data* or (7FE0,0010) *Pixel Data* converted to a
:class:`numpy.ndarray`.
"""
self.convert_pixel_data()
return cast("numpy.ndarray", self._pixel_array)
def waveform_array(self, index: int) -> "numpy.ndarray":
"""Return an :class:`~numpy.ndarray` for the multiplex group at
`index` in the (5400,0100) *Waveform Sequence*.
.. versionadded:: 2.1
Parameters
----------
index : int
The index of the multiplex group to return the array for.
Returns
------
numpy.ndarray
The *Waveform Data* for the multiplex group as an
:class:`~numpy.ndarray` with shape (samples, channels). If
(003A,0210) *Channel Sensitivity* is present
then the values will be in the units specified by the (003A,0211)
*Channel Sensitivity Units Sequence*.
See Also
--------
:func:`~pydicom.waveforms.numpy_handler.generate_multiplex`
:func:`~pydicom.waveforms.numpy_handler.multiplex_array`
"""
if not wave_handler.is_available():
raise RuntimeError("The waveform data handler requires numpy")
return wave_handler.multiplex_array(self, index, as_raw=False)
# Format strings spec'd according to python string formatting options
# See http://docs.python.org/library/stdtypes.html#string-formatting-operations # noqa
default_element_format = "%(tag)s %(name)-35.35s %(VR)s: %(repval)s"
default_sequence_element_format = "%(tag)s %(name)-35.35s %(VR)s: %(repval)s" # noqa
def formatted_lines(
self,
element_format: str = default_element_format,
sequence_element_format: str = default_sequence_element_format,
indent_format: Optional[str] = None
) -> Iterator[str]:
"""Iterate through the :class:`Dataset` yielding formatted :class:`str`
for each element.
Parameters
----------
element_format : str
The string format to use for non-sequence elements. Formatting uses
the attributes of
:class:`~pydicom.dataelem.DataElement`. Default is
``"%(tag)s %(name)-35.35s %(VR)s: %(repval)s"``.
sequence_element_format : str
The string format to use for sequence elements. Formatting uses
the attributes of
:class:`~pydicom.dataelem.DataElement`. Default is
``"%(tag)s %(name)-35.35s %(VR)s: %(repval)s"``
indent_format : str or None
Placeholder for future functionality.
Yields
------
str
A string representation of an element.
"""
exclusion = ('from_json', 'to_json', 'to_json_dict', 'clear')
for elem in self.iterall():
# Get all the attributes possible for this data element (e.g.
# gets descriptive text name too)
# This is the dictionary of names that can be used in the format
# string
elem_dict = {
attr: (
getattr(elem, attr)() if callable(getattr(elem, attr))
else getattr(elem, attr)
)
for attr in dir(elem) if not attr.startswith("_")
and attr not in exclusion
}
if elem.VR == "SQ":
yield sequence_element_format % elem_dict
else:
yield element_format % elem_dict
def _pretty_str(
self, indent: int = 0, top_level_only: bool = False
) -> str:
"""Return a string of the DataElements in the Dataset, with indented
levels.
This private method is called by the ``__str__()`` method for handling
print statements or ``str(dataset)``, and the ``__repr__()`` method.
It is also used by ``top()``, therefore the `top_level_only` flag.
This function recurses, with increasing indentation levels.
..versionchanged:: 2.0
The file meta information is returned in its own section,
if :data:`~pydicom.config.show_file_meta` is ``True`` (default)
Parameters
----------
indent : int, optional
The indent level offset (default ``0``).
top_level_only : bool, optional
When True, only create a string for the top level elements, i.e.
exclude elements within any Sequences (default ``False``).
Returns
-------
str
A string representation of the Dataset.
"""
strings = []
indent_str = self.indent_chars * indent
nextindent_str = self.indent_chars * (indent + 1)
# Display file meta, if configured to do so, and have a non-empty one
if (
hasattr(self, "file_meta") and self.file_meta
and pydicom.config.show_file_meta
):
strings.append(f"{'Dataset.file_meta ':-<49}")
for elem in self.file_meta:
with tag_in_exception(elem.tag):
strings.append(indent_str + repr(elem))
strings.append(f"{'':-<49}")
for elem in self:
with tag_in_exception(elem.tag):
if elem.VR == "SQ": # a sequence
strings.append(
f"{indent_str}{str(elem.tag)} {elem.description()} "
f"{len(elem.value)} item(s) ---- "
)
if not top_level_only:
for dataset in elem.value:
strings.append(dataset._pretty_str(indent + 1))
strings.append(nextindent_str + "---------")
else:
strings.append(indent_str + repr(elem))
return "\n".join(strings)
def remove_private_tags(self) -> None:
"""Remove all private elements from the :class:`Dataset`."""
def remove_callback(dataset: "Dataset", elem: DataElement) -> None:
"""Internal method to use as callback to walk() method."""
if elem.tag.is_private:
# can't del self[tag] - won't be right dataset on recursion
del dataset[elem.tag]
self.walk(remove_callback)
def save_as(
self,
filename: Union[str, "os.PathLike[AnyStr]", BinaryIO],
write_like_original: bool = True
) -> None:
"""Write the :class:`Dataset` to `filename`.
Wrapper for pydicom.filewriter.dcmwrite, passing this dataset to it.
See documentation for that function for details.
See Also
--------
pydicom.filewriter.dcmwrite
Write a DICOM file from a :class:`FileDataset` instance.
"""
pydicom.dcmwrite(filename, self, write_like_original)
def ensure_file_meta(self) -> None:
"""Create an empty ``Dataset.file_meta`` if none exists.
.. versionadded:: 1.2
"""
# Changed in v2.0 so does not re-assign self.file_meta with getattr()
if not hasattr(self, "file_meta"):
self.file_meta = FileMetaDataset()
def fix_meta_info(self, enforce_standard: bool = True) -> None:
"""Ensure the file meta info exists and has the correct values
for transfer syntax and media storage UIDs.
.. versionadded:: 1.2
.. warning::
The transfer syntax for ``is_implicit_VR = False`` and
``is_little_endian = True`` is ambiguous and will therefore not
be set.
Parameters
----------
enforce_standard : bool, optional
If ``True``, a check for incorrect and missing elements is
performed (see :func:`~validate_file_meta`).
"""
self.ensure_file_meta()
if self.is_little_endian and self.is_implicit_VR:
self.file_meta.TransferSyntaxUID = ImplicitVRLittleEndian
elif not self.is_little_endian and not self.is_implicit_VR:
self.file_meta.TransferSyntaxUID = ExplicitVRBigEndian
elif not self.is_little_endian and self.is_implicit_VR:
raise NotImplementedError("Implicit VR Big Endian is not a "
"supported Transfer Syntax.")
if 'SOPClassUID' in self:
self.file_meta.MediaStorageSOPClassUID = self.SOPClassUID
if 'SOPInstanceUID' in self:
self.file_meta.MediaStorageSOPInstanceUID = self.SOPInstanceUID
if enforce_standard:
validate_file_meta(self.file_meta, enforce_standard=True)
def __setattr__(self, name: str, value: Any) -> None:
"""Intercept any attempts to set a value for an instance attribute.
If name is a DICOM keyword, set the corresponding tag and DataElement.
Else, set an instance (python) attribute as any other class would do.
Parameters
----------
name : str
The keyword for the element you wish to add/change. If
`name` is not a DICOM element keyword then this will be the
name of the attribute to be added/changed.
value
The value for the attribute to be added/changed.
"""
tag = tag_for_keyword(name)
if tag is not None: # successfully mapped name to a tag
if tag not in self:
# don't have this tag yet->create the data_element instance
VR = dictionary_VR(tag)
data_element = DataElement(tag, VR, value)
if VR == 'SQ':
# let a sequence know its parent dataset to pass it
# to its items, who may need parent dataset tags
# to resolve ambiguous tags
data_element.parent = self
else:
# already have this data_element, just changing its value
data_element = self[tag]
data_element.value = value
# Now have data_element - store it in this dict
self[tag] = data_element
elif repeater_has_keyword(name):
# Check if `name` is repeaters element
raise ValueError(
f"'{name}' is a DICOM repeating group element and must be "
"added using the add() or add_new() methods."
)
elif name == "file_meta":
self._set_file_meta(value)
else:
# Warn if `name` is camel case but not a keyword
if _RE_CAMEL_CASE.match(name):
msg = (
f"Camel case attribute '{name}' used which is not in the "
"element keyword data dictionary"
)
if config.INVALID_KEYWORD_BEHAVIOR == "WARN":
warnings.warn(msg)
elif config.INVALID_KEYWORD_BEHAVIOR == "RAISE":
raise ValueError(msg)
# name not in dicom dictionary - setting a non-dicom instance
# attribute
# XXX note if user mis-spells a dicom data_element - no error!!!
object.__setattr__(self, name, value)
def _set_file_meta(self, value: Optional["Dataset"]) -> None:
if value is not None and not isinstance(value, FileMetaDataset):
if config._use_future:
raise TypeError(
"Pydicom Future: Dataset.file_meta must be an instance "
"of FileMetaDataset"
)
FileMetaDataset.validate(value)
warnings.warn(
"Starting in pydicom 3.0, Dataset.file_meta must be a "
"FileMetaDataset class instance",
DeprecationWarning
)
self.__dict__["file_meta"] = value
def __setitem__(
self, key: Union[slice, TagType], elem: _DatasetValue
) -> None:
"""Operator for ``Dataset[key] = elem``.
Parameters
----------
key : int or Tuple[int, int] or str
The tag for the element to be added to the :class:`Dataset`.
elem : dataelem.DataElement or dataelem.RawDataElement
The element to add to the :class:`Dataset`.
Raises
------
NotImplementedError
If `key` is a :class:`slice`.
ValueError
If the `key` value doesn't match the corresponding
:attr:`DataElement.tag<pydicom.dataelem.tag>`.
"""
if isinstance(key, slice):
raise NotImplementedError(
'Slicing is not supported when setting Dataset items'
)
try:
key = Tag(key)
except Exception as exc:
raise ValueError(
f"Unable to convert the key '{key}' to an element tag"
) from exc
if not isinstance(elem, (DataElement, RawDataElement)):
raise TypeError("Dataset items must be 'DataElement' instances")
if isinstance(elem.tag, BaseTag):
elem_tag = elem.tag
else:
elem_tag = Tag(elem.tag)
if key != elem_tag:
raise ValueError(
f"The key '{key}' doesn't match the 'DataElement' tag "
f"'{elem_tag}'"
)
if elem_tag.is_private:
# See PS 3.5-2008 section 7.8.1 (p. 44) for how blocks are reserved
logger.debug(f"Setting private tag {elem_tag}")
private_block = elem_tag.element >> 8
private_creator_tag = Tag(elem_tag.group, private_block)
if private_creator_tag in self and elem_tag != private_creator_tag:
if isinstance(elem, RawDataElement):
elem = DataElement_from_raw(
elem, self._character_set, self
)
elem.private_creator = self[private_creator_tag].value
self._dict[elem_tag] = elem
def _slice_dataset(
self,
start: Optional[TagType],
stop: Optional[TagType],
step: Optional[int]
) -> List[BaseTag]:
"""Return the element tags in the Dataset that match the slice.
Parameters
----------
start : int or 2-tuple of int or None
The slice's starting element tag value, in any format accepted by
:func:`~pydicom.tag.Tag`.
stop : int or 2-tuple of int or None
The slice's stopping element tag value, in any format accepted by
:func:`~pydicom.tag.Tag`.
step : int or None
The slice's step size.
Returns
------
list of BaseTag
The tags in the :class:`Dataset` that meet the conditions of the
slice.
"""
# Check the starting/stopping Tags are valid when used
if start is not None:
start = Tag(start)
if stop is not None:
stop = Tag(stop)
all_tags = sorted(self._dict.keys())
# If the Dataset is empty, return an empty list
if not all_tags:
return []
# Special case the common situations:
# - start and/or stop are None
# - step is 1
if start is None:
if stop is None:
# For step=1 avoid copying the list
return all_tags if step == 1 else all_tags[::step]
else: # Have a stop value, get values until that point
step1_list = list(takewhile(lambda x: x < stop, all_tags))
return step1_list if step == 1 else step1_list[::step]
# Have a non-None start value. Find its index
i_start = bisect_left(all_tags, start)
if stop is None:
return all_tags[i_start::step]
i_stop = bisect_left(all_tags, stop)
return all_tags[i_start:i_stop:step]
def __str__(self) -> str:
"""Handle str(dataset).
..versionchanged:: 2.0
The file meta information was added in its own section,
if :data:`pydicom.config.show_file_meta` is ``True``
"""
return self._pretty_str()
def top(self) -> str:
"""Return a :class:`str` representation of the top level elements. """
return self._pretty_str(top_level_only=True)
def trait_names(self) -> List[str]:
"""Return a :class:`list` of valid names for auto-completion code.
Used in IPython, so that data element names can be found and offered
for autocompletion on the IPython command line.
"""
return dir(self)
def update(self, d: _DatasetType) -> None:
"""Extend :meth:`dict.update` to handle DICOM tags and keywords.
Parameters
----------
dictionary : dict or Dataset
The :class:`dict` or :class:`Dataset` to use when updating the
current object.
"""
for key, value in list(d.items()):
if isinstance(key, str):
setattr(self, key, value)
else:
self[Tag(cast(int, key))] = value
def iterall(self) -> Iterator[DataElement]:
"""Iterate through the :class:`Dataset`, yielding all the elements.
Unlike ``iter(Dataset)``, this *does* recurse into sequences,
and so yields all elements as if dataset were "flattened".
Yields
------
dataelem.DataElement
"""
for elem in self:
yield elem
if elem.VR == "SQ":
for ds in elem.value:
yield from ds.iterall()
def walk(
self,
callback: Callable[["Dataset", DataElement], None],
recursive: bool = True
) -> None:
"""Iterate through the :class:`Dataset's<Dataset>` elements and run
`callback` on each.
Visit all elements in the :class:`Dataset`, possibly recursing into
sequences and their items. The `callback` function is called for each
:class:`~pydicom.dataelem.DataElement` (including elements
with a VR of 'SQ'). Can be used to perform an operation on certain
types of elements.
For example,
:meth:`~Dataset.remove_private_tags` finds all elements with private
tags and deletes them.
The elements will be returned in order of increasing tag number within
their current :class:`Dataset`.
Parameters
----------
callback
A callable function that takes two arguments:
* a :class:`Dataset`
* a :class:`~pydicom.dataelem.DataElement` belonging
to that :class:`Dataset`
recursive : bool, optional
Flag to indicate whether to recurse into sequences (default
``True``).
"""
taglist = sorted(self._dict.keys())
for tag in taglist:
with tag_in_exception(tag):
data_element = self[tag]
callback(self, data_element) # self = this Dataset
# 'tag in self' below needed in case callback deleted
# data_element
if recursive and tag in self and data_element.VR == "SQ":
sequence = data_element.value
for dataset in sequence:
dataset.walk(callback)
@classmethod
def from_json(
cls: Type["Dataset"],
json_dataset: Union[Dict[str, Any], str, bytes, bytearray],
bulk_data_uri_handler: Optional[
Union[
Callable[[str, str, str], Union[None, str, int, float, bytes]],
Callable[[str], Union[None, str, int, float, bytes]]
]
] = None
) -> "Dataset":
"""Return a :class:`Dataset` from a DICOM JSON Model object.
.. versionadded:: 1.3
See the DICOM Standard, Part 18, :dcm:`Annex F<part18/chapter_F.html>`.
Parameters
----------
json_dataset : dict, str, bytes or bytearray
:class:`dict`, :class:`str`, :class:`bytes` or :class:`bytearray`
representing a DICOM Data Set formatted based on the :dcm:`DICOM
JSON Model<part18/chapter_F.html>`.
bulk_data_uri_handler : callable, optional
Callable function that accepts either the tag, vr and
"BulkDataURI" value or just the "BulkDataURI" value of the JSON
representation of a data element and returns the actual value of
that data element (retrieved via DICOMweb WADO-RS). If no
`bulk_data_uri_handler` is specified (default) then the
corresponding element will have an "empty" value such as
``""``, ``b""`` or ``None`` depending on the `vr` (i.e. the
Value Multiplicity will be 0).
Returns
-------
Dataset
"""
if isinstance(json_dataset, (str, bytes, bytearray)):
json_dataset = cast(Dict[str, Any], json.loads(json_dataset))
dataset = cls()
for tag, mapping in json_dataset.items():
# `tag` is an element tag in uppercase hex format as a str
# `mapping` is Dict[str, Any] and should have keys 'vr' and at most
# one of ('Value', 'BulkDataURI', 'InlineBinary') but may have
# none of those if the element's VM is 0
vr = mapping['vr']
unique_value_keys = tuple(
set(mapping.keys()) & set(jsonrep.JSON_VALUE_KEYS)
)
if len(unique_value_keys) == 0:
value_key = None
value = ['']
else:
value_key = unique_value_keys[0]
value = mapping[value_key]
data_element = DataElement.from_json(
cls, tag, vr, value, value_key, bulk_data_uri_handler
)
dataset.add(data_element)
return dataset
def to_json_dict(
self,
bulk_data_threshold: int = 1024,
bulk_data_element_handler: Optional[Callable[[DataElement], str]] = None, # noqa
suppress_invalid_tags: bool = False,
) -> Dict[str, Any]:
"""Return a dictionary representation of the :class:`Dataset`
conforming to the DICOM JSON Model as described in the DICOM
Standard, Part 18, :dcm:`Annex F<part18/chapter_F.html>`.
.. versionadded:: 1.4
Parameters
----------
bulk_data_threshold : int, optional
Threshold for the length of a base64-encoded binary data element
above which the element should be considered bulk data and the
value provided as a URI rather than included inline (default:
``1024``). Ignored if no bulk data handler is given.
bulk_data_element_handler : callable, optional
Callable function that accepts a bulk data element and returns a
JSON representation of the data element (dictionary including the
"vr" key and either the "InlineBinary" or the "BulkDataURI" key).
suppress_invalid_tags : bool, optional
Flag to specify if errors while serializing tags should be logged
and the tag dropped or if the error should be bubbled up.
Returns
-------
dict
:class:`Dataset` representation based on the DICOM JSON Model.
"""
json_dataset = {}
for key in self.keys():
json_key = '{:08X}'.format(key)
data_element = self[key]
try:
json_dataset[json_key] = data_element.to_json_dict(
bulk_data_element_handler=bulk_data_element_handler,
bulk_data_threshold=bulk_data_threshold
)
except Exception as exc:
logger.error(f"Error while processing tag {json_key}")
if not suppress_invalid_tags:
raise exc
return json_dataset
def to_json(
self,
bulk_data_threshold: int = 1024,
bulk_data_element_handler: Optional[Callable[[DataElement], str]] = None, # noqa
dump_handler: Optional[Callable[[Dict[str, Any]], str]] = None,
suppress_invalid_tags: bool = False,
) -> str:
"""Return a JSON representation of the :class:`Dataset`.
.. versionadded:: 1.3
See the DICOM Standard, Part 18, :dcm:`Annex F<part18/chapter_F.html>`.
Parameters
----------
bulk_data_threshold : int, optional
Threshold for the length of a base64-encoded binary data element
above which the element should be considered bulk data and the
value provided as a URI rather than included inline (default:
``1024``). Ignored if no bulk data handler is given.
bulk_data_element_handler : callable, optional
Callable function that accepts a bulk data element and returns a
JSON representation of the data element (dictionary including the
"vr" key and either the "InlineBinary" or the "BulkDataURI" key).
dump_handler : callable, optional
Callable function that accepts a :class:`dict` and returns the
serialized (dumped) JSON string (by default uses
:func:`json.dumps`).
.. note:
Make sure to use a dump handler that sorts the keys (see
example below) to create DICOM-conformant JSON.
suppress_invalid_tags : bool, optional
Flag to specify if errors while serializing tags should be logged
and the tag dropped or if the error should be bubbled up.
Returns
-------
str
:class:`Dataset` serialized into a string based on the DICOM JSON
Model.
Examples
--------
>>> def my_json_dumps(data):
... return json.dumps(data, indent=4, sort_keys=True)
>>> ds.to_json(dump_handler=my_json_dumps)
"""
if dump_handler is None:
def json_dump(d: Any) -> str:
return json.dumps(d, sort_keys=True)
dump_handler = json_dump
return dump_handler(
self.to_json_dict(
bulk_data_threshold,
bulk_data_element_handler,
suppress_invalid_tags=suppress_invalid_tags
)
)
def __getstate__(self) -> Dict[str, Any]:
# pickle cannot handle weakref - remove parent
d = self.__dict__.copy()
del d['parent']
return d
def __setstate__(self, state: Dict[str, Any]) -> None:
self.__dict__.update(state)
# re-add parent - it will be set to the parent dataset on demand
# if the dataset is in a sequence
self.__dict__['parent'] = None
__repr__ = __str__
_FileDataset = TypeVar("_FileDataset", bound="FileDataset")
class FileDataset(Dataset):
"""An extension of :class:`Dataset` to make reading and writing to
file-like easier.
Attributes
----------
preamble : str or bytes or None
The optional DICOM preamble prepended to the :class:`FileDataset`, if
available.
file_meta : FileMetaDataset or None
The Dataset's file meta information as a :class:`FileMetaDataset`,
if available (``None`` if not present).
Consists of group ``0x0002`` elements.
filename : str or None
The filename that the :class:`FileDataset` was read from (if read from
file) or ``None`` if the filename is not available (if read from a
:class:`io.BytesIO` or similar).
fileobj_type
The object type of the file-like the :class:`FileDataset` was read
from.
is_implicit_VR : bool
``True`` if the dataset encoding is implicit VR, ``False`` otherwise.
is_little_endian : bool
``True`` if the dataset encoding is little endian byte ordering,
``False`` otherwise.
timestamp : float or None
The modification time of the file the :class:`FileDataset` was read
from, ``None`` if the modification time is not available.
"""
def __init__(
self,
filename_or_obj: Union[str, "os.PathLike[AnyStr]", BinaryIO],
dataset: _DatasetType,
preamble: Optional[bytes] = None,
file_meta: Optional["FileMetaDataset"] = None,
is_implicit_VR: bool = True,
is_little_endian: bool = True
) -> None:
"""Initialize a :class:`FileDataset` read from a DICOM file.
Parameters
----------
filename_or_obj : str or PathLike or BytesIO or None
Full path and filename to the file, memory buffer object, or
``None`` if is a :class:`io.BytesIO`.
dataset : Dataset or dict
Some form of dictionary, usually a :class:`Dataset` returned from
:func:`~pydicom.filereader.dcmread`.
preamble : bytes or str, optional
The 128-byte DICOM preamble.
file_meta : FileMetaDataset, optional
The file meta :class:`FileMetaDataset`, such as the one returned by
:func:`~pydicom.filereader.read_file_meta_info`, or an empty
:class:`FileMetaDataset` if no file meta information is in the
file.
is_implicit_VR : bool, optional
``True`` (default) if implicit VR transfer syntax used; ``False``
if explicit VR.
is_little_endian : bool
``True`` (default) if little-endian transfer syntax used; ``False``
if big-endian.
"""
Dataset.__init__(self, dataset)
self.preamble = preamble
self.file_meta: "FileMetaDataset" = (
file_meta if file_meta is not None else FileMetaDataset()
)
self.is_implicit_VR: bool = is_implicit_VR
self.is_little_endian: bool = is_little_endian
filename: Optional[str] = None
filename_or_obj = path_from_pathlike(filename_or_obj)
self.fileobj_type: Any
self.filename: Union[str, BinaryIO]
if isinstance(filename_or_obj, str):
filename = filename_or_obj
self.fileobj_type = open
elif isinstance(filename_or_obj, io.BufferedReader):
filename = filename_or_obj.name
# This is the appropriate constructor for io.BufferedReader
self.fileobj_type = open
else:
# use __class__ python <2.7?;
# http://docs.python.org/reference/datamodel.html
self.fileobj_type = filename_or_obj.__class__
if hasattr(filename_or_obj, "name"):
filename = filename_or_obj.name
elif hasattr(filename_or_obj, "filename"):
filename = (
filename_or_obj.filename # type: ignore[attr-defined]
)
else:
# e.g. came from BytesIO or something file-like
self.filename = filename_or_obj
self.timestamp = None
if filename:
self.filename = filename
if os.path.exists(filename):
statinfo = os.stat(filename)
self.timestamp = statinfo.st_mtime
def _copy_implementation(self, copy_function: Callable) -> "FileDataset":
"""Implementation of ``__copy__`` and ``__deepcopy__``.
Sets the filename to ``None`` if it isn't a string,
and copies all other attributes using `copy_function`.
"""
copied = self.__class__(
self.filename, self, self.preamble, self.file_meta,
self.is_implicit_VR, self.is_little_endian
)
filename = self.filename
if filename is not None and not isinstance(filename, str):
warnings.warn("The 'filename' attribute of the dataset is a "
"file-like object and will be set to None "
"in the copied object")
self.filename = None # type: ignore[assignment]
for (k, v) in self.__dict__.items():
copied.__dict__[k] = copy_function(v)
self.filename = filename
return copied
def __copy__(self) -> "FileDataset":
"""Return a shallow copy of the file dataset.
Make sure that the filename is not copied in case it is a file-like
object.
Returns
-------
FileDataset
A shallow copy of the file data set.
"""
return self._copy_implementation(copy.copy)
def __deepcopy__(self, _: Optional[Dict[int, Any]]) -> "FileDataset":
"""Return a deep copy of the file dataset.
Make sure that the filename is not copied in case it is a file-like
object.
Returns
-------
FileDataset
A deep copy of the file data set.
"""
return self._copy_implementation(copy.deepcopy)
def validate_file_meta(
file_meta: "FileMetaDataset", enforce_standard: bool = True
) -> None:
"""Validate the *File Meta Information* elements in `file_meta`.
.. versionchanged:: 1.2
Moved from :mod:`pydicom.filewriter`.
Parameters
----------
file_meta : Dataset
The *File Meta Information* data elements.
enforce_standard : bool, optional
If ``False``, then only a check for invalid elements is performed.
If ``True`` (default), the following elements will be added if not
already present:
* (0002,0001) *File Meta Information Version*
* (0002,0012) *Implementation Class UID*
* (0002,0013) *Implementation Version Name*
and the following elements will be checked:
* (0002,0002) *Media Storage SOP Class UID*
* (0002,0003) *Media Storage SOP Instance UID*
* (0002,0010) *Transfer Syntax UID*
Raises
------
ValueError
If `enforce_standard` is ``True`` and any of the checked *File Meta
Information* elements are missing from `file_meta`.
ValueError
If any non-Group 2 Elements are present in `file_meta`.
"""
# Check that no non-Group 2 Elements are present
for elem in file_meta.elements():
if elem.tag.group != 0x0002:
raise ValueError("Only File Meta Information Group (0002,eeee) "
"elements must be present in 'file_meta'.")
if enforce_standard:
if 'FileMetaInformationVersion' not in file_meta:
file_meta.FileMetaInformationVersion = b'\x00\x01'
if 'ImplementationClassUID' not in file_meta:
file_meta.ImplementationClassUID = UID(PYDICOM_IMPLEMENTATION_UID)
if 'ImplementationVersionName' not in file_meta:
file_meta.ImplementationVersionName = (
'PYDICOM ' + ".".join(str(x) for x in __version_info__))
# Check that required File Meta Information elements are present
missing = []
for element in [0x0002, 0x0003, 0x0010]:
if Tag(0x0002, element) not in file_meta:
missing.append(Tag(0x0002, element))
if missing:
msg = ("Missing required File Meta Information elements from "
"'file_meta':\n")
for tag in missing:
msg += '\t{0} {1}\n'.format(tag, keyword_for_tag(tag))
raise ValueError(msg[:-1]) # Remove final newline
class FileMetaDataset(Dataset):
"""Contains a collection (dictionary) of group 2 DICOM Data Elements.
.. versionadded:: 2.0
Derived from :class:`~pydicom.dataset.Dataset`, but only allows
Group 2 (File Meta Information) data elements
"""
def __init__(self, *args: _DatasetType, **kwargs: Any) -> None:
"""Initialize a FileMetaDataset
Parameters are as per :class:`Dataset`; this overrides the super class
only to check that all are group 2 data elements
Raises
------
ValueError
If any data elements are not group 2.
TypeError
If the passed argument is not a :class:`dict` or :class:`Dataset`
"""
super().__init__(*args, **kwargs)
FileMetaDataset.validate(self._dict)
# Set type hints for the possible contents - VR, Type (1|1C|3)
self.FileMetaInformationGroupLength: int # UL, 1
self.FileMetaInformationVersion: bytes # OB, 1
self.MediaStorageSOPClassUID: UID # UI, 1
self.MediaStorageSOPInstanceUID: UID # UI, 1
self.TransferSyntaxUID: UID # UI, 1
self.ImplementationClassUID: UID # UI, 1
self.ImplementationVersionName: Optional[str] # SH, 3
self.SourceApplicationEntityTitle: Optional[str] # AE, 3
self.SendingApplicationEntityTitle: Optional[str] # AE, 3
self.ReceivingApplicationEntityTitle: Optional[str] # AE, 3
self.SourcePresentationAddress: Optional[str] # UR, 3
self.ReceivingPresentationAddress: Optional[str] # UR, 3
self.PrivateInformationCreatorUID: Optional[UID] # UI, 3
self.PrivateInformation: bytes # OB, 1C
@staticmethod
def validate(init_value: _DatasetType) -> None:
"""Raise errors if initialization value is not acceptable for file_meta
Parameters
----------
init_value: dict or Dataset
The tag:data element pairs to initialize a file meta dataset
Raises
------
TypeError
If the passed argument is not a :class:`dict` or :class:`Dataset`
ValueError
If any data elements passed are not group 2.
"""
if init_value is None:
return
if not isinstance(init_value, (Dataset, dict)):
raise TypeError(
"Argument must be a dict or Dataset, not {}".format(
type(init_value)
)
)
non_group2 = [
Tag(tag) for tag in init_value.keys() if Tag(tag).group != 2
]
if non_group2:
msg = "Attempted to set non-group 2 elements: {}"
raise ValueError(msg.format(non_group2))
def __setitem__(
self, key: Union[slice, TagType], value: _DatasetValue
) -> None:
"""Override parent class to only allow setting of group 2 elements.
Parameters
----------
key : int or Tuple[int, int] or str
The tag for the element to be added to the Dataset.
value : dataelem.DataElement or dataelem.RawDataElement
The element to add to the :class:`FileMetaDataset`.
Raises
------
ValueError
If `key` is not a DICOM Group 2 tag.
"""
if isinstance(value.tag, BaseTag):
tag = value.tag
else:
tag = Tag(value.tag)
if tag.group != 2:
raise ValueError(
"Only group 2 data elements are allowed in a FileMetaDataset"
)
super().__setitem__(key, value)
_RE_CAMEL_CASE = re.compile(
# Ensure mix of upper and lowercase and digits, no underscores
# If first character is lowercase ensure at least one uppercase char
"(?P<start>(^[A-Za-z])((?=.+?[A-Z])[A-Za-z0-9]+)|(^[A-Z])([A-Za-z0-9]+))"
"(?P<last>[A-za-z0-9][^_]$)" # Last character is alphanumeric
)
|
import numpy as np
import itertools as it
class SymbolicArray(np.ndarray):
def __new__(cls, arr, symbolic=None, **kwargs):
if isinstance(arr, cls):
return arr
arr = np.array(arr, copy=False, **kwargs)
obj = arr.view(cls)
obj.symbolic = str(symbolic or np.array2string(arr, separator=',', threshold=np.inf, floatmode='unique'))
return obj
def expand(self):
sym = self.symbolic
for k,v in self.locals.items():
sym = sym.replace(k,v)
return sym
def __array_finalize__(self, obj) -> None:
if obj is None: return
# This attribute should be maintained!
self.symbolic = getattr(obj, 'symbolic', None)
self.locals = getattr(obj, 'locals', {})
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
assert method == '__call__'
return np.core.overrides.array_function_dispatch \
(lambda *args, **kwargs: args, verify=False, module='numpy') (ufunc) \
(*inputs, **kwargs)
def __array_function__(self, func, types, inputs, kwargs):
assert func.__module__
obj = SymbolicArray (
func (
*(x.view(np.ndarray) if isinstance(x, SymbolicArray) else x for x in inputs),
**kwargs
),
f"{func.__module__}.{func.__name__}({", ".join(self._symbolic_args(inputs, kwargs))})"
)
for x in filter(lambda x: isinstance(x, type(self)), inputs):
obj.locals |= x.locals
if obj.symbolic.count(x.symbolic) > 1 and len(x.symbolic) > 5:
var = f"var{abs(hash(x.symbolic))}"
# add symbol to memory
obj.locals[var] = x.symbolic
# substitute
obj.symbolic = obj.symbolic.replace(x.symbolic, var)
return obj
def _symbolic_args(self, inputs, kwargs):
return it.chain (
(x.symbolic if isinstance(x, type(self)) else repr(x) for x in inputs),
(f'{x}={repr(y)}' for x,y in kwargs.items()),
) | import numpy as np
import itertools as it
class SymbolicArray(np.ndarray):
def __new__(cls, arr, symbolic=None, **kwargs):
if isinstance(arr, cls):
return arr
arr = np.array(arr, copy=False, **kwargs)
obj = arr.view(cls)
obj.symbolic = str(symbolic or np.array2string(arr, separator=',', threshold=np.inf, floatmode='unique'))
return obj
def expand(self):
sym = self.symbolic
for k,v in self.locals.items():
sym = sym.replace(k,v)
return sym
def __array_finalize__(self, obj) -> None:
if obj is None: return
# This attribute should be maintained!
self.symbolic = getattr(obj, 'symbolic', None)
self.locals = getattr(obj, 'locals', {})
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
assert method == '__call__'
return np.core.overrides.array_function_dispatch \
(lambda *args, **kwargs: args, verify=False, module='numpy') (ufunc) \
(*inputs, **kwargs)
def __array_function__(self, func, types, inputs, kwargs):
assert func.__module__
obj = SymbolicArray (
func (
*(x.view(np.ndarray) if isinstance(x, SymbolicArray) else x for x in inputs),
**kwargs
),
f"{func.__module__}.{func.__name__}({', '.join(self._symbolic_args(inputs, kwargs))})"
)
for x in filter(lambda x: isinstance(x, type(self)), inputs):
obj.locals |= x.locals
if obj.symbolic.count(x.symbolic) > 1 and len(x.symbolic) > 5:
var = f"var{abs(hash(x.symbolic))}"
# add symbol to memory
obj.locals[var] = x.symbolic
# substitute
obj.symbolic = obj.symbolic.replace(x.symbolic, var)
return obj
def _symbolic_args(self, inputs, kwargs):
return it.chain (
(x.symbolic if isinstance(x, type(self)) else repr(x) for x in inputs),
(f'{x}={repr(y)}' for x,y in kwargs.items()),
) |
from abc import (
ABC,
abstractmethod,
)
from enum import Enum
import itertools
from typing import (
TYPE_CHECKING,
Any,
Collection,
Dict,
Iterable,
List,
Optional,
Sequence,
Tuple,
Union,
cast,
)
from platon_abi import (
grammar,
)
from platon_abi.codec import (
ABICodec, WasmABICodec,
)
from platon_abi.registry import registry_wasm
from platon_typing import (
Bech32Address,
HexStr,
TypeStr,
)
from platon_utils import (
encode_hex,
event_abi_to_log_topic,
is_list_like,
keccak,
to_bytes,
to_dict,
to_hex,
to_tuple,
)
from platon_utils.curried import (
apply_formatter_if,
)
from platon_utils.toolz import (
complement,
compose,
cons,
curry,
valfilter,
)
import platon
from platon._utils.abi import (
exclude_indexed_event_inputs,
get_abi_input_names,
get_indexed_event_inputs,
map_abi_data,
normalize_event_input_types,
)
from platon._utils.encoding import (
encode_single_packed,
hexstr_if_str,
)
from platon._utils.normalizers import (
BASE_RETURN_NORMALIZERS,
)
from platon.datastructures import (
AttributeDict,
)
from platon.exceptions import (
InvalidEventABI,
LogTopicError,
MismatchedABI,
)
from platon.types import (
ABIEvent,
ABIEventParams,
BlockIdentifier,
EventData,
FilterParams,
LogReceipt,
)
if TYPE_CHECKING:
from platon import Web3
from platon._utils.filters import (
LogFilter,
)
def construct_event_topic_set(
event_abi: ABIEvent, abi_codec: ABICodec,
arguments: Optional[Union[Sequence[Any], Dict[str, Any]]] = None
) -> List[HexStr]:
if arguments is None:
arguments = {}
if isinstance(arguments, (list, tuple)):
if len(arguments) != len(event_abi['inputs']):
raise ValueError(
"When passing an argument list, the number of arguments must "
"match the event constructor."
)
arguments = {
arg['name']: [arg_value]
for arg, arg_value
in zip(event_abi['inputs'], arguments)
}
normalized_args = {
key: value if is_list_like(value) else [value]
# type ignored b/c arguments is always a dict at this point
for key, value in arguments.items() # type: ignore
}
# typed dict cannot be used w/ a normal Dict
# https://github.com/python/mypy/issues/4976
event_topic = encode_hex(event_abi_to_log_topic(event_abi)) # type: ignore
indexed_args = get_indexed_event_inputs(event_abi)
zipped_abi_and_args = [
(arg, normalized_args.get(arg['name'], [None]))
for arg in indexed_args
]
encoded_args = [
[
None if option is None else encode_hex(abi_codec.encode_single(arg['type'], option))
for option in arg_options]
for arg, arg_options in zipped_abi_and_args
]
topics = list(normalize_topic_list([event_topic] + encoded_args)) # type: ignore
return topics
def construct_event_data_set(
event_abi: ABIEvent, abi_codec: ABICodec,
arguments: Optional[Union[Sequence[Any], Dict[str, Any]]] = None
) -> List[List[Optional[HexStr]]]:
if arguments is None:
arguments = {}
if isinstance(arguments, (list, tuple)):
if len(arguments) != len(event_abi['inputs']):
raise ValueError(
"When passing an argument list, the number of arguments must "
"match the event constructor."
)
arguments = {
arg['name']: [arg_value]
for arg, arg_value
in zip(event_abi['inputs'], arguments)
}
normalized_args = {
key: value if is_list_like(value) else [value]
# type ignored b/c at this point arguments is always a dict
for key, value in arguments.items() # type: ignore
}
non_indexed_args = exclude_indexed_event_inputs(event_abi)
zipped_abi_and_args = [
(arg, normalized_args.get(arg['name'], [None]))
for arg in non_indexed_args
]
encoded_args = [
[
None if option is None else encode_hex(abi_codec.encode_single(arg['type'], option))
for option in arg_options]
for arg, arg_options in zipped_abi_and_args
]
data = [
list(permutation)
if any(value is not None for value in permutation)
else []
for permutation in itertools.product(*encoded_args)
]
return data
def is_dynamic_sized_type(type_str: TypeStr) -> bool:
abi_type = grammar.parse(type_str)
return abi_type.is_dynamic
@to_tuple
def get_event_abi_types_for_decoding(event_inputs: Sequence[ABIEventParams]) -> Iterable[TypeStr]:
"""
Event logs use the `keccak(value)` for indexed inputs of type `bytes` or
`string`. Because of this we need to modify the types so that we can
decode the log entries using the correct types.
"""
for input_abi in event_inputs:
if input_abi['indexed'] and is_dynamic_sized_type(input_abi['type']):
yield 'bytes32'
else:
yield input_abi['type']
@curry
def get_event_data(abi_codec: ABICodec, event_abi: ABIEvent, log_entry: LogReceipt, vm_type: str = None) -> EventData:
"""
Given an event ABI and a log entry for that event, return the decoded
event data
"""
if event_abi['anonymous']:
log_topics = log_entry['topics']
elif not log_entry['topics']:
raise MismatchedABI("Expected non-anonymous event to have 1 or more topics")
# type ignored b/c event_abi_to_log_topic(event_abi: Dict[str, Any])
elif event_abi_to_log_topic(event_abi, vm_type) != log_entry['topics'][0]: # type: ignore
raise MismatchedABI("The event signature did not match the provided ABI")
else:
log_topics = log_entry['topics'][1:]
log_topics_abi = get_indexed_event_inputs(event_abi)
log_topic_normalized_inputs = normalize_event_input_types(log_topics_abi)
log_topic_types = get_event_abi_types_for_decoding(log_topic_normalized_inputs)
log_topic_names = get_abi_input_names(ABIEvent({'inputs': log_topics_abi}))
if len(log_topics) != len(log_topic_types):
raise LogTopicError("Expected {0} log topics. Got {1}".format(
len(log_topic_types),
len(log_topics),
))
log_data = hexstr_if_str(to_bytes, log_entry['data'])
log_data_abi = exclude_indexed_event_inputs(event_abi)
log_data_normalized_inputs = normalize_event_input_types(log_data_abi)
log_data_types = get_event_abi_types_for_decoding(log_data_normalized_inputs)
log_data_names = get_abi_input_names(ABIEvent({'inputs': log_data_abi}))
# sanity check that there are not name intersections between the topic
# names and the data argument names.
duplicate_names = set(log_topic_names).intersection(log_data_names)
if duplicate_names:
raise InvalidEventABI(
"The following argument names are duplicated "
f"between event inputs: '{", ".join(duplicate_names)}'"
)
decoded_topic_data = [
abi_codec.decode_single(topic_type, topic_data)
for topic_type, topic_data
in zip(log_topic_types, log_topics)
]
normalized_topic_data = map_abi_data(
BASE_RETURN_NORMALIZERS,
log_topic_types,
decoded_topic_data
)
if vm_type == 'wasm':
abi_codec = WasmABICodec(registry_wasm)
decoded_log_data = abi_codec.decode_abi(log_data_types, log_data)
normalized_log_data = map_abi_data(
BASE_RETURN_NORMALIZERS,
log_data_types,
decoded_log_data
)
event_args = dict(itertools.chain(
zip(log_topic_names, normalized_topic_data),
zip(log_data_names, normalized_log_data),
))
event_data = {
'args': event_args,
'event': event_abi['name'],
'logIndex': log_entry['logIndex'],
'transactionIndex': log_entry['transactionIndex'],
'transactionHash': log_entry['transactionHash'],
'address': log_entry['address'],
'blockHash': log_entry['blockHash'],
'blockNumber': log_entry['blockNumber'],
}
return cast(EventData, AttributeDict.recursive(event_data))
@to_tuple
def pop_singlets(seq: Sequence[Any]) -> Iterable[Any]:
yield from (i[0] if is_list_like(i) and len(i) == 1 else i for i in seq)
@curry
def remove_trailing_from_seq(seq: Sequence[Any],
remove_value: Optional[Any] = None) -> Sequence[Any]:
index = len(seq)
while index > 0 and seq[index - 1] == remove_value:
index -= 1
return seq[:index]
normalize_topic_list = compose(
remove_trailing_from_seq(remove_value=None),
pop_singlets, )
def is_indexed(arg: Any) -> bool:
if isinstance(arg, TopicArgumentFilter) is True:
return True
return False
is_not_indexed = complement(is_indexed)
class EventFilterBuilder:
formatter = None
_fromBlock = None
_toBlock = None
_address = None
_immutable = False
def __init__(
self, event_abi: ABIEvent, abi_codec: ABICodec,
formatter: Optional[EventData] = None
) -> None:
self.event_abi = event_abi
self.abi_codec = abi_codec
self.formatter = formatter
self.event_topic = initialize_event_topics(self.event_abi)
self.args = AttributeDict(
_build_argument_filters_from_event_abi(event_abi, abi_codec))
self._ordered_arg_names = tuple(arg['name'] for arg in event_abi['inputs'])
@property
def fromBlock(self) -> BlockIdentifier:
return self._fromBlock
@fromBlock.setter
def fromBlock(self, value: BlockIdentifier) -> None:
if self._fromBlock is None and not self._immutable:
self._fromBlock = value
else:
raise ValueError(
f"fromBlock is already set to {self._fromBlock!r}. "
"Resetting filter parameters is not permitted")
@property
def toBlock(self) -> BlockIdentifier:
return self._toBlock
@toBlock.setter
def toBlock(self, value: BlockIdentifier) -> None:
if self._toBlock is None and not self._immutable:
self._toBlock = value
else:
raise ValueError(
f"toBlock is already set to {self._toBlock!r}. "
"Resetting filter parameters is not permitted")
@property
def address(self) -> Bech32Address:
return self._address
@address.setter
def address(self, value: Bech32Address) -> None:
if self._address is None and not self._immutable:
self._address = value
else:
raise ValueError(
f"address is already set to {self.address!r}. "
"Resetting filter parameters is not permitted")
@property
def ordered_args(self) -> Tuple[Any, ...]:
return tuple(map(self.args.__getitem__, self._ordered_arg_names))
@property # type: ignore
@to_tuple
def indexed_args(self) -> Tuple[Any, ...]:
return tuple(filter(is_indexed, self.ordered_args))
@property # type: ignore
@to_tuple
def data_args(self) -> Tuple[Any, ...]:
return tuple(filter(is_not_indexed, self.ordered_args))
@property
def topics(self) -> List[HexStr]:
arg_topics = tuple(arg.match_values for arg in self.indexed_args)
return normalize_topic_list(cons(to_hex(self.event_topic), arg_topics))
@property
def data_argument_values(self) -> Tuple[Any, ...]:
if self.data_args is not None:
return tuple(arg.match_values for arg in self.data_args)
else:
return (None,)
@property
def filter_params(self) -> FilterParams:
params = {
"topics": self.topics,
"fromBlock": self.fromBlock,
"toBlock": self.toBlock,
"address": self.address
}
return valfilter(lambda x: x is not None, params)
def deploy(self, w3: "Web3") -> "LogFilter":
if not isinstance(w3, platon.Web3):
raise ValueError("Invalid platon argument: got: {0}".format(repr(w3)))
for arg in AttributeDict.values(self.args):
arg._immutable = True
self._immutable = True
log_filter = cast("LogFilter", w3.platon.filter(self.filter_params))
log_filter.filter_params = self.filter_params
log_filter.set_data_filters(self.data_argument_values)
log_filter.builder = self
if self.formatter is not None:
log_filter.log_entry_formatter = self.formatter
return log_filter
def initialize_event_topics(event_abi: ABIEvent) -> Union[bytes, List[Any]]:
if event_abi['anonymous'] is False:
# https://github.com/python/mypy/issues/4976
return event_abi_to_log_topic(event_abi) # type: ignore
else:
return list()
@to_dict
def _build_argument_filters_from_event_abi(
event_abi: ABIEvent, abi_codec: ABICodec
) -> Iterable[Tuple[str, 'BaseArgumentFilter']]:
for item in event_abi['inputs']:
key = item['name']
value: 'BaseArgumentFilter'
if item['indexed'] is True:
value = TopicArgumentFilter(abi_codec=abi_codec, arg_type=item['type'])
else:
value = DataArgumentFilter(arg_type=item['type'])
yield key, value
array_to_tuple = apply_formatter_if(is_list_like, tuple)
@to_tuple
def _normalize_match_values(match_values: Collection[Any]) -> Iterable[Any]:
for value in match_values:
yield array_to_tuple(value)
class BaseArgumentFilter(ABC):
_match_values: Tuple[Any, ...] = None
_immutable = False
def __init__(self, arg_type: TypeStr) -> None:
self.arg_type = arg_type
def match_single(self, value: Any) -> None:
if self._immutable:
raise ValueError("Setting values is forbidden after filter is deployed.")
if self._match_values is None:
self._match_values = _normalize_match_values((value,))
else:
raise ValueError("An argument match value/s has already been set.")
def match_any(self, *values: Collection[Any]) -> None:
if self._immutable:
raise ValueError("Setting values is forbidden after filter is deployed.")
if self._match_values is None:
self._match_values = _normalize_match_values(values)
else:
raise ValueError("An argument match value/s has already been set.")
@property
@abstractmethod
def match_values(self) -> None:
pass
class DataArgumentFilter(BaseArgumentFilter):
# type ignore b/c conflict with BaseArgumentFilter.match_values type
@property
def match_values(self) -> Tuple[TypeStr, Tuple[Any, ...]]: # type: ignore
return (self.arg_type, self._match_values)
class TopicArgumentFilter(BaseArgumentFilter):
def __init__(self, arg_type: TypeStr, abi_codec: ABICodec) -> None:
self.abi_codec = abi_codec
self.arg_type = arg_type
@to_tuple
def _get_match_values(self) -> Iterable[HexStr]:
yield from (self._encode(value) for value in self._match_values)
# type ignore b/c conflict with BaseArgumentFilter.match_values type
@property
def match_values(self) -> Optional[Tuple[HexStr, ...]]: # type: ignore
if self._match_values is not None:
return self._get_match_values()
else:
return None
def _encode(self, value: Any) -> HexStr:
if is_dynamic_sized_type(self.arg_type):
return to_hex(keccak(encode_single_packed(self.arg_type, value)))
else:
return to_hex(self.abi_codec.encode_single(self.arg_type, value))
class EventLogErrorFlags(Enum):
Discard = 'discard'
Ignore = 'ignore'
Strict = 'strict'
Warn = 'warn'
@classmethod
def flag_options(self) -> List[str]:
return [key.upper() for key in self.__members__.keys()]
| from abc import (
ABC,
abstractmethod,
)
from enum import Enum
import itertools
from typing import (
TYPE_CHECKING,
Any,
Collection,
Dict,
Iterable,
List,
Optional,
Sequence,
Tuple,
Union,
cast,
)
from platon_abi import (
grammar,
)
from platon_abi.codec import (
ABICodec, WasmABICodec,
)
from platon_abi.registry import registry_wasm
from platon_typing import (
Bech32Address,
HexStr,
TypeStr,
)
from platon_utils import (
encode_hex,
event_abi_to_log_topic,
is_list_like,
keccak,
to_bytes,
to_dict,
to_hex,
to_tuple,
)
from platon_utils.curried import (
apply_formatter_if,
)
from platon_utils.toolz import (
complement,
compose,
cons,
curry,
valfilter,
)
import platon
from platon._utils.abi import (
exclude_indexed_event_inputs,
get_abi_input_names,
get_indexed_event_inputs,
map_abi_data,
normalize_event_input_types,
)
from platon._utils.encoding import (
encode_single_packed,
hexstr_if_str,
)
from platon._utils.normalizers import (
BASE_RETURN_NORMALIZERS,
)
from platon.datastructures import (
AttributeDict,
)
from platon.exceptions import (
InvalidEventABI,
LogTopicError,
MismatchedABI,
)
from platon.types import (
ABIEvent,
ABIEventParams,
BlockIdentifier,
EventData,
FilterParams,
LogReceipt,
)
if TYPE_CHECKING:
from platon import Web3
from platon._utils.filters import (
LogFilter,
)
def construct_event_topic_set(
event_abi: ABIEvent, abi_codec: ABICodec,
arguments: Optional[Union[Sequence[Any], Dict[str, Any]]] = None
) -> List[HexStr]:
if arguments is None:
arguments = {}
if isinstance(arguments, (list, tuple)):
if len(arguments) != len(event_abi['inputs']):
raise ValueError(
"When passing an argument list, the number of arguments must "
"match the event constructor."
)
arguments = {
arg['name']: [arg_value]
for arg, arg_value
in zip(event_abi['inputs'], arguments)
}
normalized_args = {
key: value if is_list_like(value) else [value]
# type ignored b/c arguments is always a dict at this point
for key, value in arguments.items() # type: ignore
}
# typed dict cannot be used w/ a normal Dict
# https://github.com/python/mypy/issues/4976
event_topic = encode_hex(event_abi_to_log_topic(event_abi)) # type: ignore
indexed_args = get_indexed_event_inputs(event_abi)
zipped_abi_and_args = [
(arg, normalized_args.get(arg['name'], [None]))
for arg in indexed_args
]
encoded_args = [
[
None if option is None else encode_hex(abi_codec.encode_single(arg['type'], option))
for option in arg_options]
for arg, arg_options in zipped_abi_and_args
]
topics = list(normalize_topic_list([event_topic] + encoded_args)) # type: ignore
return topics
def construct_event_data_set(
event_abi: ABIEvent, abi_codec: ABICodec,
arguments: Optional[Union[Sequence[Any], Dict[str, Any]]] = None
) -> List[List[Optional[HexStr]]]:
if arguments is None:
arguments = {}
if isinstance(arguments, (list, tuple)):
if len(arguments) != len(event_abi['inputs']):
raise ValueError(
"When passing an argument list, the number of arguments must "
"match the event constructor."
)
arguments = {
arg['name']: [arg_value]
for arg, arg_value
in zip(event_abi['inputs'], arguments)
}
normalized_args = {
key: value if is_list_like(value) else [value]
# type ignored b/c at this point arguments is always a dict
for key, value in arguments.items() # type: ignore
}
non_indexed_args = exclude_indexed_event_inputs(event_abi)
zipped_abi_and_args = [
(arg, normalized_args.get(arg['name'], [None]))
for arg in non_indexed_args
]
encoded_args = [
[
None if option is None else encode_hex(abi_codec.encode_single(arg['type'], option))
for option in arg_options]
for arg, arg_options in zipped_abi_and_args
]
data = [
list(permutation)
if any(value is not None for value in permutation)
else []
for permutation in itertools.product(*encoded_args)
]
return data
def is_dynamic_sized_type(type_str: TypeStr) -> bool:
abi_type = grammar.parse(type_str)
return abi_type.is_dynamic
@to_tuple
def get_event_abi_types_for_decoding(event_inputs: Sequence[ABIEventParams]) -> Iterable[TypeStr]:
"""
Event logs use the `keccak(value)` for indexed inputs of type `bytes` or
`string`. Because of this we need to modify the types so that we can
decode the log entries using the correct types.
"""
for input_abi in event_inputs:
if input_abi['indexed'] and is_dynamic_sized_type(input_abi['type']):
yield 'bytes32'
else:
yield input_abi['type']
@curry
def get_event_data(abi_codec: ABICodec, event_abi: ABIEvent, log_entry: LogReceipt, vm_type: str = None) -> EventData:
"""
Given an event ABI and a log entry for that event, return the decoded
event data
"""
if event_abi['anonymous']:
log_topics = log_entry['topics']
elif not log_entry['topics']:
raise MismatchedABI("Expected non-anonymous event to have 1 or more topics")
# type ignored b/c event_abi_to_log_topic(event_abi: Dict[str, Any])
elif event_abi_to_log_topic(event_abi, vm_type) != log_entry['topics'][0]: # type: ignore
raise MismatchedABI("The event signature did not match the provided ABI")
else:
log_topics = log_entry['topics'][1:]
log_topics_abi = get_indexed_event_inputs(event_abi)
log_topic_normalized_inputs = normalize_event_input_types(log_topics_abi)
log_topic_types = get_event_abi_types_for_decoding(log_topic_normalized_inputs)
log_topic_names = get_abi_input_names(ABIEvent({'inputs': log_topics_abi}))
if len(log_topics) != len(log_topic_types):
raise LogTopicError("Expected {0} log topics. Got {1}".format(
len(log_topic_types),
len(log_topics),
))
log_data = hexstr_if_str(to_bytes, log_entry['data'])
log_data_abi = exclude_indexed_event_inputs(event_abi)
log_data_normalized_inputs = normalize_event_input_types(log_data_abi)
log_data_types = get_event_abi_types_for_decoding(log_data_normalized_inputs)
log_data_names = get_abi_input_names(ABIEvent({'inputs': log_data_abi}))
# sanity check that there are not name intersections between the topic
# names and the data argument names.
duplicate_names = set(log_topic_names).intersection(log_data_names)
if duplicate_names:
raise InvalidEventABI(
"The following argument names are duplicated "
f"between event inputs: '{', '.join(duplicate_names)}'"
)
decoded_topic_data = [
abi_codec.decode_single(topic_type, topic_data)
for topic_type, topic_data
in zip(log_topic_types, log_topics)
]
normalized_topic_data = map_abi_data(
BASE_RETURN_NORMALIZERS,
log_topic_types,
decoded_topic_data
)
if vm_type == 'wasm':
abi_codec = WasmABICodec(registry_wasm)
decoded_log_data = abi_codec.decode_abi(log_data_types, log_data)
normalized_log_data = map_abi_data(
BASE_RETURN_NORMALIZERS,
log_data_types,
decoded_log_data
)
event_args = dict(itertools.chain(
zip(log_topic_names, normalized_topic_data),
zip(log_data_names, normalized_log_data),
))
event_data = {
'args': event_args,
'event': event_abi['name'],
'logIndex': log_entry['logIndex'],
'transactionIndex': log_entry['transactionIndex'],
'transactionHash': log_entry['transactionHash'],
'address': log_entry['address'],
'blockHash': log_entry['blockHash'],
'blockNumber': log_entry['blockNumber'],
}
return cast(EventData, AttributeDict.recursive(event_data))
@to_tuple
def pop_singlets(seq: Sequence[Any]) -> Iterable[Any]:
yield from (i[0] if is_list_like(i) and len(i) == 1 else i for i in seq)
@curry
def remove_trailing_from_seq(seq: Sequence[Any],
remove_value: Optional[Any] = None) -> Sequence[Any]:
index = len(seq)
while index > 0 and seq[index - 1] == remove_value:
index -= 1
return seq[:index]
normalize_topic_list = compose(
remove_trailing_from_seq(remove_value=None),
pop_singlets, )
def is_indexed(arg: Any) -> bool:
if isinstance(arg, TopicArgumentFilter) is True:
return True
return False
is_not_indexed = complement(is_indexed)
class EventFilterBuilder:
formatter = None
_fromBlock = None
_toBlock = None
_address = None
_immutable = False
def __init__(
self, event_abi: ABIEvent, abi_codec: ABICodec,
formatter: Optional[EventData] = None
) -> None:
self.event_abi = event_abi
self.abi_codec = abi_codec
self.formatter = formatter
self.event_topic = initialize_event_topics(self.event_abi)
self.args = AttributeDict(
_build_argument_filters_from_event_abi(event_abi, abi_codec))
self._ordered_arg_names = tuple(arg['name'] for arg in event_abi['inputs'])
@property
def fromBlock(self) -> BlockIdentifier:
return self._fromBlock
@fromBlock.setter
def fromBlock(self, value: BlockIdentifier) -> None:
if self._fromBlock is None and not self._immutable:
self._fromBlock = value
else:
raise ValueError(
f"fromBlock is already set to {self._fromBlock!r}. "
"Resetting filter parameters is not permitted")
@property
def toBlock(self) -> BlockIdentifier:
return self._toBlock
@toBlock.setter
def toBlock(self, value: BlockIdentifier) -> None:
if self._toBlock is None and not self._immutable:
self._toBlock = value
else:
raise ValueError(
f"toBlock is already set to {self._toBlock!r}. "
"Resetting filter parameters is not permitted")
@property
def address(self) -> Bech32Address:
return self._address
@address.setter
def address(self, value: Bech32Address) -> None:
if self._address is None and not self._immutable:
self._address = value
else:
raise ValueError(
f"address is already set to {self.address!r}. "
"Resetting filter parameters is not permitted")
@property
def ordered_args(self) -> Tuple[Any, ...]:
return tuple(map(self.args.__getitem__, self._ordered_arg_names))
@property # type: ignore
@to_tuple
def indexed_args(self) -> Tuple[Any, ...]:
return tuple(filter(is_indexed, self.ordered_args))
@property # type: ignore
@to_tuple
def data_args(self) -> Tuple[Any, ...]:
return tuple(filter(is_not_indexed, self.ordered_args))
@property
def topics(self) -> List[HexStr]:
arg_topics = tuple(arg.match_values for arg in self.indexed_args)
return normalize_topic_list(cons(to_hex(self.event_topic), arg_topics))
@property
def data_argument_values(self) -> Tuple[Any, ...]:
if self.data_args is not None:
return tuple(arg.match_values for arg in self.data_args)
else:
return (None,)
@property
def filter_params(self) -> FilterParams:
params = {
"topics": self.topics,
"fromBlock": self.fromBlock,
"toBlock": self.toBlock,
"address": self.address
}
return valfilter(lambda x: x is not None, params)
def deploy(self, w3: "Web3") -> "LogFilter":
if not isinstance(w3, platon.Web3):
raise ValueError("Invalid platon argument: got: {0}".format(repr(w3)))
for arg in AttributeDict.values(self.args):
arg._immutable = True
self._immutable = True
log_filter = cast("LogFilter", w3.platon.filter(self.filter_params))
log_filter.filter_params = self.filter_params
log_filter.set_data_filters(self.data_argument_values)
log_filter.builder = self
if self.formatter is not None:
log_filter.log_entry_formatter = self.formatter
return log_filter
def initialize_event_topics(event_abi: ABIEvent) -> Union[bytes, List[Any]]:
if event_abi['anonymous'] is False:
# https://github.com/python/mypy/issues/4976
return event_abi_to_log_topic(event_abi) # type: ignore
else:
return list()
@to_dict
def _build_argument_filters_from_event_abi(
event_abi: ABIEvent, abi_codec: ABICodec
) -> Iterable[Tuple[str, 'BaseArgumentFilter']]:
for item in event_abi['inputs']:
key = item['name']
value: 'BaseArgumentFilter'
if item['indexed'] is True:
value = TopicArgumentFilter(abi_codec=abi_codec, arg_type=item['type'])
else:
value = DataArgumentFilter(arg_type=item['type'])
yield key, value
array_to_tuple = apply_formatter_if(is_list_like, tuple)
@to_tuple
def _normalize_match_values(match_values: Collection[Any]) -> Iterable[Any]:
for value in match_values:
yield array_to_tuple(value)
class BaseArgumentFilter(ABC):
_match_values: Tuple[Any, ...] = None
_immutable = False
def __init__(self, arg_type: TypeStr) -> None:
self.arg_type = arg_type
def match_single(self, value: Any) -> None:
if self._immutable:
raise ValueError("Setting values is forbidden after filter is deployed.")
if self._match_values is None:
self._match_values = _normalize_match_values((value,))
else:
raise ValueError("An argument match value/s has already been set.")
def match_any(self, *values: Collection[Any]) -> None:
if self._immutable:
raise ValueError("Setting values is forbidden after filter is deployed.")
if self._match_values is None:
self._match_values = _normalize_match_values(values)
else:
raise ValueError("An argument match value/s has already been set.")
@property
@abstractmethod
def match_values(self) -> None:
pass
class DataArgumentFilter(BaseArgumentFilter):
# type ignore b/c conflict with BaseArgumentFilter.match_values type
@property
def match_values(self) -> Tuple[TypeStr, Tuple[Any, ...]]: # type: ignore
return (self.arg_type, self._match_values)
class TopicArgumentFilter(BaseArgumentFilter):
def __init__(self, arg_type: TypeStr, abi_codec: ABICodec) -> None:
self.abi_codec = abi_codec
self.arg_type = arg_type
@to_tuple
def _get_match_values(self) -> Iterable[HexStr]:
yield from (self._encode(value) for value in self._match_values)
# type ignore b/c conflict with BaseArgumentFilter.match_values type
@property
def match_values(self) -> Optional[Tuple[HexStr, ...]]: # type: ignore
if self._match_values is not None:
return self._get_match_values()
else:
return None
def _encode(self, value: Any) -> HexStr:
if is_dynamic_sized_type(self.arg_type):
return to_hex(keccak(encode_single_packed(self.arg_type, value)))
else:
return to_hex(self.abi_codec.encode_single(self.arg_type, value))
class EventLogErrorFlags(Enum):
Discard = 'discard'
Ignore = 'ignore'
Strict = 'strict'
Warn = 'warn'
@classmethod
def flag_options(self) -> List[str]:
return [key.upper() for key in self.__members__.keys()]
|
import pandas as pd
import psycopg2
import psycopg2.extras
class DBData():
def __init__(self, schema='wage_trust_demo'):
self._CSTR = {
'user' : 'postgres',
'password' : 'docker',
'host' : 'wage_trust_db'
}
self._schema = schema
def _col_name_clean(self, col_name):
col_name = col_name.lower()
if ' ' in col_name:
col_name = col_name.replace(' ','_')
if '/' in col_name:
col_name = col_name.replace('/','_')
if "'" in col_name:
col_name = col_name.replace("'", "\"")
return col_name
def create_table(self, df, col_json, col_time, p_key, table_name):
fields = []
for col in df.columns:
col_name = self._col_name_clean(col)
if col.lower() in col_json:
field = col_name + ' ' + 'json'
elif col.lower() in col_time:
field = col_name + ' ' + 'TIMESTAMPTZ'
else:
if df[col].dtype == 'object':
field = col_name + ' ' + 'text'
if df[col].dtype == 'int64':
field = col_name + ' ' + 'integer'
if df[col].dtype == 'bool':
field = col_name + ' ' + 'BOOLEAN'
if df[col].dtype == 'float64':
field = col_name + ' ' + 'float'
fields.append(field)
if len(p_key) > 0:
fields.append(' PRIMARY KEY ({})'.format(','.join(p_key)))
query_txt = 'CREATE TABLE IF NOT EXISTS {}.{} ({});'.format(self._schema, table_name, ','.join(fields))
with psycopg2.connect(**self._CSTR) as conn:
with conn.cursor() as cur:
cur.execute(query_txt)
conn.commit()
def insert_data(self,df, table_name):
#Collect table column names
query_txt = f'''
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_schema = '{self._schema}'
AND table_name = '{table_name}'
'''
with psycopg2.connect(**self._CSTR) as conn:
with conn.cursor() as cur:
tab_col_df = pd.read_sql(query_txt, con=conn)
tab_col_name = tab_col_df['column_name'].to_list()
#create df column name check dict
df_col_name = {self._col_name_clean(col): col for col in df.columns}
#refine table column names with df col names
res_tab_col = [col for col in tab_col_name if col in df_col_name.keys()]
#prepare insert query txt
ins = f'''insert into {'.'.join([self._schema, table_name])} ''' + \
str(tuple(res_tab_col)).replace("'", "\"") + ''' values %s '''
ivals = []
for _, row in df.iterrows():
tmp_val = []
for col in res_tab_col:
tmp_val.append(str(row[df_col_name[col]]))
ivals.append(tuple(tmp_val))
print(ins)
print(ivals)
with psycopg2.connect(**self._CSTR) as conn:
with conn.cursor() as cur:
psycopg2.extras.execute_values(cur, ins, ivals, page_size=ivals.__len__())
conn.commit()
def retrieve_data(self, table_name):
query_txt = f"SELECT * FROM {self._schema}.{table_name}"
with psycopg2.connect(**self._CSTR) as conn:
with conn.cursor() as cur:
df = pd.read_sql(query_txt, con=conn)
return df
| import pandas as pd
import psycopg2
import psycopg2.extras
class DBData():
def __init__(self, schema='wage_trust_demo'):
self._CSTR = {
'user' : 'postgres',
'password' : 'docker',
'host' : 'wage_trust_db'
}
self._schema = schema
def _col_name_clean(self, col_name):
col_name = col_name.lower()
if ' ' in col_name:
col_name = col_name.replace(' ','_')
if '/' in col_name:
col_name = col_name.replace('/','_')
if "'" in col_name:
col_name = col_name.replace("'", "\"")
return col_name
def create_table(self, df, col_json, col_time, p_key, table_name):
fields = []
for col in df.columns:
col_name = self._col_name_clean(col)
if col.lower() in col_json:
field = col_name + ' ' + 'json'
elif col.lower() in col_time:
field = col_name + ' ' + 'TIMESTAMPTZ'
else:
if df[col].dtype == 'object':
field = col_name + ' ' + 'text'
if df[col].dtype == 'int64':
field = col_name + ' ' + 'integer'
if df[col].dtype == 'bool':
field = col_name + ' ' + 'BOOLEAN'
if df[col].dtype == 'float64':
field = col_name + ' ' + 'float'
fields.append(field)
if len(p_key) > 0:
fields.append(' PRIMARY KEY ({})'.format(','.join(p_key)))
query_txt = 'CREATE TABLE IF NOT EXISTS {}.{} ({});'.format(self._schema, table_name, ','.join(fields))
with psycopg2.connect(**self._CSTR) as conn:
with conn.cursor() as cur:
cur.execute(query_txt)
conn.commit()
def insert_data(self,df, table_name):
#Collect table column names
query_txt = f'''
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_schema = '{self._schema}'
AND table_name = '{table_name}'
'''
with psycopg2.connect(**self._CSTR) as conn:
with conn.cursor() as cur:
tab_col_df = pd.read_sql(query_txt, con=conn)
tab_col_name = tab_col_df['column_name'].to_list()
#create df column name check dict
df_col_name = {self._col_name_clean(col): col for col in df.columns}
#refine table column names with df col names
res_tab_col = [col for col in tab_col_name if col in df_col_name.keys()]
#prepare insert query txt
ins = f'''insert into {'.'.join([self._schema, table_name])} ''' + \
str(tuple(res_tab_col)).replace("'", "\"") + ''' values %s '''
ivals = []
for _, row in df.iterrows():
tmp_val = []
for col in res_tab_col:
tmp_val.append(str(row[df_col_name[col]]))
ivals.append(tuple(tmp_val))
print(ins)
print(ivals)
with psycopg2.connect(**self._CSTR) as conn:
with conn.cursor() as cur:
psycopg2.extras.execute_values(cur, ins, ivals, page_size=ivals.__len__())
conn.commit()
def retrieve_data(self, table_name):
query_txt = f"SELECT * FROM {self._schema}.{table_name}"
with psycopg2.connect(**self._CSTR) as conn:
with conn.cursor() as cur:
df = pd.read_sql(query_txt, con=conn)
return df
|
import logging
from TwitchWebsocket.Message import Message
from Settings import Settings
from Log import Log
Log(__file__)
# Modules
import tkinter as tk
import tkinter.scrolledtext as tkst
import tkinter.font as tkFont
import time, json
from datetime import datetime
from functools import reduce
import threading
class App(threading.Thread):
# Initialise the thread
def __init__(self, bot, db):
threading.Thread.__init__(self)
# Attributes
self.bot = bot
self.db = db
self.running = False
# Start the thread
self.start()
# Quit properly
def callback(self):
# Quit the GUI
self.root.quit()
# Join the bot thread
self.bot.stop()
# This terminates the entire program
# Clear output field
def clear(self):
self.txt.delete("1.0", tk.END)
# Hide the OAUTH password
def hide(self):
if self.login_entries[4]['state'] == 'normal':
self.oauth = self.login_entries[4].get()
self.login_entries[4].delete(0, tk.END)
self.login_entries[4].insert(0, "*" * 44)
self.login_entries[4].configure(state='readonly')
else:
self.login_entries[4].configure(state='normal')
self.login_entries[4].delete(0, tk.END)
self.login_entries[4].insert(0, self.oauth)
def now_running(self):
self.running = True
def update_login(self):
# Get settings
login = [entry.get() for entry in self.login_entries]
# Set the settings on the bot
chan = login[2] if len(login[2]) > 0 and login[2][0] == "#" else "#" + login[2]
try:
port = int(login[1])
except:
port = 0
if self.login_entries[4]['state'] == 'normal':
auth = login[4]
else:
auth = self.oauth
self.bot.set_login_settings(login[0], port, chan, login[3], auth)
def next_level(self):
# Pick the next level
self.bot.handle_next_level()
def run(self):
self.login_dict = {"Host": self.bot.host, "Port":self.bot.port, "Chan": self.bot.chan.replace("#", ""), "User": self.bot.nick, "Auth": self.bot.auth}
# Set up GUI
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
self.root.resizable(0, 1)
self.root.minsize(width=283, height=205)
self.root.title("Twitch Bot GUI")
self.root.grid_rowconfigure(6, weight=1)
self.login_entries = []
self.oauth = ""
# Handle Run/Stop button functionality
def run_stop():
if self.run_stop_button['text'] == "Run":
self.update_login()
self.bot.start()
else:
self.bot.stop()
self.running = False
if self.run_stop_button['text'] == "Stop":
self.run_stop_button.configure(text="Run")
else:
self.run_stop_button.configure(text="Stop")
self.m = max([len(str(self.login_dict[i])) for i in self.login_dict]) + 1
# Fields for the GUI main page
for x, i in enumerate(self.login_dict):
if x == 4:
self.hide_button = tk.Button(self.root, text=i, command=self.hide)
self.hide_button.grid(row=x, padx=(12, 4))
self.hide_button.config(width=4)
else:
tk.Label(self.root, text=i + ":").grid(row=x, padx=(12, 4))
e = tk.Entry(self.root, width=self.m)
e.grid(row=x, column=1, sticky="W", columnspan=5, pady=2)
e.insert(0, self.login_dict[i])
self.login_entries.append(e)
# Hide the OAUTH password.
self.hide()
# Run/Stop Button
self.run_stop_button = tk.Button(self.root, text='Run', command=run_stop)
self.run_stop_button.grid(row=len(self.login_dict), column=0, pady=4, padx=(9, 0))
self.run_stop_button.config(width=4)
# Clear, Vote and Settings buttons
tk.Button(self.root, text="{:^23}".format("Pick Next Level"), command=self.next_level).grid(row=len(self.login_dict), column=1, columnspan=2, pady=4)
self.clear_button = tk.Button(self.root, text='Clear', command=self.clear_db)
self.clear_button.grid(row=len(self.login_dict), column=5, pady=4)
#tk.Button(self.root, text='Settings', command=self.settings).grid(row=len(self.login_dict), column=5, pady=4, padx=(74, 25))
# Output field
self.txt = tkst.ScrolledText(self.root, undo=True, borderwidth=3, relief="groove", width=self.m, height=17)
self.txt.config(font=('consolas', '8'), undo=True, wrap='word') #font=('consolas', '12')
self.txt.grid(column=0, padx=(10, 6), pady=(2, 5), sticky="news", columnspan=6)
# Configure bold font for specific output messages to use
self.bold_font = tkFont.Font(self.txt, self.txt.cget("font"))
self.bold_font.configure(weight="bold")
self.txt.tag_configure("bold", font=self.bold_font)
self.update_levels()
# GUI Loop
self.root.mainloop()
def update_levels(self):
# Get the current level
current_level = self.db.get_current_level()
# Get all non-current levels
level_data = self.db.get_levels()
# Clear out
self.txt.delete("1.0", tk.END)
# Insert headers
self.txt.insert(tk.END, "Level's Creator : Code\n", "bold")
# Insert current levels
if len(current_level) != 0:
self.txt.insert(tk.END, f"{current_level[0][0]: <24} : {current_level[0][1]: <12} \n", "bold")
else:
self.txt.insert(tk.END, "{: <24} : {: <12} \n".format("No level picked yet", "XXX-XXX-XXX"), "bold")
self.txt.insert(tk.END, f"{"":-<39} \n", "bold")
# Insert non-current levels
for tup in level_data:
self.txt.insert(tk.END, f"{tup[0]: <24} : {tup[1]: <12} \n")
# Update clear time
clear_time = self.db.get_clear_time()
if clear_time:
self.clear_button.configure(text="Clear: " + time.strftime('%b-%d %H:%M', time.localtime(clear_time[0][0])))
def clear_db(self):
self.db.clear()
self.update_levels()
|
import logging
from TwitchWebsocket.Message import Message
from Settings import Settings
from Log import Log
Log(__file__)
# Modules
import tkinter as tk
import tkinter.scrolledtext as tkst
import tkinter.font as tkFont
import time, json
from datetime import datetime
from functools import reduce
import threading
class App(threading.Thread):
# Initialise the thread
def __init__(self, bot, db):
threading.Thread.__init__(self)
# Attributes
self.bot = bot
self.db = db
self.running = False
# Start the thread
self.start()
# Quit properly
def callback(self):
# Quit the GUI
self.root.quit()
# Join the bot thread
self.bot.stop()
# This terminates the entire program
# Clear output field
def clear(self):
self.txt.delete("1.0", tk.END)
# Hide the OAUTH password
def hide(self):
if self.login_entries[4]['state'] == 'normal':
self.oauth = self.login_entries[4].get()
self.login_entries[4].delete(0, tk.END)
self.login_entries[4].insert(0, "*" * 44)
self.login_entries[4].configure(state='readonly')
else:
self.login_entries[4].configure(state='normal')
self.login_entries[4].delete(0, tk.END)
self.login_entries[4].insert(0, self.oauth)
def now_running(self):
self.running = True
def update_login(self):
# Get settings
login = [entry.get() for entry in self.login_entries]
# Set the settings on the bot
chan = login[2] if len(login[2]) > 0 and login[2][0] == "#" else "#" + login[2]
try:
port = int(login[1])
except:
port = 0
if self.login_entries[4]['state'] == 'normal':
auth = login[4]
else:
auth = self.oauth
self.bot.set_login_settings(login[0], port, chan, login[3], auth)
def next_level(self):
# Pick the next level
self.bot.handle_next_level()
def run(self):
self.login_dict = {"Host": self.bot.host, "Port":self.bot.port, "Chan": self.bot.chan.replace("#", ""), "User": self.bot.nick, "Auth": self.bot.auth}
# Set up GUI
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
self.root.resizable(0, 1)
self.root.minsize(width=283, height=205)
self.root.title("Twitch Bot GUI")
self.root.grid_rowconfigure(6, weight=1)
self.login_entries = []
self.oauth = ""
# Handle Run/Stop button functionality
def run_stop():
if self.run_stop_button['text'] == "Run":
self.update_login()
self.bot.start()
else:
self.bot.stop()
self.running = False
if self.run_stop_button['text'] == "Stop":
self.run_stop_button.configure(text="Run")
else:
self.run_stop_button.configure(text="Stop")
self.m = max([len(str(self.login_dict[i])) for i in self.login_dict]) + 1
# Fields for the GUI main page
for x, i in enumerate(self.login_dict):
if x == 4:
self.hide_button = tk.Button(self.root, text=i, command=self.hide)
self.hide_button.grid(row=x, padx=(12, 4))
self.hide_button.config(width=4)
else:
tk.Label(self.root, text=i + ":").grid(row=x, padx=(12, 4))
e = tk.Entry(self.root, width=self.m)
e.grid(row=x, column=1, sticky="W", columnspan=5, pady=2)
e.insert(0, self.login_dict[i])
self.login_entries.append(e)
# Hide the OAUTH password.
self.hide()
# Run/Stop Button
self.run_stop_button = tk.Button(self.root, text='Run', command=run_stop)
self.run_stop_button.grid(row=len(self.login_dict), column=0, pady=4, padx=(9, 0))
self.run_stop_button.config(width=4)
# Clear, Vote and Settings buttons
tk.Button(self.root, text="{:^23}".format("Pick Next Level"), command=self.next_level).grid(row=len(self.login_dict), column=1, columnspan=2, pady=4)
self.clear_button = tk.Button(self.root, text='Clear', command=self.clear_db)
self.clear_button.grid(row=len(self.login_dict), column=5, pady=4)
#tk.Button(self.root, text='Settings', command=self.settings).grid(row=len(self.login_dict), column=5, pady=4, padx=(74, 25))
# Output field
self.txt = tkst.ScrolledText(self.root, undo=True, borderwidth=3, relief="groove", width=self.m, height=17)
self.txt.config(font=('consolas', '8'), undo=True, wrap='word') #font=('consolas', '12')
self.txt.grid(column=0, padx=(10, 6), pady=(2, 5), sticky="news", columnspan=6)
# Configure bold font for specific output messages to use
self.bold_font = tkFont.Font(self.txt, self.txt.cget("font"))
self.bold_font.configure(weight="bold")
self.txt.tag_configure("bold", font=self.bold_font)
self.update_levels()
# GUI Loop
self.root.mainloop()
def update_levels(self):
# Get the current level
current_level = self.db.get_current_level()
# Get all non-current levels
level_data = self.db.get_levels()
# Clear out
self.txt.delete("1.0", tk.END)
# Insert headers
self.txt.insert(tk.END, "Level's Creator : Code\n", "bold")
# Insert current levels
if len(current_level) != 0:
self.txt.insert(tk.END, f"{current_level[0][0]: <24} : {current_level[0][1]: <12} \n", "bold")
else:
self.txt.insert(tk.END, "{: <24} : {: <12} \n".format("No level picked yet", "XXX-XXX-XXX"), "bold")
self.txt.insert(tk.END, f"{'':-<39} \n", "bold")
# Insert non-current levels
for tup in level_data:
self.txt.insert(tk.END, f"{tup[0]: <24} : {tup[1]: <12} \n")
# Update clear time
clear_time = self.db.get_clear_time()
if clear_time:
self.clear_button.configure(text="Clear: " + time.strftime('%b-%d %H:%M', time.localtime(clear_time[0][0])))
def clear_db(self):
self.db.clear()
self.update_levels()
|
nome = str(input('Qual é seu nome completo? ')).strip()
print(f'Seu nome tem Silva? {'Silva' in nome.title().split()}')
| nome = str(input('Qual é seu nome completo? ')).strip()
print(f'Seu nome tem Silva? {"Silva" in nome.title().split()}')
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pathlib import Path
from typing import Optional, Union
import os
import shutil
import tempfile
from synthtool import _tracked_paths, metadata, shell
from synthtool.log import logger
from synthtool.sources import git
GOOGLEAPIS_URL: str = git.make_repo_clone_url("googleapis/googleapis")
GOOGLEAPIS_PRIVATE_URL: str = git.make_repo_clone_url("googleapis/googleapis-private")
DISCOVERY_ARTIFACT_MANAGER_URL: str = git.make_repo_clone_url(
"googleapis/discovery-artifact-manager"
)
LOCAL_GOOGLEAPIS: Optional[str] = os.environ.get("SYNTHTOOL_GOOGLEAPIS")
LOCAL_DISCOVERY_ARTIFACT_MANAGER: Optional[str] = os.environ.get(
"SYNTHTOOL_DISCOVERY_ARTIFACT_MANAGER"
)
class GAPICBazel:
"""A synthtool component that can produce libraries using bazel build.
"""
def __init__(self):
self._ensure_dependencies_installed()
self._googleapis = None
self._googleapis_private = None
self._discovery_artifact_manager = None
def py_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "python", **kwargs)
def go_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "go", **kwargs)
def node_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "nodejs", **kwargs)
def csharp_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "csharp", **kwargs)
def php_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "php", **kwargs)
def java_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(
service, version, "java", tar_strip_components=0, **kwargs
)
def ruby_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "ruby", **kwargs)
def _generate_code(
self,
service: str,
version: str,
language: str,
*,
private: bool = False,
discogapic: bool = False,
proto_path: Union[str, Path] = None,
output_dir: Union[str, Path] = None,
bazel_target: str = None,
include_protos: bool = False,
proto_output_path: Union[str, Path] = None,
tar_strip_components: int = 1,
):
# Determine which googleapis repo to use
if discogapic:
api_definitions_repo = self._clone_discovery_artifact_manager()
api_definitions_repo_name = "discovery-artifact-manager"
elif private:
api_definitions_repo = self._clone_googleapis_private()
api_definitions_repo_name = "googleapis_private"
else:
api_definitions_repo = self._clone_googleapis()
api_definitions_repo_name = "googleapis"
# Sanity check: We should have a googleapis repo; if we do not,
# something went wrong, and we should abort.
if not api_definitions_repo:
raise RuntimeError(
f"Unable to generate {service}, the sources repository repository"
"is unavailable."
)
# Calculate proto_path if necessary.
if not bazel_target or include_protos:
# If bazel_target is not specified explicitly, we will need
# proto_path to calculate it. If include_protos is True,
# we will need the proto_path to copy the protos.
if not proto_path:
if bazel_target:
# Calculate proto_path from the full bazel target, which is
# in the format "//proto_path:target_name
proto_path = bazel_target.split(":")[0][2:]
else:
# If bazel_target is not specified, assume the protos are
# simply under google/cloud, where the most of the protos
# usually are.
proto_path = f"google/cloud/{service}/{version}"
protos = Path(proto_path)
if protos.is_absolute():
protos = protos.relative_to("/")
# Determine bazel target based on per-language patterns
# Java: google-cloud-{{assembly_name}}-{{version}}-java
# Go: gapi-cloud-{{assembly_name}}-{{version}}-go
# Python: {{assembly_name}}-{{version}}-py
# PHP: google-cloud-{{assembly_name}}-{{version}}-php
# Node.js: {{assembly_name}}-{{version}}-nodejs
# Ruby: google-cloud-{{assembly_name}}-{{version}}-ruby
# C#: google-cloud-{{assembly_name}}-{{version}}-csharp
if not bazel_target:
# Determine where the protos we are generating actually live.
# We can sometimes (but not always) determine this from the service
# and version; in other cases, the user must provide it outright.
parts = list(protos.parts)
while len(parts) > 0 and parts[0] != "google":
parts.pop(0)
if len(parts) == 0:
raise RuntimeError(
f"Cannot determine bazel_target from proto_path {protos}."
"Please set bazel_target explicitly."
)
if language == "python":
suffix = f"{service}-{version}-py"
elif language == "nodejs":
suffix = f"{service}-{version}-nodejs"
elif language == "go":
suffix = f"gapi-{"-".join(parts[1:])}-go"
else:
suffix = f"{"-".join(parts)}-{language}"
bazel_target = f"//{os.path.sep.join(parts)}:{suffix}"
# Sanity check: Do we have protos where we think we should?
if not (api_definitions_repo / protos).exists():
raise FileNotFoundError(
f"Unable to find directory for protos: {(api_definitions_repo / protos)}."
)
if not tuple((api_definitions_repo / protos).glob("*.proto")):
raise FileNotFoundError(
f"Directory {(api_definitions_repo / protos)} exists, but no protos found."
)
if not (api_definitions_repo / protos / "BUILD.bazel"):
raise FileNotFoundError(
f"File {(api_definitions_repo / protos / "BUILD.bazel")} does not exist."
)
# Ensure the desired output directory exists.
# If none was provided, create a temporary directory.
if not output_dir:
output_dir = tempfile.mkdtemp()
output_dir = Path(output_dir).resolve()
# Let's build some stuff now.
cwd = os.getcwd()
os.chdir(str(api_definitions_repo))
bazel_run_args = [
"bazel",
"--max_idle_secs=240",
"build",
bazel_target,
]
logger.debug(f"Generating code for: {bazel_target}.")
shell.run(bazel_run_args)
# We've got tar file!
# its location: bazel-bin/google/cloud/language/v1/language-v1-nodejs.tar.gz
# bazel_target: //google/cloud/language/v1:language-v1-nodejs
tar_file = (
f"bazel-bin{os.path.sep}{bazel_target[2:].replace(":", os.path.sep)}.tar.gz"
)
tar_run_args = [
"tar",
"-C",
str(output_dir),
f"--strip-components={tar_strip_components}",
"-xzf",
tar_file,
]
shell.run(tar_run_args)
# Get the *.protos files and put them in a protos dir in the output
if include_protos:
proto_files = protos.glob("**/*.proto")
# By default, put the protos at the root in a folder named 'protos'.
# Specific languages can be cased here to put them in a more language
# appropriate place.
if not proto_output_path:
proto_output_path = output_dir / "protos"
if language == "python":
# place protos alongsize the *_pb2.py files
proto_output_path = (
output_dir / f"google/cloud/{service}_{version}/proto"
)
else:
proto_output_path = Path(output_dir / proto_output_path)
os.makedirs(proto_output_path, exist_ok=True)
for i in proto_files:
logger.debug(f"Copy: {i} to {proto_output_path / i.name}")
shutil.copyfile(i, proto_output_path / i.name)
logger.success(f"Placed proto files into {proto_output_path}.")
os.chdir(cwd)
# Sanity check: Does the output location have code in it?
# If not, complain.
if not tuple(output_dir.iterdir()):
raise RuntimeError(
f"Code generation seemed to succeed, but {output_dir} is empty."
)
# Huzzah, it worked.
logger.success(f"Generated code into {output_dir}.")
# Record this in the synthtool metadata.
metadata.add_client_destination(
source=api_definitions_repo_name,
api_name=service,
api_version=version,
language=language,
generator="bazel",
)
_tracked_paths.add(output_dir)
return output_dir
def _clone_googleapis(self):
if self._googleapis:
return self._googleapis
if LOCAL_GOOGLEAPIS:
self._googleapis = Path(LOCAL_GOOGLEAPIS).expanduser()
logger.debug(f"Using local googleapis at {self._googleapis}")
else:
logger.debug("Cloning googleapis.")
self._googleapis = git.clone(GOOGLEAPIS_URL)
return self._googleapis
def _clone_googleapis_private(self):
if self._googleapis_private:
return self._googleapis_private
if LOCAL_GOOGLEAPIS:
self._googleapis_private = Path(LOCAL_GOOGLEAPIS).expanduser()
logger.debug(
f"Using local googleapis at {self._googleapis_private} for googleapis-private"
)
else:
logger.debug("Cloning googleapis-private.")
self._googleapis_private = git.clone(GOOGLEAPIS_PRIVATE_URL)
return self._googleapis_private
def _clone_discovery_artifact_manager(self):
if self._discovery_artifact_manager:
return self._discovery_artifact_manager
if LOCAL_DISCOVERY_ARTIFACT_MANAGER:
self._discovery_artifact_manager = Path(
LOCAL_DISCOVERY_ARTIFACT_MANAGER
).expanduser()
logger.debug(
f"Using local discovery_artifact_manager at {self._discovery_artifact_manager} for googleapis-private"
)
else:
logger.debug("Cloning discovery-artifact-manager.")
self._discovery_artifact_manager = git.clone(DISCOVERY_ARTIFACT_MANAGER_URL)
return self._discovery_artifact_manager
def _ensure_dependencies_installed(self):
logger.debug("Ensuring dependencies.")
dependencies = ["bazel", "zip", "unzip", "tar"]
failed_dependencies = []
for dependency in dependencies:
return_code = shell.run(["which", dependency], check=False).returncode
if return_code:
failed_dependencies.append(dependency)
if failed_dependencies:
raise EnvironmentError(
f"Dependencies missing: {", ".join(failed_dependencies)}"
)
| # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pathlib import Path
from typing import Optional, Union
import os
import shutil
import tempfile
from synthtool import _tracked_paths, metadata, shell
from synthtool.log import logger
from synthtool.sources import git
GOOGLEAPIS_URL: str = git.make_repo_clone_url("googleapis/googleapis")
GOOGLEAPIS_PRIVATE_URL: str = git.make_repo_clone_url("googleapis/googleapis-private")
DISCOVERY_ARTIFACT_MANAGER_URL: str = git.make_repo_clone_url(
"googleapis/discovery-artifact-manager"
)
LOCAL_GOOGLEAPIS: Optional[str] = os.environ.get("SYNTHTOOL_GOOGLEAPIS")
LOCAL_DISCOVERY_ARTIFACT_MANAGER: Optional[str] = os.environ.get(
"SYNTHTOOL_DISCOVERY_ARTIFACT_MANAGER"
)
class GAPICBazel:
"""A synthtool component that can produce libraries using bazel build.
"""
def __init__(self):
self._ensure_dependencies_installed()
self._googleapis = None
self._googleapis_private = None
self._discovery_artifact_manager = None
def py_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "python", **kwargs)
def go_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "go", **kwargs)
def node_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "nodejs", **kwargs)
def csharp_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "csharp", **kwargs)
def php_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "php", **kwargs)
def java_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(
service, version, "java", tar_strip_components=0, **kwargs
)
def ruby_library(self, service: str, version: str, **kwargs) -> Path:
return self._generate_code(service, version, "ruby", **kwargs)
def _generate_code(
self,
service: str,
version: str,
language: str,
*,
private: bool = False,
discogapic: bool = False,
proto_path: Union[str, Path] = None,
output_dir: Union[str, Path] = None,
bazel_target: str = None,
include_protos: bool = False,
proto_output_path: Union[str, Path] = None,
tar_strip_components: int = 1,
):
# Determine which googleapis repo to use
if discogapic:
api_definitions_repo = self._clone_discovery_artifact_manager()
api_definitions_repo_name = "discovery-artifact-manager"
elif private:
api_definitions_repo = self._clone_googleapis_private()
api_definitions_repo_name = "googleapis_private"
else:
api_definitions_repo = self._clone_googleapis()
api_definitions_repo_name = "googleapis"
# Sanity check: We should have a googleapis repo; if we do not,
# something went wrong, and we should abort.
if not api_definitions_repo:
raise RuntimeError(
f"Unable to generate {service}, the sources repository repository"
"is unavailable."
)
# Calculate proto_path if necessary.
if not bazel_target or include_protos:
# If bazel_target is not specified explicitly, we will need
# proto_path to calculate it. If include_protos is True,
# we will need the proto_path to copy the protos.
if not proto_path:
if bazel_target:
# Calculate proto_path from the full bazel target, which is
# in the format "//proto_path:target_name
proto_path = bazel_target.split(":")[0][2:]
else:
# If bazel_target is not specified, assume the protos are
# simply under google/cloud, where the most of the protos
# usually are.
proto_path = f"google/cloud/{service}/{version}"
protos = Path(proto_path)
if protos.is_absolute():
protos = protos.relative_to("/")
# Determine bazel target based on per-language patterns
# Java: google-cloud-{{assembly_name}}-{{version}}-java
# Go: gapi-cloud-{{assembly_name}}-{{version}}-go
# Python: {{assembly_name}}-{{version}}-py
# PHP: google-cloud-{{assembly_name}}-{{version}}-php
# Node.js: {{assembly_name}}-{{version}}-nodejs
# Ruby: google-cloud-{{assembly_name}}-{{version}}-ruby
# C#: google-cloud-{{assembly_name}}-{{version}}-csharp
if not bazel_target:
# Determine where the protos we are generating actually live.
# We can sometimes (but not always) determine this from the service
# and version; in other cases, the user must provide it outright.
parts = list(protos.parts)
while len(parts) > 0 and parts[0] != "google":
parts.pop(0)
if len(parts) == 0:
raise RuntimeError(
f"Cannot determine bazel_target from proto_path {protos}."
"Please set bazel_target explicitly."
)
if language == "python":
suffix = f"{service}-{version}-py"
elif language == "nodejs":
suffix = f"{service}-{version}-nodejs"
elif language == "go":
suffix = f"gapi-{'-'.join(parts[1:])}-go"
else:
suffix = f"{'-'.join(parts)}-{language}"
bazel_target = f"//{os.path.sep.join(parts)}:{suffix}"
# Sanity check: Do we have protos where we think we should?
if not (api_definitions_repo / protos).exists():
raise FileNotFoundError(
f"Unable to find directory for protos: {(api_definitions_repo / protos)}."
)
if not tuple((api_definitions_repo / protos).glob("*.proto")):
raise FileNotFoundError(
f"Directory {(api_definitions_repo / protos)} exists, but no protos found."
)
if not (api_definitions_repo / protos / "BUILD.bazel"):
raise FileNotFoundError(
f"File {(api_definitions_repo / protos / 'BUILD.bazel')} does not exist."
)
# Ensure the desired output directory exists.
# If none was provided, create a temporary directory.
if not output_dir:
output_dir = tempfile.mkdtemp()
output_dir = Path(output_dir).resolve()
# Let's build some stuff now.
cwd = os.getcwd()
os.chdir(str(api_definitions_repo))
bazel_run_args = [
"bazel",
"--max_idle_secs=240",
"build",
bazel_target,
]
logger.debug(f"Generating code for: {bazel_target}.")
shell.run(bazel_run_args)
# We've got tar file!
# its location: bazel-bin/google/cloud/language/v1/language-v1-nodejs.tar.gz
# bazel_target: //google/cloud/language/v1:language-v1-nodejs
tar_file = (
f"bazel-bin{os.path.sep}{bazel_target[2:].replace(':', os.path.sep)}.tar.gz"
)
tar_run_args = [
"tar",
"-C",
str(output_dir),
f"--strip-components={tar_strip_components}",
"-xzf",
tar_file,
]
shell.run(tar_run_args)
# Get the *.protos files and put them in a protos dir in the output
if include_protos:
proto_files = protos.glob("**/*.proto")
# By default, put the protos at the root in a folder named 'protos'.
# Specific languages can be cased here to put them in a more language
# appropriate place.
if not proto_output_path:
proto_output_path = output_dir / "protos"
if language == "python":
# place protos alongsize the *_pb2.py files
proto_output_path = (
output_dir / f"google/cloud/{service}_{version}/proto"
)
else:
proto_output_path = Path(output_dir / proto_output_path)
os.makedirs(proto_output_path, exist_ok=True)
for i in proto_files:
logger.debug(f"Copy: {i} to {proto_output_path / i.name}")
shutil.copyfile(i, proto_output_path / i.name)
logger.success(f"Placed proto files into {proto_output_path}.")
os.chdir(cwd)
# Sanity check: Does the output location have code in it?
# If not, complain.
if not tuple(output_dir.iterdir()):
raise RuntimeError(
f"Code generation seemed to succeed, but {output_dir} is empty."
)
# Huzzah, it worked.
logger.success(f"Generated code into {output_dir}.")
# Record this in the synthtool metadata.
metadata.add_client_destination(
source=api_definitions_repo_name,
api_name=service,
api_version=version,
language=language,
generator="bazel",
)
_tracked_paths.add(output_dir)
return output_dir
def _clone_googleapis(self):
if self._googleapis:
return self._googleapis
if LOCAL_GOOGLEAPIS:
self._googleapis = Path(LOCAL_GOOGLEAPIS).expanduser()
logger.debug(f"Using local googleapis at {self._googleapis}")
else:
logger.debug("Cloning googleapis.")
self._googleapis = git.clone(GOOGLEAPIS_URL)
return self._googleapis
def _clone_googleapis_private(self):
if self._googleapis_private:
return self._googleapis_private
if LOCAL_GOOGLEAPIS:
self._googleapis_private = Path(LOCAL_GOOGLEAPIS).expanduser()
logger.debug(
f"Using local googleapis at {self._googleapis_private} for googleapis-private"
)
else:
logger.debug("Cloning googleapis-private.")
self._googleapis_private = git.clone(GOOGLEAPIS_PRIVATE_URL)
return self._googleapis_private
def _clone_discovery_artifact_manager(self):
if self._discovery_artifact_manager:
return self._discovery_artifact_manager
if LOCAL_DISCOVERY_ARTIFACT_MANAGER:
self._discovery_artifact_manager = Path(
LOCAL_DISCOVERY_ARTIFACT_MANAGER
).expanduser()
logger.debug(
f"Using local discovery_artifact_manager at {self._discovery_artifact_manager} for googleapis-private"
)
else:
logger.debug("Cloning discovery-artifact-manager.")
self._discovery_artifact_manager = git.clone(DISCOVERY_ARTIFACT_MANAGER_URL)
return self._discovery_artifact_manager
def _ensure_dependencies_installed(self):
logger.debug("Ensuring dependencies.")
dependencies = ["bazel", "zip", "unzip", "tar"]
failed_dependencies = []
for dependency in dependencies:
return_code = shell.run(["which", dependency], check=False).returncode
if return_code:
failed_dependencies.append(dependency)
if failed_dependencies:
raise EnvironmentError(
f"Dependencies missing: {', '.join(failed_dependencies)}"
)
|
from abc import ABC, abstractmethod
from enum import Enum, auto
from itertools import chain
from typing import (
Any,
ClassVar,
Dict,
FrozenSet,
Iterable,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
)
from datamodel_code_generator.format import PythonVersion
from datamodel_code_generator.imports import (
IMPORT_ABC_MAPPING,
IMPORT_ABC_SEQUENCE,
IMPORT_DICT,
IMPORT_LIST,
IMPORT_LITERAL,
IMPORT_MAPPING,
IMPORT_OPTIONAL,
IMPORT_SEQUENCE,
IMPORT_UNION,
Import,
)
from datamodel_code_generator.reference import Reference, _BaseModel
T = TypeVar('T')
class StrictTypes(Enum):
str = 'str'
bytes = 'bytes'
int = 'int'
float = 'float'
bool = 'bool'
def chain_as_tuple(*iterables: Iterable[T]) -> Tuple[T, ...]:
return tuple(chain(*iterables))
class DataType(_BaseModel):
type: Optional[str]
reference: Optional[Reference]
data_types: List['DataType'] = []
is_func: bool = False
kwargs: Optional[Dict[str, Any]]
imports: List[Import] = []
python_version: PythonVersion = PythonVersion.PY_38
is_optional: bool = False
is_dict: bool = False
is_list: bool = False
literals: List[str] = []
use_standard_collections: bool = False
use_generic_container: bool = False
alias: Optional[str] = None
parent: Optional[Any] = None
children: List[Any] = []
strict: bool = False
_exclude_fields: ClassVar[Set[str]] = {'parent', 'children'}
_pass_fields: ClassVar[Set[str]] = {'parent', 'children', 'data_types', 'reference'}
@classmethod
def from_import(
cls,
import_: Import,
*,
is_optional: bool = False,
is_dict: bool = False,
is_list: bool = False,
strict: bool = False,
kwargs: Optional[Dict[str, Any]] = None,
) -> 'DataType':
return cls(
type=import_.import_,
imports=[import_],
is_optional=is_optional,
is_dict=is_dict,
is_list=is_list,
is_func=True if kwargs else False,
strict=strict,
kwargs=kwargs,
)
@property
def unresolved_types(self) -> FrozenSet[str]:
return frozenset(
{
t.reference.path
for data_types in self.data_types
for t in data_types.all_data_types
if t.reference
}
| ({self.reference.path} if self.reference else set())
)
def replace_reference(self, reference: Reference) -> None:
if not self.reference: # pragma: no cover
raise Exception(
f'`{self.__class__.__name__}.replace_reference()` can\'t be called'
f' when `reference` field is empty.'
)
self.reference.children.remove(self)
self.reference = reference
reference.children.append(self)
@property
def module_name(self) -> Optional[str]:
return self.reference.module_name if self.reference else None
@property
def full_name(self) -> str:
module_name = self.module_name
if module_name:
return f'{module_name}.{self.type}'
return self.type # type: ignore
@property
def all_data_types(self) -> Iterator['DataType']:
for data_type in self.data_types:
yield from data_type.all_data_types
yield self
@property
def is_enum(self) -> bool:
return (
self.reference.source.base_class == 'Enum'
if self.reference and self.reference.source
else False
)
@property
def all_imports(self) -> Iterator[Import]:
for data_type in self.data_types:
yield from data_type.all_imports
yield from self.imports
def __init__(self, **values: Any) -> None:
super().__init__(**values) # type: ignore
for type_ in self.data_types:
if type_.type == 'Any' and type_.is_optional:
if any(
t for t in self.data_types if t.type != 'Any'
): # pragma: no cover
self.is_optional = True
self.data_types = [
t
for t in self.data_types
if not (t.type == 'Any' and t.is_optional)
]
break
imports: Tuple[Tuple[bool, Import], ...] = (
(self.is_optional, IMPORT_OPTIONAL),
(len(self.data_types) > 1, IMPORT_UNION),
(any(self.literals), IMPORT_LITERAL),
)
if self.use_generic_container:
if self.use_standard_collections:
imports = (
*imports,
(self.is_list, IMPORT_ABC_SEQUENCE),
(self.is_dict, IMPORT_ABC_MAPPING),
)
else:
imports = (
*imports,
(self.is_list, IMPORT_SEQUENCE),
(self.is_dict, IMPORT_MAPPING),
)
elif not self.use_standard_collections:
imports = (
*imports,
(self.is_list, IMPORT_LIST),
(self.is_dict, IMPORT_DICT),
)
for field, import_ in imports:
if field and import_ not in self.imports:
self.imports.append(import_)
for data_type in self.data_types:
if data_type.reference:
data_type.parent = self
if self.reference:
self.reference.children.append(self)
@property
def type_hint(self) -> str:
type_: Optional[str] = self.alias or self.type
if not type_:
if len(self.data_types) > 1:
type_ = f"Union[{", ".join(data_type.type_hint for data_type in self.data_types)}]"
elif len(self.data_types) == 1:
type_ = self.data_types[0].type_hint
elif self.literals:
type_ = (
f"Literal[{", ".join(repr(literal) for literal in self.literals)}]"
)
else:
if self.reference:
type_ = self.reference.short_name
else:
# TODO support strict Any
# type_ = 'Any'
type_ = ''
if self.is_list:
if self.use_generic_container:
list_ = 'Sequence'
elif self.use_standard_collections:
list_ = 'list'
else:
list_ = 'List'
type_ = f'{list_}[{type_}]' if type_ else list_
elif self.is_dict:
if self.use_generic_container:
dict_ = 'Mapping'
elif self.use_standard_collections:
dict_ = 'dict'
else:
dict_ = 'Dict'
type_ = f'{dict_}[str, {type_}]' if type_ else dict_
if self.is_optional and type_ != 'Any':
type_ = f'Optional[{type_}]'
elif self.is_func:
if self.kwargs:
kwargs: str = ', '.join(f'{k}={v}' for k, v in self.kwargs.items())
return f'{type_}({kwargs})'
return f'{type_}()'
return type_
DataType.update_forward_refs()
class DataTypeStandardCollections(DataType):
use_standard_collections: bool = True
class DataTypeGenericContainer(DataType):
use_generic_container: bool = True
class DataTypeGenericContainerStandardCollections(DataType):
use_standard_collections: bool = True
use_generic_container: bool = True
class Types(Enum):
integer = auto()
int32 = auto()
int64 = auto()
number = auto()
float = auto()
double = auto()
decimal = auto()
time = auto()
string = auto()
byte = auto()
binary = auto()
date = auto()
date_time = auto()
password = auto()
email = auto()
uuid = auto()
uuid1 = auto()
uuid2 = auto()
uuid3 = auto()
uuid4 = auto()
uuid5 = auto()
uri = auto()
hostname = auto()
ipv4 = auto()
ipv6 = auto()
boolean = auto()
object = auto()
null = auto()
array = auto()
any = auto()
class DataTypeManager(ABC):
def __init__(
self,
python_version: PythonVersion = PythonVersion.PY_38,
use_standard_collections: bool = False,
use_generic_container_types: bool = False,
strict_types: Optional[Sequence[StrictTypes]] = None,
) -> None:
self.python_version = python_version
self.use_standard_collections: bool = use_standard_collections
self.use_generic_container_types: bool = use_generic_container_types
self.strict_types: Sequence[StrictTypes] = strict_types or ()
self.data_type: Type[DataType]
if use_generic_container_types:
if use_standard_collections:
self.data_type = DataTypeGenericContainerStandardCollections
else:
self.data_type = DataTypeGenericContainer
elif use_standard_collections:
self.data_type = DataTypeStandardCollections
else:
self.data_type = DataType
@abstractmethod
def get_data_type(self, types: Types, **kwargs: Any) -> DataType:
raise NotImplementedError
| from abc import ABC, abstractmethod
from enum import Enum, auto
from itertools import chain
from typing import (
Any,
ClassVar,
Dict,
FrozenSet,
Iterable,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
)
from datamodel_code_generator.format import PythonVersion
from datamodel_code_generator.imports import (
IMPORT_ABC_MAPPING,
IMPORT_ABC_SEQUENCE,
IMPORT_DICT,
IMPORT_LIST,
IMPORT_LITERAL,
IMPORT_MAPPING,
IMPORT_OPTIONAL,
IMPORT_SEQUENCE,
IMPORT_UNION,
Import,
)
from datamodel_code_generator.reference import Reference, _BaseModel
T = TypeVar('T')
class StrictTypes(Enum):
str = 'str'
bytes = 'bytes'
int = 'int'
float = 'float'
bool = 'bool'
def chain_as_tuple(*iterables: Iterable[T]) -> Tuple[T, ...]:
return tuple(chain(*iterables))
class DataType(_BaseModel):
type: Optional[str]
reference: Optional[Reference]
data_types: List['DataType'] = []
is_func: bool = False
kwargs: Optional[Dict[str, Any]]
imports: List[Import] = []
python_version: PythonVersion = PythonVersion.PY_38
is_optional: bool = False
is_dict: bool = False
is_list: bool = False
literals: List[str] = []
use_standard_collections: bool = False
use_generic_container: bool = False
alias: Optional[str] = None
parent: Optional[Any] = None
children: List[Any] = []
strict: bool = False
_exclude_fields: ClassVar[Set[str]] = {'parent', 'children'}
_pass_fields: ClassVar[Set[str]] = {'parent', 'children', 'data_types', 'reference'}
@classmethod
def from_import(
cls,
import_: Import,
*,
is_optional: bool = False,
is_dict: bool = False,
is_list: bool = False,
strict: bool = False,
kwargs: Optional[Dict[str, Any]] = None,
) -> 'DataType':
return cls(
type=import_.import_,
imports=[import_],
is_optional=is_optional,
is_dict=is_dict,
is_list=is_list,
is_func=True if kwargs else False,
strict=strict,
kwargs=kwargs,
)
@property
def unresolved_types(self) -> FrozenSet[str]:
return frozenset(
{
t.reference.path
for data_types in self.data_types
for t in data_types.all_data_types
if t.reference
}
| ({self.reference.path} if self.reference else set())
)
def replace_reference(self, reference: Reference) -> None:
if not self.reference: # pragma: no cover
raise Exception(
f'`{self.__class__.__name__}.replace_reference()` can\'t be called'
f' when `reference` field is empty.'
)
self.reference.children.remove(self)
self.reference = reference
reference.children.append(self)
@property
def module_name(self) -> Optional[str]:
return self.reference.module_name if self.reference else None
@property
def full_name(self) -> str:
module_name = self.module_name
if module_name:
return f'{module_name}.{self.type}'
return self.type # type: ignore
@property
def all_data_types(self) -> Iterator['DataType']:
for data_type in self.data_types:
yield from data_type.all_data_types
yield self
@property
def is_enum(self) -> bool:
return (
self.reference.source.base_class == 'Enum'
if self.reference and self.reference.source
else False
)
@property
def all_imports(self) -> Iterator[Import]:
for data_type in self.data_types:
yield from data_type.all_imports
yield from self.imports
def __init__(self, **values: Any) -> None:
super().__init__(**values) # type: ignore
for type_ in self.data_types:
if type_.type == 'Any' and type_.is_optional:
if any(
t for t in self.data_types if t.type != 'Any'
): # pragma: no cover
self.is_optional = True
self.data_types = [
t
for t in self.data_types
if not (t.type == 'Any' and t.is_optional)
]
break
imports: Tuple[Tuple[bool, Import], ...] = (
(self.is_optional, IMPORT_OPTIONAL),
(len(self.data_types) > 1, IMPORT_UNION),
(any(self.literals), IMPORT_LITERAL),
)
if self.use_generic_container:
if self.use_standard_collections:
imports = (
*imports,
(self.is_list, IMPORT_ABC_SEQUENCE),
(self.is_dict, IMPORT_ABC_MAPPING),
)
else:
imports = (
*imports,
(self.is_list, IMPORT_SEQUENCE),
(self.is_dict, IMPORT_MAPPING),
)
elif not self.use_standard_collections:
imports = (
*imports,
(self.is_list, IMPORT_LIST),
(self.is_dict, IMPORT_DICT),
)
for field, import_ in imports:
if field and import_ not in self.imports:
self.imports.append(import_)
for data_type in self.data_types:
if data_type.reference:
data_type.parent = self
if self.reference:
self.reference.children.append(self)
@property
def type_hint(self) -> str:
type_: Optional[str] = self.alias or self.type
if not type_:
if len(self.data_types) > 1:
type_ = f"Union[{', '.join(data_type.type_hint for data_type in self.data_types)}]"
elif len(self.data_types) == 1:
type_ = self.data_types[0].type_hint
elif self.literals:
type_ = (
f"Literal[{', '.join(repr(literal) for literal in self.literals)}]"
)
else:
if self.reference:
type_ = self.reference.short_name
else:
# TODO support strict Any
# type_ = 'Any'
type_ = ''
if self.is_list:
if self.use_generic_container:
list_ = 'Sequence'
elif self.use_standard_collections:
list_ = 'list'
else:
list_ = 'List'
type_ = f'{list_}[{type_}]' if type_ else list_
elif self.is_dict:
if self.use_generic_container:
dict_ = 'Mapping'
elif self.use_standard_collections:
dict_ = 'dict'
else:
dict_ = 'Dict'
type_ = f'{dict_}[str, {type_}]' if type_ else dict_
if self.is_optional and type_ != 'Any':
type_ = f'Optional[{type_}]'
elif self.is_func:
if self.kwargs:
kwargs: str = ', '.join(f'{k}={v}' for k, v in self.kwargs.items())
return f'{type_}({kwargs})'
return f'{type_}()'
return type_
DataType.update_forward_refs()
class DataTypeStandardCollections(DataType):
use_standard_collections: bool = True
class DataTypeGenericContainer(DataType):
use_generic_container: bool = True
class DataTypeGenericContainerStandardCollections(DataType):
use_standard_collections: bool = True
use_generic_container: bool = True
class Types(Enum):
integer = auto()
int32 = auto()
int64 = auto()
number = auto()
float = auto()
double = auto()
decimal = auto()
time = auto()
string = auto()
byte = auto()
binary = auto()
date = auto()
date_time = auto()
password = auto()
email = auto()
uuid = auto()
uuid1 = auto()
uuid2 = auto()
uuid3 = auto()
uuid4 = auto()
uuid5 = auto()
uri = auto()
hostname = auto()
ipv4 = auto()
ipv6 = auto()
boolean = auto()
object = auto()
null = auto()
array = auto()
any = auto()
class DataTypeManager(ABC):
def __init__(
self,
python_version: PythonVersion = PythonVersion.PY_38,
use_standard_collections: bool = False,
use_generic_container_types: bool = False,
strict_types: Optional[Sequence[StrictTypes]] = None,
) -> None:
self.python_version = python_version
self.use_standard_collections: bool = use_standard_collections
self.use_generic_container_types: bool = use_generic_container_types
self.strict_types: Sequence[StrictTypes] = strict_types or ()
self.data_type: Type[DataType]
if use_generic_container_types:
if use_standard_collections:
self.data_type = DataTypeGenericContainerStandardCollections
else:
self.data_type = DataTypeGenericContainer
elif use_standard_collections:
self.data_type = DataTypeStandardCollections
else:
self.data_type = DataType
@abstractmethod
def get_data_type(self, types: Types, **kwargs: Any) -> DataType:
raise NotImplementedError
|
#!/usr/bin/env python3
# Copyright (c) 2018-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoin-wallet."""
import hashlib
import os
import stat
import subprocess
import textwrap
from collections import OrderedDict
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
BUFFER_SIZE = 16 * 1024
class ToolWalletTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
self.rpc_timeout = 120
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
self.skip_if_no_wallet_tool()
def bitcoin_wallet_process(self, *args):
binary = self.config["environment"]["BUILDDIR"] + '/src/xaya-wallet' + self.config["environment"]["EXEEXT"]
default_args = ['-datadir={}'.format(self.nodes[0].datadir), '-chain=%s' % self.chain]
if not self.options.descriptors and 'create' in args:
default_args.append('-legacy')
return subprocess.Popen([binary] + default_args + list(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
def assert_raises_tool_error(self, error, *args):
p = self.bitcoin_wallet_process(*args)
stdout, stderr = p.communicate()
assert_equal(p.poll(), 1)
assert_equal(stdout, '')
assert_equal(stderr.strip(), error)
def assert_tool_output(self, output, *args):
p = self.bitcoin_wallet_process(*args)
stdout, stderr = p.communicate()
assert_equal(stderr, '')
assert_equal(stdout, output)
assert_equal(p.poll(), 0)
def wallet_shasum(self):
h = hashlib.sha1()
mv = memoryview(bytearray(BUFFER_SIZE))
with open(self.wallet_path, 'rb', buffering=0) as f:
for n in iter(lambda: f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
def wallet_timestamp(self):
return os.path.getmtime(self.wallet_path)
def wallet_permissions(self):
return oct(os.lstat(self.wallet_path).st_mode)[-3:]
def log_wallet_timestamp_comparison(self, old, new):
result = 'unchanged' if new == old else 'increased!'
self.log.debug('Wallet file timestamp {}'.format(result))
def get_expected_info_output(self, name="", transactions=0, keypool=2, address=0):
wallet_name = self.default_wallet_name if name == "" else name
if self.options.descriptors:
output_types = 4 # p2pkh, p2sh, segwit, bech32m
return textwrap.dedent('''\
Wallet info
===========
Name: %s
Format: sqlite
Descriptors: yes
Encrypted: no
HD (hd seed available): yes
Keypool Size: %d
Transactions: %d
Address Book: %d
''' % (wallet_name, keypool * output_types, transactions, address))
else:
output_types = 3 # p2pkh, p2sh, segwit. Legacy wallets do not support bech32m.
return textwrap.dedent('''\
Wallet info
===========
Name: %s
Format: bdb
Descriptors: no
Encrypted: no
HD (hd seed available): yes
Keypool Size: %d
Transactions: %d
Address Book: %d
''' % (wallet_name, keypool, transactions, address * output_types))
def read_dump(self, filename):
dump = OrderedDict()
with open(filename, "r", encoding="utf8") as f:
for row in f:
row = row.strip()
key, value = row.split(',')
dump[key] = value
return dump
def assert_is_sqlite(self, filename):
with open(filename, 'rb') as f:
file_magic = f.read(16)
assert file_magic == b'SQLite format 3\x00'
def assert_is_bdb(self, filename):
with open(filename, 'rb') as f:
f.seek(12, 0)
file_magic = f.read(4)
assert file_magic == b'\x00\x05\x31\x62' or file_magic == b'\x62\x31\x05\x00'
def write_dump(self, dump, filename, magic=None, skip_checksum=False):
if magic is None:
magic = "BITCOIN_CORE_WALLET_DUMP"
with open(filename, "w", encoding="utf8") as f:
row = ",".join([magic, dump[magic]]) + "\n"
f.write(row)
for k, v in dump.items():
if k == magic or k == "checksum":
continue
row = ",".join([k, v]) + "\n"
f.write(row)
if not skip_checksum:
row = ",".join(["checksum", dump["checksum"]]) + "\n"
f.write(row)
def assert_dump(self, expected, received):
e = expected.copy()
r = received.copy()
# BDB will add a "version" record that is not present in sqlite
# In that case, we should ignore this record in both
# But because this also effects the checksum, we also need to drop that.
v_key = "0776657273696f6e" # Version key
if v_key in e and v_key not in r:
del e[v_key]
del e["checksum"]
del r["checksum"]
if v_key not in e and v_key in r:
del r[v_key]
del e["checksum"]
del r["checksum"]
assert_equal(len(e), len(r))
for k, v in e.items():
assert_equal(v, r[k])
def do_tool_createfromdump(self, wallet_name, dumpfile, file_format=None):
dumppath = os.path.join(self.nodes[0].datadir, dumpfile)
rt_dumppath = os.path.join(self.nodes[0].datadir, "rt-{}.dump".format(wallet_name))
dump_data = self.read_dump(dumppath)
args = ["-wallet={}".format(wallet_name),
"-dumpfile={}".format(dumppath)]
if file_format is not None:
args.append("-format={}".format(file_format))
args.append("createfromdump")
load_output = ""
if file_format is not None and file_format != dump_data["format"]:
load_output += "Warning: Dumpfile wallet format \"{}\" does not match command line specified format \"{}\".\n".format(dump_data["format"], file_format)
self.assert_tool_output(load_output, *args)
assert os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", wallet_name))
self.assert_tool_output("The dumpfile may contain private keys. To ensure the safety of your Bitcoin, do not share the dumpfile.\n", '-wallet={}'.format(wallet_name), '-dumpfile={}'.format(rt_dumppath), 'dump')
rt_dump_data = self.read_dump(rt_dumppath)
wallet_dat = os.path.join(self.nodes[0].datadir, "regtest/wallets/", wallet_name, "wallet.dat")
if rt_dump_data["format"] == "bdb":
self.assert_is_bdb(wallet_dat)
else:
self.assert_is_sqlite(wallet_dat)
def test_invalid_tool_commands_and_args(self):
self.log.info('Testing that various invalid commands raise with specific error messages')
self.assert_raises_tool_error("Error parsing command line arguments: Invalid command 'foo'", 'foo')
# `bitcoin-wallet help` raises an error. Use `bitcoin-wallet -help`.
self.assert_raises_tool_error("Error parsing command line arguments: Invalid command 'help'", 'help')
self.assert_raises_tool_error('Error: Additional arguments provided (create). Methods do not take arguments. Please refer to `-help`.', 'info', 'create')
self.assert_raises_tool_error('Error parsing command line arguments: Invalid parameter -foo', '-foo')
self.assert_raises_tool_error('No method provided. Run `xaya-wallet -help` for valid methods.')
self.assert_raises_tool_error('Wallet name must be provided when creating a new wallet.', 'create')
locked_dir = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets")
error = 'Error initializing wallet database environment "{}"!'.format(locked_dir)
if self.options.descriptors:
error = f"SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another instance of {self.config["environment"]["PACKAGE_NAME"]}?"
self.assert_raises_tool_error(
error,
'-wallet=' + self.default_wallet_name,
'info',
)
path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "nonexistent.dat")
self.assert_raises_tool_error("Failed to load database path '{}'. Path does not exist.".format(path), '-wallet=nonexistent.dat', 'info')
def test_tool_wallet_info(self):
# Stop the node to close the wallet to call the info command.
self.stop_node(0)
self.log.info('Calling wallet tool info, testing output')
#
# TODO: Wallet tool info should work with wallet file permissions set to
# read-only without raising:
# "Error loading wallet.dat. Is wallet being used by another process?"
# The following lines should be uncommented and the tests still succeed:
#
# self.log.debug('Setting wallet file permissions to 400 (read-only)')
# os.chmod(self.wallet_path, stat.S_IRUSR)
# assert self.wallet_permissions() in ['400', '666'] # Sanity check. 666 because Appveyor.
# shasum_before = self.wallet_shasum()
timestamp_before = self.wallet_timestamp()
self.log.debug('Wallet file timestamp before calling info: {}'.format(timestamp_before))
out = self.get_expected_info_output(address=1)
self.assert_tool_output(out, '-wallet=' + self.default_wallet_name, 'info')
timestamp_after = self.wallet_timestamp()
self.log.debug('Wallet file timestamp after calling info: {}'.format(timestamp_after))
self.log_wallet_timestamp_comparison(timestamp_before, timestamp_after)
self.log.debug('Setting wallet file permissions back to 600 (read/write)')
os.chmod(self.wallet_path, stat.S_IRUSR | stat.S_IWUSR)
assert self.wallet_permissions() in ['600', '666'] # Sanity check. 666 because Appveyor.
#
# TODO: Wallet tool info should not write to the wallet file.
# The following lines should be uncommented and the tests still succeed:
#
# assert_equal(timestamp_before, timestamp_after)
# shasum_after = self.wallet_shasum()
# assert_equal(shasum_before, shasum_after)
# self.log.debug('Wallet file shasum unchanged\n')
def test_tool_wallet_info_after_transaction(self):
"""
Mutate the wallet with a transaction to verify that the info command
output changes accordingly.
"""
self.start_node(0)
self.log.info('Generating transaction to mutate wallet')
self.generate(self.nodes[0], 1)
self.stop_node(0)
self.log.info('Calling wallet tool info after generating a transaction, testing output')
shasum_before = self.wallet_shasum()
timestamp_before = self.wallet_timestamp()
self.log.debug('Wallet file timestamp before calling info: {}'.format(timestamp_before))
out = self.get_expected_info_output(transactions=1, address=1)
self.assert_tool_output(out, '-wallet=' + self.default_wallet_name, 'info')
shasum_after = self.wallet_shasum()
timestamp_after = self.wallet_timestamp()
self.log.debug('Wallet file timestamp after calling info: {}'.format(timestamp_after))
self.log_wallet_timestamp_comparison(timestamp_before, timestamp_after)
#
# TODO: Wallet tool info should not write to the wallet file.
# This assertion should be uncommented and succeed:
# assert_equal(timestamp_before, timestamp_after)
assert_equal(shasum_before, shasum_after)
self.log.debug('Wallet file shasum unchanged\n')
def test_tool_wallet_create_on_existing_wallet(self):
self.log.info('Calling wallet tool create on an existing wallet, testing output')
shasum_before = self.wallet_shasum()
timestamp_before = self.wallet_timestamp()
self.log.debug('Wallet file timestamp before calling create: {}'.format(timestamp_before))
out = "Topping up keypool...\n" + self.get_expected_info_output(name="foo", keypool=2000)
self.assert_tool_output(out, '-wallet=foo', 'create')
shasum_after = self.wallet_shasum()
timestamp_after = self.wallet_timestamp()
self.log.debug('Wallet file timestamp after calling create: {}'.format(timestamp_after))
self.log_wallet_timestamp_comparison(timestamp_before, timestamp_after)
assert_equal(timestamp_before, timestamp_after)
assert_equal(shasum_before, shasum_after)
self.log.debug('Wallet file shasum unchanged\n')
def test_getwalletinfo_on_different_wallet(self):
self.log.info('Starting node with arg -wallet=foo')
self.start_node(0, ['-nowallet', '-wallet=foo'])
self.log.info('Calling getwalletinfo on a different wallet ("foo"), testing output')
shasum_before = self.wallet_shasum()
timestamp_before = self.wallet_timestamp()
self.log.debug('Wallet file timestamp before calling getwalletinfo: {}'.format(timestamp_before))
out = self.nodes[0].getwalletinfo()
self.stop_node(0)
shasum_after = self.wallet_shasum()
timestamp_after = self.wallet_timestamp()
self.log.debug('Wallet file timestamp after calling getwalletinfo: {}'.format(timestamp_after))
assert_equal(0, out['txcount'])
if not self.options.descriptors:
assert_equal(1000, out['keypoolsize'])
assert_equal(1000, out['keypoolsize_hd_internal'])
assert_equal(True, 'hdseedid' in out)
else:
assert_equal(4000, out['keypoolsize'])
assert_equal(4000, out['keypoolsize_hd_internal'])
self.log_wallet_timestamp_comparison(timestamp_before, timestamp_after)
assert_equal(timestamp_before, timestamp_after)
assert_equal(shasum_after, shasum_before)
self.log.debug('Wallet file shasum unchanged\n')
def test_salvage(self):
# TODO: Check salvage actually salvages and doesn't break things. https://github.com/bitcoin/bitcoin/issues/7463
self.log.info('Check salvage')
self.start_node(0)
self.nodes[0].createwallet("salvage")
self.stop_node(0)
self.assert_tool_output('', '-wallet=salvage', 'salvage')
def test_dump_createfromdump(self):
self.start_node(0)
self.nodes[0].createwallet("todump")
file_format = self.nodes[0].get_wallet_rpc("todump").getwalletinfo()["format"]
self.nodes[0].createwallet("todump2")
self.stop_node(0)
self.log.info('Checking dump arguments')
self.assert_raises_tool_error('No dump file provided. To use dump, -dumpfile=<filename> must be provided.', '-wallet=todump', 'dump')
self.log.info('Checking basic dump')
wallet_dump = os.path.join(self.nodes[0].datadir, "wallet.dump")
self.assert_tool_output('The dumpfile may contain private keys. To ensure the safety of your Bitcoin, do not share the dumpfile.\n', '-wallet=todump', '-dumpfile={}'.format(wallet_dump), 'dump')
dump_data = self.read_dump(wallet_dump)
orig_dump = dump_data.copy()
# Check the dump magic
assert_equal(dump_data['BITCOIN_CORE_WALLET_DUMP'], '1')
# Check the file format
assert_equal(dump_data["format"], file_format)
self.log.info('Checking that a dumpfile cannot be overwritten')
self.assert_raises_tool_error('File {} already exists. If you are sure this is what you want, move it out of the way first.'.format(wallet_dump), '-wallet=todump2', '-dumpfile={}'.format(wallet_dump), 'dump')
self.log.info('Checking createfromdump arguments')
self.assert_raises_tool_error('No dump file provided. To use createfromdump, -dumpfile=<filename> must be provided.', '-wallet=todump', 'createfromdump')
non_exist_dump = os.path.join(self.nodes[0].datadir, "wallet.nodump")
self.assert_raises_tool_error('Unknown wallet file format "notaformat" provided. Please provide one of "bdb" or "sqlite".', '-wallet=todump', '-format=notaformat', '-dumpfile={}'.format(wallet_dump), 'createfromdump')
self.assert_raises_tool_error('Dump file {} does not exist.'.format(non_exist_dump), '-wallet=todump', '-dumpfile={}'.format(non_exist_dump), 'createfromdump')
wallet_path = os.path.join(self.nodes[0].datadir, 'regtest', 'wallets', 'todump2')
self.assert_raises_tool_error('Failed to create database path \'{}\'. Database already exists.'.format(wallet_path), '-wallet=todump2', '-dumpfile={}'.format(wallet_dump), 'createfromdump')
self.assert_raises_tool_error("The -descriptors option can only be used with the 'create' command.", '-descriptors', '-wallet=todump2', '-dumpfile={}'.format(wallet_dump), 'createfromdump')
self.log.info('Checking createfromdump')
self.do_tool_createfromdump("load", "wallet.dump")
if self.is_bdb_compiled():
self.do_tool_createfromdump("load-bdb", "wallet.dump", "bdb")
if self.is_sqlite_compiled():
self.do_tool_createfromdump("load-sqlite", "wallet.dump", "sqlite")
self.log.info('Checking createfromdump handling of magic and versions')
bad_ver_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_ver1.dump")
dump_data["BITCOIN_CORE_WALLET_DUMP"] = "0"
self.write_dump(dump_data, bad_ver_wallet_dump)
self.assert_raises_tool_error('Error: Dumpfile version is not supported. This version of xaya-wallet only supports version 1 dumpfiles. Got dumpfile with version 0', '-wallet=badload', '-dumpfile={}'.format(bad_ver_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
bad_ver_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_ver2.dump")
dump_data["BITCOIN_CORE_WALLET_DUMP"] = "2"
self.write_dump(dump_data, bad_ver_wallet_dump)
self.assert_raises_tool_error('Error: Dumpfile version is not supported. This version of xaya-wallet only supports version 1 dumpfiles. Got dumpfile with version 2', '-wallet=badload', '-dumpfile={}'.format(bad_ver_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
bad_magic_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_magic.dump")
del dump_data["BITCOIN_CORE_WALLET_DUMP"]
dump_data["not_the_right_magic"] = "1"
self.write_dump(dump_data, bad_magic_wallet_dump, "not_the_right_magic")
self.assert_raises_tool_error('Error: Dumpfile identifier record is incorrect. Got "not_the_right_magic", expected "BITCOIN_CORE_WALLET_DUMP".', '-wallet=badload', '-dumpfile={}'.format(bad_magic_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
self.log.info('Checking createfromdump handling of checksums')
bad_sum_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_sum1.dump")
dump_data = orig_dump.copy()
checksum = dump_data["checksum"]
dump_data["checksum"] = "1" * 64
self.write_dump(dump_data, bad_sum_wallet_dump)
self.assert_raises_tool_error('Error: Dumpfile checksum does not match. Computed {}, expected {}'.format(checksum, "1" * 64), '-wallet=bad', '-dumpfile={}'.format(bad_sum_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
bad_sum_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_sum2.dump")
del dump_data["checksum"]
self.write_dump(dump_data, bad_sum_wallet_dump, skip_checksum=True)
self.assert_raises_tool_error('Error: Missing checksum', '-wallet=badload', '-dumpfile={}'.format(bad_sum_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
bad_sum_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_sum3.dump")
dump_data["checksum"] = "2" * 10
self.write_dump(dump_data, bad_sum_wallet_dump)
self.assert_raises_tool_error('Error: Checksum is not the correct size', '-wallet=badload', '-dumpfile={}'.format(bad_sum_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
dump_data["checksum"] = "3" * 66
self.write_dump(dump_data, bad_sum_wallet_dump)
self.assert_raises_tool_error('Error: Checksum is not the correct size', '-wallet=badload', '-dumpfile={}'.format(bad_sum_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
def run_test(self):
self.wallet_path = os.path.join(self.nodes[0].datadir, self.chain, 'wallets', self.default_wallet_name, self.wallet_data_filename)
self.test_invalid_tool_commands_and_args()
# Warning: The following tests are order-dependent.
self.test_tool_wallet_info()
self.test_tool_wallet_info_after_transaction()
self.test_tool_wallet_create_on_existing_wallet()
self.test_getwalletinfo_on_different_wallet()
if not self.options.descriptors:
# Salvage is a legacy wallet only thing
self.test_salvage()
self.test_dump_createfromdump()
if __name__ == '__main__':
ToolWalletTest().main()
| #!/usr/bin/env python3
# Copyright (c) 2018-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoin-wallet."""
import hashlib
import os
import stat
import subprocess
import textwrap
from collections import OrderedDict
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
BUFFER_SIZE = 16 * 1024
class ToolWalletTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
self.rpc_timeout = 120
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
self.skip_if_no_wallet_tool()
def bitcoin_wallet_process(self, *args):
binary = self.config["environment"]["BUILDDIR"] + '/src/xaya-wallet' + self.config["environment"]["EXEEXT"]
default_args = ['-datadir={}'.format(self.nodes[0].datadir), '-chain=%s' % self.chain]
if not self.options.descriptors and 'create' in args:
default_args.append('-legacy')
return subprocess.Popen([binary] + default_args + list(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
def assert_raises_tool_error(self, error, *args):
p = self.bitcoin_wallet_process(*args)
stdout, stderr = p.communicate()
assert_equal(p.poll(), 1)
assert_equal(stdout, '')
assert_equal(stderr.strip(), error)
def assert_tool_output(self, output, *args):
p = self.bitcoin_wallet_process(*args)
stdout, stderr = p.communicate()
assert_equal(stderr, '')
assert_equal(stdout, output)
assert_equal(p.poll(), 0)
def wallet_shasum(self):
h = hashlib.sha1()
mv = memoryview(bytearray(BUFFER_SIZE))
with open(self.wallet_path, 'rb', buffering=0) as f:
for n in iter(lambda: f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
def wallet_timestamp(self):
return os.path.getmtime(self.wallet_path)
def wallet_permissions(self):
return oct(os.lstat(self.wallet_path).st_mode)[-3:]
def log_wallet_timestamp_comparison(self, old, new):
result = 'unchanged' if new == old else 'increased!'
self.log.debug('Wallet file timestamp {}'.format(result))
def get_expected_info_output(self, name="", transactions=0, keypool=2, address=0):
wallet_name = self.default_wallet_name if name == "" else name
if self.options.descriptors:
output_types = 4 # p2pkh, p2sh, segwit, bech32m
return textwrap.dedent('''\
Wallet info
===========
Name: %s
Format: sqlite
Descriptors: yes
Encrypted: no
HD (hd seed available): yes
Keypool Size: %d
Transactions: %d
Address Book: %d
''' % (wallet_name, keypool * output_types, transactions, address))
else:
output_types = 3 # p2pkh, p2sh, segwit. Legacy wallets do not support bech32m.
return textwrap.dedent('''\
Wallet info
===========
Name: %s
Format: bdb
Descriptors: no
Encrypted: no
HD (hd seed available): yes
Keypool Size: %d
Transactions: %d
Address Book: %d
''' % (wallet_name, keypool, transactions, address * output_types))
def read_dump(self, filename):
dump = OrderedDict()
with open(filename, "r", encoding="utf8") as f:
for row in f:
row = row.strip()
key, value = row.split(',')
dump[key] = value
return dump
def assert_is_sqlite(self, filename):
with open(filename, 'rb') as f:
file_magic = f.read(16)
assert file_magic == b'SQLite format 3\x00'
def assert_is_bdb(self, filename):
with open(filename, 'rb') as f:
f.seek(12, 0)
file_magic = f.read(4)
assert file_magic == b'\x00\x05\x31\x62' or file_magic == b'\x62\x31\x05\x00'
def write_dump(self, dump, filename, magic=None, skip_checksum=False):
if magic is None:
magic = "BITCOIN_CORE_WALLET_DUMP"
with open(filename, "w", encoding="utf8") as f:
row = ",".join([magic, dump[magic]]) + "\n"
f.write(row)
for k, v in dump.items():
if k == magic or k == "checksum":
continue
row = ",".join([k, v]) + "\n"
f.write(row)
if not skip_checksum:
row = ",".join(["checksum", dump["checksum"]]) + "\n"
f.write(row)
def assert_dump(self, expected, received):
e = expected.copy()
r = received.copy()
# BDB will add a "version" record that is not present in sqlite
# In that case, we should ignore this record in both
# But because this also effects the checksum, we also need to drop that.
v_key = "0776657273696f6e" # Version key
if v_key in e and v_key not in r:
del e[v_key]
del e["checksum"]
del r["checksum"]
if v_key not in e and v_key in r:
del r[v_key]
del e["checksum"]
del r["checksum"]
assert_equal(len(e), len(r))
for k, v in e.items():
assert_equal(v, r[k])
def do_tool_createfromdump(self, wallet_name, dumpfile, file_format=None):
dumppath = os.path.join(self.nodes[0].datadir, dumpfile)
rt_dumppath = os.path.join(self.nodes[0].datadir, "rt-{}.dump".format(wallet_name))
dump_data = self.read_dump(dumppath)
args = ["-wallet={}".format(wallet_name),
"-dumpfile={}".format(dumppath)]
if file_format is not None:
args.append("-format={}".format(file_format))
args.append("createfromdump")
load_output = ""
if file_format is not None and file_format != dump_data["format"]:
load_output += "Warning: Dumpfile wallet format \"{}\" does not match command line specified format \"{}\".\n".format(dump_data["format"], file_format)
self.assert_tool_output(load_output, *args)
assert os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", wallet_name))
self.assert_tool_output("The dumpfile may contain private keys. To ensure the safety of your Bitcoin, do not share the dumpfile.\n", '-wallet={}'.format(wallet_name), '-dumpfile={}'.format(rt_dumppath), 'dump')
rt_dump_data = self.read_dump(rt_dumppath)
wallet_dat = os.path.join(self.nodes[0].datadir, "regtest/wallets/", wallet_name, "wallet.dat")
if rt_dump_data["format"] == "bdb":
self.assert_is_bdb(wallet_dat)
else:
self.assert_is_sqlite(wallet_dat)
def test_invalid_tool_commands_and_args(self):
self.log.info('Testing that various invalid commands raise with specific error messages')
self.assert_raises_tool_error("Error parsing command line arguments: Invalid command 'foo'", 'foo')
# `bitcoin-wallet help` raises an error. Use `bitcoin-wallet -help`.
self.assert_raises_tool_error("Error parsing command line arguments: Invalid command 'help'", 'help')
self.assert_raises_tool_error('Error: Additional arguments provided (create). Methods do not take arguments. Please refer to `-help`.', 'info', 'create')
self.assert_raises_tool_error('Error parsing command line arguments: Invalid parameter -foo', '-foo')
self.assert_raises_tool_error('No method provided. Run `xaya-wallet -help` for valid methods.')
self.assert_raises_tool_error('Wallet name must be provided when creating a new wallet.', 'create')
locked_dir = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets")
error = 'Error initializing wallet database environment "{}"!'.format(locked_dir)
if self.options.descriptors:
error = f"SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another instance of {self.config['environment']['PACKAGE_NAME']}?"
self.assert_raises_tool_error(
error,
'-wallet=' + self.default_wallet_name,
'info',
)
path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "nonexistent.dat")
self.assert_raises_tool_error("Failed to load database path '{}'. Path does not exist.".format(path), '-wallet=nonexistent.dat', 'info')
def test_tool_wallet_info(self):
# Stop the node to close the wallet to call the info command.
self.stop_node(0)
self.log.info('Calling wallet tool info, testing output')
#
# TODO: Wallet tool info should work with wallet file permissions set to
# read-only without raising:
# "Error loading wallet.dat. Is wallet being used by another process?"
# The following lines should be uncommented and the tests still succeed:
#
# self.log.debug('Setting wallet file permissions to 400 (read-only)')
# os.chmod(self.wallet_path, stat.S_IRUSR)
# assert self.wallet_permissions() in ['400', '666'] # Sanity check. 666 because Appveyor.
# shasum_before = self.wallet_shasum()
timestamp_before = self.wallet_timestamp()
self.log.debug('Wallet file timestamp before calling info: {}'.format(timestamp_before))
out = self.get_expected_info_output(address=1)
self.assert_tool_output(out, '-wallet=' + self.default_wallet_name, 'info')
timestamp_after = self.wallet_timestamp()
self.log.debug('Wallet file timestamp after calling info: {}'.format(timestamp_after))
self.log_wallet_timestamp_comparison(timestamp_before, timestamp_after)
self.log.debug('Setting wallet file permissions back to 600 (read/write)')
os.chmod(self.wallet_path, stat.S_IRUSR | stat.S_IWUSR)
assert self.wallet_permissions() in ['600', '666'] # Sanity check. 666 because Appveyor.
#
# TODO: Wallet tool info should not write to the wallet file.
# The following lines should be uncommented and the tests still succeed:
#
# assert_equal(timestamp_before, timestamp_after)
# shasum_after = self.wallet_shasum()
# assert_equal(shasum_before, shasum_after)
# self.log.debug('Wallet file shasum unchanged\n')
def test_tool_wallet_info_after_transaction(self):
"""
Mutate the wallet with a transaction to verify that the info command
output changes accordingly.
"""
self.start_node(0)
self.log.info('Generating transaction to mutate wallet')
self.generate(self.nodes[0], 1)
self.stop_node(0)
self.log.info('Calling wallet tool info after generating a transaction, testing output')
shasum_before = self.wallet_shasum()
timestamp_before = self.wallet_timestamp()
self.log.debug('Wallet file timestamp before calling info: {}'.format(timestamp_before))
out = self.get_expected_info_output(transactions=1, address=1)
self.assert_tool_output(out, '-wallet=' + self.default_wallet_name, 'info')
shasum_after = self.wallet_shasum()
timestamp_after = self.wallet_timestamp()
self.log.debug('Wallet file timestamp after calling info: {}'.format(timestamp_after))
self.log_wallet_timestamp_comparison(timestamp_before, timestamp_after)
#
# TODO: Wallet tool info should not write to the wallet file.
# This assertion should be uncommented and succeed:
# assert_equal(timestamp_before, timestamp_after)
assert_equal(shasum_before, shasum_after)
self.log.debug('Wallet file shasum unchanged\n')
def test_tool_wallet_create_on_existing_wallet(self):
self.log.info('Calling wallet tool create on an existing wallet, testing output')
shasum_before = self.wallet_shasum()
timestamp_before = self.wallet_timestamp()
self.log.debug('Wallet file timestamp before calling create: {}'.format(timestamp_before))
out = "Topping up keypool...\n" + self.get_expected_info_output(name="foo", keypool=2000)
self.assert_tool_output(out, '-wallet=foo', 'create')
shasum_after = self.wallet_shasum()
timestamp_after = self.wallet_timestamp()
self.log.debug('Wallet file timestamp after calling create: {}'.format(timestamp_after))
self.log_wallet_timestamp_comparison(timestamp_before, timestamp_after)
assert_equal(timestamp_before, timestamp_after)
assert_equal(shasum_before, shasum_after)
self.log.debug('Wallet file shasum unchanged\n')
def test_getwalletinfo_on_different_wallet(self):
self.log.info('Starting node with arg -wallet=foo')
self.start_node(0, ['-nowallet', '-wallet=foo'])
self.log.info('Calling getwalletinfo on a different wallet ("foo"), testing output')
shasum_before = self.wallet_shasum()
timestamp_before = self.wallet_timestamp()
self.log.debug('Wallet file timestamp before calling getwalletinfo: {}'.format(timestamp_before))
out = self.nodes[0].getwalletinfo()
self.stop_node(0)
shasum_after = self.wallet_shasum()
timestamp_after = self.wallet_timestamp()
self.log.debug('Wallet file timestamp after calling getwalletinfo: {}'.format(timestamp_after))
assert_equal(0, out['txcount'])
if not self.options.descriptors:
assert_equal(1000, out['keypoolsize'])
assert_equal(1000, out['keypoolsize_hd_internal'])
assert_equal(True, 'hdseedid' in out)
else:
assert_equal(4000, out['keypoolsize'])
assert_equal(4000, out['keypoolsize_hd_internal'])
self.log_wallet_timestamp_comparison(timestamp_before, timestamp_after)
assert_equal(timestamp_before, timestamp_after)
assert_equal(shasum_after, shasum_before)
self.log.debug('Wallet file shasum unchanged\n')
def test_salvage(self):
# TODO: Check salvage actually salvages and doesn't break things. https://github.com/bitcoin/bitcoin/issues/7463
self.log.info('Check salvage')
self.start_node(0)
self.nodes[0].createwallet("salvage")
self.stop_node(0)
self.assert_tool_output('', '-wallet=salvage', 'salvage')
def test_dump_createfromdump(self):
self.start_node(0)
self.nodes[0].createwallet("todump")
file_format = self.nodes[0].get_wallet_rpc("todump").getwalletinfo()["format"]
self.nodes[0].createwallet("todump2")
self.stop_node(0)
self.log.info('Checking dump arguments')
self.assert_raises_tool_error('No dump file provided. To use dump, -dumpfile=<filename> must be provided.', '-wallet=todump', 'dump')
self.log.info('Checking basic dump')
wallet_dump = os.path.join(self.nodes[0].datadir, "wallet.dump")
self.assert_tool_output('The dumpfile may contain private keys. To ensure the safety of your Bitcoin, do not share the dumpfile.\n', '-wallet=todump', '-dumpfile={}'.format(wallet_dump), 'dump')
dump_data = self.read_dump(wallet_dump)
orig_dump = dump_data.copy()
# Check the dump magic
assert_equal(dump_data['BITCOIN_CORE_WALLET_DUMP'], '1')
# Check the file format
assert_equal(dump_data["format"], file_format)
self.log.info('Checking that a dumpfile cannot be overwritten')
self.assert_raises_tool_error('File {} already exists. If you are sure this is what you want, move it out of the way first.'.format(wallet_dump), '-wallet=todump2', '-dumpfile={}'.format(wallet_dump), 'dump')
self.log.info('Checking createfromdump arguments')
self.assert_raises_tool_error('No dump file provided. To use createfromdump, -dumpfile=<filename> must be provided.', '-wallet=todump', 'createfromdump')
non_exist_dump = os.path.join(self.nodes[0].datadir, "wallet.nodump")
self.assert_raises_tool_error('Unknown wallet file format "notaformat" provided. Please provide one of "bdb" or "sqlite".', '-wallet=todump', '-format=notaformat', '-dumpfile={}'.format(wallet_dump), 'createfromdump')
self.assert_raises_tool_error('Dump file {} does not exist.'.format(non_exist_dump), '-wallet=todump', '-dumpfile={}'.format(non_exist_dump), 'createfromdump')
wallet_path = os.path.join(self.nodes[0].datadir, 'regtest', 'wallets', 'todump2')
self.assert_raises_tool_error('Failed to create database path \'{}\'. Database already exists.'.format(wallet_path), '-wallet=todump2', '-dumpfile={}'.format(wallet_dump), 'createfromdump')
self.assert_raises_tool_error("The -descriptors option can only be used with the 'create' command.", '-descriptors', '-wallet=todump2', '-dumpfile={}'.format(wallet_dump), 'createfromdump')
self.log.info('Checking createfromdump')
self.do_tool_createfromdump("load", "wallet.dump")
if self.is_bdb_compiled():
self.do_tool_createfromdump("load-bdb", "wallet.dump", "bdb")
if self.is_sqlite_compiled():
self.do_tool_createfromdump("load-sqlite", "wallet.dump", "sqlite")
self.log.info('Checking createfromdump handling of magic and versions')
bad_ver_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_ver1.dump")
dump_data["BITCOIN_CORE_WALLET_DUMP"] = "0"
self.write_dump(dump_data, bad_ver_wallet_dump)
self.assert_raises_tool_error('Error: Dumpfile version is not supported. This version of xaya-wallet only supports version 1 dumpfiles. Got dumpfile with version 0', '-wallet=badload', '-dumpfile={}'.format(bad_ver_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
bad_ver_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_ver2.dump")
dump_data["BITCOIN_CORE_WALLET_DUMP"] = "2"
self.write_dump(dump_data, bad_ver_wallet_dump)
self.assert_raises_tool_error('Error: Dumpfile version is not supported. This version of xaya-wallet only supports version 1 dumpfiles. Got dumpfile with version 2', '-wallet=badload', '-dumpfile={}'.format(bad_ver_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
bad_magic_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_magic.dump")
del dump_data["BITCOIN_CORE_WALLET_DUMP"]
dump_data["not_the_right_magic"] = "1"
self.write_dump(dump_data, bad_magic_wallet_dump, "not_the_right_magic")
self.assert_raises_tool_error('Error: Dumpfile identifier record is incorrect. Got "not_the_right_magic", expected "BITCOIN_CORE_WALLET_DUMP".', '-wallet=badload', '-dumpfile={}'.format(bad_magic_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
self.log.info('Checking createfromdump handling of checksums')
bad_sum_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_sum1.dump")
dump_data = orig_dump.copy()
checksum = dump_data["checksum"]
dump_data["checksum"] = "1" * 64
self.write_dump(dump_data, bad_sum_wallet_dump)
self.assert_raises_tool_error('Error: Dumpfile checksum does not match. Computed {}, expected {}'.format(checksum, "1" * 64), '-wallet=bad', '-dumpfile={}'.format(bad_sum_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
bad_sum_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_sum2.dump")
del dump_data["checksum"]
self.write_dump(dump_data, bad_sum_wallet_dump, skip_checksum=True)
self.assert_raises_tool_error('Error: Missing checksum', '-wallet=badload', '-dumpfile={}'.format(bad_sum_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
bad_sum_wallet_dump = os.path.join(self.nodes[0].datadir, "wallet-bad_sum3.dump")
dump_data["checksum"] = "2" * 10
self.write_dump(dump_data, bad_sum_wallet_dump)
self.assert_raises_tool_error('Error: Checksum is not the correct size', '-wallet=badload', '-dumpfile={}'.format(bad_sum_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
dump_data["checksum"] = "3" * 66
self.write_dump(dump_data, bad_sum_wallet_dump)
self.assert_raises_tool_error('Error: Checksum is not the correct size', '-wallet=badload', '-dumpfile={}'.format(bad_sum_wallet_dump), 'createfromdump')
assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "regtest/wallets", "badload"))
def run_test(self):
self.wallet_path = os.path.join(self.nodes[0].datadir, self.chain, 'wallets', self.default_wallet_name, self.wallet_data_filename)
self.test_invalid_tool_commands_and_args()
# Warning: The following tests are order-dependent.
self.test_tool_wallet_info()
self.test_tool_wallet_info_after_transaction()
self.test_tool_wallet_create_on_existing_wallet()
self.test_getwalletinfo_on_different_wallet()
if not self.options.descriptors:
# Salvage is a legacy wallet only thing
self.test_salvage()
self.test_dump_createfromdump()
if __name__ == '__main__':
ToolWalletTest().main()
|
#!/usr/bin/env python3
import uvicorn
import argparse
import sys
import yaml
import os
from suzieq.utils import load_sq_config, get_sq_install_dir
from suzieq.restServer.query import app_init
def get_cert_files(cfg):
sqdir = get_sq_install_dir()
ssl_certfile = cfg.get('rest', {}) \
.get('rest_certfile', f'{sqdir}/config/etc/cert.pem')
ssl_keyfile = cfg.get('rest', {}) \
.get('rest_keyfile', f'{sqdir}/config/etc/key.pem')
if not os.path.isfile(ssl_certfile):
print(f"ERROR: Missing certificate file: {ssl_certfile}")
sys.exit(1)
if not os.path.isfile(ssl_keyfile):
print(f"ERROR: Missing certificate file: {ssl_keyfile}")
sys.exit(1)
return ssl_keyfile, ssl_certfile
def get_log_file(cfg):
tempdir = cfg.get('temp-directory', '/tmp')
if not os.path.exists(tempdir):
os.makedirs(tempdir, exist_ok=True)
return f"{tempdir}/sq-rest-server.log"
def get_log_config(cfg):
log_config = uvicorn.config.LOGGING_CONFIG
log_config['handlers']['access']['class'] = 'logging.handlers.RotatingFileHandler'
log_config['handlers']['access']['maxBytes'] = 10000000
log_config['handlers']['access']['backupCount'] = 2
log_config['handlers']['default']['class'] = 'logging.handlers.RotatingFileHandler'
log_config['handlers']['default']['maxBytes'] = 10_000_000
log_config['handlers']['default']['backupCount'] = 2
log_config['handlers']['access']['filename'] = get_log_file(cfg)
del(log_config['handlers']['access']['stream'])
log_config['handlers']['default']['filename'] = get_log_file(cfg)
del(log_config['handlers']['default']['stream'])
return log_config
def rest_main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-c",
"--config",
type=str, help="alternate config file",
default=f'{os.getenv('HOME')}/.suzieq/suzieq-cfg.yml'
)
userargs = parser.parse_args()
app = app_init(userargs.config)
cfg = load_sq_config(config_file=userargs.config)
try:
api_key = cfg['rest']['API_KEY']
except KeyError:
print('missing API_KEY in config file')
exit(1)
log_level = cfg.get('rest', {}).get('logging-level', 'INFO').lower()
ssl_keyfile, ssl_certfile = get_cert_files(cfg)
srvr_addr = cfg.get('rest', {}).get('address', '127.0.0.1')
srvr_port = cfg.get('rest', {}).get('port', 8000)
uvicorn.run(app, host=srvr_addr, port=srvr_port,
log_level=log_level,
log_config=get_log_config(cfg),
ssl_keyfile=ssl_keyfile,
ssl_certfile=ssl_certfile)
if __name__ == "__main__":
rest_main()
| #!/usr/bin/env python3
import uvicorn
import argparse
import sys
import yaml
import os
from suzieq.utils import load_sq_config, get_sq_install_dir
from suzieq.restServer.query import app_init
def get_cert_files(cfg):
sqdir = get_sq_install_dir()
ssl_certfile = cfg.get('rest', {}) \
.get('rest_certfile', f'{sqdir}/config/etc/cert.pem')
ssl_keyfile = cfg.get('rest', {}) \
.get('rest_keyfile', f'{sqdir}/config/etc/key.pem')
if not os.path.isfile(ssl_certfile):
print(f"ERROR: Missing certificate file: {ssl_certfile}")
sys.exit(1)
if not os.path.isfile(ssl_keyfile):
print(f"ERROR: Missing certificate file: {ssl_keyfile}")
sys.exit(1)
return ssl_keyfile, ssl_certfile
def get_log_file(cfg):
tempdir = cfg.get('temp-directory', '/tmp')
if not os.path.exists(tempdir):
os.makedirs(tempdir, exist_ok=True)
return f"{tempdir}/sq-rest-server.log"
def get_log_config(cfg):
log_config = uvicorn.config.LOGGING_CONFIG
log_config['handlers']['access']['class'] = 'logging.handlers.RotatingFileHandler'
log_config['handlers']['access']['maxBytes'] = 10000000
log_config['handlers']['access']['backupCount'] = 2
log_config['handlers']['default']['class'] = 'logging.handlers.RotatingFileHandler'
log_config['handlers']['default']['maxBytes'] = 10_000_000
log_config['handlers']['default']['backupCount'] = 2
log_config['handlers']['access']['filename'] = get_log_file(cfg)
del(log_config['handlers']['access']['stream'])
log_config['handlers']['default']['filename'] = get_log_file(cfg)
del(log_config['handlers']['default']['stream'])
return log_config
def rest_main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-c",
"--config",
type=str, help="alternate config file",
default=f'{os.getenv("HOME")}/.suzieq/suzieq-cfg.yml'
)
userargs = parser.parse_args()
app = app_init(userargs.config)
cfg = load_sq_config(config_file=userargs.config)
try:
api_key = cfg['rest']['API_KEY']
except KeyError:
print('missing API_KEY in config file')
exit(1)
log_level = cfg.get('rest', {}).get('logging-level', 'INFO').lower()
ssl_keyfile, ssl_certfile = get_cert_files(cfg)
srvr_addr = cfg.get('rest', {}).get('address', '127.0.0.1')
srvr_port = cfg.get('rest', {}).get('port', 8000)
uvicorn.run(app, host=srvr_addr, port=srvr_port,
log_level=log_level,
log_config=get_log_config(cfg),
ssl_keyfile=ssl_keyfile,
ssl_certfile=ssl_certfile)
if __name__ == "__main__":
rest_main()
|
import asyncio
from typing import (
List,
Dict,
Optional,
Any,
)
from hummingbot.core.utils.wallet_setup import (
create_and_save_wallet,
import_and_save_wallet,
list_wallets,
unlock_wallet,
save_wallet
)
from hummingbot.client.config.config_var import ConfigVar
from hummingbot.client.config.in_memory_config_map import in_memory_config_map
from hummingbot.client.config.global_config_map import global_config_map
from hummingbot.client.config.config_helpers import (
get_strategy_config_map,
write_config_to_yml,
load_required_configs,
parse_cvar_value,
copy_strategy_template,
parse_cvar_default_value_prompt
)
from hummingbot.core.utils.async_utils import safe_ensure_future
from hummingbot.client.config.config_crypt import (
list_encrypted_file_paths,
decrypt_file,
decrypt_config_value,
encrypted_config_file_exists,
get_encrypted_config_path,
encrypt_n_save_config_value
)
from os import unlink
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from hummingbot.client.hummingbot_application import HummingbotApplication
class ConfigCommand:
def config(self, # type: HummingbotApplication
key: str = None,
key_list: Optional[List[str]] = None):
"""
Router function that for all commands related to bot configuration
"""
self.app.clear_input()
if self.strategy or (self.config_complete and key is None):
safe_ensure_future(self.reset_config_loop(key))
return
if key is not None:
try:
self._get_config_var_with_key(key)
safe_ensure_future(self._config_single_key(key), loop=self.ev_loop)
except ValueError as e:
self.logger().error(e)
self._notify("Invalid config variable %s" % (key,))
elif key_list is not None:
keys = key_list
safe_ensure_future(self._config_loop(keys), loop=self.ev_loop)
else:
keys = self._get_empty_configs()
safe_ensure_future(self._config_loop(keys), loop=self.ev_loop)
@property
def config_complete(self, # type: HummingbotApplication
) -> bool:
"""
Returns bool value that indicates if the bot's configuration is all complete.
"""
config_map = load_required_configs()
keys = self._get_empty_configs()
for key in keys:
cvar = config_map.get(key)
if cvar.value is None and cvar.required:
if cvar.is_secure and cvar.key != "wallet" and self.load_secure_var(cvar):
continue
return False
return True
@staticmethod
def load_secure_var(cvar):
if encrypted_config_file_exists(cvar):
password = in_memory_config_map.get("password").value
if password is not None:
cvar.value = decrypt_config_value(cvar, password)
return True
return False
@staticmethod
def _get_empty_configs() -> List[str]:
"""
Returns a list of required config keys whose current value is None or an empty string.
"""
config_map = load_required_configs()
return [key for key, config in config_map.items() if config.value is None]
@staticmethod
def get_all_available_config_keys() -> List[str]:
"""
Returns a list of config keys that are currently relevant, including the ones that are not required.
"""
all_available_config_keys = list(in_memory_config_map.keys()) + list(global_config_map.keys())
current_strategy: str = in_memory_config_map.get("strategy").value
strategy_cm: Optional[Dict[str, ConfigVar]] = get_strategy_config_map(current_strategy)
if strategy_cm:
all_available_config_keys += list(strategy_cm.keys())
return all_available_config_keys
async def reset_config_loop(self, # type: HummingbotApplication
key: str = None):
"""
Handler function that allows user to redo the config step.
"""
strategy = in_memory_config_map.get("strategy").value
strategy_cm = get_strategy_config_map(strategy)
self.placeholder_mode = True
self.app.toggle_hide_input()
if self.strategy:
choice = await self.app.prompt(prompt=f"Would you like to stop running the {strategy} strategy "
f"and reconfigure the bot? (Yes/No) >>> ")
else:
choice = await self.app.prompt(prompt=f"Would you like to reconfigure the bot? (Yes/No) >>> ")
self.app.change_prompt(prompt=">>> ")
self.app.toggle_hide_input()
self.placeholder_mode = False
if choice.lower() in {"y", "yes"}:
# Clear application states that are specific to config
self.starting_balances = {}
if self.strategy:
await self.stop_loop()
if key is None:
# Clear original strategy config map
if strategy_cm:
for k in strategy_cm:
strategy_cm[k].value = None
in_memory_config_map.get("strategy").value = None
in_memory_config_map.get("strategy_file_path").value = None
self.clear_application_warning()
self.config(key)
else:
self._notify("Aborted.")
async def _create_or_import_wallet(self, # type: HummingbotApplication
):
"""
Special handler function that asks the user to either create a new wallet,
or import one by entering the private key.
"""
choice = await self.app.prompt(prompt=global_config_map.get("wallet").prompt)
if choice == "import":
private_key = await self.app.prompt(prompt="Your wallet private key >>> ", is_password=True)
password = in_memory_config_map["password"].value
try:
self.acct = import_and_save_wallet(password, private_key)
self._notify("Wallet %s imported into hummingbot" % (self.acct.address,))
except Exception as e:
self._notify(f"Failed to import wallet key: {e}")
result = await self._create_or_import_wallet()
return result
elif choice == "create":
password = in_memory_config_map["password"].value
self.acct = create_and_save_wallet(password)
self._notify("New wallet %s created" % (self.acct.address,))
else:
self._notify('Invalid choice. Please enter "create" or "import".')
result = await self._create_or_import_wallet()
return result
return self.acct.address
async def _unlock_wallet(self, # type: HummingbotApplication
):
"""
Special handler function that helps the user unlock an existing wallet, or redirect user to create a new wallet.
"""
choice = await self.app.prompt(prompt="Would you like to unlock your previously saved wallet? (Yes/No) >>> ")
if choice.lower() in {"y", "yes"}:
wallets = list_wallets()
self._notify("Existing wallets:")
self.list(obj="wallets")
if len(wallets) == 1:
public_key = wallets[0]
else:
public_key = await self.app.prompt(prompt="Which wallet would you like to import ? >>> ")
password = in_memory_config_map["password"].value
try:
acct = unlock_wallet(public_key=public_key, password=password)
self._notify("Wallet %s unlocked" % (acct.address,))
self.acct = acct
return self.acct.address
except ValueError as err:
if str(err) != "MAC mismatch":
raise err
self._notify("The wallet was locked by a different password.")
old_password = await self.app.prompt(prompt="Please enter the password >>> ", is_password=True)
try:
acct = unlock_wallet(public_key=public_key, password=old_password)
self._notify("Wallet %s unlocked" % (acct.address,))
save_wallet(acct, password)
self._notify(f"Wallet {acct.address} is now saved with your main password.")
self.acct = acct
return self.acct.address
except ValueError as err:
if str(err) != "MAC mismatch":
raise err
self._notify("Cannot unlock wallet. Please try again.")
return await self._unlock_wallet()
else:
value = await self._create_or_import_wallet()
return value
async def _import_or_create_strategy_config(self, # type: HummingbotApplication
):
"""
Special handler function that asks if the user wants to import or create a new strategy config.
"""
current_strategy: str = in_memory_config_map.get("strategy").value
strategy_file_path_cv: ConfigVar = in_memory_config_map.get("strategy_file_path")
choice = await self.app.prompt(prompt="Import previous configs or create a new config file? "
"(import/create) >>> ")
if choice == "import":
strategy_path = await self.app.prompt(strategy_file_path_cv.prompt)
strategy_path = strategy_path
self._notify(f"Loading previously saved config file from {strategy_path}...")
elif choice == "create":
strategy_path = await copy_strategy_template(current_strategy)
self._notify(f"A new config file {strategy_path} created.")
self._notify(f"Please see https://docs.hummingbot.io/strategies/{current_strategy.replace("_", "-")}/ "
f"while setting up these below configuration.")
else:
self._notify('Invalid choice. Please enter "create" or "import".')
strategy_path = await self._import_or_create_strategy_config()
return strategy_path
async def _one_password_config(self, # type: HummingbotApplication
):
"""
Special handler function to handle one password unlocking all secure conf variable and wallets
- let a user creates a new password if there is no existing encrypted_files or key_files.
- verify the entered password is valid by trying to unlock files.
"""
encrypted_files = list_encrypted_file_paths()
wallets = list_wallets()
password_valid = False
err_msg = "Invalid password, please try again."
if not encrypted_files and not wallets:
password = await self.app.prompt(prompt="Enter your new password >>> ", is_password=True)
re_password = await self.app.prompt(prompt="Please reenter your password >>> ", is_password=True)
if password == re_password:
password_valid = True
else:
err_msg = "Passwords entered do not match, please try again."
else:
password = await self.app.prompt(prompt="Enter your password >>> ", is_password=True)
if encrypted_files:
try:
decrypt_file(encrypted_files[0], password)
password_valid = True
except ValueError as err:
if str(err) != "MAC mismatch":
raise err
else:
for wallet in wallets:
try:
unlock_wallet(public_key=wallet, password=password)
password_valid = True
break
except ValueError as err:
if str(err) != "MAC mismatch":
raise err
if password_valid:
return password
else:
self._notify(err_msg)
return await self._one_password_config()
async def prompt_single_variable(self, # type: HummingbotApplication
cvar: ConfigVar,
requirement_overwrite: bool = False) -> Any:
"""
Prompt a single variable in the input pane, validates and returns the user input
:param cvar: the config var to be prompted
:param requirement_overwrite: Set to true when a config var is forced to be prompted,
even if it is not required by default setting
:return: a validated user input or the variable's default value
"""
if cvar.required or requirement_overwrite:
if cvar.key == "password":
return await self._one_password_config()
if cvar.key == "strategy_file_path":
val = await self._import_or_create_strategy_config()
elif cvar.key == "wallet":
wallets = list_wallets()
if len(wallets) > 0:
val = await self._unlock_wallet()
else:
val = await self._create_or_import_wallet()
else:
if cvar.value is None:
self.app.set_text(parse_cvar_default_value_prompt(cvar))
val = await self.app.prompt(prompt=cvar.prompt, is_password=cvar.is_secure)
if not cvar.validate(val):
# If the user inputs an empty string, use the default
val_is_empty = val is None or (isinstance(val, str) and len(val) == 0)
if cvar.default is not None and val_is_empty:
val = cvar.default
else:
self._notify("%s is not a valid %s value" % (val, cvar.key))
val = await self.prompt_single_variable(cvar, requirement_overwrite)
else:
val = cvar.value
if val is None or (isinstance(val, str) and len(val) == 0):
val = cvar.default
return val
@staticmethod
def _get_config_var_with_key(key: str) -> ConfigVar:
"""
Check if key exists in `in_memory_config-map`, `global_config_map`, and `strategy_config_map`.
If so, return the corresponding ConfigVar for that key
"""
current_strategy: str = in_memory_config_map.get("strategy").value
strategy_cm: Optional[Dict[str, ConfigVar]] = get_strategy_config_map(current_strategy)
if key in in_memory_config_map:
cv: ConfigVar = in_memory_config_map.get(key)
elif key in global_config_map:
cv: ConfigVar = global_config_map.get(key)
elif strategy_cm is not None and key in strategy_cm:
cv: ConfigVar = strategy_cm.get(key)
else:
raise ValueError(f"No config variable associated with key name {key}")
return cv
async def _inner_config_loop(self, keys: List[str]):
"""
Inner loop used by `self._config_loop` that recursively calls itself until all required configs are filled.
This enables the bot to detect any newly added requirements as the user fills currently required variables.
Use case example:
When the user selects a particular market, the API keys related to that market becomes required.
:param keys:
"""
for key in keys:
cv: ConfigVar = self._get_config_var_with_key(key)
if cv.value is not None and cv.key != "wallet":
continue
value = await self.prompt_single_variable(cv, requirement_overwrite=False)
cv.value = parse_cvar_value(cv, value)
if self.config_complete:
break
if not self.config_complete:
await self._inner_config_loop(self._get_empty_configs())
async def _config_loop(self, # type: HummingbotApplication
keys: List[str] = []):
"""
Loop until all necessary config variables are complete and the bot is ready for "start"
"""
self._notify("Please follow the prompt to complete configurations: ")
self.placeholder_mode = True
self.app.toggle_hide_input()
try:
await self._inner_config_loop(keys)
await write_config_to_yml()
self._notify("\nConfig process complete. Enter \"start\" to start market making.")
self.app.set_text("start")
except asyncio.TimeoutError:
self.logger().error("Prompt timeout")
except Exception as err:
self.logger().error("Unknown error while writing config. %s" % (err,), exc_info=True)
finally:
self.app.toggle_hide_input()
self.placeholder_mode = False
self.app.change_prompt(prompt=">>> ")
async def _config_single_key(self, # type: HummingbotApplication
key: str):
"""
Configure a single variable only.
Prompt the user to finish all configurations if there are remaining empty configs at the end.
"""
self._notify("Please follow the prompt to complete configurations: ")
self.placeholder_mode = True
self.app.toggle_hide_input()
try:
cv: ConfigVar = self._get_config_var_with_key(key)
value = await self.prompt_single_variable(cv, requirement_overwrite=True)
cv.value = parse_cvar_value(cv, value)
if cv.is_secure:
await self._encrypt_n_save_config_value(cv)
else:
await write_config_to_yml()
self._notify(f"\nNew config saved:\n{key}: {str(value)}")
if not self.config_complete:
choice = await self.app.prompt("Your configuration is incomplete. Would you like to proceed and "
"finish all necessary configurations? (Yes/No) >>> ")
if choice.lower() in {"y", "yes"}:
self.config()
return
else:
self._notify("Aborted.")
except asyncio.TimeoutError:
self.logger().error("Prompt timeout")
except Exception as err:
self.logger().error("Unknown error while writing config. %s" % (err,), exc_info=True)
finally:
self.app.toggle_hide_input()
self.placeholder_mode = False
self.app.change_prompt(prompt=">>> ")
async def _encrypt_n_save_config_value(self, # type: HummingbotApplication
cvar: ConfigVar):
if in_memory_config_map.get("password").value is None:
in_memory_config_map.get("password").value = await self._one_password_config()
password = in_memory_config_map.get("password").value
if encrypted_config_file_exists(cvar):
unlink(get_encrypted_config_path(cvar))
encrypt_n_save_config_value(cvar, password)
| import asyncio
from typing import (
List,
Dict,
Optional,
Any,
)
from hummingbot.core.utils.wallet_setup import (
create_and_save_wallet,
import_and_save_wallet,
list_wallets,
unlock_wallet,
save_wallet
)
from hummingbot.client.config.config_var import ConfigVar
from hummingbot.client.config.in_memory_config_map import in_memory_config_map
from hummingbot.client.config.global_config_map import global_config_map
from hummingbot.client.config.config_helpers import (
get_strategy_config_map,
write_config_to_yml,
load_required_configs,
parse_cvar_value,
copy_strategy_template,
parse_cvar_default_value_prompt
)
from hummingbot.core.utils.async_utils import safe_ensure_future
from hummingbot.client.config.config_crypt import (
list_encrypted_file_paths,
decrypt_file,
decrypt_config_value,
encrypted_config_file_exists,
get_encrypted_config_path,
encrypt_n_save_config_value
)
from os import unlink
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from hummingbot.client.hummingbot_application import HummingbotApplication
class ConfigCommand:
def config(self, # type: HummingbotApplication
key: str = None,
key_list: Optional[List[str]] = None):
"""
Router function that for all commands related to bot configuration
"""
self.app.clear_input()
if self.strategy or (self.config_complete and key is None):
safe_ensure_future(self.reset_config_loop(key))
return
if key is not None:
try:
self._get_config_var_with_key(key)
safe_ensure_future(self._config_single_key(key), loop=self.ev_loop)
except ValueError as e:
self.logger().error(e)
self._notify("Invalid config variable %s" % (key,))
elif key_list is not None:
keys = key_list
safe_ensure_future(self._config_loop(keys), loop=self.ev_loop)
else:
keys = self._get_empty_configs()
safe_ensure_future(self._config_loop(keys), loop=self.ev_loop)
@property
def config_complete(self, # type: HummingbotApplication
) -> bool:
"""
Returns bool value that indicates if the bot's configuration is all complete.
"""
config_map = load_required_configs()
keys = self._get_empty_configs()
for key in keys:
cvar = config_map.get(key)
if cvar.value is None and cvar.required:
if cvar.is_secure and cvar.key != "wallet" and self.load_secure_var(cvar):
continue
return False
return True
@staticmethod
def load_secure_var(cvar):
if encrypted_config_file_exists(cvar):
password = in_memory_config_map.get("password").value
if password is not None:
cvar.value = decrypt_config_value(cvar, password)
return True
return False
@staticmethod
def _get_empty_configs() -> List[str]:
"""
Returns a list of required config keys whose current value is None or an empty string.
"""
config_map = load_required_configs()
return [key for key, config in config_map.items() if config.value is None]
@staticmethod
def get_all_available_config_keys() -> List[str]:
"""
Returns a list of config keys that are currently relevant, including the ones that are not required.
"""
all_available_config_keys = list(in_memory_config_map.keys()) + list(global_config_map.keys())
current_strategy: str = in_memory_config_map.get("strategy").value
strategy_cm: Optional[Dict[str, ConfigVar]] = get_strategy_config_map(current_strategy)
if strategy_cm:
all_available_config_keys += list(strategy_cm.keys())
return all_available_config_keys
async def reset_config_loop(self, # type: HummingbotApplication
key: str = None):
"""
Handler function that allows user to redo the config step.
"""
strategy = in_memory_config_map.get("strategy").value
strategy_cm = get_strategy_config_map(strategy)
self.placeholder_mode = True
self.app.toggle_hide_input()
if self.strategy:
choice = await self.app.prompt(prompt=f"Would you like to stop running the {strategy} strategy "
f"and reconfigure the bot? (Yes/No) >>> ")
else:
choice = await self.app.prompt(prompt=f"Would you like to reconfigure the bot? (Yes/No) >>> ")
self.app.change_prompt(prompt=">>> ")
self.app.toggle_hide_input()
self.placeholder_mode = False
if choice.lower() in {"y", "yes"}:
# Clear application states that are specific to config
self.starting_balances = {}
if self.strategy:
await self.stop_loop()
if key is None:
# Clear original strategy config map
if strategy_cm:
for k in strategy_cm:
strategy_cm[k].value = None
in_memory_config_map.get("strategy").value = None
in_memory_config_map.get("strategy_file_path").value = None
self.clear_application_warning()
self.config(key)
else:
self._notify("Aborted.")
async def _create_or_import_wallet(self, # type: HummingbotApplication
):
"""
Special handler function that asks the user to either create a new wallet,
or import one by entering the private key.
"""
choice = await self.app.prompt(prompt=global_config_map.get("wallet").prompt)
if choice == "import":
private_key = await self.app.prompt(prompt="Your wallet private key >>> ", is_password=True)
password = in_memory_config_map["password"].value
try:
self.acct = import_and_save_wallet(password, private_key)
self._notify("Wallet %s imported into hummingbot" % (self.acct.address,))
except Exception as e:
self._notify(f"Failed to import wallet key: {e}")
result = await self._create_or_import_wallet()
return result
elif choice == "create":
password = in_memory_config_map["password"].value
self.acct = create_and_save_wallet(password)
self._notify("New wallet %s created" % (self.acct.address,))
else:
self._notify('Invalid choice. Please enter "create" or "import".')
result = await self._create_or_import_wallet()
return result
return self.acct.address
async def _unlock_wallet(self, # type: HummingbotApplication
):
"""
Special handler function that helps the user unlock an existing wallet, or redirect user to create a new wallet.
"""
choice = await self.app.prompt(prompt="Would you like to unlock your previously saved wallet? (Yes/No) >>> ")
if choice.lower() in {"y", "yes"}:
wallets = list_wallets()
self._notify("Existing wallets:")
self.list(obj="wallets")
if len(wallets) == 1:
public_key = wallets[0]
else:
public_key = await self.app.prompt(prompt="Which wallet would you like to import ? >>> ")
password = in_memory_config_map["password"].value
try:
acct = unlock_wallet(public_key=public_key, password=password)
self._notify("Wallet %s unlocked" % (acct.address,))
self.acct = acct
return self.acct.address
except ValueError as err:
if str(err) != "MAC mismatch":
raise err
self._notify("The wallet was locked by a different password.")
old_password = await self.app.prompt(prompt="Please enter the password >>> ", is_password=True)
try:
acct = unlock_wallet(public_key=public_key, password=old_password)
self._notify("Wallet %s unlocked" % (acct.address,))
save_wallet(acct, password)
self._notify(f"Wallet {acct.address} is now saved with your main password.")
self.acct = acct
return self.acct.address
except ValueError as err:
if str(err) != "MAC mismatch":
raise err
self._notify("Cannot unlock wallet. Please try again.")
return await self._unlock_wallet()
else:
value = await self._create_or_import_wallet()
return value
async def _import_or_create_strategy_config(self, # type: HummingbotApplication
):
"""
Special handler function that asks if the user wants to import or create a new strategy config.
"""
current_strategy: str = in_memory_config_map.get("strategy").value
strategy_file_path_cv: ConfigVar = in_memory_config_map.get("strategy_file_path")
choice = await self.app.prompt(prompt="Import previous configs or create a new config file? "
"(import/create) >>> ")
if choice == "import":
strategy_path = await self.app.prompt(strategy_file_path_cv.prompt)
strategy_path = strategy_path
self._notify(f"Loading previously saved config file from {strategy_path}...")
elif choice == "create":
strategy_path = await copy_strategy_template(current_strategy)
self._notify(f"A new config file {strategy_path} created.")
self._notify(f"Please see https://docs.hummingbot.io/strategies/{current_strategy.replace('_', '-')}/ "
f"while setting up these below configuration.")
else:
self._notify('Invalid choice. Please enter "create" or "import".')
strategy_path = await self._import_or_create_strategy_config()
return strategy_path
async def _one_password_config(self, # type: HummingbotApplication
):
"""
Special handler function to handle one password unlocking all secure conf variable and wallets
- let a user creates a new password if there is no existing encrypted_files or key_files.
- verify the entered password is valid by trying to unlock files.
"""
encrypted_files = list_encrypted_file_paths()
wallets = list_wallets()
password_valid = False
err_msg = "Invalid password, please try again."
if not encrypted_files and not wallets:
password = await self.app.prompt(prompt="Enter your new password >>> ", is_password=True)
re_password = await self.app.prompt(prompt="Please reenter your password >>> ", is_password=True)
if password == re_password:
password_valid = True
else:
err_msg = "Passwords entered do not match, please try again."
else:
password = await self.app.prompt(prompt="Enter your password >>> ", is_password=True)
if encrypted_files:
try:
decrypt_file(encrypted_files[0], password)
password_valid = True
except ValueError as err:
if str(err) != "MAC mismatch":
raise err
else:
for wallet in wallets:
try:
unlock_wallet(public_key=wallet, password=password)
password_valid = True
break
except ValueError as err:
if str(err) != "MAC mismatch":
raise err
if password_valid:
return password
else:
self._notify(err_msg)
return await self._one_password_config()
async def prompt_single_variable(self, # type: HummingbotApplication
cvar: ConfigVar,
requirement_overwrite: bool = False) -> Any:
"""
Prompt a single variable in the input pane, validates and returns the user input
:param cvar: the config var to be prompted
:param requirement_overwrite: Set to true when a config var is forced to be prompted,
even if it is not required by default setting
:return: a validated user input or the variable's default value
"""
if cvar.required or requirement_overwrite:
if cvar.key == "password":
return await self._one_password_config()
if cvar.key == "strategy_file_path":
val = await self._import_or_create_strategy_config()
elif cvar.key == "wallet":
wallets = list_wallets()
if len(wallets) > 0:
val = await self._unlock_wallet()
else:
val = await self._create_or_import_wallet()
else:
if cvar.value is None:
self.app.set_text(parse_cvar_default_value_prompt(cvar))
val = await self.app.prompt(prompt=cvar.prompt, is_password=cvar.is_secure)
if not cvar.validate(val):
# If the user inputs an empty string, use the default
val_is_empty = val is None or (isinstance(val, str) and len(val) == 0)
if cvar.default is not None and val_is_empty:
val = cvar.default
else:
self._notify("%s is not a valid %s value" % (val, cvar.key))
val = await self.prompt_single_variable(cvar, requirement_overwrite)
else:
val = cvar.value
if val is None or (isinstance(val, str) and len(val) == 0):
val = cvar.default
return val
@staticmethod
def _get_config_var_with_key(key: str) -> ConfigVar:
"""
Check if key exists in `in_memory_config-map`, `global_config_map`, and `strategy_config_map`.
If so, return the corresponding ConfigVar for that key
"""
current_strategy: str = in_memory_config_map.get("strategy").value
strategy_cm: Optional[Dict[str, ConfigVar]] = get_strategy_config_map(current_strategy)
if key in in_memory_config_map:
cv: ConfigVar = in_memory_config_map.get(key)
elif key in global_config_map:
cv: ConfigVar = global_config_map.get(key)
elif strategy_cm is not None and key in strategy_cm:
cv: ConfigVar = strategy_cm.get(key)
else:
raise ValueError(f"No config variable associated with key name {key}")
return cv
async def _inner_config_loop(self, keys: List[str]):
"""
Inner loop used by `self._config_loop` that recursively calls itself until all required configs are filled.
This enables the bot to detect any newly added requirements as the user fills currently required variables.
Use case example:
When the user selects a particular market, the API keys related to that market becomes required.
:param keys:
"""
for key in keys:
cv: ConfigVar = self._get_config_var_with_key(key)
if cv.value is not None and cv.key != "wallet":
continue
value = await self.prompt_single_variable(cv, requirement_overwrite=False)
cv.value = parse_cvar_value(cv, value)
if self.config_complete:
break
if not self.config_complete:
await self._inner_config_loop(self._get_empty_configs())
async def _config_loop(self, # type: HummingbotApplication
keys: List[str] = []):
"""
Loop until all necessary config variables are complete and the bot is ready for "start"
"""
self._notify("Please follow the prompt to complete configurations: ")
self.placeholder_mode = True
self.app.toggle_hide_input()
try:
await self._inner_config_loop(keys)
await write_config_to_yml()
self._notify("\nConfig process complete. Enter \"start\" to start market making.")
self.app.set_text("start")
except asyncio.TimeoutError:
self.logger().error("Prompt timeout")
except Exception as err:
self.logger().error("Unknown error while writing config. %s" % (err,), exc_info=True)
finally:
self.app.toggle_hide_input()
self.placeholder_mode = False
self.app.change_prompt(prompt=">>> ")
async def _config_single_key(self, # type: HummingbotApplication
key: str):
"""
Configure a single variable only.
Prompt the user to finish all configurations if there are remaining empty configs at the end.
"""
self._notify("Please follow the prompt to complete configurations: ")
self.placeholder_mode = True
self.app.toggle_hide_input()
try:
cv: ConfigVar = self._get_config_var_with_key(key)
value = await self.prompt_single_variable(cv, requirement_overwrite=True)
cv.value = parse_cvar_value(cv, value)
if cv.is_secure:
await self._encrypt_n_save_config_value(cv)
else:
await write_config_to_yml()
self._notify(f"\nNew config saved:\n{key}: {str(value)}")
if not self.config_complete:
choice = await self.app.prompt("Your configuration is incomplete. Would you like to proceed and "
"finish all necessary configurations? (Yes/No) >>> ")
if choice.lower() in {"y", "yes"}:
self.config()
return
else:
self._notify("Aborted.")
except asyncio.TimeoutError:
self.logger().error("Prompt timeout")
except Exception as err:
self.logger().error("Unknown error while writing config. %s" % (err,), exc_info=True)
finally:
self.app.toggle_hide_input()
self.placeholder_mode = False
self.app.change_prompt(prompt=">>> ")
async def _encrypt_n_save_config_value(self, # type: HummingbotApplication
cvar: ConfigVar):
if in_memory_config_map.get("password").value is None:
in_memory_config_map.get("password").value = await self._one_password_config()
password = in_memory_config_map.get("password").value
if encrypted_config_file_exists(cvar):
unlink(get_encrypted_config_path(cvar))
encrypt_n_save_config_value(cvar, password)
|
src_data_file = 'nginx_logs_head.txt'
parsed_data_file = 'nginx_logs_parsed.csv'
parsed_data = []
def row_parse(item):
remote_IP_address, row_tail = item.split(maxsplit=1)
_, _request_datetime = row_tail.split('[', maxsplit=1)
request_datetime, row_tail = _request_datetime.split(']', maxsplit=1)
_, _request_method, row_tail = row_tail.split('"', maxsplit=2)
request_method, requested_resource, _ = _request_method.split(maxsplit=2)
parsed_row = [remote_IP_address, request_datetime, request_method, requested_resource]
return list(map(str.strip, parsed_row))
with open(src_data_file, 'r', encoding='utf-8') as f:
for row in f.read().splitlines():
if not row:
continue
parsed_row = row_parse(row)
parsed_data.append(parsed_row)
with open(parsed_data_file, 'w', encoding='utf-8') as f:
for row in parsed_data:
f.write(f"{", ".join(row)}\n")
| src_data_file = 'nginx_logs_head.txt'
parsed_data_file = 'nginx_logs_parsed.csv'
parsed_data = []
def row_parse(item):
remote_IP_address, row_tail = item.split(maxsplit=1)
_, _request_datetime = row_tail.split('[', maxsplit=1)
request_datetime, row_tail = _request_datetime.split(']', maxsplit=1)
_, _request_method, row_tail = row_tail.split('"', maxsplit=2)
request_method, requested_resource, _ = _request_method.split(maxsplit=2)
parsed_row = [remote_IP_address, request_datetime, request_method, requested_resource]
return list(map(str.strip, parsed_row))
with open(src_data_file, 'r', encoding='utf-8') as f:
for row in f.read().splitlines():
if not row:
continue
parsed_row = row_parse(row)
parsed_data.append(parsed_row)
with open(parsed_data_file, 'w', encoding='utf-8') as f:
for row in parsed_data:
f.write(f"{', '.join(row)}\n")
|
import unittest
from typing import Callable, List, Tuple
import torch
import torch.fx
import torch.fx.experimental.fx_acc.acc_tracer as acc_tracer
from fx2trt_oss.fx import (
TRTInterpreter,
InputTensorSpec,
TRTModule,
)
from torch.testing._internal.common_utils import TestCase
from torch.fx.experimental.normalize import NormalizeArgs
from torch.fx.passes import shape_prop
def fetch_attr(mod, target):
"""
Fetch an attribute from the ``Module`` hierarchy of ``mod.module``.
Args:
target (str): The fully-qualfiied name of the attribute to fetch
Return:
Any: The value of the attribute.
"""
target_atoms = target.split(".")
attr_itr = mod
for i, atom in enumerate(target_atoms):
if not hasattr(attr_itr, atom):
raise RuntimeError(
f"Node referenced nonexistent target {".".join(target_atoms[:i])}"
)
attr_itr = getattr(attr_itr, atom)
return attr_itr
@unittest.skipIf(not torch.cuda.is_available(), "Skip because CUDA is not available")
class TRTTestCase(TestCase):
def setUp(self):
super().setUp()
torch.manual_seed(3)
def run_test(self, mod, inputs, expected_ops, unexpected_ops, interpreter, rtol, atol):
with torch.no_grad():
cuda_inputs = []
for i in inputs:
cuda_inputs.append(i.cuda())
mod.eval()
if len(expected_ops):
self.assert_has_op(mod, expected_ops)
if unexpected_ops:
self.assert_unexpected_op(mod, unexpected_ops)
interpreter_result = interpreter.run(fp16_mode=False)
trt_mod = TRTModule(
interpreter_result.engine,
interpreter_result.input_names,
interpreter_result.output_names,
)
ref_outputs = mod(*inputs)
outputs = trt_mod(*cuda_inputs)
if isinstance(outputs, torch.Tensor):
ref_outputs = [ref_outputs]
outputs = [outputs]
for out, ref in zip(outputs, ref_outputs):
torch.testing.assert_allclose(out.cpu(), ref, rtol=rtol, atol=atol)
def run_test_custom_compare_results(
self,
mod,
inputs,
expected_ops,
interpreter,
comparators: List[Tuple[Callable, List]],
fp16_mode=False,
):
"""
Runs the test and compares the result using the provided comparators.
The size of comparators must be equal to the number of outputs from 'mod'.
mod - a model to run.
inputs - a list of the model inputs.
expected ops - a list of ops that should be verified.
interpreter - used for converting the model to TRT.
comparators - a list of (func, args) pairs corresponding to each of
the module outputs. usage: func(x, y, *args)
"""
with torch.no_grad():
cuda_inputs = []
for i in inputs:
cuda_inputs.append(i.cuda())
mod.eval()
if len(expected_ops):
self.assert_has_op(mod, expected_ops)
interpreter_result = interpreter.run(fp16_mode=fp16_mode)
trt_mod = TRTModule(
interpreter_result.engine,
interpreter_result.input_names,
interpreter_result.output_names,
)
res_trt = trt_mod(*cuda_inputs).cpu()
res_cpu = mod(*inputs)
assert len(res_trt) == len(res_cpu)
assert len(res_cpu) == len(comparators)
for output_trt, output_cpu, comparator in zip(
res_trt, res_cpu, comparators
):
comp_func = comparator[0]
args = comparator[1]
self.assertTrue(comp_func(output_trt, output_cpu, *args))
def run_test_with_error(self, mod, inputs, interpreter, expect_error):
with self.assertRaises(expect_error):
with torch.no_grad():
cuda_inputs = []
for i in inputs:
cuda_inputs.append(i.cuda())
mod.eval()
interpreter.run(fp16_mode=False)
def assert_has_op(self, mod, ops):
ops_in_mod = set()
for node in mod.graph.nodes:
if node.op == "call_module":
ops_in_mod.add(type(fetch_attr(mod, node.target)))
elif node.op in {"call_function", "call_method"}:
ops_in_mod.add(node.target)
self.assertTrue(
ops_in_mod >= ops, f"expected ops {ops}, actuall ops {ops_in_mod}"
)
def assert_unexpected_op(self, mod, ops):
for node in mod.graph.nodes:
if (node.op == "call_module"):
if type(fetch_attr(mod, node.target)) in ops:
return False
elif node.op in {"call_function", "call_method"}:
if node.target in ops:
return False
return True
class VanillaTestCase(TRTTestCase):
def run_test(self, mod, inputs, expected_ops, rtol=1e-05, atol=1e-06):
mod = torch.fx.symbolic_trace(mod)
shape_prop.ShapeProp(mod).propagate(*inputs)
mod = NormalizeArgs(mod).transform()
interp = TRTInterpreter(mod, InputTensorSpec.from_tensors(inputs))
super().run_test(mod, inputs, expected_ops, None, interp, rtol, atol)
def run_test_custom_compare_results(
self,
mod,
inputs,
expected_ops,
interpreter,
comparators: List[Tuple[Callable, List]],
fp16_mode=False,
):
# interpreter is ignored, we do not need this for Vanilla tests
# Note this is different from internal version, we need to fix the test case
# after we refactor the internal callsites to use this file
mod = torch.fx.symbolic_trace(mod)
shape_prop.ShapeProp(mod).propagate(*inputs)
mod = NormalizeArgs(mod).transform()
interp = TRTInterpreter(mod, InputTensorSpec.from_tensors(inputs))
super().run_test_custom_compare_results(
mod, inputs, expected_ops, interp, comparators, fp16_mode=fp16_mode
)
class AccTestCase(TRTTestCase):
def run_test(
self,
mod,
inputs,
expected_ops,
unexpected_ops=None,
apply_passes=None,
test_explicit_batch_dim=True,
test_implicit_batch_dim=True,
rtol=1e-03,
atol=1e-03,
):
mod.eval()
mod = acc_tracer.trace(mod, inputs)
if apply_passes is not None:
for p in apply_passes:
mod = p(mod)
if test_implicit_batch_dim:
interp = TRTInterpreter(mod, InputTensorSpec.from_tensors(inputs))
super().run_test(mod, inputs, expected_ops, unexpected_ops, interp, rtol, atol)
if test_explicit_batch_dim:
interp = TRTInterpreter(
mod, InputTensorSpec.from_tensors(inputs), explicit_batch_dimension=True
)
super().run_test(mod, inputs, expected_ops, unexpected_ops, interp, rtol, atol)
def run_test_with_assert_error(
self,
mod,
inputs,
expect_error,
test_explicit_batch_dim=True,
test_implicit_batch_dim=True,
):
mod.eval()
mod = acc_tracer.trace(mod, inputs)
if test_implicit_batch_dim:
interp = TRTInterpreter(mod, InputTensorSpec.from_tensors(inputs))
super().run_test_with_error(mod, inputs, interp, expect_error)
if test_explicit_batch_dim:
interp = TRTInterpreter(
mod, InputTensorSpec.from_tensors(inputs), explicit_batch_dimension=True
)
super().run_test_with_error(mod, inputs, interp, expect_error)
def run_test_with_dynamic_shape(
self,
mod,
input_specs,
expected_ops,
unexpected_ops=None,
rtol=1e-03,
atol=1e-03,
):
mod.eval()
inputs = InputTensorSpec.create_inputs_from_specs(input_specs)
mod = acc_tracer.trace(mod, inputs)
interp = TRTInterpreter(mod, input_specs, explicit_batch_dimension=True)
super().run_test(mod, inputs, expected_ops, unexpected_ops, interp, rtol, atol)
| import unittest
from typing import Callable, List, Tuple
import torch
import torch.fx
import torch.fx.experimental.fx_acc.acc_tracer as acc_tracer
from fx2trt_oss.fx import (
TRTInterpreter,
InputTensorSpec,
TRTModule,
)
from torch.testing._internal.common_utils import TestCase
from torch.fx.experimental.normalize import NormalizeArgs
from torch.fx.passes import shape_prop
def fetch_attr(mod, target):
"""
Fetch an attribute from the ``Module`` hierarchy of ``mod.module``.
Args:
target (str): The fully-qualfiied name of the attribute to fetch
Return:
Any: The value of the attribute.
"""
target_atoms = target.split(".")
attr_itr = mod
for i, atom in enumerate(target_atoms):
if not hasattr(attr_itr, atom):
raise RuntimeError(
f"Node referenced nonexistent target {'.'.join(target_atoms[:i])}"
)
attr_itr = getattr(attr_itr, atom)
return attr_itr
@unittest.skipIf(not torch.cuda.is_available(), "Skip because CUDA is not available")
class TRTTestCase(TestCase):
def setUp(self):
super().setUp()
torch.manual_seed(3)
def run_test(self, mod, inputs, expected_ops, unexpected_ops, interpreter, rtol, atol):
with torch.no_grad():
cuda_inputs = []
for i in inputs:
cuda_inputs.append(i.cuda())
mod.eval()
if len(expected_ops):
self.assert_has_op(mod, expected_ops)
if unexpected_ops:
self.assert_unexpected_op(mod, unexpected_ops)
interpreter_result = interpreter.run(fp16_mode=False)
trt_mod = TRTModule(
interpreter_result.engine,
interpreter_result.input_names,
interpreter_result.output_names,
)
ref_outputs = mod(*inputs)
outputs = trt_mod(*cuda_inputs)
if isinstance(outputs, torch.Tensor):
ref_outputs = [ref_outputs]
outputs = [outputs]
for out, ref in zip(outputs, ref_outputs):
torch.testing.assert_allclose(out.cpu(), ref, rtol=rtol, atol=atol)
def run_test_custom_compare_results(
self,
mod,
inputs,
expected_ops,
interpreter,
comparators: List[Tuple[Callable, List]],
fp16_mode=False,
):
"""
Runs the test and compares the result using the provided comparators.
The size of comparators must be equal to the number of outputs from 'mod'.
mod - a model to run.
inputs - a list of the model inputs.
expected ops - a list of ops that should be verified.
interpreter - used for converting the model to TRT.
comparators - a list of (func, args) pairs corresponding to each of
the module outputs. usage: func(x, y, *args)
"""
with torch.no_grad():
cuda_inputs = []
for i in inputs:
cuda_inputs.append(i.cuda())
mod.eval()
if len(expected_ops):
self.assert_has_op(mod, expected_ops)
interpreter_result = interpreter.run(fp16_mode=fp16_mode)
trt_mod = TRTModule(
interpreter_result.engine,
interpreter_result.input_names,
interpreter_result.output_names,
)
res_trt = trt_mod(*cuda_inputs).cpu()
res_cpu = mod(*inputs)
assert len(res_trt) == len(res_cpu)
assert len(res_cpu) == len(comparators)
for output_trt, output_cpu, comparator in zip(
res_trt, res_cpu, comparators
):
comp_func = comparator[0]
args = comparator[1]
self.assertTrue(comp_func(output_trt, output_cpu, *args))
def run_test_with_error(self, mod, inputs, interpreter, expect_error):
with self.assertRaises(expect_error):
with torch.no_grad():
cuda_inputs = []
for i in inputs:
cuda_inputs.append(i.cuda())
mod.eval()
interpreter.run(fp16_mode=False)
def assert_has_op(self, mod, ops):
ops_in_mod = set()
for node in mod.graph.nodes:
if node.op == "call_module":
ops_in_mod.add(type(fetch_attr(mod, node.target)))
elif node.op in {"call_function", "call_method"}:
ops_in_mod.add(node.target)
self.assertTrue(
ops_in_mod >= ops, f"expected ops {ops}, actuall ops {ops_in_mod}"
)
def assert_unexpected_op(self, mod, ops):
for node in mod.graph.nodes:
if (node.op == "call_module"):
if type(fetch_attr(mod, node.target)) in ops:
return False
elif node.op in {"call_function", "call_method"}:
if node.target in ops:
return False
return True
class VanillaTestCase(TRTTestCase):
def run_test(self, mod, inputs, expected_ops, rtol=1e-05, atol=1e-06):
mod = torch.fx.symbolic_trace(mod)
shape_prop.ShapeProp(mod).propagate(*inputs)
mod = NormalizeArgs(mod).transform()
interp = TRTInterpreter(mod, InputTensorSpec.from_tensors(inputs))
super().run_test(mod, inputs, expected_ops, None, interp, rtol, atol)
def run_test_custom_compare_results(
self,
mod,
inputs,
expected_ops,
interpreter,
comparators: List[Tuple[Callable, List]],
fp16_mode=False,
):
# interpreter is ignored, we do not need this for Vanilla tests
# Note this is different from internal version, we need to fix the test case
# after we refactor the internal callsites to use this file
mod = torch.fx.symbolic_trace(mod)
shape_prop.ShapeProp(mod).propagate(*inputs)
mod = NormalizeArgs(mod).transform()
interp = TRTInterpreter(mod, InputTensorSpec.from_tensors(inputs))
super().run_test_custom_compare_results(
mod, inputs, expected_ops, interp, comparators, fp16_mode=fp16_mode
)
class AccTestCase(TRTTestCase):
def run_test(
self,
mod,
inputs,
expected_ops,
unexpected_ops=None,
apply_passes=None,
test_explicit_batch_dim=True,
test_implicit_batch_dim=True,
rtol=1e-03,
atol=1e-03,
):
mod.eval()
mod = acc_tracer.trace(mod, inputs)
if apply_passes is not None:
for p in apply_passes:
mod = p(mod)
if test_implicit_batch_dim:
interp = TRTInterpreter(mod, InputTensorSpec.from_tensors(inputs))
super().run_test(mod, inputs, expected_ops, unexpected_ops, interp, rtol, atol)
if test_explicit_batch_dim:
interp = TRTInterpreter(
mod, InputTensorSpec.from_tensors(inputs), explicit_batch_dimension=True
)
super().run_test(mod, inputs, expected_ops, unexpected_ops, interp, rtol, atol)
def run_test_with_assert_error(
self,
mod,
inputs,
expect_error,
test_explicit_batch_dim=True,
test_implicit_batch_dim=True,
):
mod.eval()
mod = acc_tracer.trace(mod, inputs)
if test_implicit_batch_dim:
interp = TRTInterpreter(mod, InputTensorSpec.from_tensors(inputs))
super().run_test_with_error(mod, inputs, interp, expect_error)
if test_explicit_batch_dim:
interp = TRTInterpreter(
mod, InputTensorSpec.from_tensors(inputs), explicit_batch_dimension=True
)
super().run_test_with_error(mod, inputs, interp, expect_error)
def run_test_with_dynamic_shape(
self,
mod,
input_specs,
expected_ops,
unexpected_ops=None,
rtol=1e-03,
atol=1e-03,
):
mod.eval()
inputs = InputTensorSpec.create_inputs_from_specs(input_specs)
mod = acc_tracer.trace(mod, inputs)
interp = TRTInterpreter(mod, input_specs, explicit_batch_dimension=True)
super().run_test(mod, inputs, expected_ops, unexpected_ops, interp, rtol, atol)
|
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
import importlib
import operator
import types
from importlib.util import find_spec
from typing import List, Tuple, Union
from pkg_resources import DistributionNotFound
try:
from packaging.version import Version
except (ModuleNotFoundError, DistributionNotFound):
Version = None
def _module_available(module_path: str) -> bool:
"""Check if a path is available in your environment.
>>> _module_available('os')
True
>>> _module_available('bla.bla')
False
"""
try:
return find_spec(module_path) is not None
except AttributeError:
# Python 3.6
return False
except ModuleNotFoundError:
# Python 3.7+
return False
except ValueError:
# Sometimes __spec__ can be None and gives a ValueError
return True
def _compare_version(package: str, op, version) -> bool:
"""Compare package version with some requirements.
>>> _compare_version("torch", operator.ge, "0.1")
True
"""
try:
pkg = importlib.import_module(package)
except (ModuleNotFoundError, DistributionNotFound, ValueError):
return False
try:
pkg_version = Version(pkg.__version__)
except TypeError:
# this is mock by sphinx, so it shall return True to generate all summaries
return True
return op(pkg_version, Version(version))
_TORCH_AVAILABLE = _module_available("torch")
_PL_AVAILABLE = _module_available("pytorch_lightning")
_BOLTS_AVAILABLE = _module_available("pl_bolts") and _compare_version("torch", operator.lt, "1.9.0")
_PANDAS_AVAILABLE = _module_available("pandas")
_SKLEARN_AVAILABLE = _module_available("sklearn")
_PYTORCHTABULAR_AVAILABLE = _module_available("pytorch_tabular")
_FORECASTING_AVAILABLE = _module_available("pytorch_forecasting")
_KORNIA_AVAILABLE = _module_available("kornia")
_COCO_AVAILABLE = _module_available("pycocotools")
_TIMM_AVAILABLE = _module_available("timm")
_TORCHVISION_AVAILABLE = _module_available("torchvision")
_PYTORCHVIDEO_AVAILABLE = _module_available("pytorchvideo")
_MATPLOTLIB_AVAILABLE = _module_available("matplotlib")
_TRANSFORMERS_AVAILABLE = _module_available("transformers")
_PYSTICHE_AVAILABLE = _module_available("pystiche")
_FIFTYONE_AVAILABLE = _module_available("fiftyone")
_FASTAPI_AVAILABLE = _module_available("fastapi")
_PYDANTIC_AVAILABLE = _module_available("pydantic")
_GRAPHVIZ_AVAILABLE = _module_available("graphviz")
_CYTOOLZ_AVAILABLE = _module_available("cytoolz")
_UVICORN_AVAILABLE = _module_available("uvicorn")
_PIL_AVAILABLE = _module_available("PIL")
_OPEN3D_AVAILABLE = _module_available("open3d")
_SEGMENTATION_MODELS_AVAILABLE = _module_available("segmentation_models_pytorch")
_FASTFACE_AVAILABLE = _module_available("fastface") and _compare_version("pytorch_lightning", operator.lt, "1.5.0")
_LIBROSA_AVAILABLE = _module_available("librosa")
_TORCH_SCATTER_AVAILABLE = _module_available("torch_scatter")
_TORCH_SPARSE_AVAILABLE = _module_available("torch_sparse")
_TORCH_GEOMETRIC_AVAILABLE = _module_available("torch_geometric")
_NETWORKX_AVAILABLE = _module_available("networkx")
_TORCHAUDIO_AVAILABLE = _module_available("torchaudio")
_SENTENCEPIECE_AVAILABLE = _module_available("sentencepiece")
_DATASETS_AVAILABLE = _module_available("datasets")
_TM_TEXT_AVAILABLE: bool = _module_available("torchmetrics.text")
_ICEVISION_AVAILABLE = _module_available("icevision")
_ICEDATA_AVAILABLE = _module_available("icedata")
_LEARN2LEARN_AVAILABLE = _module_available("learn2learn") and _compare_version("learn2learn", operator.ge, "0.1.6")
_TORCH_ORT_AVAILABLE = _module_available("torch_ort")
_VISSL_AVAILABLE = _module_available("vissl") and _module_available("classy_vision")
_ALBUMENTATIONS_AVAILABLE = _module_available("albumentations")
_BAAL_AVAILABLE = _module_available("baal")
_TORCH_OPTIMIZER_AVAILABLE = _module_available("torch_optimizer")
_SENTENCE_TRANSFORMERS_AVAILABLE = _module_available("sentence_transformers")
if _PIL_AVAILABLE:
from PIL import Image # noqa: F401
else:
class Image:
Image = object
if Version:
_TORCHVISION_GREATER_EQUAL_0_9 = _compare_version("torchvision", operator.ge, "0.9.0")
_PL_GREATER_EQUAL_1_4_3 = _compare_version("pytorch_lightning", operator.ge, "1.4.3")
_PL_GREATER_EQUAL_1_4_0 = _compare_version("pytorch_lightning", operator.ge, "1.4.0")
_PL_GREATER_EQUAL_1_5_0 = _compare_version("pytorch_lightning", operator.ge, "1.5.0")
_PANDAS_GREATER_EQUAL_1_3_0 = _compare_version("pandas", operator.ge, "1.3.0")
_ICEVISION_GREATER_EQUAL_0_11_0 = _compare_version("icevision", operator.ge, "0.11.0")
_TEXT_AVAILABLE = all(
[
_TRANSFORMERS_AVAILABLE,
_SENTENCEPIECE_AVAILABLE,
_DATASETS_AVAILABLE,
_TM_TEXT_AVAILABLE,
_SENTENCE_TRANSFORMERS_AVAILABLE,
]
)
_TABULAR_AVAILABLE = _PANDAS_AVAILABLE and _FORECASTING_AVAILABLE and _PYTORCHTABULAR_AVAILABLE
_VIDEO_AVAILABLE = _TORCHVISION_AVAILABLE and _PIL_AVAILABLE and _PYTORCHVIDEO_AVAILABLE and _KORNIA_AVAILABLE
_IMAGE_AVAILABLE = all(
[
_TORCHVISION_AVAILABLE,
_TIMM_AVAILABLE,
_PIL_AVAILABLE,
_KORNIA_AVAILABLE,
_PYSTICHE_AVAILABLE,
_SEGMENTATION_MODELS_AVAILABLE,
]
)
_SERVE_AVAILABLE = _FASTAPI_AVAILABLE and _PYDANTIC_AVAILABLE and _CYTOOLZ_AVAILABLE and _UVICORN_AVAILABLE
_POINTCLOUD_AVAILABLE = _OPEN3D_AVAILABLE and _TORCHVISION_AVAILABLE
_AUDIO_AVAILABLE = all([_TORCHAUDIO_AVAILABLE, _LIBROSA_AVAILABLE, _TRANSFORMERS_AVAILABLE])
_GRAPH_AVAILABLE = (
_TORCH_SCATTER_AVAILABLE and _TORCH_SPARSE_AVAILABLE and _TORCH_GEOMETRIC_AVAILABLE and _NETWORKX_AVAILABLE
)
_EXTRAS_AVAILABLE = {
"image": _IMAGE_AVAILABLE,
"tabular": _TABULAR_AVAILABLE,
"text": _TEXT_AVAILABLE,
"video": _VIDEO_AVAILABLE,
"pointcloud": _POINTCLOUD_AVAILABLE,
"serve": _SERVE_AVAILABLE,
"audio": _AUDIO_AVAILABLE,
"graph": _GRAPH_AVAILABLE,
}
def requires(module_paths: Union[str, Tuple[bool, str], List[Union[str, Tuple[bool, str]]]]):
if not isinstance(module_paths, list):
module_paths = [module_paths]
def decorator(func):
available = True
extras = []
modules = []
for module_path in module_paths:
if isinstance(module_path, str):
if module_path in _EXTRAS_AVAILABLE:
extras.append(module_path)
if not _EXTRAS_AVAILABLE[module_path]:
available = False
else:
modules.append(module_path)
if not _module_available(module_path):
available = False
else:
available, module_path = module_path
modules.append(module_path)
if not available:
modules = [f"'{module}'" for module in modules]
modules.append(f"'lightning-flash[{",".join(extras)}]'")
@functools.wraps(func)
def wrapper(*args, **kwargs):
raise ModuleNotFoundError(
f"Required dependencies not available. Please run: pip install {" ".join(modules)}"
)
return wrapper
return func
return decorator
def example_requires(module_paths: Union[str, List[str]]):
return requires(module_paths)(lambda: None)()
def lazy_import(module_name, callback=None):
"""Returns a proxy module object that will lazily import the given module the first time it is used.
Example usage::
# Lazy version of `import tensorflow as tf`
tf = lazy_import("tensorflow")
# Other commands
# Now the module is loaded
tf.__version__
Args:
module_name: the fully-qualified module name to import
callback (None): a callback function to call before importing the
module
Returns:
a proxy module object that will be lazily imported when first used
"""
return LazyModule(module_name, callback=callback)
class LazyModule(types.ModuleType):
"""Proxy module that lazily imports the underlying module the first time it is actually used.
Args:
module_name: the fully-qualified module name to import
callback (None): a callback function to call before importing the
module
"""
def __init__(self, module_name, callback=None):
super().__init__(module_name)
self._module = None
self._callback = callback
def __getattr__(self, item):
if self._module is None:
self._import_module()
return getattr(self._module, item)
def __dir__(self):
if self._module is None:
self._import_module()
return dir(self._module)
def _import_module(self):
# Execute callback, if any
if self._callback is not None:
self._callback()
# Actually import the module
module = importlib.import_module(self.__name__)
self._module = module
# Update this object's dict so that attribute references are efficient
# (__getattr__ is only called on lookups that fail)
self.__dict__.update(module.__dict__)
| # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
import importlib
import operator
import types
from importlib.util import find_spec
from typing import List, Tuple, Union
from pkg_resources import DistributionNotFound
try:
from packaging.version import Version
except (ModuleNotFoundError, DistributionNotFound):
Version = None
def _module_available(module_path: str) -> bool:
"""Check if a path is available in your environment.
>>> _module_available('os')
True
>>> _module_available('bla.bla')
False
"""
try:
return find_spec(module_path) is not None
except AttributeError:
# Python 3.6
return False
except ModuleNotFoundError:
# Python 3.7+
return False
except ValueError:
# Sometimes __spec__ can be None and gives a ValueError
return True
def _compare_version(package: str, op, version) -> bool:
"""Compare package version with some requirements.
>>> _compare_version("torch", operator.ge, "0.1")
True
"""
try:
pkg = importlib.import_module(package)
except (ModuleNotFoundError, DistributionNotFound, ValueError):
return False
try:
pkg_version = Version(pkg.__version__)
except TypeError:
# this is mock by sphinx, so it shall return True to generate all summaries
return True
return op(pkg_version, Version(version))
_TORCH_AVAILABLE = _module_available("torch")
_PL_AVAILABLE = _module_available("pytorch_lightning")
_BOLTS_AVAILABLE = _module_available("pl_bolts") and _compare_version("torch", operator.lt, "1.9.0")
_PANDAS_AVAILABLE = _module_available("pandas")
_SKLEARN_AVAILABLE = _module_available("sklearn")
_PYTORCHTABULAR_AVAILABLE = _module_available("pytorch_tabular")
_FORECASTING_AVAILABLE = _module_available("pytorch_forecasting")
_KORNIA_AVAILABLE = _module_available("kornia")
_COCO_AVAILABLE = _module_available("pycocotools")
_TIMM_AVAILABLE = _module_available("timm")
_TORCHVISION_AVAILABLE = _module_available("torchvision")
_PYTORCHVIDEO_AVAILABLE = _module_available("pytorchvideo")
_MATPLOTLIB_AVAILABLE = _module_available("matplotlib")
_TRANSFORMERS_AVAILABLE = _module_available("transformers")
_PYSTICHE_AVAILABLE = _module_available("pystiche")
_FIFTYONE_AVAILABLE = _module_available("fiftyone")
_FASTAPI_AVAILABLE = _module_available("fastapi")
_PYDANTIC_AVAILABLE = _module_available("pydantic")
_GRAPHVIZ_AVAILABLE = _module_available("graphviz")
_CYTOOLZ_AVAILABLE = _module_available("cytoolz")
_UVICORN_AVAILABLE = _module_available("uvicorn")
_PIL_AVAILABLE = _module_available("PIL")
_OPEN3D_AVAILABLE = _module_available("open3d")
_SEGMENTATION_MODELS_AVAILABLE = _module_available("segmentation_models_pytorch")
_FASTFACE_AVAILABLE = _module_available("fastface") and _compare_version("pytorch_lightning", operator.lt, "1.5.0")
_LIBROSA_AVAILABLE = _module_available("librosa")
_TORCH_SCATTER_AVAILABLE = _module_available("torch_scatter")
_TORCH_SPARSE_AVAILABLE = _module_available("torch_sparse")
_TORCH_GEOMETRIC_AVAILABLE = _module_available("torch_geometric")
_NETWORKX_AVAILABLE = _module_available("networkx")
_TORCHAUDIO_AVAILABLE = _module_available("torchaudio")
_SENTENCEPIECE_AVAILABLE = _module_available("sentencepiece")
_DATASETS_AVAILABLE = _module_available("datasets")
_TM_TEXT_AVAILABLE: bool = _module_available("torchmetrics.text")
_ICEVISION_AVAILABLE = _module_available("icevision")
_ICEDATA_AVAILABLE = _module_available("icedata")
_LEARN2LEARN_AVAILABLE = _module_available("learn2learn") and _compare_version("learn2learn", operator.ge, "0.1.6")
_TORCH_ORT_AVAILABLE = _module_available("torch_ort")
_VISSL_AVAILABLE = _module_available("vissl") and _module_available("classy_vision")
_ALBUMENTATIONS_AVAILABLE = _module_available("albumentations")
_BAAL_AVAILABLE = _module_available("baal")
_TORCH_OPTIMIZER_AVAILABLE = _module_available("torch_optimizer")
_SENTENCE_TRANSFORMERS_AVAILABLE = _module_available("sentence_transformers")
if _PIL_AVAILABLE:
from PIL import Image # noqa: F401
else:
class Image:
Image = object
if Version:
_TORCHVISION_GREATER_EQUAL_0_9 = _compare_version("torchvision", operator.ge, "0.9.0")
_PL_GREATER_EQUAL_1_4_3 = _compare_version("pytorch_lightning", operator.ge, "1.4.3")
_PL_GREATER_EQUAL_1_4_0 = _compare_version("pytorch_lightning", operator.ge, "1.4.0")
_PL_GREATER_EQUAL_1_5_0 = _compare_version("pytorch_lightning", operator.ge, "1.5.0")
_PANDAS_GREATER_EQUAL_1_3_0 = _compare_version("pandas", operator.ge, "1.3.0")
_ICEVISION_GREATER_EQUAL_0_11_0 = _compare_version("icevision", operator.ge, "0.11.0")
_TEXT_AVAILABLE = all(
[
_TRANSFORMERS_AVAILABLE,
_SENTENCEPIECE_AVAILABLE,
_DATASETS_AVAILABLE,
_TM_TEXT_AVAILABLE,
_SENTENCE_TRANSFORMERS_AVAILABLE,
]
)
_TABULAR_AVAILABLE = _PANDAS_AVAILABLE and _FORECASTING_AVAILABLE and _PYTORCHTABULAR_AVAILABLE
_VIDEO_AVAILABLE = _TORCHVISION_AVAILABLE and _PIL_AVAILABLE and _PYTORCHVIDEO_AVAILABLE and _KORNIA_AVAILABLE
_IMAGE_AVAILABLE = all(
[
_TORCHVISION_AVAILABLE,
_TIMM_AVAILABLE,
_PIL_AVAILABLE,
_KORNIA_AVAILABLE,
_PYSTICHE_AVAILABLE,
_SEGMENTATION_MODELS_AVAILABLE,
]
)
_SERVE_AVAILABLE = _FASTAPI_AVAILABLE and _PYDANTIC_AVAILABLE and _CYTOOLZ_AVAILABLE and _UVICORN_AVAILABLE
_POINTCLOUD_AVAILABLE = _OPEN3D_AVAILABLE and _TORCHVISION_AVAILABLE
_AUDIO_AVAILABLE = all([_TORCHAUDIO_AVAILABLE, _LIBROSA_AVAILABLE, _TRANSFORMERS_AVAILABLE])
_GRAPH_AVAILABLE = (
_TORCH_SCATTER_AVAILABLE and _TORCH_SPARSE_AVAILABLE and _TORCH_GEOMETRIC_AVAILABLE and _NETWORKX_AVAILABLE
)
_EXTRAS_AVAILABLE = {
"image": _IMAGE_AVAILABLE,
"tabular": _TABULAR_AVAILABLE,
"text": _TEXT_AVAILABLE,
"video": _VIDEO_AVAILABLE,
"pointcloud": _POINTCLOUD_AVAILABLE,
"serve": _SERVE_AVAILABLE,
"audio": _AUDIO_AVAILABLE,
"graph": _GRAPH_AVAILABLE,
}
def requires(module_paths: Union[str, Tuple[bool, str], List[Union[str, Tuple[bool, str]]]]):
if not isinstance(module_paths, list):
module_paths = [module_paths]
def decorator(func):
available = True
extras = []
modules = []
for module_path in module_paths:
if isinstance(module_path, str):
if module_path in _EXTRAS_AVAILABLE:
extras.append(module_path)
if not _EXTRAS_AVAILABLE[module_path]:
available = False
else:
modules.append(module_path)
if not _module_available(module_path):
available = False
else:
available, module_path = module_path
modules.append(module_path)
if not available:
modules = [f"'{module}'" for module in modules]
modules.append(f"'lightning-flash[{','.join(extras)}]'")
@functools.wraps(func)
def wrapper(*args, **kwargs):
raise ModuleNotFoundError(
f"Required dependencies not available. Please run: pip install {' '.join(modules)}"
)
return wrapper
return func
return decorator
def example_requires(module_paths: Union[str, List[str]]):
return requires(module_paths)(lambda: None)()
def lazy_import(module_name, callback=None):
"""Returns a proxy module object that will lazily import the given module the first time it is used.
Example usage::
# Lazy version of `import tensorflow as tf`
tf = lazy_import("tensorflow")
# Other commands
# Now the module is loaded
tf.__version__
Args:
module_name: the fully-qualified module name to import
callback (None): a callback function to call before importing the
module
Returns:
a proxy module object that will be lazily imported when first used
"""
return LazyModule(module_name, callback=callback)
class LazyModule(types.ModuleType):
"""Proxy module that lazily imports the underlying module the first time it is actually used.
Args:
module_name: the fully-qualified module name to import
callback (None): a callback function to call before importing the
module
"""
def __init__(self, module_name, callback=None):
super().__init__(module_name)
self._module = None
self._callback = callback
def __getattr__(self, item):
if self._module is None:
self._import_module()
return getattr(self._module, item)
def __dir__(self):
if self._module is None:
self._import_module()
return dir(self._module)
def _import_module(self):
# Execute callback, if any
if self._callback is not None:
self._callback()
# Actually import the module
module = importlib.import_module(self.__name__)
self._module = module
# Update this object's dict so that attribute references are efficient
# (__getattr__ is only called on lookups that fail)
self.__dict__.update(module.__dict__)
|
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Estimating the susceptibility distortions without fieldmaps.
.. testsetup::
>>> tmpdir = getfixture('tmpdir')
>>> tmp = tmpdir.chdir() # changing to a temporary directory
>>> data = np.zeros((10, 10, 10, 1, 3))
>>> data[..., 1] = 1
>>> nb.Nifti1Image(data, None, None).to_filename(
... tmpdir.join('field.nii.gz').strpath)
.. _sdc_fieldmapless :
Fieldmap-less approaches
~~~~~~~~~~~~~~~~~~~~~~~~
Many studies acquired (especially with legacy MRI protocols) do not have any
information to estimate susceptibility-derived distortions.
In the absence of data with the specific purpose of estimating the :math:`B_0`
inhomogeneity map, researchers resort to nonlinear registration to an
«*anatomically correct*» map of the same individual (normally acquired with
:abbr:`T1w (T1-weighted)`, or :abbr:`T2w (T2-weighted)` sequences).
One of the most prominent proposals of this approach is found in [Studholme2000]_.
*SDCFlows* includes an (experimental) procedure (see :py:func:`init_syn_sdc_wf` below),
based on nonlinear image registration with ANTs' symmetric normalization (SyN) technique.
This workflow takes a skull-stripped :abbr:`T1w (T1-weighted)` image and
a reference :abbr:`EPI (Echo-Planar Imaging)` image, and estimates a field of nonlinear
displacements that accounts for susceptibility-derived distortions.
To more accurately estimate the warping on typically distorted regions, this
implementation uses an average :math:`B_0` mapping described in [Treiber2016]_.
The implementation is a variation on those developed in [Huntenburg2014]_ and
[Wang2017]_.
Feedback will be enthusiastically received.
References
----------
.. [Studholme2000] Studholme et al. (2000) Accurate alignment of functional EPI data to
anatomical MRI using a physics-based distortion model,
IEEE Trans Med Imag 19(11):1115-1127, 2000, doi: `10.1109/42.896788
<https://doi.org/10.1109/42.896788>`__.
.. [Treiber2016] Treiber, J. M. et al. (2016) Characterization and Correction
of Geometric Distortions in 814 Diffusion Weighted Images,
PLoS ONE 11(3): e0152472. doi:`10.1371/journal.pone.0152472
<https://doi.org/10.1371/journal.pone.0152472>`_.
.. [Wang2017] Wang S, et al. (2017) Evaluation of Field Map and Nonlinear
Registration Methods for Correction of Susceptibility Artifacts
in Diffusion MRI. Front. Neuroinform. 11:17.
doi:`10.3389/fninf.2017.00017
<https://doi.org/10.3389/fninf.2017.00017>`_.
.. [Huntenburg2014] Huntenburg, J. M. (2014) `Evaluating Nonlinear
Coregistration of BOLD EPI and T1w Images
<http://pubman.mpdl.mpg.de/pubman/item/escidoc:2327525:5/component/escidoc:2327523/master_thesis_huntenburg_4686947.pdf>`__,
Berlin: Master Thesis, Freie Universität.
"""
from pkg_resources import resource_filename
from nipype.pipeline import engine as pe
from nipype.interfaces import utility as niu
from niworkflows.engine.workflows import LiterateWorkflow as Workflow
DEFAULT_MEMORY_MIN_GB = 0.01
INPUT_FIELDS = (
"epi_ref",
"epi_mask",
"anat_ref",
"anat_mask",
"sd_prior",
)
def init_syn_sdc_wf(
*,
atlas_threshold=3,
debug=False,
name="syn_sdc_wf",
omp_nthreads=1,
):
"""
Build the *fieldmap-less* susceptibility-distortion estimation workflow.
SyN deformation is restricted to the phase-encoding (PE) direction.
If no PE direction is specified, anterior-posterior PE is assumed.
SyN deformation is also restricted to regions that are expected to have a
>3mm (approximately 1 voxel) warp, based on the fieldmap atlas.
Workflow Graph
.. workflow ::
:graph2use: orig
:simple_form: yes
from sdcflows.workflows.fit.syn import init_syn_sdc_wf
wf = init_syn_sdc_wf(omp_nthreads=8)
Parameters
----------
atlas_threshold : :obj:`float`
Exclude from the registration metric computation areas with average distortions
below this threshold (in mm).
debug : :obj:`bool`
Whether a fast (less accurate) configuration of the workflow should be applied.
name : :obj:`str`
Name for this workflow
omp_nthreads : :obj:`int`
Parallelize internal tasks across the number of CPUs given by this option.
Inputs
------
epi_ref : :obj:`tuple` (:obj:`str`, :obj:`dict`)
A tuple, where the first element is the path of the distorted EPI
reference map (e.g., an average of *b=0* volumes), and the second
element is a dictionary of associated metadata.
epi_mask : :obj:`str`
A path to a brain mask corresponding to ``epi_ref``.
anat_ref : :obj:`str`
A preprocessed, skull-stripped anatomical (T1w or T2w) image resampled in EPI space.
anat_mask : :obj:`str`
Path to the brain mask corresponding to ``anat_ref`` in EPI space.
sd_prior : :obj:`str`
A template map of areas with strong susceptibility distortions (SD) to regularize
the cost function of SyN
Outputs
-------
fmap : :obj:`str`
The path of the estimated fieldmap.
fmap_ref : :obj:`str`
The path of an unwarped conversion of files in ``epi_ref``.
fmap_coeff : :obj:`str` or :obj:`list` of :obj:`str`
The path(s) of the B-Spline coefficients supporting the fieldmap.
"""
from pkg_resources import resource_filename as pkgrf
from packaging.version import parse as parseversion, Version
from niworkflows.interfaces.fixes import (
FixHeaderApplyTransforms as ApplyTransforms,
FixHeaderRegistration as Registration,
)
from niworkflows.interfaces.header import CopyXForm
from niworkflows.interfaces.nibabel import Binarize, RegridToZooms
from ...utils.misc import front as _pop
from ...interfaces.utils import Reoblique
from ...interfaces.bspline import (
BSplineApprox,
DEFAULT_LF_ZOOMS_MM,
DEFAULT_HF_ZOOMS_MM,
DEFAULT_ZOOMS_MM,
)
from ...interfaces.brainmask import BinaryDilation, Union
ants_version = Registration().version
if ants_version and parseversion(ants_version) < Version("2.2.0"):
raise RuntimeError(
f"Please upgrade ANTs to 2.2 or older ({ants_version} found)."
)
workflow = Workflow(name=name)
workflow.__desc__ = f"""\
A deformation field to correct for susceptibility distortions was estimated
based on *fMRIPrep*'s *fieldmap-less* approach.
The deformation field is that resulting from co-registering the EPI reference
to the same-subject T1w-reference with its intensity inverted [@fieldmapless1;
@fieldmapless2].
Registration is performed with `antsRegistration`
(ANTs {ants_version or "-- version unknown"}), and
the process regularized by constraining deformation to be nonzero only
along the phase-encoding direction, and modulated with an average fieldmap
template [@fieldmapless3].
"""
inputnode = pe.Node(niu.IdentityInterface(INPUT_FIELDS), name="inputnode")
outputnode = pe.Node(
niu.IdentityInterface(["fmap", "fmap_ref", "fmap_coeff", "fmap_mask"]),
name="outputnode",
)
warp_dir = pe.Node(
niu.Function(function=_warp_dir),
run_without_submitting=True,
name="warp_dir",
)
atlas_msk = pe.Node(Binarize(thresh_low=atlas_threshold), name="atlas_msk")
anat_dilmsk = pe.Node(BinaryDilation(), name="anat_dilmsk")
epi_dilmsk = pe.Node(BinaryDilation(), name="epi_dilmsk")
amask2epi = pe.Node(
ApplyTransforms(interpolation="MultiLabel", transforms="identity"),
name="amask2epi",
)
prior2epi = pe.Node(
ApplyTransforms(interpolation="MultiLabel", transforms="identity"),
name="prior2epi",
)
prior_dilmsk = pe.Node(BinaryDilation(radius=4), name="prior_dilmsk")
epi_umask = pe.Node(Union(), name="epi_umask")
moving_masks = pe.Node(
niu.Merge(3),
name="moving_masks",
run_without_submitting=True,
)
fixed_masks = pe.Node(
niu.Merge(3),
name="fixed_masks",
mem_gb=DEFAULT_MEMORY_MIN_GB,
run_without_submitting=True,
)
deoblique = pe.Node(CopyXForm(fields=["epi_ref"]), name="deoblique")
reoblique = pe.Node(Reoblique(), name="reoblique")
# Set a manageable size for the epi reference
find_zooms = pe.Node(niu.Function(function=_adjust_zooms), name="find_zooms")
zooms_epi = pe.Node(RegridToZooms(), name="zooms_epi")
# SyN Registration Core
syn = pe.Node(
Registration(
from_file=pkgrf("sdcflows", f"data/sd_syn{"_debug" * debug}.json")
),
name="syn",
n_procs=omp_nthreads,
)
syn.inputs.output_warped_image = debug
syn.inputs.output_inverse_warped_image = debug
if debug:
syn.inputs.args = "--write-interval-volumes 5"
unwarp_ref = pe.Node(
ApplyTransforms(interpolation="BSpline"),
name="unwarp_ref",
)
# Extract nonzero component
extract_field = pe.Node(niu.Function(function=_extract_field), name="extract_field")
# Check zooms (avoid very expensive B-Splines fitting)
zooms_field = pe.Node(
ApplyTransforms(interpolation="BSpline", transforms="identity"),
name="zooms_field",
)
zooms_bmask = pe.Node(
ApplyTransforms(interpolation="MultiLabel", transforms="identity"),
name="zooms_bmask",
)
# Regularize with B-Splines
bs_filter = pe.Node(BSplineApprox(), n_procs=omp_nthreads, name="bs_filter")
bs_filter.interface._always_run = debug
bs_filter.inputs.bs_spacing = (
[DEFAULT_LF_ZOOMS_MM, DEFAULT_HF_ZOOMS_MM] if not debug else [DEFAULT_ZOOMS_MM]
)
bs_filter.inputs.extrapolate = not debug
# fmt: off
workflow.connect([
(inputnode, extract_field, [("epi_ref", "epi_meta")]),
(inputnode, atlas_msk, [("sd_prior", "in_file")]),
(inputnode, deoblique, [(("epi_ref", _pop), "epi_ref"),
("epi_mask", "hdr_file")]),
(inputnode, reoblique, [(("epi_ref", _pop), "in_epi")]),
(inputnode, epi_dilmsk, [("epi_mask", "in_file")]),
(inputnode, zooms_bmask, [("anat_mask", "input_image")]),
(inputnode, fixed_masks, [("anat_mask", "in2")]),
(inputnode, anat_dilmsk, [("anat_mask", "in_file")]),
(inputnode, warp_dir, [("epi_ref", "intuple")]),
(inputnode, syn, [("anat_ref", "moving_image")]),
(epi_dilmsk, prior2epi, [("out_file", "reference_image")]),
(atlas_msk, prior2epi, [("out_file", "input_image")]),
(prior2epi, prior_dilmsk, [("output_image", "in_file")]),
(anat_dilmsk, fixed_masks, [("out_file", "in1")]),
(warp_dir, syn, [("out", "restrict_deformation")]),
(inputnode, find_zooms, [("anat_ref", "in_anat"),
(("epi_ref", _pop), "in_epi")]),
(deoblique, zooms_epi, [("epi_ref", "in_file")]),
(deoblique, unwarp_ref, [("epi_ref", "input_image")]),
(find_zooms, zooms_epi, [("out", "zooms")]),
(zooms_epi, unwarp_ref, [("out_file", "reference_image")]),
(atlas_msk, fixed_masks, [("out_mask", "in3")]),
(fixed_masks, syn, [("out", "moving_image_masks")]),
(epi_dilmsk, epi_umask, [("out_file", "in1")]),
(epi_dilmsk, amask2epi, [("out_file", "reference_image")]),
(anat_dilmsk, amask2epi, [("out_file", "input_image")]),
(amask2epi, epi_umask, [("output_image", "in2")]),
(epi_umask, moving_masks, [("out_file", "in1")]),
(prior_dilmsk, moving_masks, [("out_file", "in2")]),
(prior2epi, moving_masks, [("output_image", "in3")]),
(moving_masks, syn, [("out", "fixed_image_masks")]),
(deoblique, syn, [("epi_ref", "fixed_image")]),
(syn, extract_field, [("reverse_transforms", "in_file")]),
(syn, unwarp_ref, [("reverse_transforms", "transforms")]),
(unwarp_ref, zooms_bmask, [("output_image", "reference_image")]),
(unwarp_ref, zooms_field, [("output_image", "reference_image")]),
(extract_field, zooms_field, [("out", "input_image")]),
(unwarp_ref, reoblique, [("output_image", "in_plumb")]),
(zooms_field, reoblique, [("output_image", "in_field")]),
(zooms_bmask, reoblique, [("output_image", "in_mask")]),
(reoblique, bs_filter, [("out_field", "in_data"),
("out_mask", "in_mask")]),
(reoblique, outputnode, [("out_epi", "fmap_ref"),
("out_mask", "fmap_mask")]),
(bs_filter, outputnode, [
("out_extrapolated" if not debug else "out_field", "fmap"),
("out_coeff", "fmap_coeff")]),
])
# fmt: on
return workflow
def init_syn_preprocessing_wf(
*,
debug=False,
name="syn_preprocessing_wf",
omp_nthreads=1,
auto_bold_nss=False,
t1w_inversion=False,
):
"""
Prepare EPI references and co-registration to anatomical for SyN.
Workflow Graph
.. workflow ::
:graph2use: orig
:simple_form: yes
from sdcflows.workflows.fit.syn import init_syn_sdc_wf
wf = init_syn_sdc_wf(omp_nthreads=8)
Parameters
----------
debug : :obj:`bool`
Whether a fast (less accurate) configuration of the workflow should be applied.
name : :obj:`str`
Name for this workflow
omp_nthreads : :obj:`int`
Parallelize internal tasks across the number of CPUs given by this option.
auto_bold_nss : :obj:`bool`
Set up the reference workflow to automatically execute nonsteady states detection
of BOLD images.
t1w_inversion : :obj:`bool`
Run T1w intensity inversion so that it looks more like a T2 contrast.
Inputs
------
in_epis : :obj:`list` of :obj:`str`
Distorted EPI images that will be merged together to create the
EPI reference file.
t_masks : :obj:`list` of :obj:`bool`
(optional) mask of timepoints for calculating an EPI reference.
Not used if ``auto_bold_nss=True``.
in_meta : :obj:`list` of :obj:`dict`
Metadata dictionaries corresponding to the ``in_epis`` input.
in_anat : :obj:`str`
A preprocessed anatomical (T1w or T2w) image.
mask_anat : :obj:`str`
A brainmask corresponding to the anatomical (T1w or T2w) image.
std2anat_xfm : :obj:`str`
inverse registration transform of T1w image to MNI template.
Outputs
-------
epi_ref : :obj:`tuple` (:obj:`str`, :obj:`dict`)
A tuple, where the first element is the path of the distorted EPI
reference map (e.g., an average of *b=0* volumes), and the second
element is a dictionary of associated metadata.
anat_ref : :obj:`str`
Path to the anatomical, skull-stripped reference in EPI space.
anat_mask : :obj:`str`
Path to the brain mask corresponding to ``anat_ref`` in EPI space.
sd_prior : :obj:`str`
A template map of areas with strong susceptibility distortions (SD) to regularize
the cost function of SyN.
"""
from pkg_resources import resource_filename as pkgrf
from niworkflows.interfaces.nibabel import (
IntensityClip,
ApplyMask,
GenerateSamplingReference,
)
from niworkflows.interfaces.fixes import (
FixHeaderApplyTransforms as ApplyTransforms,
FixHeaderRegistration as Registration,
)
from niworkflows.workflows.epi.refmap import init_epi_reference_wf
from ...interfaces.utils import Deoblique, DenoiseImage
from ...interfaces.brainmask import BrainExtraction, BinaryDilation
workflow = Workflow(name=name)
inputnode = pe.Node(
niu.IdentityInterface(
fields=[
"in_epis",
"t_masks",
"in_meta",
"in_anat",
"mask_anat",
"std2anat_xfm",
]
),
name="inputnode",
)
outputnode = pe.Node(
niu.IdentityInterface(
fields=["epi_ref", "epi_mask", "anat_ref", "anat_mask", "sd_prior"]
),
name="outputnode",
)
deob_epi = pe.Node(Deoblique(), name="deob_epi")
# Mapping & preparing prior knowledge
# Concatenate transform files:
# 1) MNI -> anat; 2) ATLAS -> MNI
transform_list = pe.Node(
niu.Merge(3),
name="transform_list",
mem_gb=DEFAULT_MEMORY_MIN_GB,
run_without_submitting=True,
)
transform_list.inputs.in3 = pkgrf(
"sdcflows", "data/fmap_atlas_2_MNI152NLin2009cAsym_affine.mat"
)
prior2epi = pe.Node(
ApplyTransforms(
invert_transform_flags=[True, False, False],
input_image=pkgrf("sdcflows", "data/fmap_atlas.nii.gz"),
),
name="prior2epi",
n_procs=omp_nthreads,
mem_gb=0.3,
)
anat2epi = pe.Node(
ApplyTransforms(invert_transform_flags=[True]),
name="anat2epi",
n_procs=omp_nthreads,
mem_gb=0.3,
)
mask2epi = pe.Node(
ApplyTransforms(invert_transform_flags=[True], interpolation="MultiLabel"),
name="mask2epi",
n_procs=omp_nthreads,
mem_gb=0.3,
)
mask_dtype = pe.Node(
niu.Function(function=_set_dtype, input_names=["in_file", "dtype"]),
name="mask_dtype",
)
mask_dtype.inputs.dtype = "uint8"
epi_reference_wf = init_epi_reference_wf(
omp_nthreads=omp_nthreads,
auto_bold_nss=auto_bold_nss,
)
epi_brain = pe.Node(BrainExtraction(), name="epi_brain")
merge_output = pe.Node(
niu.Function(function=_merge_meta),
name="merge_output",
run_without_submitting=True,
)
mask_anat = pe.Node(ApplyMask(), name="mask_anat")
clip_anat = pe.Node(
IntensityClip(p_min=0.0, p_max=99.8, invert=t1w_inversion), name="clip_anat"
)
ref_anat = pe.Node(DenoiseImage(copy_header=True), name="ref_anat",
n_procs=omp_nthreads)
epi2anat = pe.Node(
Registration(from_file=resource_filename("sdcflows", "data/affine.json")),
name="epi2anat",
n_procs=omp_nthreads,
)
epi2anat.inputs.output_warped_image = debug
epi2anat.inputs.output_inverse_warped_image = debug
if debug:
epi2anat.inputs.args = "--write-interval-volumes 5"
clip_anat_final = pe.Node(
IntensityClip(p_min=0.0, p_max=100), name="clip_anat_final"
)
anat_dilmsk = pe.Node(BinaryDilation(), name="anat_dilmsk")
epi_dilmsk = pe.Node(BinaryDilation(), name="epi_dilmsk")
sampling_ref = pe.Node(GenerateSamplingReference(), name="sampling_ref")
# fmt:off
workflow.connect([
(inputnode, transform_list, [("std2anat_xfm", "in2")]),
(inputnode, epi_reference_wf, [("in_epis", "inputnode.in_files")]),
(inputnode, merge_output, [("in_meta", "meta_list")]),
(inputnode, anat_dilmsk, [("mask_anat", "in_file")]),
(inputnode, mask_anat, [("in_anat", "in_file"),
("mask_anat", "in_mask")]),
(inputnode, mask2epi, [("mask_anat", "input_image")]),
(epi_reference_wf, merge_output, [("outputnode.epi_ref_file", "epi_ref")]),
(epi_reference_wf, deob_epi, [("outputnode.epi_ref_file", "in_file")]),
(mask_anat, clip_anat, [("out_file", "in_file")]),
(deob_epi, epi_brain, [("out_file", "in_file")]),
(epi_brain, epi_dilmsk, [("out_mask", "in_file")]),
(ref_anat, epi2anat, [("output_image", "fixed_image")]),
(anat_dilmsk, epi2anat, [("out_file", "fixed_image_masks")]),
(deob_epi, epi2anat, [("out_file", "moving_image")]),
(epi_dilmsk, epi2anat, [("out_file", "moving_image_masks")]),
(deob_epi, sampling_ref, [("out_file", "fixed_image")]),
(epi2anat, transform_list, [("forward_transforms", "in1")]),
(transform_list, prior2epi, [("out", "transforms")]),
(sampling_ref, prior2epi, [("out_file", "reference_image")]),
(epi2anat, anat2epi, [("forward_transforms", "transforms")]),
(sampling_ref, anat2epi, [("out_file", "reference_image")]),
(ref_anat, anat2epi, [("output_image", "input_image")]),
(epi2anat, mask2epi, [("forward_transforms", "transforms")]),
(sampling_ref, mask2epi, [("out_file", "reference_image")]),
(mask2epi, mask_dtype, [("output_image", "in_file")]),
(anat2epi, clip_anat_final, [("output_image", "in_file")]),
(merge_output, outputnode, [("out", "epi_ref")]),
(epi_brain, outputnode, [("out_mask", "epi_mask")]),
(clip_anat_final, outputnode, [("out_file", "anat_ref")]),
(mask_dtype, outputnode, [("out", "anat_mask")]),
(prior2epi, outputnode, [("output_image", "sd_prior")]),
])
# fmt:on
if t1w_inversion:
# Mask out non-brain zeros.
mask_inverted = pe.Node(ApplyMask(), name="mask_inverted")
# fmt:off
workflow.connect([
(inputnode, mask_inverted, [("mask_anat", "in_mask")]),
(clip_anat, mask_inverted, [("out_file", "in_file")]),
(mask_inverted, ref_anat, [("out_file", "input_image")]),
])
# fmt:on
else:
# fmt:off
workflow.connect([
(clip_anat, ref_anat, [("out_file", "input_image")]),
])
# fmt:on
if debug:
from niworkflows.interfaces.nibabel import RegridToZooms
regrid_anat = pe.Node(
RegridToZooms(zooms=(2.0, 2.0, 2.0), smooth=True), name="regrid_anat"
)
# fmt:off
workflow.connect([
(inputnode, regrid_anat, [("in_anat", "in_file")]),
(regrid_anat, sampling_ref, [("out_file", "moving_image")]),
])
# fmt:on
else:
# fmt:off
workflow.connect([
(inputnode, sampling_ref, [("in_anat", "moving_image")]),
])
# fmt:on
if not auto_bold_nss:
workflow.connect(inputnode, "t_masks", epi_reference_wf, "inputnode.t_masks")
return workflow
def _warp_dir(intuple, nlevels=3):
"""
Extract the ``restrict_deformation`` argument from metadata.
Example
-------
>>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "i-"}))
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
>>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "j-"}), nlevels=2)
[[0, 1, 0], [0, 1, 0]]
"""
pe = intuple[1]["PhaseEncodingDirection"][0]
return nlevels * [[int(pe == ax) for ax in "ijk"]]
def _extract_field(in_file, epi_meta):
"""
Extract the nonzero component of the deformation field estimated by ANTs.
Examples
--------
>>> nii = nb.load(
... _extract_field(
... ["field.nii.gz"],
... ("epi.nii.gz", {"PhaseEncodingDirection": "j-", "TotalReadoutTime": 0.005}))
... )
>>> nii.shape
(10, 10, 10)
>>> np.allclose(nii.get_fdata(), -200)
True
"""
from pathlib import Path
from nipype.utils.filemanip import fname_presuffix
import numpy as np
import nibabel as nb
from sdcflows.utils.epimanip import get_trt
fieldnii = nb.load(in_file[0])
trt = get_trt(epi_meta[1], in_file=epi_meta[0])
data = (
np.squeeze(fieldnii.get_fdata(dtype="float32"))[
..., "ijk".index(epi_meta[1]["PhaseEncodingDirection"][0])
]
/ trt
* (-1.0 if epi_meta[1]["PhaseEncodingDirection"].endswith("-") else 1.0)
)
out_file = Path(fname_presuffix(Path(in_file[0]).name, suffix="_fieldmap"))
nii = nb.Nifti1Image(data, fieldnii.affine, None)
nii.header.set_xyzt_units(fieldnii.header.get_xyzt_units()[0])
nii.to_filename(out_file)
return str(out_file.absolute())
def _merge_meta(epi_ref, meta_list):
"""Prepare a tuple of EPI reference and metadata."""
return (epi_ref, meta_list[0])
def _set_dtype(in_file, dtype="int16"):
"""Change the dtype of an image."""
import numpy as np
import nibabel as nb
img = nb.load(in_file)
if img.header.get_data_dtype() == np.dtype(dtype):
return in_file
from nipype.utils.filemanip import fname_presuffix
out_file = fname_presuffix(in_file, suffix=f"_{dtype}")
hdr = img.header.copy()
hdr.set_data_dtype(dtype)
img.__class__(img.dataobj, img.affine, hdr).to_filename(out_file)
return out_file
def _adjust_zooms(in_anat, in_epi, z_max=2.2, z_min=1.8):
import nibabel as nb
anat_res = min(nb.load(in_anat).header.get_zooms()[:3])
epi_res = min(nb.load(in_epi).header.get_zooms()[:3])
zoom_iso = min(
round(max(0.5 * (anat_res + epi_res), z_min), 2),
z_max,
)
return tuple([zoom_iso] * 3)
| # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Estimating the susceptibility distortions without fieldmaps.
.. testsetup::
>>> tmpdir = getfixture('tmpdir')
>>> tmp = tmpdir.chdir() # changing to a temporary directory
>>> data = np.zeros((10, 10, 10, 1, 3))
>>> data[..., 1] = 1
>>> nb.Nifti1Image(data, None, None).to_filename(
... tmpdir.join('field.nii.gz').strpath)
.. _sdc_fieldmapless :
Fieldmap-less approaches
~~~~~~~~~~~~~~~~~~~~~~~~
Many studies acquired (especially with legacy MRI protocols) do not have any
information to estimate susceptibility-derived distortions.
In the absence of data with the specific purpose of estimating the :math:`B_0`
inhomogeneity map, researchers resort to nonlinear registration to an
«*anatomically correct*» map of the same individual (normally acquired with
:abbr:`T1w (T1-weighted)`, or :abbr:`T2w (T2-weighted)` sequences).
One of the most prominent proposals of this approach is found in [Studholme2000]_.
*SDCFlows* includes an (experimental) procedure (see :py:func:`init_syn_sdc_wf` below),
based on nonlinear image registration with ANTs' symmetric normalization (SyN) technique.
This workflow takes a skull-stripped :abbr:`T1w (T1-weighted)` image and
a reference :abbr:`EPI (Echo-Planar Imaging)` image, and estimates a field of nonlinear
displacements that accounts for susceptibility-derived distortions.
To more accurately estimate the warping on typically distorted regions, this
implementation uses an average :math:`B_0` mapping described in [Treiber2016]_.
The implementation is a variation on those developed in [Huntenburg2014]_ and
[Wang2017]_.
Feedback will be enthusiastically received.
References
----------
.. [Studholme2000] Studholme et al. (2000) Accurate alignment of functional EPI data to
anatomical MRI using a physics-based distortion model,
IEEE Trans Med Imag 19(11):1115-1127, 2000, doi: `10.1109/42.896788
<https://doi.org/10.1109/42.896788>`__.
.. [Treiber2016] Treiber, J. M. et al. (2016) Characterization and Correction
of Geometric Distortions in 814 Diffusion Weighted Images,
PLoS ONE 11(3): e0152472. doi:`10.1371/journal.pone.0152472
<https://doi.org/10.1371/journal.pone.0152472>`_.
.. [Wang2017] Wang S, et al. (2017) Evaluation of Field Map and Nonlinear
Registration Methods for Correction of Susceptibility Artifacts
in Diffusion MRI. Front. Neuroinform. 11:17.
doi:`10.3389/fninf.2017.00017
<https://doi.org/10.3389/fninf.2017.00017>`_.
.. [Huntenburg2014] Huntenburg, J. M. (2014) `Evaluating Nonlinear
Coregistration of BOLD EPI and T1w Images
<http://pubman.mpdl.mpg.de/pubman/item/escidoc:2327525:5/component/escidoc:2327523/master_thesis_huntenburg_4686947.pdf>`__,
Berlin: Master Thesis, Freie Universität.
"""
from pkg_resources import resource_filename
from nipype.pipeline import engine as pe
from nipype.interfaces import utility as niu
from niworkflows.engine.workflows import LiterateWorkflow as Workflow
DEFAULT_MEMORY_MIN_GB = 0.01
INPUT_FIELDS = (
"epi_ref",
"epi_mask",
"anat_ref",
"anat_mask",
"sd_prior",
)
def init_syn_sdc_wf(
*,
atlas_threshold=3,
debug=False,
name="syn_sdc_wf",
omp_nthreads=1,
):
"""
Build the *fieldmap-less* susceptibility-distortion estimation workflow.
SyN deformation is restricted to the phase-encoding (PE) direction.
If no PE direction is specified, anterior-posterior PE is assumed.
SyN deformation is also restricted to regions that are expected to have a
>3mm (approximately 1 voxel) warp, based on the fieldmap atlas.
Workflow Graph
.. workflow ::
:graph2use: orig
:simple_form: yes
from sdcflows.workflows.fit.syn import init_syn_sdc_wf
wf = init_syn_sdc_wf(omp_nthreads=8)
Parameters
----------
atlas_threshold : :obj:`float`
Exclude from the registration metric computation areas with average distortions
below this threshold (in mm).
debug : :obj:`bool`
Whether a fast (less accurate) configuration of the workflow should be applied.
name : :obj:`str`
Name for this workflow
omp_nthreads : :obj:`int`
Parallelize internal tasks across the number of CPUs given by this option.
Inputs
------
epi_ref : :obj:`tuple` (:obj:`str`, :obj:`dict`)
A tuple, where the first element is the path of the distorted EPI
reference map (e.g., an average of *b=0* volumes), and the second
element is a dictionary of associated metadata.
epi_mask : :obj:`str`
A path to a brain mask corresponding to ``epi_ref``.
anat_ref : :obj:`str`
A preprocessed, skull-stripped anatomical (T1w or T2w) image resampled in EPI space.
anat_mask : :obj:`str`
Path to the brain mask corresponding to ``anat_ref`` in EPI space.
sd_prior : :obj:`str`
A template map of areas with strong susceptibility distortions (SD) to regularize
the cost function of SyN
Outputs
-------
fmap : :obj:`str`
The path of the estimated fieldmap.
fmap_ref : :obj:`str`
The path of an unwarped conversion of files in ``epi_ref``.
fmap_coeff : :obj:`str` or :obj:`list` of :obj:`str`
The path(s) of the B-Spline coefficients supporting the fieldmap.
"""
from pkg_resources import resource_filename as pkgrf
from packaging.version import parse as parseversion, Version
from niworkflows.interfaces.fixes import (
FixHeaderApplyTransforms as ApplyTransforms,
FixHeaderRegistration as Registration,
)
from niworkflows.interfaces.header import CopyXForm
from niworkflows.interfaces.nibabel import Binarize, RegridToZooms
from ...utils.misc import front as _pop
from ...interfaces.utils import Reoblique
from ...interfaces.bspline import (
BSplineApprox,
DEFAULT_LF_ZOOMS_MM,
DEFAULT_HF_ZOOMS_MM,
DEFAULT_ZOOMS_MM,
)
from ...interfaces.brainmask import BinaryDilation, Union
ants_version = Registration().version
if ants_version and parseversion(ants_version) < Version("2.2.0"):
raise RuntimeError(
f"Please upgrade ANTs to 2.2 or older ({ants_version} found)."
)
workflow = Workflow(name=name)
workflow.__desc__ = f"""\
A deformation field to correct for susceptibility distortions was estimated
based on *fMRIPrep*'s *fieldmap-less* approach.
The deformation field is that resulting from co-registering the EPI reference
to the same-subject T1w-reference with its intensity inverted [@fieldmapless1;
@fieldmapless2].
Registration is performed with `antsRegistration`
(ANTs {ants_version or "-- version unknown"}), and
the process regularized by constraining deformation to be nonzero only
along the phase-encoding direction, and modulated with an average fieldmap
template [@fieldmapless3].
"""
inputnode = pe.Node(niu.IdentityInterface(INPUT_FIELDS), name="inputnode")
outputnode = pe.Node(
niu.IdentityInterface(["fmap", "fmap_ref", "fmap_coeff", "fmap_mask"]),
name="outputnode",
)
warp_dir = pe.Node(
niu.Function(function=_warp_dir),
run_without_submitting=True,
name="warp_dir",
)
atlas_msk = pe.Node(Binarize(thresh_low=atlas_threshold), name="atlas_msk")
anat_dilmsk = pe.Node(BinaryDilation(), name="anat_dilmsk")
epi_dilmsk = pe.Node(BinaryDilation(), name="epi_dilmsk")
amask2epi = pe.Node(
ApplyTransforms(interpolation="MultiLabel", transforms="identity"),
name="amask2epi",
)
prior2epi = pe.Node(
ApplyTransforms(interpolation="MultiLabel", transforms="identity"),
name="prior2epi",
)
prior_dilmsk = pe.Node(BinaryDilation(radius=4), name="prior_dilmsk")
epi_umask = pe.Node(Union(), name="epi_umask")
moving_masks = pe.Node(
niu.Merge(3),
name="moving_masks",
run_without_submitting=True,
)
fixed_masks = pe.Node(
niu.Merge(3),
name="fixed_masks",
mem_gb=DEFAULT_MEMORY_MIN_GB,
run_without_submitting=True,
)
deoblique = pe.Node(CopyXForm(fields=["epi_ref"]), name="deoblique")
reoblique = pe.Node(Reoblique(), name="reoblique")
# Set a manageable size for the epi reference
find_zooms = pe.Node(niu.Function(function=_adjust_zooms), name="find_zooms")
zooms_epi = pe.Node(RegridToZooms(), name="zooms_epi")
# SyN Registration Core
syn = pe.Node(
Registration(
from_file=pkgrf("sdcflows", f"data/sd_syn{'_debug' * debug}.json")
),
name="syn",
n_procs=omp_nthreads,
)
syn.inputs.output_warped_image = debug
syn.inputs.output_inverse_warped_image = debug
if debug:
syn.inputs.args = "--write-interval-volumes 5"
unwarp_ref = pe.Node(
ApplyTransforms(interpolation="BSpline"),
name="unwarp_ref",
)
# Extract nonzero component
extract_field = pe.Node(niu.Function(function=_extract_field), name="extract_field")
# Check zooms (avoid very expensive B-Splines fitting)
zooms_field = pe.Node(
ApplyTransforms(interpolation="BSpline", transforms="identity"),
name="zooms_field",
)
zooms_bmask = pe.Node(
ApplyTransforms(interpolation="MultiLabel", transforms="identity"),
name="zooms_bmask",
)
# Regularize with B-Splines
bs_filter = pe.Node(BSplineApprox(), n_procs=omp_nthreads, name="bs_filter")
bs_filter.interface._always_run = debug
bs_filter.inputs.bs_spacing = (
[DEFAULT_LF_ZOOMS_MM, DEFAULT_HF_ZOOMS_MM] if not debug else [DEFAULT_ZOOMS_MM]
)
bs_filter.inputs.extrapolate = not debug
# fmt: off
workflow.connect([
(inputnode, extract_field, [("epi_ref", "epi_meta")]),
(inputnode, atlas_msk, [("sd_prior", "in_file")]),
(inputnode, deoblique, [(("epi_ref", _pop), "epi_ref"),
("epi_mask", "hdr_file")]),
(inputnode, reoblique, [(("epi_ref", _pop), "in_epi")]),
(inputnode, epi_dilmsk, [("epi_mask", "in_file")]),
(inputnode, zooms_bmask, [("anat_mask", "input_image")]),
(inputnode, fixed_masks, [("anat_mask", "in2")]),
(inputnode, anat_dilmsk, [("anat_mask", "in_file")]),
(inputnode, warp_dir, [("epi_ref", "intuple")]),
(inputnode, syn, [("anat_ref", "moving_image")]),
(epi_dilmsk, prior2epi, [("out_file", "reference_image")]),
(atlas_msk, prior2epi, [("out_file", "input_image")]),
(prior2epi, prior_dilmsk, [("output_image", "in_file")]),
(anat_dilmsk, fixed_masks, [("out_file", "in1")]),
(warp_dir, syn, [("out", "restrict_deformation")]),
(inputnode, find_zooms, [("anat_ref", "in_anat"),
(("epi_ref", _pop), "in_epi")]),
(deoblique, zooms_epi, [("epi_ref", "in_file")]),
(deoblique, unwarp_ref, [("epi_ref", "input_image")]),
(find_zooms, zooms_epi, [("out", "zooms")]),
(zooms_epi, unwarp_ref, [("out_file", "reference_image")]),
(atlas_msk, fixed_masks, [("out_mask", "in3")]),
(fixed_masks, syn, [("out", "moving_image_masks")]),
(epi_dilmsk, epi_umask, [("out_file", "in1")]),
(epi_dilmsk, amask2epi, [("out_file", "reference_image")]),
(anat_dilmsk, amask2epi, [("out_file", "input_image")]),
(amask2epi, epi_umask, [("output_image", "in2")]),
(epi_umask, moving_masks, [("out_file", "in1")]),
(prior_dilmsk, moving_masks, [("out_file", "in2")]),
(prior2epi, moving_masks, [("output_image", "in3")]),
(moving_masks, syn, [("out", "fixed_image_masks")]),
(deoblique, syn, [("epi_ref", "fixed_image")]),
(syn, extract_field, [("reverse_transforms", "in_file")]),
(syn, unwarp_ref, [("reverse_transforms", "transforms")]),
(unwarp_ref, zooms_bmask, [("output_image", "reference_image")]),
(unwarp_ref, zooms_field, [("output_image", "reference_image")]),
(extract_field, zooms_field, [("out", "input_image")]),
(unwarp_ref, reoblique, [("output_image", "in_plumb")]),
(zooms_field, reoblique, [("output_image", "in_field")]),
(zooms_bmask, reoblique, [("output_image", "in_mask")]),
(reoblique, bs_filter, [("out_field", "in_data"),
("out_mask", "in_mask")]),
(reoblique, outputnode, [("out_epi", "fmap_ref"),
("out_mask", "fmap_mask")]),
(bs_filter, outputnode, [
("out_extrapolated" if not debug else "out_field", "fmap"),
("out_coeff", "fmap_coeff")]),
])
# fmt: on
return workflow
def init_syn_preprocessing_wf(
*,
debug=False,
name="syn_preprocessing_wf",
omp_nthreads=1,
auto_bold_nss=False,
t1w_inversion=False,
):
"""
Prepare EPI references and co-registration to anatomical for SyN.
Workflow Graph
.. workflow ::
:graph2use: orig
:simple_form: yes
from sdcflows.workflows.fit.syn import init_syn_sdc_wf
wf = init_syn_sdc_wf(omp_nthreads=8)
Parameters
----------
debug : :obj:`bool`
Whether a fast (less accurate) configuration of the workflow should be applied.
name : :obj:`str`
Name for this workflow
omp_nthreads : :obj:`int`
Parallelize internal tasks across the number of CPUs given by this option.
auto_bold_nss : :obj:`bool`
Set up the reference workflow to automatically execute nonsteady states detection
of BOLD images.
t1w_inversion : :obj:`bool`
Run T1w intensity inversion so that it looks more like a T2 contrast.
Inputs
------
in_epis : :obj:`list` of :obj:`str`
Distorted EPI images that will be merged together to create the
EPI reference file.
t_masks : :obj:`list` of :obj:`bool`
(optional) mask of timepoints for calculating an EPI reference.
Not used if ``auto_bold_nss=True``.
in_meta : :obj:`list` of :obj:`dict`
Metadata dictionaries corresponding to the ``in_epis`` input.
in_anat : :obj:`str`
A preprocessed anatomical (T1w or T2w) image.
mask_anat : :obj:`str`
A brainmask corresponding to the anatomical (T1w or T2w) image.
std2anat_xfm : :obj:`str`
inverse registration transform of T1w image to MNI template.
Outputs
-------
epi_ref : :obj:`tuple` (:obj:`str`, :obj:`dict`)
A tuple, where the first element is the path of the distorted EPI
reference map (e.g., an average of *b=0* volumes), and the second
element is a dictionary of associated metadata.
anat_ref : :obj:`str`
Path to the anatomical, skull-stripped reference in EPI space.
anat_mask : :obj:`str`
Path to the brain mask corresponding to ``anat_ref`` in EPI space.
sd_prior : :obj:`str`
A template map of areas with strong susceptibility distortions (SD) to regularize
the cost function of SyN.
"""
from pkg_resources import resource_filename as pkgrf
from niworkflows.interfaces.nibabel import (
IntensityClip,
ApplyMask,
GenerateSamplingReference,
)
from niworkflows.interfaces.fixes import (
FixHeaderApplyTransforms as ApplyTransforms,
FixHeaderRegistration as Registration,
)
from niworkflows.workflows.epi.refmap import init_epi_reference_wf
from ...interfaces.utils import Deoblique, DenoiseImage
from ...interfaces.brainmask import BrainExtraction, BinaryDilation
workflow = Workflow(name=name)
inputnode = pe.Node(
niu.IdentityInterface(
fields=[
"in_epis",
"t_masks",
"in_meta",
"in_anat",
"mask_anat",
"std2anat_xfm",
]
),
name="inputnode",
)
outputnode = pe.Node(
niu.IdentityInterface(
fields=["epi_ref", "epi_mask", "anat_ref", "anat_mask", "sd_prior"]
),
name="outputnode",
)
deob_epi = pe.Node(Deoblique(), name="deob_epi")
# Mapping & preparing prior knowledge
# Concatenate transform files:
# 1) MNI -> anat; 2) ATLAS -> MNI
transform_list = pe.Node(
niu.Merge(3),
name="transform_list",
mem_gb=DEFAULT_MEMORY_MIN_GB,
run_without_submitting=True,
)
transform_list.inputs.in3 = pkgrf(
"sdcflows", "data/fmap_atlas_2_MNI152NLin2009cAsym_affine.mat"
)
prior2epi = pe.Node(
ApplyTransforms(
invert_transform_flags=[True, False, False],
input_image=pkgrf("sdcflows", "data/fmap_atlas.nii.gz"),
),
name="prior2epi",
n_procs=omp_nthreads,
mem_gb=0.3,
)
anat2epi = pe.Node(
ApplyTransforms(invert_transform_flags=[True]),
name="anat2epi",
n_procs=omp_nthreads,
mem_gb=0.3,
)
mask2epi = pe.Node(
ApplyTransforms(invert_transform_flags=[True], interpolation="MultiLabel"),
name="mask2epi",
n_procs=omp_nthreads,
mem_gb=0.3,
)
mask_dtype = pe.Node(
niu.Function(function=_set_dtype, input_names=["in_file", "dtype"]),
name="mask_dtype",
)
mask_dtype.inputs.dtype = "uint8"
epi_reference_wf = init_epi_reference_wf(
omp_nthreads=omp_nthreads,
auto_bold_nss=auto_bold_nss,
)
epi_brain = pe.Node(BrainExtraction(), name="epi_brain")
merge_output = pe.Node(
niu.Function(function=_merge_meta),
name="merge_output",
run_without_submitting=True,
)
mask_anat = pe.Node(ApplyMask(), name="mask_anat")
clip_anat = pe.Node(
IntensityClip(p_min=0.0, p_max=99.8, invert=t1w_inversion), name="clip_anat"
)
ref_anat = pe.Node(DenoiseImage(copy_header=True), name="ref_anat",
n_procs=omp_nthreads)
epi2anat = pe.Node(
Registration(from_file=resource_filename("sdcflows", "data/affine.json")),
name="epi2anat",
n_procs=omp_nthreads,
)
epi2anat.inputs.output_warped_image = debug
epi2anat.inputs.output_inverse_warped_image = debug
if debug:
epi2anat.inputs.args = "--write-interval-volumes 5"
clip_anat_final = pe.Node(
IntensityClip(p_min=0.0, p_max=100), name="clip_anat_final"
)
anat_dilmsk = pe.Node(BinaryDilation(), name="anat_dilmsk")
epi_dilmsk = pe.Node(BinaryDilation(), name="epi_dilmsk")
sampling_ref = pe.Node(GenerateSamplingReference(), name="sampling_ref")
# fmt:off
workflow.connect([
(inputnode, transform_list, [("std2anat_xfm", "in2")]),
(inputnode, epi_reference_wf, [("in_epis", "inputnode.in_files")]),
(inputnode, merge_output, [("in_meta", "meta_list")]),
(inputnode, anat_dilmsk, [("mask_anat", "in_file")]),
(inputnode, mask_anat, [("in_anat", "in_file"),
("mask_anat", "in_mask")]),
(inputnode, mask2epi, [("mask_anat", "input_image")]),
(epi_reference_wf, merge_output, [("outputnode.epi_ref_file", "epi_ref")]),
(epi_reference_wf, deob_epi, [("outputnode.epi_ref_file", "in_file")]),
(mask_anat, clip_anat, [("out_file", "in_file")]),
(deob_epi, epi_brain, [("out_file", "in_file")]),
(epi_brain, epi_dilmsk, [("out_mask", "in_file")]),
(ref_anat, epi2anat, [("output_image", "fixed_image")]),
(anat_dilmsk, epi2anat, [("out_file", "fixed_image_masks")]),
(deob_epi, epi2anat, [("out_file", "moving_image")]),
(epi_dilmsk, epi2anat, [("out_file", "moving_image_masks")]),
(deob_epi, sampling_ref, [("out_file", "fixed_image")]),
(epi2anat, transform_list, [("forward_transforms", "in1")]),
(transform_list, prior2epi, [("out", "transforms")]),
(sampling_ref, prior2epi, [("out_file", "reference_image")]),
(epi2anat, anat2epi, [("forward_transforms", "transforms")]),
(sampling_ref, anat2epi, [("out_file", "reference_image")]),
(ref_anat, anat2epi, [("output_image", "input_image")]),
(epi2anat, mask2epi, [("forward_transforms", "transforms")]),
(sampling_ref, mask2epi, [("out_file", "reference_image")]),
(mask2epi, mask_dtype, [("output_image", "in_file")]),
(anat2epi, clip_anat_final, [("output_image", "in_file")]),
(merge_output, outputnode, [("out", "epi_ref")]),
(epi_brain, outputnode, [("out_mask", "epi_mask")]),
(clip_anat_final, outputnode, [("out_file", "anat_ref")]),
(mask_dtype, outputnode, [("out", "anat_mask")]),
(prior2epi, outputnode, [("output_image", "sd_prior")]),
])
# fmt:on
if t1w_inversion:
# Mask out non-brain zeros.
mask_inverted = pe.Node(ApplyMask(), name="mask_inverted")
# fmt:off
workflow.connect([
(inputnode, mask_inverted, [("mask_anat", "in_mask")]),
(clip_anat, mask_inverted, [("out_file", "in_file")]),
(mask_inverted, ref_anat, [("out_file", "input_image")]),
])
# fmt:on
else:
# fmt:off
workflow.connect([
(clip_anat, ref_anat, [("out_file", "input_image")]),
])
# fmt:on
if debug:
from niworkflows.interfaces.nibabel import RegridToZooms
regrid_anat = pe.Node(
RegridToZooms(zooms=(2.0, 2.0, 2.0), smooth=True), name="regrid_anat"
)
# fmt:off
workflow.connect([
(inputnode, regrid_anat, [("in_anat", "in_file")]),
(regrid_anat, sampling_ref, [("out_file", "moving_image")]),
])
# fmt:on
else:
# fmt:off
workflow.connect([
(inputnode, sampling_ref, [("in_anat", "moving_image")]),
])
# fmt:on
if not auto_bold_nss:
workflow.connect(inputnode, "t_masks", epi_reference_wf, "inputnode.t_masks")
return workflow
def _warp_dir(intuple, nlevels=3):
"""
Extract the ``restrict_deformation`` argument from metadata.
Example
-------
>>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "i-"}))
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
>>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "j-"}), nlevels=2)
[[0, 1, 0], [0, 1, 0]]
"""
pe = intuple[1]["PhaseEncodingDirection"][0]
return nlevels * [[int(pe == ax) for ax in "ijk"]]
def _extract_field(in_file, epi_meta):
"""
Extract the nonzero component of the deformation field estimated by ANTs.
Examples
--------
>>> nii = nb.load(
... _extract_field(
... ["field.nii.gz"],
... ("epi.nii.gz", {"PhaseEncodingDirection": "j-", "TotalReadoutTime": 0.005}))
... )
>>> nii.shape
(10, 10, 10)
>>> np.allclose(nii.get_fdata(), -200)
True
"""
from pathlib import Path
from nipype.utils.filemanip import fname_presuffix
import numpy as np
import nibabel as nb
from sdcflows.utils.epimanip import get_trt
fieldnii = nb.load(in_file[0])
trt = get_trt(epi_meta[1], in_file=epi_meta[0])
data = (
np.squeeze(fieldnii.get_fdata(dtype="float32"))[
..., "ijk".index(epi_meta[1]["PhaseEncodingDirection"][0])
]
/ trt
* (-1.0 if epi_meta[1]["PhaseEncodingDirection"].endswith("-") else 1.0)
)
out_file = Path(fname_presuffix(Path(in_file[0]).name, suffix="_fieldmap"))
nii = nb.Nifti1Image(data, fieldnii.affine, None)
nii.header.set_xyzt_units(fieldnii.header.get_xyzt_units()[0])
nii.to_filename(out_file)
return str(out_file.absolute())
def _merge_meta(epi_ref, meta_list):
"""Prepare a tuple of EPI reference and metadata."""
return (epi_ref, meta_list[0])
def _set_dtype(in_file, dtype="int16"):
"""Change the dtype of an image."""
import numpy as np
import nibabel as nb
img = nb.load(in_file)
if img.header.get_data_dtype() == np.dtype(dtype):
return in_file
from nipype.utils.filemanip import fname_presuffix
out_file = fname_presuffix(in_file, suffix=f"_{dtype}")
hdr = img.header.copy()
hdr.set_data_dtype(dtype)
img.__class__(img.dataobj, img.affine, hdr).to_filename(out_file)
return out_file
def _adjust_zooms(in_anat, in_epi, z_max=2.2, z_min=1.8):
import nibabel as nb
anat_res = min(nb.load(in_anat).header.get_zooms()[:3])
epi_res = min(nb.load(in_epi).header.get_zooms()[:3])
zoom_iso = min(
round(max(0.5 * (anat_res + epi_res), z_min), 2),
z_max,
)
return tuple([zoom_iso] * 3)
|
# -*- coding: utf-8 -*-
from __future__ import print_function
import nose
from numpy.testing.decorators import slow
from datetime import datetime
from numpy import nan
from pandas import date_range,bdate_range, Timestamp
from pandas.core.index import Index, MultiIndex, Int64Index
from pandas.core.api import Categorical, DataFrame
from pandas.core.groupby import (SpecificationError, DataError,
_nargsort, _lexsort_indexer)
from pandas.core.series import Series
from pandas.core.config import option_context
from pandas.util.testing import (assert_panel_equal, assert_frame_equal,
assert_series_equal, assert_almost_equal,
assert_index_equal, assertRaisesRegexp)
from pandas.compat import(
range, long, lrange, StringIO, lmap, lzip, map,
zip, builtins, OrderedDict, product as cart_product
)
from pandas import compat
from pandas.core.panel import Panel
from pandas.tools.merge import concat
from collections import defaultdict
from functools import partial
import pandas.core.common as com
import numpy as np
import pandas.core.nanops as nanops
import pandas.util.testing as tm
import pandas as pd
from numpy.testing import assert_equal
def commonSetUp(self):
self.dateRange = bdate_range('1/1/2005', periods=250)
self.stringIndex = Index([rands(8).upper() for x in range(250)])
self.groupId = Series([x[0] for x in self.stringIndex],
index=self.stringIndex)
self.groupDict = dict((k, v) for k, v in compat.iteritems(self.groupId))
self.columnIndex = Index(['A', 'B', 'C', 'D', 'E'])
randMat = np.random.randn(250, 5)
self.stringMatrix = DataFrame(randMat, columns=self.columnIndex,
index=self.stringIndex)
self.timeMatrix = DataFrame(randMat, columns=self.columnIndex,
index=self.dateRange)
class TestGroupBy(tm.TestCase):
_multiprocess_can_split_ = True
def setUp(self):
self.ts = tm.makeTimeSeries()
self.seriesd = tm.getSeriesData()
self.tsd = tm.getTimeSeriesData()
self.frame = DataFrame(self.seriesd)
self.tsframe = DataFrame(self.tsd)
self.df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8)})
self.df_mixed_floats = DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.array(np.random.randn(8),
dtype='float32')})
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
['one', 'two', 'three']],
labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
[0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
names=['first', 'second'])
self.mframe = DataFrame(np.random.randn(10, 3), index=index,
columns=['A', 'B', 'C'])
self.three_group = DataFrame({'A': ['foo', 'foo', 'foo', 'foo',
'bar', 'bar', 'bar', 'bar',
'foo', 'foo', 'foo'],
'B': ['one', 'one', 'one', 'two',
'one', 'one', 'one', 'two',
'two', 'two', 'one'],
'C': ['dull', 'dull', 'shiny', 'dull',
'dull', 'shiny', 'shiny', 'dull',
'shiny', 'shiny', 'shiny'],
'D': np.random.randn(11),
'E': np.random.randn(11),
'F': np.random.randn(11)})
def test_basic(self):
def checkit(dtype):
data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype)
index = np.arange(9)
np.random.shuffle(index)
data = data.reindex(index)
grouped = data.groupby(lambda x: x // 3)
for k, v in grouped:
self.assertEqual(len(v), 3)
agged = grouped.aggregate(np.mean)
self.assertEqual(agged[1], 1)
assert_series_equal(agged, grouped.agg(np.mean)) # shorthand
assert_series_equal(agged, grouped.mean())
assert_series_equal(grouped.agg(np.sum), grouped.sum())
expected = grouped.apply(lambda x: x * x.sum())
transformed = grouped.transform(lambda x: x * x.sum())
self.assertEqual(transformed[7], 12)
assert_series_equal(transformed, expected)
value_grouped = data.groupby(data)
assert_series_equal(value_grouped.aggregate(np.mean), agged)
# complex agg
agged = grouped.aggregate([np.mean, np.std])
agged = grouped.aggregate({'one': np.mean,
'two': np.std})
group_constants = {
0: 10,
1: 20,
2: 30
}
agged = grouped.agg(lambda x: group_constants[x.name] + x.mean())
self.assertEqual(agged[1], 21)
# corner cases
self.assertRaises(Exception, grouped.aggregate, lambda x: x * 2)
for dtype in ['int64', 'int32', 'float64', 'float32']:
checkit(dtype)
def test_select_bad_cols(self):
df = DataFrame([[1, 2]], columns=['A', 'B'])
g = df.groupby('A')
self.assertRaises(KeyError, g.__getitem__, ['C']) # g[['C']]
self.assertRaises(KeyError, g.__getitem__, ['A', 'C']) # g[['A', 'C']]
with assertRaisesRegexp(KeyError, '^[^A]+$'):
# A should not be referenced as a bad column...
# will have to rethink regex if you change message!
g[['A', 'C']]
def test_first_last_nth(self):
# tests for first / last / nth
grouped = self.df.groupby('A')
first = grouped.first()
expected = self.df.ix[[1, 0], ['B','C','D']]
expected.index = Index(['bar', 'foo'],name='A')
expected = expected.sort_index()
assert_frame_equal(first, expected)
nth = grouped.nth(0)
assert_frame_equal(nth, expected)
last = grouped.last()
expected = self.df.ix[[5, 7], ['B','C','D']]
expected.index = Index(['bar', 'foo'],name='A')
assert_frame_equal(last, expected)
nth = grouped.nth(-1)
assert_frame_equal(nth, expected)
nth = grouped.nth(1)
expected = self.df.ix[[2, 3],['B','C','D']].copy()
expected.index = Index(['foo', 'bar'],name='A')
expected = expected.sort_index()
assert_frame_equal(nth, expected)
# it works!
grouped['B'].first()
grouped['B'].last()
grouped['B'].nth(0)
self.df.loc[self.df['A'] == 'foo', 'B'] = np.nan
self.assertTrue(com.isnull(grouped['B'].first()['foo']))
self.assertTrue(com.isnull(grouped['B'].last()['foo']))
self.assertTrue(com.isnull(grouped['B'].nth(0)[0])) # not sure what this is testing
# v0.14.0 whatsnew
df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
g = df.groupby('A')
result = g.first()
expected = df.iloc[[1,2]].set_index('A')
assert_frame_equal(result, expected)
expected = df.iloc[[1,2]].set_index('A')
result = g.nth(0,dropna='any')
assert_frame_equal(result, expected)
def test_first_last_nth_dtypes(self):
df = self.df_mixed_floats.copy()
df['E'] = True
df['F'] = 1
# tests for first / last / nth
grouped = df.groupby('A')
first = grouped.first()
expected = df.ix[[1, 0], ['B', 'C', 'D', 'E', 'F']]
expected.index = Index(['bar', 'foo'], name='A')
expected = expected.sort_index()
assert_frame_equal(first, expected)
last = grouped.last()
expected = df.ix[[5, 7], ['B', 'C', 'D', 'E', 'F']]
expected.index = Index(['bar', 'foo'], name='A')
expected = expected.sort_index()
assert_frame_equal(last, expected)
nth = grouped.nth(1)
expected = df.ix[[3, 2],['B', 'C', 'D', 'E', 'F']]
expected.index = Index(['bar', 'foo'], name='A')
expected = expected.sort_index()
assert_frame_equal(nth, expected)
# GH 2763, first/last shifting dtypes
idx = lrange(10)
idx.append(9)
s = Series(data=lrange(11), index=idx, name='IntCol')
self.assertEqual(s.dtype, 'int64')
f = s.groupby(level=0).first()
self.assertEqual(f.dtype, 'int64')
def test_nth(self):
df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
g = df.groupby('A')
assert_frame_equal(g.nth(0), df.iloc[[0, 2]].set_index('A'))
assert_frame_equal(g.nth(1), df.iloc[[1]].set_index('A'))
assert_frame_equal(g.nth(2), df.loc[[],['B']])
assert_frame_equal(g.nth(-1), df.iloc[[1, 2]].set_index('A'))
assert_frame_equal(g.nth(-2), df.iloc[[0]].set_index('A'))
assert_frame_equal(g.nth(-3), df.loc[[],['B']])
assert_series_equal(g.B.nth(0), df.B.iloc[[0, 2]])
assert_series_equal(g.B.nth(1), df.B.iloc[[1]])
assert_frame_equal(g[['B']].nth(0), df.ix[[0, 2], ['A', 'B']].set_index('A'))
exp = df.set_index('A')
assert_frame_equal(g.nth(0, dropna='any'), exp.iloc[[1, 2]])
assert_frame_equal(g.nth(-1, dropna='any'), exp.iloc[[1, 2]])
exp['B'] = np.nan
assert_frame_equal(g.nth(7, dropna='any'), exp.iloc[[1, 2]])
assert_frame_equal(g.nth(2, dropna='any'), exp.iloc[[1, 2]])
# out of bounds, regression from 0.13.1
# GH 6621
df = DataFrame({'color': {0: 'green', 1: 'green', 2: 'red', 3: 'red', 4: 'red'},
'food': {0: 'ham', 1: 'eggs', 2: 'eggs', 3: 'ham', 4: 'pork'},
'two': {0: 1.5456590000000001, 1: -0.070345000000000005, 2: -2.4004539999999999, 3: 0.46206000000000003, 4: 0.52350799999999997},
'one': {0: 0.56573799999999996, 1: -0.9742360000000001, 2: 1.033801, 3: -0.78543499999999999, 4: 0.70422799999999997}}).set_index(['color', 'food'])
result = df.groupby(level=0).nth(2)
expected = df.iloc[[-1]]
assert_frame_equal(result,expected)
result = df.groupby(level=0).nth(3)
expected = df.loc[[]]
assert_frame_equal(result,expected)
# GH 7559
# from the vbench
df = DataFrame(np.random.randint(1, 10, (100, 2)),dtype='int64')
s = df[1]
g = df[0]
expected = s.groupby(g).first()
expected2 = s.groupby(g).apply(lambda x: x.iloc[0])
assert_series_equal(expected2,expected)
# validate first
v = s[g==1].iloc[0]
self.assertEqual(expected.iloc[0],v)
self.assertEqual(expected2.iloc[0],v)
# this is NOT the same as .first (as sorted is default!)
# as it keeps the order in the series (and not the group order)
# related GH 7287
expected = s.groupby(g,sort=False).first()
expected.index = range(1,10)
result = s.groupby(g).nth(0,dropna='all')
assert_series_equal(result,expected)
# doc example
df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
g = df.groupby('A')
result = g.B.nth(0, dropna=True)
expected = g.B.first()
assert_series_equal(result,expected)
# test multiple nth values
df = DataFrame([[1, np.nan], [1, 3], [1, 4], [5, 6], [5, 7]],
columns=['A', 'B'])
g = df.groupby('A')
assert_frame_equal(g.nth(0), df.iloc[[0, 3]].set_index('A'))
assert_frame_equal(g.nth([0]), df.iloc[[0, 3]].set_index('A'))
assert_frame_equal(g.nth([0, 1]), df.iloc[[0, 1, 3, 4]].set_index('A'))
assert_frame_equal(g.nth([0, -1]), df.iloc[[0, 2, 3, 4]].set_index('A'))
assert_frame_equal(g.nth([0, 1, 2]), df.iloc[[0, 1, 2, 3, 4]].set_index('A'))
assert_frame_equal(g.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]].set_index('A'))
assert_frame_equal(g.nth([2]), df.iloc[[2]].set_index('A'))
assert_frame_equal(g.nth([3, 4]), df.loc[[],['B']])
business_dates = pd.date_range(start='4/1/2014', end='6/30/2014', freq='B')
df = DataFrame(1, index=business_dates, columns=['a', 'b'])
# get the first, fourth and last two business days for each month
result = df.groupby((df.index.year, df.index.month)).nth([0, 3, -2, -1])
expected_dates = pd.to_datetime(['2014/4/1', '2014/4/4', '2014/4/29', '2014/4/30',
'2014/5/1', '2014/5/6', '2014/5/29', '2014/5/30',
'2014/6/2', '2014/6/5', '2014/6/27', '2014/6/30'])
expected = DataFrame(1, columns=['a', 'b'], index=expected_dates)
assert_frame_equal(result, expected)
def test_nth_multi_index(self):
# PR 9090, related to issue 8979
# test nth on MultiIndex, should match .first()
grouped = self.three_group.groupby(['A', 'B'])
result = grouped.nth(0)
expected = grouped.first()
assert_frame_equal(result, expected)
def test_nth_multi_index_as_expected(self):
# PR 9090, related to issue 8979
# test nth on MultiIndex
three_group = DataFrame({'A': ['foo', 'foo', 'foo', 'foo',
'bar', 'bar', 'bar', 'bar',
'foo', 'foo', 'foo'],
'B': ['one', 'one', 'one', 'two',
'one', 'one', 'one', 'two',
'two', 'two', 'one'],
'C': ['dull', 'dull', 'shiny', 'dull',
'dull', 'shiny', 'shiny', 'dull',
'shiny', 'shiny', 'shiny']})
grouped = three_group.groupby(['A', 'B'])
result = grouped.nth(0)
expected = DataFrame({'C': ['dull', 'dull', 'dull', 'dull']},
index=MultiIndex.from_arrays([['bar', 'bar', 'foo', 'foo'], ['one', 'two', 'one', 'two']],
names=['A', 'B']))
assert_frame_equal(result, expected)
def test_grouper_index_types(self):
# related GH5375
# groupby misbehaving when using a Floatlike index
df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))
for index in [ tm.makeFloatIndex, tm.makeStringIndex,
tm.makeUnicodeIndex, tm.makeIntIndex,
tm.makeDateIndex, tm.makePeriodIndex ]:
df.index = index(len(df))
df.groupby(list('abcde')).apply(lambda x: x)
df.index = list(reversed(df.index.tolist()))
df.groupby(list('abcde')).apply(lambda x: x)
def test_grouper_multilevel_freq(self):
# GH 7885
# with level and freq specified in a pd.Grouper
from datetime import date, timedelta
d0 = date.today() - timedelta(days=14)
dates = date_range(d0, date.today())
date_index = pd.MultiIndex.from_product([dates, dates], names=['foo', 'bar'])
df = pd.DataFrame(np.random.randint(0, 100, 225), index=date_index)
# Check string level
expected = df.reset_index().groupby([pd.Grouper(key='foo', freq='W'),
pd.Grouper(key='bar', freq='W')]).sum()
result = df.groupby([pd.Grouper(level='foo', freq='W'),
pd.Grouper(level='bar', freq='W')]).sum()
assert_frame_equal(result, expected)
# Check integer level
result = df.groupby([pd.Grouper(level=0, freq='W'),
pd.Grouper(level=1, freq='W')]).sum()
assert_frame_equal(result, expected)
def test_grouper_creation_bug(self):
# GH 8795
df = DataFrame({'A':[0,0,1,1,2,2], 'B':[1,2,3,4,5,6]})
g = df.groupby('A')
expected = g.sum()
g = df.groupby(pd.Grouper(key='A'))
result = g.sum()
assert_frame_equal(result, expected)
result = g.apply(lambda x: x.sum())
assert_frame_equal(result, expected)
g = df.groupby(pd.Grouper(key='A',axis=0))
result = g.sum()
assert_frame_equal(result, expected)
# GH8866
s = Series(np.arange(8,dtype='int64'),
index=pd.MultiIndex.from_product([list('ab'),
range(2),
date_range('20130101',periods=2)],
names=['one','two','three']))
result = s.groupby(pd.Grouper(level='three',freq='M')).sum()
expected = Series([28],index=Index([Timestamp('2013-01-31')],freq='M',name='three'))
assert_series_equal(result, expected)
# just specifying a level breaks
result = s.groupby(pd.Grouper(level='one')).sum()
expected = s.groupby(level='one').sum()
assert_series_equal(result, expected)
def test_grouper_iter(self):
self.assertEqual(sorted(self.df.groupby('A').grouper), ['bar', 'foo'])
def test_empty_groups(self):
# GH # 1048
self.assertRaises(ValueError, self.df.groupby, [])
def test_groupby_grouper(self):
grouped = self.df.groupby('A')
result = self.df.groupby(grouped.grouper).mean()
expected = grouped.mean()
assert_frame_equal(result, expected)
def test_groupby_duplicated_column_errormsg(self):
# GH7511
df = DataFrame(columns=['A','B','A','C'], \
data=[range(4), range(2,6), range(0, 8, 2)])
self.assertRaises(ValueError, df.groupby, 'A')
self.assertRaises(ValueError, df.groupby, ['A', 'B'])
grouped = df.groupby('B')
c = grouped.count()
self.assertTrue(c.columns.nlevels == 1)
self.assertTrue(c.columns.size == 3)
def test_groupby_dict_mapping(self):
# GH #679
from pandas import Series
s = Series({'T1': 5})
result = s.groupby({'T1': 'T2'}).agg(sum)
expected = s.groupby(['T2']).agg(sum)
assert_series_equal(result, expected)
s = Series([1., 2., 3., 4.], index=list('abcd'))
mapping = {'a': 0, 'b': 0, 'c': 1, 'd': 1}
result = s.groupby(mapping).mean()
result2 = s.groupby(mapping).agg(np.mean)
expected = s.groupby([0, 0, 1, 1]).mean()
expected2 = s.groupby([0, 0, 1, 1]).mean()
assert_series_equal(result, expected)
assert_series_equal(result, result2)
assert_series_equal(result, expected2)
def test_groupby_bounds_check(self):
import pandas as pd
# groupby_X is code-generated, so if one variant
# does, the rest probably do to
a = np.array([1,2],dtype='object')
b = np.array([1,2,3],dtype='object')
self.assertRaises(AssertionError, pd.algos.groupby_object,a, b)
def test_groupby_grouper_f_sanity_checked(self):
import pandas as pd
dates = date_range('01-Jan-2013', periods=12, freq='MS')
ts = pd.TimeSeries(np.random.randn(12), index=dates)
# GH3035
# index.map is used to apply grouper to the index
# if it fails on the elements, map tries it on the entire index as
# a sequence. That can yield invalid results that cause trouble
# down the line.
# the surprise comes from using key[0:6] rather then str(key)[0:6]
# when the elements are Timestamp.
# the result is Index[0:6], very confusing.
self.assertRaises(AssertionError, ts.groupby,lambda key: key[0:6])
def test_groupby_nonobject_dtype(self):
key = self.mframe.index.labels[0]
grouped = self.mframe.groupby(key)
result = grouped.sum()
expected = self.mframe.groupby(key.astype('O')).sum()
assert_frame_equal(result, expected)
# GH 3911, mixed frame non-conversion
df = self.df_mixed_floats.copy()
df['value'] = lrange(len(df))
def max_value(group):
return group.ix[group['value'].idxmax()]
applied = df.groupby('A').apply(max_value)
result = applied.get_dtype_counts()
result.sort()
expected = Series({ 'object' : 2, 'float64' : 2, 'int64' : 1 })
expected.sort()
assert_series_equal(result,expected)
def test_groupby_return_type(self):
# GH2893, return a reduced type
df1 = DataFrame([{"val1": 1, "val2" : 20}, {"val1":1, "val2": 19},
{"val1":2, "val2": 27}, {"val1":2, "val2": 12}])
def func(dataf):
return dataf["val2"] - dataf["val2"].mean()
result = df1.groupby("val1", squeeze=True).apply(func)
tm.assert_isinstance(result,Series)
df2 = DataFrame([{"val1": 1, "val2" : 20}, {"val1":1, "val2": 19},
{"val1":1, "val2": 27}, {"val1":1, "val2": 12}])
def func(dataf):
return dataf["val2"] - dataf["val2"].mean()
result = df2.groupby("val1", squeeze=True).apply(func)
tm.assert_isinstance(result,Series)
# GH3596, return a consistent type (regression in 0.11 from 0.10.1)
df = DataFrame([[1,1],[1,1]],columns=['X','Y'])
result = df.groupby('X',squeeze=False).count()
tm.assert_isinstance(result,DataFrame)
# GH5592
# inconcistent return type
df = DataFrame(dict(A = [ 'Tiger', 'Tiger', 'Tiger', 'Lamb', 'Lamb', 'Pony', 'Pony' ],
B = Series(np.arange(7),dtype='int64'),
C = date_range('20130101',periods=7)))
def f(grp):
return grp.iloc[0]
expected = df.groupby('A').first()[['B']]
result = df.groupby('A').apply(f)[['B']]
assert_frame_equal(result,expected)
def f(grp):
if grp.name == 'Tiger':
return None
return grp.iloc[0]
result = df.groupby('A').apply(f)[['B']]
e = expected.copy()
e.loc['Tiger'] = np.nan
assert_frame_equal(result,e)
def f(grp):
if grp.name == 'Pony':
return None
return grp.iloc[0]
result = df.groupby('A').apply(f)[['B']]
e = expected.copy()
e.loc['Pony'] = np.nan
assert_frame_equal(result,e)
# 5592 revisited, with datetimes
def f(grp):
if grp.name == 'Pony':
return None
return grp.iloc[0]
result = df.groupby('A').apply(f)[['C']]
e = df.groupby('A').first()[['C']]
e.loc['Pony'] = np.nan
assert_frame_equal(result,e)
# scalar outputs
def f(grp):
if grp.name == 'Pony':
return None
return grp.iloc[0].loc['C']
result = df.groupby('A').apply(f)
e = df.groupby('A').first()['C'].copy()
e.loc['Pony'] = np.nan
e.name = None
assert_series_equal(result,e)
def test_agg_api(self):
# GH 6337
# http://stackoverflow.com/questions/21706030/pandas-groupby-agg-function-column-dtype-error
# different api for agg when passed custom function with mixed frame
df = DataFrame({'data1':np.random.randn(5),
'data2':np.random.randn(5),
'key1':['a','a','b','b','a'],
'key2':['one','two','one','two','one']})
grouped = df.groupby('key1')
def peak_to_peak(arr):
return arr.max() - arr.min()
expected = grouped.agg([peak_to_peak])
expected.columns=['data1','data2']
result = grouped.agg(peak_to_peak)
assert_frame_equal(result,expected)
def test_agg_regression1(self):
grouped = self.tsframe.groupby([lambda x: x.year, lambda x: x.month])
result = grouped.agg(np.mean)
expected = grouped.mean()
assert_frame_equal(result, expected)
def test_agg_datetimes_mixed(self):
data = [[1, '2012-01-01', 1.0],
[2, '2012-01-02', 2.0],
[3, None, 3.0]]
df1 = DataFrame({'key': [x[0] for x in data],
'date': [x[1] for x in data],
'value': [x[2] for x in data]})
data = [[row[0], datetime.strptime(row[1], '%Y-%m-%d').date()
if row[1] else None, row[2]] for row in data]
df2 = DataFrame({'key': [x[0] for x in data],
'date': [x[1] for x in data],
'value': [x[2] for x in data]})
df1['weights'] = df1['value'] / df1['value'].sum()
gb1 = df1.groupby('date').aggregate(np.sum)
df2['weights'] = df1['value'] / df1['value'].sum()
gb2 = df2.groupby('date').aggregate(np.sum)
assert(len(gb1) == len(gb2))
def test_agg_period_index(self):
from pandas import period_range, PeriodIndex
prng = period_range('2012-1-1', freq='M', periods=3)
df = DataFrame(np.random.randn(3, 2), index=prng)
rs = df.groupby(level=0).sum()
tm.assert_isinstance(rs.index, PeriodIndex)
# GH 3579
index = period_range(start='1999-01', periods=5, freq='M')
s1 = Series(np.random.rand(len(index)), index=index)
s2 = Series(np.random.rand(len(index)), index=index)
series = [('s1', s1), ('s2',s2)]
df = DataFrame.from_items(series)
grouped = df.groupby(df.index.month)
list(grouped)
def test_agg_must_agg(self):
grouped = self.df.groupby('A')['C']
self.assertRaises(Exception, grouped.agg, lambda x: x.describe())
self.assertRaises(Exception, grouped.agg, lambda x: x.index[:2])
def test_agg_ser_multi_key(self):
ser = self.df.C
f = lambda x: x.sum()
results = self.df.C.groupby([self.df.A, self.df.B]).aggregate(f)
expected = self.df.groupby(['A', 'B']).sum()['C']
assert_series_equal(results, expected)
def test_get_group(self):
wp = tm.makePanel()
grouped = wp.groupby(lambda x: x.month, axis='major')
gp = grouped.get_group(1)
expected = wp.reindex(major=[x for x in wp.major_axis if x.month == 1])
assert_panel_equal(gp, expected)
# GH 5267
# be datelike friendly
df = DataFrame({'DATE' : pd.to_datetime(['10-Oct-2013', '10-Oct-2013', '10-Oct-2013',
'11-Oct-2013', '11-Oct-2013', '11-Oct-2013']),
'label' : ['foo','foo','bar','foo','foo','bar'],
'VAL' : [1,2,3,4,5,6]})
g = df.groupby('DATE')
key = list(g.groups)[0]
result1 = g.get_group(key)
result2 = g.get_group(Timestamp(key).to_datetime())
result3 = g.get_group(str(Timestamp(key)))
assert_frame_equal(result1,result2)
assert_frame_equal(result1,result3)
g = df.groupby(['DATE','label'])
key = list(g.groups)[0]
result1 = g.get_group(key)
result2 = g.get_group((Timestamp(key[0]).to_datetime(),key[1]))
result3 = g.get_group((str(Timestamp(key[0])),key[1]))
assert_frame_equal(result1,result2)
assert_frame_equal(result1,result3)
# must pass a same-length tuple with multiple keys
self.assertRaises(ValueError, lambda : g.get_group('foo'))
self.assertRaises(ValueError, lambda : g.get_group(('foo')))
self.assertRaises(ValueError, lambda : g.get_group(('foo','bar','baz')))
def test_get_group_grouped_by_tuple(self):
# GH 8121
df = DataFrame([[(1,), (1, 2), (1,), (1, 2)]],
index=['ids']).T
gr = df.groupby('ids')
expected = DataFrame({'ids': [(1,), (1,)]}, index=[0, 2])
result = gr.get_group((1,))
assert_frame_equal(result, expected)
dt = pd.to_datetime(['2010-01-01', '2010-01-02', '2010-01-01',
'2010-01-02'])
df = DataFrame({'ids': [(x,) for x in dt]})
gr = df.groupby('ids')
result = gr.get_group(('2010-01-01',))
expected = DataFrame({'ids': [(dt[0],), (dt[0],)]}, index=[0, 2])
assert_frame_equal(result, expected)
def test_agg_apply_corner(self):
# nothing to group, all NA
grouped = self.ts.groupby(self.ts * np.nan)
assert_series_equal(grouped.sum(), Series([]))
assert_series_equal(grouped.agg(np.sum), Series([]))
assert_series_equal(grouped.apply(np.sum), Series([]))
# DataFrame
grouped = self.tsframe.groupby(self.tsframe['A'] * np.nan)
exp_df = DataFrame(columns=self.tsframe.columns, dtype=float)
assert_frame_equal(grouped.sum(), exp_df, check_names=False)
assert_frame_equal(grouped.agg(np.sum), exp_df, check_names=False)
assert_frame_equal(grouped.apply(np.sum), DataFrame({}, dtype=float))
def test_agg_grouping_is_list_tuple(self):
from pandas.core.groupby import Grouping
df = tm.makeTimeDataFrame()
grouped = df.groupby(lambda x: x.year)
grouper = grouped.grouper.groupings[0].grouper
grouped.grouper.groupings[0] = Grouping(self.ts.index, list(grouper))
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
grouped.grouper.groupings[0] = Grouping(self.ts.index, tuple(grouper))
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_grouping_error_on_multidim_input(self):
from pandas.core.groupby import Grouping
self.assertRaises(ValueError, \
Grouping, self.df.index, self.df[['A','A']])
def test_agg_python_multiindex(self):
grouped = self.mframe.groupby(['A', 'B'])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_apply_describe_bug(self):
grouped = self.mframe.groupby(level='first')
result = grouped.describe() # it works!
def test_apply_issues(self):
# GH 5788
s="""2011.05.16,00:00,1.40893
2011.05.16,01:00,1.40760
2011.05.16,02:00,1.40750
2011.05.16,03:00,1.40649
2011.05.17,02:00,1.40893
2011.05.17,03:00,1.40760
2011.05.17,04:00,1.40750
2011.05.17,05:00,1.40649
2011.05.18,02:00,1.40893
2011.05.18,03:00,1.40760
2011.05.18,04:00,1.40750
2011.05.18,05:00,1.40649"""
df = pd.read_csv(StringIO(s), header=None, names=['date', 'time', 'value'], parse_dates=[['date', 'time']])
df = df.set_index('date_time')
expected = df.groupby(df.index.date).idxmax()
result = df.groupby(df.index.date).apply(lambda x: x.idxmax())
assert_frame_equal(result,expected)
# GH 5789
# don't auto coerce dates
df = pd.read_csv(StringIO(s), header=None, names=['date', 'time', 'value'])
expected = Series(['00:00','02:00','02:00'],index=['2011.05.16','2011.05.17','2011.05.18'])
result = df.groupby('date').apply(lambda x: x['time'][x['value'].idxmax()])
assert_series_equal(result,expected)
def test_len(self):
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year,
lambda x: x.month,
lambda x: x.day])
self.assertEqual(len(grouped), len(df))
grouped = df.groupby([lambda x: x.year,
lambda x: x.month])
expected = len(set([(x.year, x.month) for x in df.index]))
self.assertEqual(len(grouped), expected)
def test_groups(self):
grouped = self.df.groupby(['A'])
groups = grouped.groups
self.assertIs(groups, grouped.groups) # caching works
for k, v in compat.iteritems(grouped.groups):
self.assertTrue((self.df.ix[v]['A'] == k).all())
grouped = self.df.groupby(['A', 'B'])
groups = grouped.groups
self.assertIs(groups, grouped.groups) # caching works
for k, v in compat.iteritems(grouped.groups):
self.assertTrue((self.df.ix[v]['A'] == k[0]).all())
self.assertTrue((self.df.ix[v]['B'] == k[1]).all())
def test_aggregate_str_func(self):
def _check_results(grouped):
# single series
result = grouped['A'].agg('std')
expected = grouped['A'].std()
assert_series_equal(result, expected)
# group frame by function name
result = grouped.aggregate('var')
expected = grouped.var()
assert_frame_equal(result, expected)
# group frame by function dict
result = grouped.agg(OrderedDict([['A', 'var'],
['B', 'std'],
['C', 'mean'],
['D', 'sem']]))
expected = DataFrame(OrderedDict([['A', grouped['A'].var()],
['B', grouped['B'].std()],
['C', grouped['C'].mean()],
['D', grouped['D'].sem()]]))
assert_frame_equal(result, expected)
by_weekday = self.tsframe.groupby(lambda x: x.weekday())
_check_results(by_weekday)
by_mwkday = self.tsframe.groupby([lambda x: x.month,
lambda x: x.weekday()])
_check_results(by_mwkday)
def test_aggregate_item_by_item(self):
df = self.df.copy()
df['E'] = ['a'] * len(self.df)
grouped = self.df.groupby('A')
# API change in 0.11
# def aggfun(ser):
# return len(ser + 'a')
# result = grouped.agg(aggfun)
# self.assertEqual(len(result.columns), 1)
aggfun = lambda ser: ser.size
result = grouped.agg(aggfun)
foo = (self.df.A == 'foo').sum()
bar = (self.df.A == 'bar').sum()
K = len(result.columns)
# GH5782
# odd comparisons can result here, so cast to make easy
assert_almost_equal(result.xs('foo'), np.array([foo] * K).astype('float64'))
assert_almost_equal(result.xs('bar'), np.array([bar] * K).astype('float64'))
def aggfun(ser):
return ser.size
result = DataFrame().groupby(self.df.A).agg(aggfun)
tm.assert_isinstance(result, DataFrame)
self.assertEqual(len(result), 0)
def test_agg_item_by_item_raise_typeerror(self):
from numpy.random import randint
df = DataFrame(randint(10, size=(20, 10)))
def raiseException(df):
com.pprint_thing('----------------------------------------')
com.pprint_thing(df.to_string())
raise TypeError
self.assertRaises(TypeError, df.groupby(0).agg,
raiseException)
def test_basic_regression(self):
# regression
T = [1.0 * x for x in lrange(1, 10) * 10][:1095]
result = Series(T, lrange(0, len(T)))
groupings = np.random.random((1100,))
groupings = Series(groupings, lrange(0, len(groupings))) * 10.
grouped = result.groupby(groupings)
grouped.mean()
def test_transform(self):
data = Series(np.arange(9) // 3, index=np.arange(9))
index = np.arange(9)
np.random.shuffle(index)
data = data.reindex(index)
grouped = data.groupby(lambda x: x // 3)
transformed = grouped.transform(lambda x: x * x.sum())
self.assertEqual(transformed[7], 12)
# GH 8046
# make sure that we preserve the input order
df = DataFrame(np.arange(6,dtype='int64').reshape(3,2), columns=["a","b"], index=[0,2,1])
key = [0,0,1]
expected = df.sort_index().groupby(key).transform(lambda x: x-x.mean()).groupby(key).mean()
result = df.groupby(key).transform(lambda x: x-x.mean()).groupby(key).mean()
assert_frame_equal(result, expected)
def demean(arr):
return arr - arr.mean()
people = DataFrame(np.random.randn(5, 5),
columns=['a', 'b', 'c', 'd', 'e'],
index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])
key = ['one', 'two', 'one', 'two', 'one']
result = people.groupby(key).transform(demean).groupby(key).mean()
expected = people.groupby(key).apply(demean).groupby(key).mean()
assert_frame_equal(result, expected)
# GH 8430
df = tm.makeTimeDataFrame()
g = df.groupby(pd.TimeGrouper('M'))
g.transform(lambda x: x-1)
def test_transform_fast(self):
df = DataFrame( { 'id' : np.arange( 100000 ) / 3,
'val': np.random.randn( 100000) } )
grp=df.groupby('id')['val']
values = np.repeat(grp.mean().values, com._ensure_platform_int(grp.count().values))
expected = pd.Series(values,index=df.index)
result = grp.transform(np.mean)
assert_series_equal(result,expected)
result = grp.transform('mean')
assert_series_equal(result,expected)
def test_transform_broadcast(self):
grouped = self.ts.groupby(lambda x: x.month)
result = grouped.transform(np.mean)
self.assertTrue(result.index.equals(self.ts.index))
for _, gp in grouped:
assert_fp_equal(result.reindex(gp.index), gp.mean())
grouped = self.tsframe.groupby(lambda x: x.month)
result = grouped.transform(np.mean)
self.assertTrue(result.index.equals(self.tsframe.index))
for _, gp in grouped:
agged = gp.mean()
res = result.reindex(gp.index)
for col in self.tsframe:
assert_fp_equal(res[col], agged[col])
# group columns
grouped = self.tsframe.groupby({'A': 0, 'B': 0, 'C': 1, 'D': 1},
axis=1)
result = grouped.transform(np.mean)
self.assertTrue(result.index.equals(self.tsframe.index))
self.assertTrue(result.columns.equals(self.tsframe.columns))
for _, gp in grouped:
agged = gp.mean(1)
res = result.reindex(columns=gp.columns)
for idx in gp.index:
assert_fp_equal(res.xs(idx), agged[idx])
def test_transform_bug(self):
# GH 5712
# transforming on a datetime column
df = DataFrame(dict(A = Timestamp('20130101'), B = np.arange(5)))
result = df.groupby('A')['B'].transform(lambda x: x.rank(ascending=False))
expected = Series(np.arange(5,0,step=-1),name='B')
assert_series_equal(result,expected)
def test_transform_multiple(self):
grouped = self.ts.groupby([lambda x: x.year, lambda x: x.month])
transformed = grouped.transform(lambda x: x * 2)
broadcasted = grouped.transform(np.mean)
def test_dispatch_transform(self):
df = self.tsframe[::5].reindex(self.tsframe.index)
grouped = df.groupby(lambda x: x.month)
filled = grouped.fillna(method='pad')
fillit = lambda x: x.fillna(method='pad')
expected = df.groupby(lambda x: x.month).transform(fillit)
assert_frame_equal(filled, expected)
def test_transform_select_columns(self):
f = lambda x: x.mean()
result = self.df.groupby('A')['C', 'D'].transform(f)
selection = self.df[['C', 'D']]
expected = selection.groupby(self.df['A']).transform(f)
assert_frame_equal(result, expected)
def test_transform_exclude_nuisance(self):
# this also tests orderings in transform between
# series/frame to make sure it's consistent
expected = {}
grouped = self.df.groupby('A')
expected['C'] = grouped['C'].transform(np.mean)
expected['D'] = grouped['D'].transform(np.mean)
expected = DataFrame(expected)
result = self.df.groupby('A').transform(np.mean)
assert_frame_equal(result, expected)
def test_transform_function_aliases(self):
result = self.df.groupby('A').transform('mean')
expected = self.df.groupby('A').transform(np.mean)
assert_frame_equal(result, expected)
result = self.df.groupby('A')['C'].transform('mean')
expected = self.df.groupby('A')['C'].transform(np.mean)
assert_series_equal(result, expected)
def test_with_na(self):
index = Index(np.arange(10))
for dtype in ['float64','float32','int64','int32','int16','int8']:
values = Series(np.ones(10), index, dtype=dtype)
labels = Series([nan, 'foo', 'bar', 'bar', nan, nan, 'bar',
'bar', nan, 'foo'], index=index)
# this SHOULD be an int
grouped = values.groupby(labels)
agged = grouped.agg(len)
expected = Series([4, 2], index=['bar', 'foo'])
assert_series_equal(agged, expected, check_dtype=False)
#self.assertTrue(issubclass(agged.dtype.type, np.integer))
# explicity return a float from my function
def f(x):
return float(len(x))
agged = grouped.agg(f)
expected = Series([4, 2], index=['bar', 'foo'])
assert_series_equal(agged, expected, check_dtype=False)
self.assertTrue(issubclass(agged.dtype.type, np.dtype(dtype).type))
def test_groupby_transform_with_int(self):
# GH 3740, make sure that we might upcast on item-by-item transform
# floats
df = DataFrame(dict(A = [1,1,1,2,2,2], B = Series(1,dtype='float64'), C = Series([1,2,3,1,2,3],dtype='float64'), D = 'foo'))
result = df.groupby('A').transform(lambda x: (x-x.mean())/x.std())
expected = DataFrame(dict(B = np.nan, C = Series([-1,0,1,-1,0,1],dtype='float64')))
assert_frame_equal(result,expected)
# int case
df = DataFrame(dict(A = [1,1,1,2,2,2], B = 1, C = [1,2,3,1,2,3], D = 'foo'))
result = df.groupby('A').transform(lambda x: (x-x.mean())/x.std())
expected = DataFrame(dict(B = np.nan, C = [-1,0,1,-1,0,1]))
assert_frame_equal(result,expected)
# int that needs float conversion
s = Series([2,3,4,10,5,-1])
df = DataFrame(dict(A = [1,1,1,2,2,2], B = 1, C = s, D = 'foo'))
result = df.groupby('A').transform(lambda x: (x-x.mean())/x.std())
s1 = s.iloc[0:3]
s1 = (s1-s1.mean())/s1.std()
s2 = s.iloc[3:6]
s2 = (s2-s2.mean())/s2.std()
expected = DataFrame(dict(B = np.nan, C = concat([s1,s2])))
assert_frame_equal(result,expected)
# int downcasting
result = df.groupby('A').transform(lambda x: x*2/2)
expected = DataFrame(dict(B = 1, C = [2,3,4,10,5,-1]))
assert_frame_equal(result,expected)
def test_indices_concatenation_order(self):
# GH 2808
def f1(x):
y = x[(x.b % 2) == 1]**2
if y.empty:
multiindex = MultiIndex(
levels = [[]]*2,
labels = [[]]*2,
names = ['b', 'c']
)
res = DataFrame(None,
columns=['a'],
index=multiindex)
return res
else:
y = y.set_index(['b','c'])
return y
def f2(x):
y = x[(x.b % 2) == 1]**2
if y.empty:
return DataFrame()
else:
y = y.set_index(['b','c'])
return y
def f3(x):
y = x[(x.b % 2) == 1]**2
if y.empty:
multiindex = MultiIndex(
levels = [[]]*2,
labels = [[]]*2,
names = ['foo', 'bar']
)
res = DataFrame(None,
columns=['a','b'],
index=multiindex)
return res
else:
return y
df = DataFrame({'a':[1,2,2,2],
'b':lrange(4),
'c':lrange(5,9)})
df2 = DataFrame({'a':[3,2,2,2],
'b':lrange(4),
'c':lrange(5,9)})
# correct result
result1 = df.groupby('a').apply(f1)
result2 = df2.groupby('a').apply(f1)
assert_frame_equal(result1, result2)
# should fail (not the same number of levels)
self.assertRaises(AssertionError, df.groupby('a').apply, f2)
self.assertRaises(AssertionError, df2.groupby('a').apply, f2)
# should fail (incorrect shape)
self.assertRaises(AssertionError, df.groupby('a').apply, f3)
self.assertRaises(AssertionError, df2.groupby('a').apply, f3)
def test_attr_wrapper(self):
grouped = self.ts.groupby(lambda x: x.weekday())
result = grouped.std()
expected = grouped.agg(lambda x: np.std(x, ddof=1))
assert_series_equal(result, expected)
# this is pretty cool
result = grouped.describe()
expected = {}
for name, gp in grouped:
expected[name] = gp.describe()
expected = DataFrame(expected).T
assert_frame_equal(result.unstack(), expected)
# get attribute
result = grouped.dtype
expected = grouped.agg(lambda x: x.dtype)
# make sure raises error
self.assertRaises(AttributeError, getattr, grouped, 'foo')
def test_series_describe_multikey(self):
ts = tm.makeTimeSeries()
grouped = ts.groupby([lambda x: x.year, lambda x: x.month])
result = grouped.describe().unstack()
assert_series_equal(result['mean'], grouped.mean())
assert_series_equal(result['std'], grouped.std())
assert_series_equal(result['min'], grouped.min())
def test_series_describe_single(self):
ts = tm.makeTimeSeries()
grouped = ts.groupby(lambda x: x.month)
result = grouped.apply(lambda x: x.describe())
expected = grouped.describe()
assert_series_equal(result, expected)
def test_series_agg_multikey(self):
ts = tm.makeTimeSeries()
grouped = ts.groupby([lambda x: x.year, lambda x: x.month])
result = grouped.agg(np.sum)
expected = grouped.sum()
assert_series_equal(result, expected)
def test_series_agg_multi_pure_python(self):
data = DataFrame({'A': ['foo', 'foo', 'foo', 'foo',
'bar', 'bar', 'bar', 'bar',
'foo', 'foo', 'foo'],
'B': ['one', 'one', 'one', 'two',
'one', 'one', 'one', 'two',
'two', 'two', 'one'],
'C': ['dull', 'dull', 'shiny', 'dull',
'dull', 'shiny', 'shiny', 'dull',
'shiny', 'shiny', 'shiny'],
'D': np.random.randn(11),
'E': np.random.randn(11),
'F': np.random.randn(11)})
def bad(x):
assert(len(x.base) > 0)
return 'foo'
result = data.groupby(['A', 'B']).agg(bad)
expected = data.groupby(['A', 'B']).agg(lambda x: 'foo')
assert_frame_equal(result, expected)
def test_series_index_name(self):
grouped = self.df.ix[:, ['C']].groupby(self.df['A'])
result = grouped.agg(lambda x: x.mean())
self.assertEqual(result.index.name, 'A')
def test_frame_describe_multikey(self):
grouped = self.tsframe.groupby([lambda x: x.year,
lambda x: x.month])
result = grouped.describe()
for col in self.tsframe:
expected = grouped[col].describe()
assert_series_equal(result[col], expected)
groupedT = self.tsframe.groupby({'A': 0, 'B': 0,
'C': 1, 'D': 1}, axis=1)
result = groupedT.describe()
for name, group in groupedT:
assert_frame_equal(result[name], group.describe())
def test_frame_groupby(self):
grouped = self.tsframe.groupby(lambda x: x.weekday())
# aggregate
aggregated = grouped.aggregate(np.mean)
self.assertEqual(len(aggregated), 5)
self.assertEqual(len(aggregated.columns), 4)
# by string
tscopy = self.tsframe.copy()
tscopy['weekday'] = [x.weekday() for x in tscopy.index]
stragged = tscopy.groupby('weekday').aggregate(np.mean)
assert_frame_equal(stragged, aggregated, check_names=False)
# transform
grouped = self.tsframe.head(30).groupby(lambda x: x.weekday())
transformed = grouped.transform(lambda x: x - x.mean())
self.assertEqual(len(transformed), 30)
self.assertEqual(len(transformed.columns), 4)
# transform propagate
transformed = grouped.transform(lambda x: x.mean())
for name, group in grouped:
mean = group.mean()
for idx in group.index:
assert_almost_equal(transformed.xs(idx), mean)
# iterate
for weekday, group in grouped:
self.assertEqual(group.index[0].weekday(), weekday)
# groups / group_indices
groups = grouped.groups
indices = grouped.indices
for k, v in compat.iteritems(groups):
samething = self.tsframe.index.take(indices[k])
self.assertTrue((samething == v).all())
def test_grouping_is_iterable(self):
# this code path isn't used anywhere else
# not sure it's useful
grouped = self.tsframe.groupby([lambda x: x.weekday(),
lambda x: x.year])
# test it works
for g in grouped.grouper.groupings[0]:
pass
def test_frame_groupby_columns(self):
mapping = {
'A': 0, 'B': 0, 'C': 1, 'D': 1
}
grouped = self.tsframe.groupby(mapping, axis=1)
# aggregate
aggregated = grouped.aggregate(np.mean)
self.assertEqual(len(aggregated), len(self.tsframe))
self.assertEqual(len(aggregated.columns), 2)
# transform
tf = lambda x: x - x.mean()
groupedT = self.tsframe.T.groupby(mapping, axis=0)
assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf))
# iterate
for k, v in grouped:
self.assertEqual(len(v.columns), 2)
def test_frame_set_name_single(self):
grouped = self.df.groupby('A')
result = grouped.mean()
self.assertEqual(result.index.name, 'A')
result = self.df.groupby('A', as_index=False).mean()
self.assertNotEqual(result.index.name, 'A')
result = grouped.agg(np.mean)
self.assertEqual(result.index.name, 'A')
result = grouped.agg({'C': np.mean, 'D': np.std})
self.assertEqual(result.index.name, 'A')
result = grouped['C'].mean()
self.assertEqual(result.index.name, 'A')
result = grouped['C'].agg(np.mean)
self.assertEqual(result.index.name, 'A')
result = grouped['C'].agg([np.mean, np.std])
self.assertEqual(result.index.name, 'A')
result = grouped['C'].agg({'foo': np.mean, 'bar': np.std})
self.assertEqual(result.index.name, 'A')
def test_multi_iter(self):
s = Series(np.arange(6))
k1 = np.array(['a', 'a', 'a', 'b', 'b', 'b'])
k2 = np.array(['1', '2', '1', '2', '1', '2'])
grouped = s.groupby([k1, k2])
iterated = list(grouped)
expected = [('a', '1', s[[0, 2]]),
('a', '2', s[[1]]),
('b', '1', s[[4]]),
('b', '2', s[[3, 5]])]
for i, ((one, two), three) in enumerate(iterated):
e1, e2, e3 = expected[i]
self.assertEqual(e1, one)
self.assertEqual(e2, two)
assert_series_equal(three, e3)
def test_multi_iter_frame(self):
k1 = np.array(['b', 'b', 'b', 'a', 'a', 'a'])
k2 = np.array(['1', '2', '1', '2', '1', '2'])
df = DataFrame({'v1': np.random.randn(6),
'v2': np.random.randn(6),
'k1': k1, 'k2': k2},
index=['one', 'two', 'three', 'four', 'five', 'six'])
grouped = df.groupby(['k1', 'k2'])
# things get sorted!
iterated = list(grouped)
idx = df.index
expected = [('a', '1', df.ix[idx[[4]]]),
('a', '2', df.ix[idx[[3, 5]]]),
('b', '1', df.ix[idx[[0, 2]]]),
('b', '2', df.ix[idx[[1]]])]
for i, ((one, two), three) in enumerate(iterated):
e1, e2, e3 = expected[i]
self.assertEqual(e1, one)
self.assertEqual(e2, two)
assert_frame_equal(three, e3)
# don't iterate through groups with no data
df['k1'] = np.array(['b', 'b', 'b', 'a', 'a', 'a'])
df['k2'] = np.array(['1', '1', '1', '2', '2', '2'])
grouped = df.groupby(['k1', 'k2'])
groups = {}
for key, gp in grouped:
groups[key] = gp
self.assertEqual(len(groups), 2)
# axis = 1
three_levels = self.three_group.groupby(['A', 'B', 'C']).mean()
grouped = three_levels.T.groupby(axis=1, level=(1, 2))
for key, group in grouped:
pass
def test_multi_iter_panel(self):
wp = tm.makePanel()
grouped = wp.groupby([lambda x: x.month, lambda x: x.weekday()],
axis=1)
for (month, wd), group in grouped:
exp_axis = [x for x in wp.major_axis
if x.month == month and x.weekday() == wd]
expected = wp.reindex(major=exp_axis)
assert_panel_equal(group, expected)
def test_multi_func(self):
col1 = self.df['A']
col2 = self.df['B']
grouped = self.df.groupby([col1.get, col2.get])
agged = grouped.mean()
expected = self.df.groupby(['A', 'B']).mean()
assert_frame_equal(agged.ix[:, ['C', 'D']],
expected.ix[:, ['C', 'D']],
check_names=False) # TODO groupby get drops names
# some "groups" with no data
df = DataFrame({'v1': np.random.randn(6),
'v2': np.random.randn(6),
'k1': np.array(['b', 'b', 'b', 'a', 'a', 'a']),
'k2': np.array(['1', '1', '1', '2', '2', '2'])},
index=['one', 'two', 'three', 'four', 'five', 'six'])
# only verify that it works for now
grouped = df.groupby(['k1', 'k2'])
grouped.agg(np.sum)
def test_multi_key_multiple_functions(self):
grouped = self.df.groupby(['A', 'B'])['C']
agged = grouped.agg([np.mean, np.std])
expected = DataFrame({'mean': grouped.agg(np.mean),
'std': grouped.agg(np.std)})
assert_frame_equal(agged, expected)
def test_frame_multi_key_function_list(self):
data = DataFrame({'A': ['foo', 'foo', 'foo', 'foo',
'bar', 'bar', 'bar', 'bar',
'foo', 'foo', 'foo'],
'B': ['one', 'one', 'one', 'two',
'one', 'one', 'one', 'two',
'two', 'two', 'one'],
'C': ['dull', 'dull', 'shiny', 'dull',
'dull', 'shiny', 'shiny', 'dull',
'shiny', 'shiny', 'shiny'],
'D': np.random.randn(11),
'E': np.random.randn(11),
'F': np.random.randn(11)})
grouped = data.groupby(['A', 'B'])
funcs = [np.mean, np.std]
agged = grouped.agg(funcs)
expected = concat([grouped['D'].agg(funcs), grouped['E'].agg(funcs),
grouped['F'].agg(funcs)],
keys=['D', 'E', 'F'], axis=1)
assert(isinstance(agged.index, MultiIndex))
assert(isinstance(expected.index, MultiIndex))
assert_frame_equal(agged, expected)
def test_groupby_multiple_columns(self):
data = self.df
grouped = data.groupby(['A', 'B'])
def _check_op(op):
result1 = op(grouped)
expected = defaultdict(dict)
for n1, gp1 in data.groupby('A'):
for n2, gp2 in gp1.groupby('B'):
expected[n1][n2] = op(gp2.ix[:, ['C', 'D']])
expected = dict((k, DataFrame(v)) for k, v in compat.iteritems(expected))
expected = Panel.fromDict(expected).swapaxes(0, 1)
expected.major_axis.name, expected.minor_axis.name = 'A', 'B'
# a little bit crude
for col in ['C', 'D']:
result_col = op(grouped[col])
exp = expected[col]
pivoted = result1[col].unstack()
pivoted2 = result_col.unstack()
assert_frame_equal(pivoted.reindex_like(exp), exp)
assert_frame_equal(pivoted2.reindex_like(exp), exp)
_check_op(lambda x: x.sum())
_check_op(lambda x: x.mean())
# test single series works the same
result = data['C'].groupby([data['A'], data['B']]).mean()
expected = data.groupby(['A', 'B']).mean()['C']
assert_series_equal(result, expected)
def test_groupby_as_index_agg(self):
grouped = self.df.groupby('A', as_index=False)
# single-key
result = grouped.agg(np.mean)
expected = grouped.mean()
assert_frame_equal(result, expected)
result2 = grouped.agg(OrderedDict([['C', np.mean], ['D', np.sum]]))
expected2 = grouped.mean()
expected2['D'] = grouped.sum()['D']
assert_frame_equal(result2, expected2)
grouped = self.df.groupby('A', as_index=True)
expected3 = grouped['C'].sum()
expected3 = DataFrame(expected3).rename(columns={'C': 'Q'})
result3 = grouped['C'].agg({'Q': np.sum})
assert_frame_equal(result3, expected3)
# multi-key
grouped = self.df.groupby(['A', 'B'], as_index=False)
result = grouped.agg(np.mean)
expected = grouped.mean()
assert_frame_equal(result, expected)
result2 = grouped.agg(OrderedDict([['C', np.mean], ['D', np.sum]]))
expected2 = grouped.mean()
expected2['D'] = grouped.sum()['D']
assert_frame_equal(result2, expected2)
expected3 = grouped['C'].sum()
expected3 = DataFrame(expected3).rename(columns={'C': 'Q'})
result3 = grouped['C'].agg({'Q': np.sum})
assert_frame_equal(result3, expected3)
# GH7115 & GH8112 & GH8582
df = DataFrame(np.random.randint(0, 100, (50, 3)),
columns=['jim', 'joe', 'jolie'])
ts = Series(np.random.randint(5, 10, 50), name='jim')
gr = df.groupby(ts)
_ = gr.nth(0) # invokes _set_selection_from_grouper internally
assert_frame_equal(gr.apply(sum), df.groupby(ts).apply(sum))
for attr in ['mean', 'max', 'count', 'idxmax', 'cumsum', 'all']:
gr = df.groupby(ts, as_index=False)
left = getattr(gr, attr)()
gr = df.groupby(ts.values, as_index=True)
right = getattr(gr, attr)().reset_index(drop=True)
assert_frame_equal(left, right)
def test_mulitindex_passthru(self):
# GH 7997
# regression from 0.14.1
df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
df.columns = pd.MultiIndex.from_tuples([(0,1),(1,1),(2,1)])
result = df.groupby(axis=1, level=[0,1]).first()
assert_frame_equal(result, df)
def test_multifunc_select_col_integer_cols(self):
df = self.df
df.columns = np.arange(len(df.columns))
# it works!
result = df.groupby(1, as_index=False)[2].agg({'Q': np.mean})
def test_as_index_series_return_frame(self):
grouped = self.df.groupby('A', as_index=False)
grouped2 = self.df.groupby(['A', 'B'], as_index=False)
result = grouped['C'].agg(np.sum)
expected = grouped.agg(np.sum).ix[:, ['A', 'C']]
tm.assert_isinstance(result, DataFrame)
assert_frame_equal(result, expected)
result2 = grouped2['C'].agg(np.sum)
expected2 = grouped2.agg(np.sum).ix[:, ['A', 'B', 'C']]
tm.assert_isinstance(result2, DataFrame)
assert_frame_equal(result2, expected2)
result = grouped['C'].sum()
expected = grouped.sum().ix[:, ['A', 'C']]
tm.assert_isinstance(result, DataFrame)
assert_frame_equal(result, expected)
result2 = grouped2['C'].sum()
expected2 = grouped2.sum().ix[:, ['A', 'B', 'C']]
tm.assert_isinstance(result2, DataFrame)
assert_frame_equal(result2, expected2)
# corner case
self.assertRaises(Exception, grouped['C'].__getitem__,
'D')
def test_groupby_as_index_cython(self):
data = self.df
# single-key
grouped = data.groupby('A', as_index=False)
result = grouped.mean()
expected = data.groupby(['A']).mean()
expected.insert(0, 'A', expected.index)
expected.index = np.arange(len(expected))
assert_frame_equal(result, expected)
# multi-key
grouped = data.groupby(['A', 'B'], as_index=False)
result = grouped.mean()
expected = data.groupby(['A', 'B']).mean()
arrays = lzip(*expected.index._tuple_index)
expected.insert(0, 'A', arrays[0])
expected.insert(1, 'B', arrays[1])
expected.index = np.arange(len(expected))
assert_frame_equal(result, expected)
def test_groupby_as_index_series_scalar(self):
grouped = self.df.groupby(['A', 'B'], as_index=False)
# GH #421
result = grouped['C'].agg(len)
expected = grouped.agg(len).ix[:, ['A', 'B', 'C']]
assert_frame_equal(result, expected)
def test_groupby_as_index_corner(self):
self.assertRaises(TypeError, self.ts.groupby,
lambda x: x.weekday(), as_index=False)
self.assertRaises(ValueError, self.df.groupby,
lambda x: x.lower(), as_index=False, axis=1)
def test_groupby_as_index_apply(self):
# GH #4648 and #3417
df = DataFrame({'item_id': ['b', 'b', 'a', 'c', 'a', 'b'],
'user_id': [1,2,1,1,3,1],
'time': range(6)})
g_as = df.groupby('user_id', as_index=True)
g_not_as = df.groupby('user_id', as_index=False)
res_as = g_as.head(2).index
res_not_as = g_not_as.head(2).index
exp = Index([0, 1, 2, 4])
assert_index_equal(res_as, exp)
assert_index_equal(res_not_as, exp)
res_as_apply = g_as.apply(lambda x: x.head(2)).index
res_not_as_apply = g_not_as.apply(lambda x: x.head(2)).index
# apply doesn't maintain the original ordering
# changed in GH5610 as the as_index=False returns a MI here
exp_not_as_apply = MultiIndex.from_tuples([(0, 0), (0, 2), (1, 1), (2, 4)])
exp_as_apply = MultiIndex.from_tuples([(1, 0), (1, 2), (2, 1), (3, 4)])
assert_index_equal(res_as_apply, exp_as_apply)
assert_index_equal(res_not_as_apply, exp_not_as_apply)
ind = Index(list('abcde'))
df = DataFrame([[1, 2], [2, 3], [1, 4], [1, 5], [2, 6]], index=ind)
res = df.groupby(0, as_index=False).apply(lambda x: x).index
assert_index_equal(res, ind)
def test_groupby_head_tail(self):
df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])
g_as = df.groupby('A', as_index=True)
g_not_as = df.groupby('A', as_index=False)
# as_index= False, much easier
assert_frame_equal(df.loc[[0, 2]], g_not_as.head(1))
assert_frame_equal(df.loc[[1, 2]], g_not_as.tail(1))
empty_not_as = DataFrame(columns=df.columns)
assert_frame_equal(empty_not_as, g_not_as.head(0))
assert_frame_equal(empty_not_as, g_not_as.tail(0))
assert_frame_equal(empty_not_as, g_not_as.head(-1))
assert_frame_equal(empty_not_as, g_not_as.tail(-1))
assert_frame_equal(df, g_not_as.head(7)) # contains all
assert_frame_equal(df, g_not_as.tail(7))
# as_index=True, (used to be different)
df_as = df
assert_frame_equal(df_as.loc[[0, 2]], g_as.head(1))
assert_frame_equal(df_as.loc[[1, 2]], g_as.tail(1))
empty_as = DataFrame(index=df_as.index[:0], columns=df.columns)
assert_frame_equal(empty_as, g_as.head(0))
assert_frame_equal(empty_as, g_as.tail(0))
assert_frame_equal(empty_as, g_as.head(-1))
assert_frame_equal(empty_as, g_as.tail(-1))
assert_frame_equal(df_as, g_as.head(7)) # contains all
assert_frame_equal(df_as, g_as.tail(7))
# test with selection
assert_frame_equal(g_as[[]].head(1), df_as.loc[[0,2], []])
assert_frame_equal(g_as[['A']].head(1), df_as.loc[[0,2], ['A']])
assert_frame_equal(g_as[['B']].head(1), df_as.loc[[0,2], ['B']])
assert_frame_equal(g_as[['A', 'B']].head(1), df_as.loc[[0,2]])
assert_frame_equal(g_not_as[[]].head(1), df_as.loc[[0,2], []])
assert_frame_equal(g_not_as[['A']].head(1), df_as.loc[[0,2], ['A']])
assert_frame_equal(g_not_as[['B']].head(1), df_as.loc[[0,2], ['B']])
assert_frame_equal(g_not_as[['A', 'B']].head(1), df_as.loc[[0,2]])
def test_groupby_multiple_key(self):
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year,
lambda x: x.month,
lambda x: x.day])
agged = grouped.sum()
assert_almost_equal(df.values, agged.values)
grouped = df.T.groupby([lambda x: x.year,
lambda x: x.month,
lambda x: x.day], axis=1)
agged = grouped.agg(lambda x: x.sum())
self.assertTrue(agged.index.equals(df.columns))
assert_almost_equal(df.T.values, agged.values)
agged = grouped.agg(lambda x: x.sum())
assert_almost_equal(df.T.values, agged.values)
def test_groupby_multi_corner(self):
# test that having an all-NA column doesn't mess you up
df = self.df.copy()
df['bad'] = np.nan
agged = df.groupby(['A', 'B']).mean()
expected = self.df.groupby(['A', 'B']).mean()
expected['bad'] = np.nan
assert_frame_equal(agged, expected)
def test_omit_nuisance(self):
grouped = self.df.groupby('A')
result = grouped.mean()
expected = self.df.ix[:, ['A', 'C', 'D']].groupby('A').mean()
assert_frame_equal(result, expected)
agged = grouped.agg(np.mean)
exp = grouped.mean()
assert_frame_equal(agged, exp)
df = self.df.ix[:, ['A', 'C', 'D']]
df['E'] = datetime.now()
grouped = df.groupby('A')
result = grouped.agg(np.sum)
expected = grouped.sum()
assert_frame_equal(result, expected)
# won't work with axis = 1
grouped = df.groupby({'A': 0, 'C': 0, 'D': 1, 'E': 1}, axis=1)
result = self.assertRaises(TypeError, grouped.agg,
lambda x: x.sum(0, numeric_only=False))
def test_omit_nuisance_python_multiple(self):
grouped = self.three_group.groupby(['A', 'B'])
agged = grouped.agg(np.mean)
exp = grouped.mean()
assert_frame_equal(agged, exp)
def test_empty_groups_corner(self):
# handle empty groups
df = DataFrame({'k1': np.array(['b', 'b', 'b', 'a', 'a', 'a']),
'k2': np.array(['1', '1', '1', '2', '2', '2']),
'k3': ['foo', 'bar'] * 3,
'v1': np.random.randn(6),
'v2': np.random.randn(6)})
grouped = df.groupby(['k1', 'k2'])
result = grouped.agg(np.mean)
expected = grouped.mean()
assert_frame_equal(result, expected)
grouped = self.mframe[3:5].groupby(level=0)
agged = grouped.apply(lambda x: x.mean())
agged_A = grouped['A'].apply(np.mean)
assert_series_equal(agged['A'], agged_A)
self.assertEqual(agged.index.name, 'first')
def test_apply_concat_preserve_names(self):
grouped = self.three_group.groupby(['A', 'B'])
def desc(group):
result = group.describe()
result.index.name = 'stat'
return result
def desc2(group):
result = group.describe()
result.index.name = 'stat'
result = result[:len(group)]
# weirdo
return result
def desc3(group):
result = group.describe()
# names are different
result.index.name = 'stat_%d' % len(group)
result = result[:len(group)]
# weirdo
return result
result = grouped.apply(desc)
self.assertEqual(result.index.names, ('A', 'B', 'stat'))
result2 = grouped.apply(desc2)
self.assertEqual(result2.index.names, ('A', 'B', 'stat'))
result3 = grouped.apply(desc3)
self.assertEqual(result3.index.names, ('A', 'B', None))
def test_nonsense_func(self):
df = DataFrame([0])
self.assertRaises(Exception, df.groupby, lambda x: x + 'foo')
def test_builtins_apply(self): # GH8155
df = pd.DataFrame(np.random.randint(1, 50, (1000, 2)),
columns=['jim', 'joe'])
df['jolie'] = np.random.randn(1000)
print(df.head())
for keys in ['jim', ['jim', 'joe']]: # single key & multi-key
if keys == 'jim': continue
for f in [max, min, sum]:
fname = f.__name__
result = df.groupby(keys).apply(f)
_shape = result.shape
ngroups = len(df.drop_duplicates(subset=keys))
assert result.shape == (ngroups, 3), 'invalid frame shape: '\
'{} (expected ({}, 3))'.format(result.shape, ngroups)
assert_frame_equal(result, # numpy's equivalent function
df.groupby(keys).apply(getattr(np, fname)))
if f != sum:
expected = df.groupby(keys).agg(fname).reset_index()
expected.set_index(keys, inplace=True, drop=False)
assert_frame_equal(result, expected, check_dtype=False)
assert_series_equal(getattr(result, fname)(),
getattr(df, fname)())
def test_cythonized_aggers(self):
data = {'A': [0, 0, 0, 0, 1, 1, 1, 1, 1, 1., nan, nan],
'B': ['A', 'B'] * 6,
'C': np.random.randn(12)}
df = DataFrame(data)
df.loc[2:10:2,'C'] = nan
def _testit(op):
# single column
grouped = df.drop(['B'], axis=1).groupby('A')
exp = {}
for cat, group in grouped:
exp[cat] = op(group['C'])
exp = DataFrame({'C': exp})
exp.index.name = 'A'
result = op(grouped)
assert_frame_equal(result, exp)
# multiple columns
grouped = df.groupby(['A', 'B'])
expd = {}
for (cat1, cat2), group in grouped:
expd.setdefault(cat1, {})[cat2] = op(group['C'])
exp = DataFrame(expd).T.stack(dropna=False)
result = op(grouped)['C']
assert_series_equal(result, exp)
_testit(lambda x: x.count())
_testit(lambda x: x.sum())
_testit(lambda x: x.std())
_testit(lambda x: x.var())
_testit(lambda x: x.sem())
_testit(lambda x: x.mean())
_testit(lambda x: x.median())
_testit(lambda x: x.prod())
_testit(lambda x: x.min())
_testit(lambda x: x.max())
def test_max_min_non_numeric(self):
# #2700
aa = DataFrame({'nn':[11,11,22,22],'ii':[1,2,3,4],'ss':4*['mama']})
result = aa.groupby('nn').max()
self.assertTrue('ss' in result)
result = aa.groupby('nn').min()
self.assertTrue('ss' in result)
def test_cython_agg_boolean(self):
frame = DataFrame({'a': np.random.randint(0, 5, 50),
'b': np.random.randint(0, 2, 50).astype('bool')})
result = frame.groupby('a')['b'].mean()
expected = frame.groupby('a')['b'].agg(np.mean)
assert_series_equal(result, expected)
def test_cython_agg_nothing_to_agg(self):
frame = DataFrame({'a': np.random.randint(0, 5, 50),
'b': ['foo', 'bar'] * 25})
self.assertRaises(DataError, frame.groupby('a')['b'].mean)
frame = DataFrame({'a': np.random.randint(0, 5, 50),
'b': ['foo', 'bar'] * 25})
self.assertRaises(DataError, frame[['b']].groupby(frame['a']).mean)
def test_cython_agg_nothing_to_agg_with_dates(self):
frame = DataFrame({'a': np.random.randint(0, 5, 50),
'b': ['foo', 'bar'] * 25,
'dates': pd.date_range('now', periods=50,
freq='T')})
with tm.assertRaisesRegexp(DataError, "No numeric types to aggregate"):
frame.groupby('b').dates.mean()
def test_groupby_timedelta_cython_count(self):
df = DataFrame({'g': list('ab' * 2),
'delt': np.arange(4).astype('timedelta64[ns]')})
expected = Series([2, 2], index=['a', 'b'], name='delt')
result = df.groupby('g').delt.count()
tm.assert_series_equal(expected, result)
def test_cython_agg_frame_columns(self):
# #2113
df = DataFrame({'x': [1, 2, 3], 'y': [3, 4, 5]})
result = df.groupby(level=0, axis='columns').mean()
result = df.groupby(level=0, axis='columns').mean()
result = df.groupby(level=0, axis='columns').mean()
_ = df.groupby(level=0, axis='columns').mean()
def test_wrap_aggregated_output_multindex(self):
df = self.mframe.T
df['baz', 'two'] = 'peekaboo'
keys = [np.array([0, 0, 1]), np.array([0, 0, 1])]
agged = df.groupby(keys).agg(np.mean)
tm.assert_isinstance(agged.columns, MultiIndex)
def aggfun(ser):
if ser.name == ('foo', 'one'):
raise TypeError
else:
return ser.sum()
agged2 = df.groupby(keys).aggregate(aggfun)
self.assertEqual(len(agged2.columns) + 1, len(df.columns))
def test_groupby_level(self):
frame = self.mframe
deleveled = frame.reset_index()
result0 = frame.groupby(level=0).sum()
result1 = frame.groupby(level=1).sum()
expected0 = frame.groupby(deleveled['first'].values).sum()
expected1 = frame.groupby(deleveled['second'].values).sum()
expected0 = expected0.reindex(frame.index.levels[0])
expected1 = expected1.reindex(frame.index.levels[1])
self.assertEqual(result0.index.name, 'first')
self.assertEqual(result1.index.name, 'second')
assert_frame_equal(result0, expected0)
assert_frame_equal(result1, expected1)
self.assertEqual(result0.index.name, frame.index.names[0])
self.assertEqual(result1.index.name, frame.index.names[1])
# groupby level name
result0 = frame.groupby(level='first').sum()
result1 = frame.groupby(level='second').sum()
assert_frame_equal(result0, expected0)
assert_frame_equal(result1, expected1)
# axis=1
result0 = frame.T.groupby(level=0, axis=1).sum()
result1 = frame.T.groupby(level=1, axis=1).sum()
assert_frame_equal(result0, expected0.T)
assert_frame_equal(result1, expected1.T)
# raise exception for non-MultiIndex
self.assertRaises(ValueError, self.df.groupby, level=1)
def test_groupby_level_index_names(self):
## GH4014 this used to raise ValueError since 'exp'>1 (in py2)
df = DataFrame({'exp' : ['A']*3 + ['B']*3, 'var1' : lrange(6),}).set_index('exp')
df.groupby(level='exp')
self.assertRaises(ValueError, df.groupby, level='foo')
def test_groupby_level_with_nas(self):
index = MultiIndex(levels=[[1, 0], [0, 1, 2, 3]],
labels=[[1, 1, 1, 1, 0, 0, 0, 0],
[0, 1, 2, 3, 0, 1, 2, 3]])
# factorizing doesn't confuse things
s = Series(np.arange(8.), index=index)
result = s.groupby(level=0).sum()
expected = Series([22., 6.], index=[1, 0])
assert_series_equal(result, expected)
index = MultiIndex(levels=[[1, 0], [0, 1, 2, 3]],
labels=[[1, 1, 1, 1, -1, 0, 0, 0],
[0, 1, 2, 3, 0, 1, 2, 3]])
# factorizing doesn't confuse things
s = Series(np.arange(8.), index=index)
result = s.groupby(level=0).sum()
expected = Series([18., 6.], index=[1, 0])
assert_series_equal(result, expected)
def test_groupby_level_apply(self):
frame = self.mframe
result = frame.groupby(level=0).count()
self.assertEqual(result.index.name, 'first')
result = frame.groupby(level=1).count()
self.assertEqual(result.index.name, 'second')
result = frame['A'].groupby(level=0).count()
self.assertEqual(result.index.name, 'first')
def test_groupby_args(self):
#PR8618 and issue 8015
frame = self.mframe
def j():
frame.groupby()
self.assertRaisesRegexp(TypeError, "You have to supply one of 'by' and 'level'", j)
def k():
frame.groupby(by=None, level=None)
self.assertRaisesRegexp(TypeError, "You have to supply one of 'by' and 'level'", k)
def test_groupby_level_mapper(self):
frame = self.mframe
deleveled = frame.reset_index()
mapper0 = {'foo': 0, 'bar': 0,
'baz': 1, 'qux': 1}
mapper1 = {'one': 0, 'two': 0, 'three': 1}
result0 = frame.groupby(mapper0, level=0).sum()
result1 = frame.groupby(mapper1, level=1).sum()
mapped_level0 = np.array([mapper0.get(x) for x in deleveled['first']])
mapped_level1 = np.array([mapper1.get(x) for x in deleveled['second']])
expected0 = frame.groupby(mapped_level0).sum()
expected1 = frame.groupby(mapped_level1).sum()
expected0.index.name, expected1.index.name = 'first', 'second'
assert_frame_equal(result0, expected0)
assert_frame_equal(result1, expected1)
def test_groupby_level_0_nonmulti(self):
# #1313
a = Series([1, 2, 3, 10, 4, 5, 20, 6], Index([1, 2, 3, 1,
4, 5, 2, 6], name='foo'))
result = a.groupby(level=0).sum()
self.assertEqual(result.index.name, a.index.name)
def test_level_preserve_order(self):
grouped = self.mframe.groupby(level=0)
exp_labels = np.array([0, 0, 0, 1, 1, 2, 2, 3, 3, 3])
assert_almost_equal(grouped.grouper.labels[0], exp_labels)
def test_grouping_labels(self):
grouped = self.mframe.groupby(self.mframe.index.get_level_values(0))
exp_labels = np.array([2, 2, 2, 0, 0, 1, 1, 3, 3, 3])
assert_almost_equal(grouped.grouper.labels[0], exp_labels)
def test_cython_fail_agg(self):
dr = bdate_range('1/1/2000', periods=50)
ts = Series(['A', 'B', 'C', 'D', 'E'] * 10, index=dr)
grouped = ts.groupby(lambda x: x.month)
summed = grouped.sum()
expected = grouped.agg(np.sum)
assert_series_equal(summed, expected)
def test_apply_series_to_frame(self):
def f(piece):
return DataFrame({'value': piece,
'demeaned': piece - piece.mean(),
'logged': np.log(piece)})
dr = bdate_range('1/1/2000', periods=100)
ts = Series(np.random.randn(100), index=dr)
grouped = ts.groupby(lambda x: x.month)
result = grouped.apply(f)
tm.assert_isinstance(result, DataFrame)
self.assertTrue(result.index.equals(ts.index))
def test_apply_series_yield_constant(self):
result = self.df.groupby(['A', 'B'])['C'].apply(len)
self.assertEqual(result.index.names[:2], ('A', 'B'))
def test_apply_frame_to_series(self):
grouped = self.df.groupby(['A', 'B'])
result = grouped.apply(len)
expected = grouped.count()['C']
self.assertTrue(result.index.equals(expected.index))
self.assert_numpy_array_equal(result.values, expected.values)
def test_apply_frame_concat_series(self):
def trans(group):
return group.groupby('B')['C'].sum().order()[:2]
def trans2(group):
grouped = group.groupby(df.reindex(group.index)['B'])
return grouped.sum().order()[:2]
df = DataFrame({'A': np.random.randint(0, 5, 1000),
'B': np.random.randint(0, 5, 1000),
'C': np.random.randn(1000)})
result = df.groupby('A').apply(trans)
exp = df.groupby('A')['C'].apply(trans2)
assert_series_equal(result, exp)
def test_apply_transform(self):
grouped = self.ts.groupby(lambda x: x.month)
result = grouped.apply(lambda x: x * 2)
expected = grouped.transform(lambda x: x * 2)
assert_series_equal(result, expected)
def test_apply_multikey_corner(self):
grouped = self.tsframe.groupby([lambda x: x.year,
lambda x: x.month])
def f(group):
return group.sort('A')[-5:]
result = grouped.apply(f)
for key, group in grouped:
assert_frame_equal(result.ix[key], f(group))
def test_mutate_groups(self):
# GH3380
mydf = DataFrame({
'cat1' : ['a'] * 8 + ['b'] * 6,
'cat2' : ['c'] * 2 + ['d'] * 2 + ['e'] * 2 + ['f'] * 2 + ['c'] * 2 + ['d'] * 2 + ['e'] * 2,
'cat3' : lmap(lambda x: 'g%s' % x, lrange(1,15)),
'val' : np.random.randint(100, size=14),
})
def f_copy(x):
x = x.copy()
x['rank'] = x.val.rank(method='min')
return x.groupby('cat2')['rank'].min()
def f_no_copy(x):
x['rank'] = x.val.rank(method='min')
return x.groupby('cat2')['rank'].min()
grpby_copy = mydf.groupby('cat1').apply(f_copy)
grpby_no_copy = mydf.groupby('cat1').apply(f_no_copy)
assert_series_equal(grpby_copy,grpby_no_copy)
def test_no_mutate_but_looks_like(self):
# GH 8467
# first show's mutation indicator
# second does not, but should yield the same results
df = DataFrame({'key': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'value': range(9)})
result1 = df.groupby('key', group_keys=True).apply(lambda x: x[:].key)
result2 = df.groupby('key', group_keys=True).apply(lambda x: x.key)
assert_series_equal(result1, result2)
def test_apply_chunk_view(self):
# Low level tinkering could be unsafe, make sure not
df = DataFrame({'key': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'value': lrange(9)})
# return view
f = lambda x: x[:2]
result = df.groupby('key', group_keys=False).apply(f)
expected = df.take([0, 1, 3, 4, 6, 7])
assert_frame_equal(result, expected)
def test_apply_no_name_column_conflict(self):
df = DataFrame({'name': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2],
'name2': [0, 0, 0, 1, 1, 1, 0, 0, 1, 1],
'value': lrange(10)[::-1]})
# it works! #2605
grouped = df.groupby(['name', 'name2'])
grouped.apply(lambda x: x.sort('value'))
def test_groupby_series_indexed_differently(self):
s1 = Series([5.0, -9.0, 4.0, 100., -5., 55., 6.7],
index=Index(['a', 'b', 'c', 'd', 'e', 'f', 'g']))
s2 = Series([1.0, 1.0, 4.0, 5.0, 5.0, 7.0],
index=Index(['a', 'b', 'd', 'f', 'g', 'h']))
grouped = s1.groupby(s2)
agged = grouped.mean()
exp = s1.groupby(s2.reindex(s1.index).get).mean()
assert_series_equal(agged, exp)
def test_groupby_with_hier_columns(self):
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two',
'one', 'two', 'one', 'two']]))
index = MultiIndex.from_tuples(tuples)
columns = MultiIndex.from_tuples([('A', 'cat'), ('B', 'dog'),
('B', 'cat'), ('A', 'dog')])
df = DataFrame(np.random.randn(8, 4), index=index,
columns=columns)
result = df.groupby(level=0).mean()
self.assertTrue(result.columns.equals(columns))
result = df.groupby(level=0, axis=1).mean()
self.assertTrue(result.index.equals(df.index))
result = df.groupby(level=0).agg(np.mean)
self.assertTrue(result.columns.equals(columns))
result = df.groupby(level=0).apply(lambda x: x.mean())
self.assertTrue(result.columns.equals(columns))
result = df.groupby(level=0, axis=1).agg(lambda x: x.mean(1))
self.assertTrue(result.columns.equals(Index(['A', 'B'])))
self.assertTrue(result.index.equals(df.index))
# add a nuisance column
sorted_columns, _ = columns.sortlevel(0)
df['A', 'foo'] = 'bar'
result = df.groupby(level=0).mean()
self.assertTrue(result.columns.equals(df.columns[:-1]))
def test_pass_args_kwargs(self):
from numpy import percentile
def f(x, q=None, axis=0):
return percentile(x, q, axis=axis)
g = lambda x: percentile(x, 80, axis=0)
# Series
ts_grouped = self.ts.groupby(lambda x: x.month)
agg_result = ts_grouped.agg(percentile, 80, axis=0)
apply_result = ts_grouped.apply(percentile, 80, axis=0)
trans_result = ts_grouped.transform(percentile, 80, axis=0)
agg_expected = ts_grouped.quantile(.8)
trans_expected = ts_grouped.transform(g)
assert_series_equal(apply_result, agg_expected)
assert_series_equal(agg_result, agg_expected)
assert_series_equal(trans_result, trans_expected)
agg_result = ts_grouped.agg(f, q=80)
apply_result = ts_grouped.apply(f, q=80)
trans_result = ts_grouped.transform(f, q=80)
assert_series_equal(agg_result, agg_expected)
assert_series_equal(apply_result, agg_expected)
assert_series_equal(trans_result, trans_expected)
# DataFrame
df_grouped = self.tsframe.groupby(lambda x: x.month)
agg_result = df_grouped.agg(percentile, 80, axis=0)
apply_result = df_grouped.apply(DataFrame.quantile, .8)
expected = df_grouped.quantile(.8)
assert_frame_equal(apply_result, expected)
assert_frame_equal(agg_result, expected)
agg_result = df_grouped.agg(f, q=80)
apply_result = df_grouped.apply(DataFrame.quantile, q=.8)
assert_frame_equal(agg_result, expected)
assert_frame_equal(apply_result, expected)
# def test_cython_na_bug(self):
# values = np.random.randn(10)
# shape = (5, 5)
# label_list = [np.array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2], dtype=np.int32),
# np.array([1, 2, 3, 4, 0, 1, 2, 3, 3, 4], dtype=np.int32)]
# lib.group_aggregate(values, label_list, shape)
def test_size(self):
grouped = self.df.groupby(['A', 'B'])
result = grouped.size()
for key, group in grouped:
self.assertEqual(result[key], len(group))
grouped = self.df.groupby('A')
result = grouped.size()
for key, group in grouped:
self.assertEqual(result[key], len(group))
grouped = self.df.groupby('B')
result = grouped.size()
for key, group in grouped:
self.assertEqual(result[key], len(group))
def test_count(self):
# GH5610
# count counts non-nulls
df = pd.DataFrame([[1, 2, 'foo'], [1, nan, 'bar'], [3, nan, nan]],
columns=['A', 'B', 'C'])
count_as = df.groupby('A').count()
count_not_as = df.groupby('A', as_index=False).count()
expected = DataFrame([[1, 2], [0, 0]], columns=['B', 'C'], index=[1,3])
expected.index.name='A'
assert_frame_equal(count_not_as, expected.reset_index())
assert_frame_equal(count_as, expected)
count_B = df.groupby('A')['B'].count()
assert_series_equal(count_B, expected['B'])
def test_count_object(self):
df = pd.DataFrame({'a': ['a'] * 3 + ['b'] * 3,
'c': [2] * 3 + [3] * 3})
result = df.groupby('c').a.count()
expected = pd.Series([3, 3], index=[2, 3], name='a')
tm.assert_series_equal(result, expected)
df = pd.DataFrame({'a': ['a', np.nan, np.nan] + ['b'] * 3,
'c': [2] * 3 + [3] * 3})
result = df.groupby('c').a.count()
expected = pd.Series([1, 3], index=[2, 3], name='a')
tm.assert_series_equal(result, expected)
def test_count_cross_type(self): # GH8169
vals = np.hstack((np.random.randint(0,5,(100,2)),
np.random.randint(0,2,(100,2))))
df = pd.DataFrame(vals, columns=['a', 'b', 'c', 'd'])
df[df==2] = np.nan
expected = df.groupby(['c', 'd']).count()
for t in ['float32', 'object']:
df['a'] = df['a'].astype(t)
df['b'] = df['b'].astype(t)
result = df.groupby(['c', 'd']).count()
tm.assert_frame_equal(result, expected)
def test_non_cython_api(self):
# GH5610
# non-cython calls should not include the grouper
df = DataFrame([[1, 2, 'foo'], [1, nan, 'bar',], [3, nan, 'baz']], columns=['A', 'B','C'])
g = df.groupby('A')
gni = df.groupby('A',as_index=False)
# mad
expected = DataFrame([[0],[nan]],columns=['B'],index=[1,3])
expected.index.name = 'A'
result = g.mad()
assert_frame_equal(result,expected)
expected = DataFrame([[0.,0.],[0,nan]],columns=['A','B'],index=[0,1])
result = gni.mad()
assert_frame_equal(result,expected)
# describe
expected = DataFrame(dict(B = concat([df.loc[[0,1],'B'].describe(),df.loc[[2],'B'].describe()],keys=[1,3])))
expected.index.names = ['A',None]
result = g.describe()
assert_frame_equal(result,expected)
expected = concat([df.loc[[0,1],['A','B']].describe(),df.loc[[2],['A','B']].describe()],keys=[0,1])
result = gni.describe()
assert_frame_equal(result,expected)
# any
expected = DataFrame([[True, True],[False, True]],columns=['B','C'],index=[1,3])
expected.index.name = 'A'
result = g.any()
assert_frame_equal(result,expected)
# idxmax
expected = DataFrame([[0],[nan]],columns=['B'],index=[1,3])
expected.index.name = 'A'
result = g.idxmax()
assert_frame_equal(result,expected)
def test_cython_api2(self):
# this takes the fast apply path
# cumsum (GH5614)
df = DataFrame([[1, 2, np.nan], [1, np.nan, 9], [3, 4, 9]], columns=['A', 'B', 'C'])
expected = DataFrame([[2, np.nan], [np.nan, 9], [4, 9]], columns=['B', 'C'])
result = df.groupby('A').cumsum()
assert_frame_equal(result,expected)
expected = DataFrame([[1, 2, np.nan], [2, np.nan, 9], [3, 4, 9]], columns=['A', 'B', 'C']).astype('float64')
result = df.groupby('A', as_index=False).cumsum()
assert_frame_equal(result,expected)
def test_grouping_ndarray(self):
grouped = self.df.groupby(self.df['A'].values)
result = grouped.sum()
expected = self.df.groupby('A').sum()
assert_frame_equal(result, expected, check_names=False) # Note: no names when grouping by value
def test_agg_consistency(self):
# agg with ([]) and () not consistent
# GH 6715
def P1(a):
try:
return np.percentile(a.dropna(), q=1)
except:
return np.nan
import datetime as dt
df = DataFrame({'col1':[1,2,3,4],
'col2':[10,25,26,31],
'date':[dt.date(2013,2,10),dt.date(2013,2,10),dt.date(2013,2,11),dt.date(2013,2,11)]})
g = df.groupby('date')
expected = g.agg([P1])
expected.columns = expected.columns.levels[0]
result = g.agg(P1)
assert_frame_equal(result, expected)
def test_apply_typecast_fail(self):
df = DataFrame({'d': [1., 1., 1., 2., 2., 2.],
'c': np.tile(['a', 'b', 'c'], 2),
'v': np.arange(1., 7.)})
def f(group):
v = group['v']
group['v2'] = (v - v.min()) / (v.max() - v.min())
return group
result = df.groupby('d').apply(f)
expected = df.copy()
expected['v2'] = np.tile([0., 0.5, 1], 2)
assert_frame_equal(result, expected)
def test_apply_multiindex_fail(self):
index = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1],
[1, 2, 3, 1, 2, 3]])
df = DataFrame({'d': [1., 1., 1., 2., 2., 2.],
'c': np.tile(['a', 'b', 'c'], 2),
'v': np.arange(1., 7.)}, index=index)
def f(group):
v = group['v']
group['v2'] = (v - v.min()) / (v.max() - v.min())
return group
result = df.groupby('d').apply(f)
expected = df.copy()
expected['v2'] = np.tile([0., 0.5, 1], 2)
assert_frame_equal(result, expected)
def test_apply_corner(self):
result = self.tsframe.groupby(lambda x: x.year).apply(lambda x: x * 2)
expected = self.tsframe * 2
assert_frame_equal(result, expected)
def test_apply_without_copy(self):
# GH 5545
# returning a non-copy in an applied function fails
data = DataFrame({'id_field' : [100, 100, 200, 300], 'category' : ['a','b','c','c'], 'value' : [1,2,3,4]})
def filt1(x):
if x.shape[0] == 1:
return x.copy()
else:
return x[x.category == 'c']
def filt2(x):
if x.shape[0] == 1:
return x
else:
return x[x.category == 'c']
expected = data.groupby('id_field').apply(filt1)
result = data.groupby('id_field').apply(filt2)
assert_frame_equal(result,expected)
def test_apply_use_categorical_name(self):
from pandas import qcut
cats = qcut(self.df.C, 4)
def get_stats(group):
return {'min': group.min(), 'max': group.max(),
'count': group.count(), 'mean': group.mean()}
result = self.df.groupby(cats).D.apply(get_stats)
self.assertEqual(result.index.names[0], 'C')
def test_apply_corner_cases(self):
# #535, can't use sliding iterator
N = 1000
labels = np.random.randint(0, 100, size=N)
df = DataFrame({'key': labels,
'value1': np.random.randn(N),
'value2': ['foo', 'bar', 'baz', 'qux'] * (N // 4)})
grouped = df.groupby('key')
def f(g):
g['value3'] = g['value1'] * 2
return g
result = grouped.apply(f)
self.assertTrue('value3' in result)
def test_transform_mixed_type(self):
index = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1],
[1, 2, 3, 1, 2, 3]])
df = DataFrame({'d': [1., 1., 1., 2., 2., 2.],
'c': np.tile(['a', 'b', 'c'], 2),
'v': np.arange(1., 7.)}, index=index)
def f(group):
group['g'] = group['d'] * 2
return group[:1]
grouped = df.groupby('c')
result = grouped.apply(f)
self.assertEqual(result['d'].dtype, np.float64)
# this is by definition a mutating operation!
with option_context('mode.chained_assignment',None):
for key, group in grouped:
res = f(group)
assert_frame_equal(res, result.ix[key])
def test_groupby_wrong_multi_labels(self):
from pandas import read_csv
data = """index,foo,bar,baz,spam,data
0,foo1,bar1,baz1,spam2,20
1,foo1,bar2,baz1,spam3,30
2,foo2,bar2,baz1,spam2,40
3,foo1,bar1,baz2,spam1,50
4,foo3,bar1,baz2,spam1,60"""
data = read_csv(StringIO(data), index_col=0)
grouped = data.groupby(['foo', 'bar', 'baz', 'spam'])
result = grouped.agg(np.mean)
expected = grouped.mean()
assert_frame_equal(result, expected)
def test_groupby_series_with_name(self):
result = self.df.groupby(self.df['A']).mean()
result2 = self.df.groupby(self.df['A'], as_index=False).mean()
self.assertEqual(result.index.name, 'A')
self.assertIn('A', result2)
result = self.df.groupby([self.df['A'], self.df['B']]).mean()
result2 = self.df.groupby([self.df['A'], self.df['B']],
as_index=False).mean()
self.assertEqual(result.index.names, ('A', 'B'))
self.assertIn('A', result2)
self.assertIn('B', result2)
def test_seriesgroupby_name_attr(self):
# GH 6265
result = self.df.groupby('A')['C']
self.assertEqual(result.count().name, 'C')
self.assertEqual(result.mean().name, 'C')
testFunc = lambda x: np.sum(x)*2
self.assertEqual(result.agg(testFunc).name, 'C')
def test_groupby_name_propagation(self):
# GH 6124
def summarize(df, name=None):
return Series({
'count': 1,
'mean': 2,
'omissions': 3,
}, name=name)
def summarize_random_name(df):
# Provide a different name for each Series. In this case, groupby
# should not attempt to propagate the Series name since they are
# inconsistent.
return Series({
'count': 1,
'mean': 2,
'omissions': 3,
}, name=df.iloc[0]['A'])
metrics = self.df.groupby('A').apply(summarize)
self.assertEqual(metrics.columns.name, None)
metrics = self.df.groupby('A').apply(summarize, 'metrics')
self.assertEqual(metrics.columns.name, 'metrics')
metrics = self.df.groupby('A').apply(summarize_random_name)
self.assertEqual(metrics.columns.name, None)
def test_groupby_nonstring_columns(self):
df = DataFrame([np.arange(10) for x in range(10)])
grouped = df.groupby(0)
result = grouped.mean()
expected = df.groupby(df[0]).mean()
assert_frame_equal(result, expected)
def test_cython_grouper_series_bug_noncontig(self):
arr = np.empty((100, 100))
arr.fill(np.nan)
obj = Series(arr[:, 0], index=lrange(100))
inds = np.tile(lrange(10), 10)
result = obj.groupby(inds).agg(Series.median)
self.assertTrue(result.isnull().all())
def test_series_grouper_noncontig_index(self):
index = Index(tm.rands_array(10, 100))
values = Series(np.random.randn(50), index=index[::2])
labels = np.random.randint(0, 5, 50)
# it works!
grouped = values.groupby(labels)
# accessing the index elements causes segfault
f = lambda x: len(set(map(id, x.index)))
grouped.agg(f)
def test_convert_objects_leave_decimal_alone(self):
from decimal import Decimal
s = Series(lrange(5))
labels = np.array(['a', 'b', 'c', 'd', 'e'], dtype='O')
def convert_fast(x):
return Decimal(str(x.mean()))
def convert_force_pure(x):
# base will be length 0
assert(len(x.base) > 0)
return Decimal(str(x.mean()))
grouped = s.groupby(labels)
result = grouped.agg(convert_fast)
self.assertEqual(result.dtype, np.object_)
tm.assert_isinstance(result[0], Decimal)
result = grouped.agg(convert_force_pure)
self.assertEqual(result.dtype, np.object_)
tm.assert_isinstance(result[0], Decimal)
def test_fast_apply(self):
# make sure that fast apply is correctly called
# rather than raising any kind of error
# otherwise the python path will be callsed
# which slows things down
N = 1000
labels = np.random.randint(0, 2000, size=N)
labels2 = np.random.randint(0, 3, size=N)
df = DataFrame({'key': labels,
'key2': labels2,
'value1': np.random.randn(N),
'value2': ['foo', 'bar', 'baz', 'qux'] * (N // 4)})
def f(g):
return 1
g = df.groupby(['key', 'key2'])
grouper = g.grouper
splitter = grouper._get_splitter(g._selected_obj, axis=g.axis)
group_keys = grouper._get_group_keys()
values, mutated = splitter.fast_apply(f, group_keys)
self.assertFalse(mutated)
def test_apply_with_mixed_dtype(self):
# GH3480, apply with mixed dtype on axis=1 breaks in 0.11
df = DataFrame({'foo1' : ['one', 'two', 'two', 'three', 'one', 'two'],
'foo2' : np.random.randn(6)})
result = df.apply(lambda x: x, axis=1)
assert_series_equal(df.get_dtype_counts(), result.get_dtype_counts())
# GH 3610 incorrect dtype conversion with as_index=False
df = DataFrame({"c1" : [1,2,6,6,8]})
df["c2"] = df.c1/2.0
result1 = df.groupby("c2").mean().reset_index().c2
result2 = df.groupby("c2", as_index=False).mean().c2
assert_series_equal(result1,result2)
def test_groupby_aggregation_mixed_dtype(self):
# GH 6212
expected = DataFrame({
'v1': [5,5,7,np.nan,3,3,4,1],
'v2': [55,55,77,np.nan,33,33,44,11]},
index=MultiIndex.from_tuples([(1,95),(1,99),(2,95),(2,99),('big','damp'),
('blue','dry'),('red','red'),('red','wet')],
names=['by1','by2']))
df = DataFrame({
'v1': [1,3,5,7,8,3,5,np.nan,4,5,7,9],
'v2': [11,33,55,77,88,33,55,np.nan,44,55,77,99],
'by1': ["red", "blue", 1, 2, np.nan, "big", 1, 2, "red", 1, np.nan, 12],
'by2': ["wet", "dry", 99, 95, np.nan, "damp", 95, 99, "red", 99, np.nan,
np.nan]
})
g = df.groupby(['by1','by2'])
result = g[['v1','v2']].mean()
assert_frame_equal(result,expected)
def test_groupby_dtype_inference_empty(self):
# GH 6733
df = DataFrame({'x': [], 'range': np.arange(0,dtype='int64')})
result = df.groupby('x').first()
expected = DataFrame({'range' : Series([],index=Index([],name='x'),dtype='int64') })
assert_frame_equal(result,expected,by_blocks=True)
def test_groupby_list_infer_array_like(self):
result = self.df.groupby(list(self.df['A'])).mean()
expected = self.df.groupby(self.df['A']).mean()
assert_frame_equal(result, expected, check_names=False)
self.assertRaises(Exception, self.df.groupby, list(self.df['A'][:-1]))
# pathological case of ambiguity
df = DataFrame({'foo': [0, 1], 'bar': [3, 4],
'val': np.random.randn(2)})
result = df.groupby(['foo', 'bar']).mean()
expected = df.groupby([df['foo'], df['bar']]).mean()[['val']]
def test_dictify(self):
dict(iter(self.df.groupby('A')))
dict(iter(self.df.groupby(['A', 'B'])))
dict(iter(self.df['C'].groupby(self.df['A'])))
dict(iter(self.df['C'].groupby([self.df['A'], self.df['B']])))
dict(iter(self.df.groupby('A')['C']))
dict(iter(self.df.groupby(['A', 'B'])['C']))
def test_sparse_friendly(self):
sdf = self.df[['C', 'D']].to_sparse()
panel = tm.makePanel()
tm.add_nans(panel)
def _check_work(gp):
gp.mean()
gp.agg(np.mean)
dict(iter(gp))
# it works!
_check_work(sdf.groupby(lambda x: x // 2))
_check_work(sdf['C'].groupby(lambda x: x // 2))
_check_work(sdf.groupby(self.df['A']))
# do this someday
# _check_work(panel.groupby(lambda x: x.month, axis=1))
def test_panel_groupby(self):
self.panel = tm.makePanel()
tm.add_nans(self.panel)
grouped = self.panel.groupby({'ItemA': 0, 'ItemB': 0, 'ItemC': 1},
axis='items')
agged = grouped.mean()
agged2 = grouped.agg(lambda x: x.mean('items'))
tm.assert_panel_equal(agged, agged2)
self.assert_numpy_array_equal(agged.items, [0, 1])
grouped = self.panel.groupby(lambda x: x.month, axis='major')
agged = grouped.mean()
self.assert_numpy_array_equal(agged.major_axis, sorted(list(set(self.panel.major_axis.month))))
grouped = self.panel.groupby({'A': 0, 'B': 0, 'C': 1, 'D': 1},
axis='minor')
agged = grouped.mean()
self.assert_numpy_array_equal(agged.minor_axis, [0, 1])
def test_numpy_groupby(self):
from pandas.core.groupby import numpy_groupby
data = np.random.randn(100, 100)
labels = np.random.randint(0, 10, size=100)
df = DataFrame(data)
result = df.groupby(labels).sum().values
expected = numpy_groupby(data, labels)
assert_almost_equal(result, expected)
result = df.groupby(labels, axis=1).sum().values
expected = numpy_groupby(data, labels, axis=1)
assert_almost_equal(result, expected)
def test_groupby_2d_malformed(self):
d = DataFrame(index=lrange(2))
d['group'] = ['g1', 'g2']
d['zeros'] = [0, 0]
d['ones'] = [1, 1]
d['label'] = ['l1', 'l2']
tmp = d.groupby(['group']).mean()
res_values = np.array([[0., 1.], [0., 1.]])
self.assert_numpy_array_equal(tmp.columns, ['zeros', 'ones'])
self.assert_numpy_array_equal(tmp.values, res_values)
def test_int32_overflow(self):
B = np.concatenate((np.arange(10000), np.arange(10000),
np.arange(5000)))
A = np.arange(25000)
df = DataFrame({'A': A, 'B': B,
'C': A, 'D': B,
'E': np.random.randn(25000)})
left = df.groupby(['A', 'B', 'C', 'D']).sum()
right = df.groupby(['D', 'C', 'B', 'A']).sum()
self.assertEqual(len(left), len(right))
def test_int64_overflow(self):
from pandas.core.groupby import _int64_overflow_possible
B = np.concatenate((np.arange(1000), np.arange(1000),
np.arange(500)))
A = np.arange(2500)
df = DataFrame({'A': A, 'B': B,
'C': A, 'D': B,
'E': A, 'F': B,
'G': A, 'H': B,
'values': np.random.randn(2500)})
lg = df.groupby(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'])
rg = df.groupby(['H', 'G', 'F', 'E', 'D', 'C', 'B', 'A'])
left = lg.sum()['values']
right = rg.sum()['values']
exp_index, _ = left.index.sortlevel(0)
self.assertTrue(left.index.equals(exp_index))
exp_index, _ = right.index.sortlevel(0)
self.assertTrue(right.index.equals(exp_index))
tups = list(map(tuple, df[['A', 'B', 'C', 'D',
'E', 'F', 'G', 'H']].values))
tups = com._asarray_tuplesafe(tups)
expected = df.groupby(tups).sum()['values']
for k, v in compat.iteritems(expected):
self.assertEqual(left[k], right[k[::-1]])
self.assertEqual(left[k], v)
self.assertEqual(len(left), len(right))
# GH9096
values = range(55109)
data = pd.DataFrame.from_dict({'a': values, 'b': values,
'c': values, 'd': values})
grouped = data.groupby(['a', 'b', 'c', 'd'])
self.assertEqual(len(grouped), len(values))
arr = np.random.randint(- 1 << 12, 1 << 12, (1 << 15, 5))
i = np.random.choice(len(arr), len(arr) * 4)
arr = np.vstack((arr, arr[i])) # add sume duplicate rows
i = np.random.permutation(len(arr))
arr = arr[i] # shuffle rows
df = DataFrame(arr, columns=list('abcde'))
df['jim'], df['joe'] = np.random.randn(2, len(df)) * 10
gr = df.groupby(list('abcde'))
# verify this is testing what it is supposed to test!
self.assertTrue(_int64_overflow_possible(gr.grouper.shape))
# mannually compute groupings
jim, joe = defaultdict(list), defaultdict(list)
for key, a, b in zip(map(tuple, arr), df['jim'], df['joe']):
jim[key].append(a)
joe[key].append(b)
self.assertEqual(len(gr), len(jim))
mi = MultiIndex.from_tuples(jim.keys(), names=list('abcde'))
def aggr(func):
f = lambda a: np.fromiter(map(func, a), dtype='f8')
arr = np.vstack((f(jim.values()), f(joe.values()))).T
res = DataFrame(arr, columns=['jim', 'joe'], index=mi)
return res.sort_index()
assert_frame_equal(gr.mean(), aggr(np.mean))
assert_frame_equal(gr.median(), aggr(np.median))
def test_groupby_sort_multi(self):
df = DataFrame({'a': ['foo', 'bar', 'baz'],
'b': [3, 2, 1],
'c': [0, 1, 2],
'd': np.random.randn(3)})
tups = lmap(tuple, df[['a', 'b', 'c']].values)
tups = com._asarray_tuplesafe(tups)
result = df.groupby(['a', 'b', 'c'], sort=True).sum()
self.assert_numpy_array_equal(result.index.values,
tups[[1, 2, 0]])
tups = lmap(tuple, df[['c', 'a', 'b']].values)
tups = com._asarray_tuplesafe(tups)
result = df.groupby(['c', 'a', 'b'], sort=True).sum()
self.assert_numpy_array_equal(result.index.values, tups)
tups = lmap(tuple, df[['b', 'c', 'a']].values)
tups = com._asarray_tuplesafe(tups)
result = df.groupby(['b', 'c', 'a'], sort=True).sum()
self.assert_numpy_array_equal(result.index.values,
tups[[2, 1, 0]])
df = DataFrame({'a': [0, 1, 2, 0, 1, 2],
'b': [0, 0, 0, 1, 1, 1],
'd': np.random.randn(6)})
grouped = df.groupby(['a', 'b'])['d']
result = grouped.sum()
_check_groupby(df, result, ['a', 'b'], 'd')
def test_intercept_builtin_sum(self):
s = Series([1., 2., np.nan, 3.])
grouped = s.groupby([0, 1, 2, 2])
result = grouped.agg(builtins.sum)
result2 = grouped.apply(builtins.sum)
expected = grouped.sum()
assert_series_equal(result, expected)
assert_series_equal(result2, expected)
def test_column_select_via_attr(self):
result = self.df.groupby('A').C.sum()
expected = self.df.groupby('A')['C'].sum()
assert_series_equal(result, expected)
self.df['mean'] = 1.5
result = self.df.groupby('A').mean()
expected = self.df.groupby('A').agg(np.mean)
assert_frame_equal(result, expected)
def test_rank_apply(self):
lev1 = tm.rands_array(10, 100)
lev2 = tm.rands_array(10, 130)
lab1 = np.random.randint(0, 100, size=500)
lab2 = np.random.randint(0, 130, size=500)
df = DataFrame({'value': np.random.randn(500),
'key1': lev1.take(lab1),
'key2': lev2.take(lab2)})
result = df.groupby(['key1', 'key2']).value.rank()
expected = []
for key, piece in df.groupby(['key1', 'key2']):
expected.append(piece.value.rank())
expected = concat(expected, axis=0)
expected = expected.reindex(result.index)
assert_series_equal(result, expected)
result = df.groupby(['key1', 'key2']).value.rank(pct=True)
expected = []
for key, piece in df.groupby(['key1', 'key2']):
expected.append(piece.value.rank(pct=True))
expected = concat(expected, axis=0)
expected = expected.reindex(result.index)
assert_series_equal(result, expected)
def test_dont_clobber_name_column(self):
df = DataFrame({'key': ['a', 'a', 'a', 'b', 'b', 'b'],
'name': ['foo', 'bar', 'baz'] * 2})
result = df.groupby('key').apply(lambda x: x)
assert_frame_equal(result, df)
def test_skip_group_keys(self):
from pandas import concat
tsf = tm.makeTimeDataFrame()
grouped = tsf.groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.sort_index(by='A')[:3])
pieces = []
for key, group in grouped:
pieces.append(group.sort_index(by='A')[:3])
expected = concat(pieces)
assert_frame_equal(result, expected)
grouped = tsf['A'].groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.order()[:3])
pieces = []
for key, group in grouped:
pieces.append(group.order()[:3])
expected = concat(pieces)
assert_series_equal(result, expected)
def test_no_nonsense_name(self):
# GH #995
s = self.frame['C'].copy()
s.name = None
result = s.groupby(self.frame['A']).agg(np.sum)
self.assertIsNone(result.name)
def test_wrap_agg_out(self):
grouped = self.three_group.groupby(['A', 'B'])
def func(ser):
if ser.dtype == np.object:
raise TypeError
else:
return ser.sum()
result = grouped.aggregate(func)
exp_grouped = self.three_group.ix[:, self.three_group.columns != 'C']
expected = exp_grouped.groupby(['A', 'B']).aggregate(func)
assert_frame_equal(result, expected)
def test_multifunc_sum_bug(self):
# GH #1065
x = DataFrame(np.arange(9).reshape(3, 3))
x['test'] = 0
x['fl'] = [1.3, 1.5, 1.6]
grouped = x.groupby('test')
result = grouped.agg({'fl': 'sum', 2: 'size'})
self.assertEqual(result['fl'].dtype, np.float64)
def test_handle_dict_return_value(self):
def f(group):
return {'min': group.min(), 'max': group.max()}
def g(group):
return Series({'min': group.min(), 'max': group.max()})
result = self.df.groupby('A')['C'].apply(f)
expected = self.df.groupby('A')['C'].apply(g)
tm.assert_isinstance(result, Series)
assert_series_equal(result, expected)
def test_getitem_list_of_columns(self):
df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8),
'E': np.random.randn(8)})
result = df.groupby('A')[['C', 'D']].mean()
result2 = df.groupby('A')['C', 'D'].mean()
result3 = df.groupby('A')[df.columns[2:4]].mean()
expected = df.ix[:, ['A', 'C', 'D']].groupby('A').mean()
assert_frame_equal(result, expected)
assert_frame_equal(result2, expected)
assert_frame_equal(result3, expected)
def test_agg_multiple_functions_maintain_order(self):
# GH #610
funcs = [('mean', np.mean), ('max', np.max), ('min', np.min)]
result = self.df.groupby('A')['C'].agg(funcs)
exp_cols = ['mean', 'max', 'min']
self.assert_numpy_array_equal(result.columns, exp_cols)
def test_multiple_functions_tuples_and_non_tuples(self):
# #1359
funcs = [('foo', 'mean'), 'std']
ex_funcs = [('foo', 'mean'), ('std', 'std')]
result = self.df.groupby('A')['C'].agg(funcs)
expected = self.df.groupby('A')['C'].agg(ex_funcs)
assert_frame_equal(result, expected)
result = self.df.groupby('A').agg(funcs)
expected = self.df.groupby('A').agg(ex_funcs)
assert_frame_equal(result, expected)
def test_agg_multiple_functions_too_many_lambdas(self):
grouped = self.df.groupby('A')
funcs = ['mean', lambda x: x.mean(), lambda x: x.std()]
self.assertRaises(SpecificationError, grouped.agg, funcs)
def test_more_flexible_frame_multi_function(self):
from pandas import concat
grouped = self.df.groupby('A')
exmean = grouped.agg(OrderedDict([['C', np.mean], ['D', np.mean]]))
exstd = grouped.agg(OrderedDict([['C', np.std], ['D', np.std]]))
expected = concat([exmean, exstd], keys=['mean', 'std'], axis=1)
expected = expected.swaplevel(0, 1, axis=1).sortlevel(0, axis=1)
d = OrderedDict([['C', [np.mean, np.std]], ['D', [np.mean, np.std]]])
result = grouped.aggregate(d)
assert_frame_equal(result, expected)
# be careful
result = grouped.aggregate(OrderedDict([['C', np.mean],
['D', [np.mean, np.std]]]))
expected = grouped.aggregate(OrderedDict([['C', np.mean],
['D', [np.mean, np.std]]]))
assert_frame_equal(result, expected)
def foo(x):
return np.mean(x)
def bar(x):
return np.std(x, ddof=1)
d = OrderedDict([['C', np.mean],
['D', OrderedDict([['foo', np.mean],
['bar', np.std]])]])
result = grouped.aggregate(d)
d = OrderedDict([['C', [np.mean]], ['D', [foo, bar]]])
expected = grouped.aggregate(d)
assert_frame_equal(result, expected)
def test_multi_function_flexible_mix(self):
# GH #1268
grouped = self.df.groupby('A')
d = OrderedDict([['C', OrderedDict([['foo', 'mean'],
[
'bar', 'std']])],
['D', 'sum']])
result = grouped.aggregate(d)
d2 = OrderedDict([['C', OrderedDict([['foo', 'mean'],
[
'bar', 'std']])],
['D', ['sum']]])
result2 = grouped.aggregate(d2)
d3 = OrderedDict([['C', OrderedDict([['foo', 'mean'],
[
'bar', 'std']])],
['D', {'sum': 'sum'}]])
expected = grouped.aggregate(d3)
assert_frame_equal(result, expected)
assert_frame_equal(result2, expected)
def test_agg_callables(self):
# GH 7929
df = DataFrame({'foo' : [1,2], 'bar' :[3,4]}).astype(np.int64)
class fn_class(object):
def __call__(self, x):
return sum(x)
equiv_callables = [sum, np.sum,
lambda x: sum(x),
lambda x: x.sum(),
partial(sum), fn_class()]
expected = df.groupby("foo").agg(sum)
for ecall in equiv_callables:
result = df.groupby('foo').agg(ecall)
assert_frame_equal(result, expected)
def test_set_group_name(self):
def f(group):
assert group.name is not None
return group
def freduce(group):
assert group.name is not None
return group.sum()
def foo(x):
return freduce(x)
def _check_all(grouped):
# make sure all these work
grouped.apply(f)
grouped.aggregate(freduce)
grouped.aggregate({'C': freduce, 'D': freduce})
grouped.transform(f)
grouped['C'].apply(f)
grouped['C'].aggregate(freduce)
grouped['C'].aggregate([freduce, foo])
grouped['C'].transform(f)
_check_all(self.df.groupby('A'))
_check_all(self.df.groupby(['A', 'B']))
def test_no_dummy_key_names(self):
# GH #1291
result = self.df.groupby(self.df['A'].values).sum()
self.assertIsNone(result.index.name)
result = self.df.groupby([self.df['A'].values,
self.df['B'].values]).sum()
self.assertEqual(result.index.names, (None, None))
def test_groupby_sort_categorical(self):
# dataframe groupby sort was being ignored # GH 8868
df = DataFrame([['(7.5, 10]', 10, 10],
['(7.5, 10]', 8, 20],
['(2.5, 5]', 5, 30],
['(5, 7.5]', 6, 40],
['(2.5, 5]', 4, 50],
['(0, 2.5]', 1, 60],
['(5, 7.5]', 7, 70]], columns=['range', 'foo', 'bar'])
df['range'] = Categorical(df['range'],ordered=True)
index = Index(['(0, 2.5]', '(2.5, 5]', '(5, 7.5]', '(7.5, 10]'], dtype='object')
index.name = 'range'
result_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]], columns=['foo', 'bar'])
result_sort.index = index
index = Index(['(7.5, 10]', '(2.5, 5]', '(5, 7.5]', '(0, 2.5]'], dtype='object')
index.name = 'range'
result_nosort = DataFrame([[10, 10], [5, 30], [6, 40], [1, 60]], index=index, columns=['foo', 'bar'])
result_nosort.index = index
col = 'range'
assert_frame_equal(result_sort, df.groupby(col, sort=True).first())
assert_frame_equal(result_nosort, df.groupby(col, sort=False).first())
df['range'] = Categorical(df['range'],ordered=False)
index = Index(['(0, 2.5]', '(2.5, 5]', '(5, 7.5]', '(7.5, 10]'], dtype='object')
index.name = 'range'
result_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]], columns=['foo', 'bar'])
result_sort.index = index
index = Index(['(7.5, 10]', '(2.5, 5]', '(5, 7.5]', '(0, 2.5]'], dtype='object')
index.name = 'range'
result_nosort = DataFrame([[10, 10], [5, 30], [6, 40], [1, 60]], index=index, columns=['foo', 'bar'])
result_nosort.index = index
col = 'range'
#### this is an unordered categorical, but we allow this ####
assert_frame_equal(result_sort, df.groupby(col, sort=True).first())
assert_frame_equal(result_nosort, df.groupby(col, sort=False).first())
def test_groupby_sort_multiindex_series(self):
# series multiindex groupby sort argument was not being passed through _compress_group_index
# GH 9444
index = MultiIndex(levels=[[1, 2], [1, 2]],
labels=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]],
names=['a', 'b'])
mseries = Series([0, 1, 2, 3, 4, 5], index=index)
index = MultiIndex(levels=[[1, 2], [1, 2]],
labels=[[0, 0, 1], [1, 0, 0]],
names=['a', 'b'])
mseries_result = Series([0, 2, 4], index=index)
result = mseries.groupby(level=['a', 'b'], sort=False).first()
assert_series_equal(result, mseries_result)
result = mseries.groupby(level=['a', 'b'], sort=True).first()
assert_series_equal(result, mseries_result.sort_index())
def test_groupby_categorical(self):
levels = ['foo', 'bar', 'baz', 'qux']
codes = np.random.randint(0, 4, size=100)
cats = Categorical.from_codes(codes, levels, name='myfactor', ordered=True)
data = DataFrame(np.random.randn(100, 4))
result = data.groupby(cats).mean()
expected = data.groupby(np.asarray(cats)).mean()
expected = expected.reindex(levels)
expected.index.name = 'myfactor'
assert_frame_equal(result, expected)
self.assertEqual(result.index.name, cats.name)
grouped = data.groupby(cats)
desc_result = grouped.describe()
idx = cats.codes.argsort()
ord_labels = np.asarray(cats).take(idx)
ord_data = data.take(idx)
expected = ord_data.groupby(ord_labels, sort=False).describe()
expected.index.names = ['myfactor', None]
assert_frame_equal(desc_result, expected)
def test_groupby_datetime_categorical(self):
# GH9049: ensure backward compatibility
levels = pd.date_range('2014-01-01', periods=4)
codes = np.random.randint(0, 4, size=100)
cats = Categorical.from_codes(codes, levels, name='myfactor', ordered=True)
data = DataFrame(np.random.randn(100, 4))
result = data.groupby(cats).mean()
expected = data.groupby(np.asarray(cats)).mean()
expected = expected.reindex(levels)
expected.index.name = 'myfactor'
assert_frame_equal(result, expected)
self.assertEqual(result.index.name, cats.name)
grouped = data.groupby(cats)
desc_result = grouped.describe()
idx = cats.codes.argsort()
ord_labels = np.asarray(cats).take(idx)
ord_data = data.take(idx)
expected = ord_data.groupby(ord_labels, sort=False).describe()
expected.index.names = ['myfactor', None]
assert_frame_equal(desc_result, expected)
def test_groupby_groups_datetimeindex(self):
# #1430
from pandas.tseries.api import DatetimeIndex
periods = 1000
ind = DatetimeIndex(start='2012/1/1', freq='5min', periods=periods)
df = DataFrame({'high': np.arange(periods),
'low': np.arange(periods)}, index=ind)
grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))
# it works!
groups = grouped.groups
tm.assert_isinstance(list(groups.keys())[0], datetime)
def test_groupby_groups_datetimeindex_tz(self):
# GH 3950
dates = ['2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00',
'2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00']
df = DataFrame({'label': ['a', 'a', 'a', 'b', 'b', 'b'],
'datetime': dates,
'value1': np.arange(6,dtype='int64'),
'value2': [1, 2] * 3})
df['datetime'] = df['datetime'].apply(lambda d: Timestamp(d, tz='US/Pacific'))
exp_idx1 = pd.DatetimeIndex(['2011-07-19 07:00:00', '2011-07-19 07:00:00',
'2011-07-19 08:00:00', '2011-07-19 08:00:00',
'2011-07-19 09:00:00', '2011-07-19 09:00:00'],
tz='US/Pacific', name='datetime')
exp_idx2 = Index(['a', 'b'] * 3, name='label')
exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2])
expected = DataFrame({'value1': [0, 3, 1, 4, 2, 5], 'value2': [1, 2, 2, 1, 1, 2]},
index=exp_idx, columns=['value1', 'value2'])
result = df.groupby(['datetime', 'label']).sum()
assert_frame_equal(result, expected)
# by level
didx = pd.DatetimeIndex(dates, tz='Asia/Tokyo')
df = DataFrame({'value1': np.arange(6,dtype='int64'),
'value2': [1, 2, 3, 1, 2, 3]},
index=didx)
exp_idx = pd.DatetimeIndex(['2011-07-19 07:00:00', '2011-07-19 08:00:00',
'2011-07-19 09:00:00'], tz='Asia/Tokyo')
expected = DataFrame({'value1': [3, 5, 7], 'value2': [2, 4, 6]},
index=exp_idx, columns=['value1', 'value2'])
result = df.groupby(level=0).sum()
assert_frame_equal(result, expected)
def test_groupby_reindex_inside_function(self):
from pandas.tseries.api import DatetimeIndex
periods = 1000
ind = DatetimeIndex(start='2012/1/1', freq='5min', periods=periods)
df = DataFrame({'high': np.arange(
periods), 'low': np.arange(periods)}, index=ind)
def agg_before(hour, func, fix=False):
"""
Run an aggregate func on the subset of data.
"""
def _func(data):
d = data.select(lambda x: x.hour < 11).dropna()
if fix:
data[data.index[0]]
if len(d) == 0:
return None
return func(d)
return _func
def afunc(data):
d = data.select(lambda x: x.hour < 11).dropna()
return np.max(d)
grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))
closure_bad = grouped.agg({'high': agg_before(11, np.max)})
closure_good = grouped.agg({'high': agg_before(11, np.max, True)})
assert_frame_equal(closure_bad, closure_good)
def test_multiindex_columns_empty_level(self):
l = [['count', 'values'], ['to filter', '']]
midx = MultiIndex.from_tuples(l)
df = DataFrame([[long(1), 'A']], columns=midx)
grouped = df.groupby('to filter').groups
self.assert_numpy_array_equal(grouped['A'], [0])
grouped = df.groupby([('to filter', '')]).groups
self.assert_numpy_array_equal(grouped['A'], [0])
df = DataFrame([[long(1), 'A'], [long(2), 'B']], columns=midx)
expected = df.groupby('to filter').groups
result = df.groupby([('to filter', '')]).groups
self.assertEqual(result, expected)
df = DataFrame([[long(1), 'A'], [long(2), 'A']], columns=midx)
expected = df.groupby('to filter').groups
result = df.groupby([('to filter', '')]).groups
self.assertEqual(result, expected)
def test_cython_median(self):
df = DataFrame(np.random.randn(1000))
df.values[::2] = np.nan
labels = np.random.randint(0, 50, size=1000).astype(float)
labels[::17] = np.nan
result = df.groupby(labels).median()
exp = df.groupby(labels).agg(nanops.nanmedian)
assert_frame_equal(result, exp)
df = DataFrame(np.random.randn(1000, 5))
rs = df.groupby(labels).agg(np.median)
xp = df.groupby(labels).median()
assert_frame_equal(rs, xp)
def test_groupby_categorical_no_compress(self):
data = Series(np.random.randn(9))
codes = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])
cats = Categorical.from_codes(codes, [0, 1, 2], ordered=True)
result = data.groupby(cats).mean()
exp = data.groupby(codes).mean()
assert_series_equal(result, exp)
codes = np.array([0, 0, 0, 1, 1, 1, 3, 3, 3])
cats = Categorical.from_codes(codes, [0, 1, 2, 3], ordered=True)
result = data.groupby(cats).mean()
exp = data.groupby(codes).mean().reindex(cats.categories)
assert_series_equal(result, exp)
cats = Categorical(["a", "a", "a", "b", "b", "b", "c", "c", "c"],
categories=["a","b","c","d"], ordered=True)
data = DataFrame({"a":[1,1,1,2,2,2,3,4,5], "b":cats})
result = data.groupby("b").mean()
result = result["a"].values
exp = np.array([1,2,4,np.nan])
self.assert_numpy_array_equivalent(result, exp)
def test_groupby_non_arithmetic_agg_types(self):
# GH9311, GH6620
df = pd.DataFrame([{'a': 1, 'b': 1},
{'a': 1, 'b': 2},
{'a': 2, 'b': 3},
{'a': 2, 'b': 4}])
dtypes = ['int8', 'int16', 'int32', 'int64',
'float32', 'float64']
grp_exp = {'first': {'df': [{'a': 1, 'b': 1}, {'a': 2, 'b': 3}]},
'last': {'df': [{'a': 1, 'b': 2}, {'a': 2, 'b': 4}]},
'min': {'df': [{'a': 1, 'b': 1}, {'a': 2, 'b': 3}]},
'max': {'df': [{'a': 1, 'b': 2}, {'a': 2, 'b': 4}]},
'nth': {'df': [{'a': 1, 'b': 2}, {'a': 2, 'b': 4}],
'args': [1]},
'count': {'df': [{'a': 1, 'b': 2}, {'a': 2, 'b': 2}],
'out_type': 'int64'}}
for dtype in dtypes:
df_in = df.copy()
df_in['b'] = df_in.b.astype(dtype)
for method, data in compat.iteritems(grp_exp):
if 'args' not in data:
data['args'] = []
if 'out_type' in data:
out_type = data['out_type']
else:
out_type = dtype
exp = data['df']
df_out = pd.DataFrame(exp)
df_out['b'] = df_out.b.astype(out_type)
df_out.set_index('a', inplace=True)
grpd = df_in.groupby('a')
t = getattr(grpd, method)(*data['args'])
assert_frame_equal(t, df_out)
def test_groupby_non_arithmetic_agg_intlike_precision(self):
# GH9311, GH6620
c = 24650000000000000
inputs = ((Timestamp('2011-01-15 12:50:28.502376'),
Timestamp('2011-01-20 12:50:28.593448')),
(1 + c, 2 + c))
for i in inputs:
df = pd.DataFrame([{'a': 1,
'b': i[0]},
{'a': 1,
'b': i[1]}])
grp_exp = {'first': {'expected': i[0]},
'last': {'expected': i[1]},
'min': {'expected': i[0]},
'max': {'expected': i[1]},
'nth': {'expected': i[1], 'args': [1]},
'count': {'expected': 2}}
for method, data in compat.iteritems(grp_exp):
if 'args' not in data:
data['args'] = []
grpd = df.groupby('a')
res = getattr(grpd, method)(*data['args'])
self.assertEqual(res.iloc[0].b, data['expected'])
def test_groupby_first_datetime64(self):
df = DataFrame([(1, 1351036800000000000), (2, 1351036800000000000)])
df[1] = df[1].view('M8[ns]')
self.assertTrue(issubclass(df[1].dtype.type, np.datetime64))
result = df.groupby(level=0).first()
got_dt = result[1].dtype
self.assertTrue(issubclass(got_dt.type, np.datetime64))
result = df[1].groupby(level=0).first()
got_dt = result.dtype
self.assertTrue(issubclass(got_dt.type, np.datetime64))
def test_groupby_max_datetime64(self):
# GH 5869
# datetimelike dtype conversion from int
df = DataFrame(dict(A = Timestamp('20130101'), B = np.arange(5)))
expected = df.groupby('A')['A'].apply(lambda x: x.max())
result = df.groupby('A')['A'].max()
assert_series_equal(result,expected)
def test_groupby_datetime64_32_bit(self):
# GH 6410 / numpy 4328
# 32-bit under 1.9-dev indexing issue
df = DataFrame({"A": range(2), "B": [pd.Timestamp('2000-01-1')]*2})
result = df.groupby("A")["B"].transform(min)
expected = Series([pd.Timestamp('2000-01-1')]*2)
assert_series_equal(result,expected)
def test_groupby_categorical_unequal_len(self):
import pandas as pd
#GH3011
series = Series([np.nan, np.nan, 1, 1, 2, 2, 3, 3, 4, 4])
# The raises only happens with categorical, not with series of types category
bins = pd.cut(series.dropna().values, 4)
# len(bins) != len(series) here
self.assertRaises(ValueError,lambda : series.groupby(bins).mean())
def test_groupby_multiindex_missing_pair(self):
# GH9049
df = DataFrame({'group1': ['a','a','a','b'],
'group2': ['c','c','d','c'],
'value': [1,1,1,5]})
df = df.set_index(['group1', 'group2'])
df_grouped = df.groupby(level=['group1','group2'], sort=True)
res = df_grouped.agg('sum')
idx = MultiIndex.from_tuples([('a','c'), ('a','d'), ('b','c')], names=['group1', 'group2'])
exp = DataFrame([[2], [1], [5]], index=idx, columns=['value'])
tm.assert_frame_equal(res, exp)
def test_groupby_levels_and_columns(self):
# GH9344, GH9049
idx_names = ['x', 'y']
idx = pd.MultiIndex.from_tuples([(1, 1), (1, 2), (3, 4), (5, 6)], names=idx_names)
df = pd.DataFrame(np.arange(12).reshape(-1, 3), index=idx)
by_levels = df.groupby(level=idx_names).mean()
by_columns = df.reset_index().groupby(idx_names).mean()
tm.assert_frame_equal(by_levels, by_columns)
def test_gb_apply_list_of_unequal_len_arrays(self):
# GH1738
df = DataFrame({'group1': ['a','a','a','b','b','b','a','a','a','b','b','b'],
'group2': ['c','c','d','d','d','e','c','c','d','d','d','e'],
'weight': [1.1,2,3,4,5,6,2,4,6,8,1,2],
'value': [7.1,8,9,10,11,12,8,7,6,5,4,3]
})
df = df.set_index(['group1', 'group2'])
df_grouped = df.groupby(level=['group1','group2'], sort=True)
def noddy(value, weight):
out = np.array( value * weight ).repeat(3)
return out
# the kernel function returns arrays of unequal length
# pandas sniffs the first one, sees it's an array and not
# a list, and assumed the rest are of equal length
# and so tries a vstack
# don't die
no_toes = df_grouped.apply(lambda x: noddy(x.value, x.weight ))
def test_groupby_with_empty(self):
import pandas as pd
index = pd.DatetimeIndex(())
data = ()
series = pd.Series(data, index)
grouper = pd.tseries.resample.TimeGrouper('D')
grouped = series.groupby(grouper)
assert next(iter(grouped), None) is None
def test_groupby_with_timegrouper(self):
# GH 4161
# TimeGrouper requires a sorted index
# also verifies that the resultant index has the correct name
import datetime as DT
df_original = DataFrame({
'Buyer': 'Carl Carl Carl Carl Joe Carl'.split(),
'Quantity': [18,3,5,1,9,3],
'Date' : [
DT.datetime(2013,9,1,13,0),
DT.datetime(2013,9,1,13,5),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,3,10,0),
DT.datetime(2013,12,2,12,0),
DT.datetime(2013,9,2,14,0),
]})
# GH 6908 change target column's order
df_reordered = df_original.sort(columns='Quantity')
for df in [df_original, df_reordered]:
df = df.set_index(['Date'])
expected = DataFrame({ 'Quantity' : np.nan },
index=date_range('20130901 13:00:00','20131205 13:00:00',
freq='5D',name='Date',closed='left'))
expected.iloc[[0,6,18],0] = np.array([24.,6.,9.],dtype='float64')
result1 = df.resample('5D',how=sum)
assert_frame_equal(result1, expected)
df_sorted = df.sort_index()
result2 = df_sorted.groupby(pd.TimeGrouper(freq='5D')).sum()
assert_frame_equal(result2, expected)
result3 = df.groupby(pd.TimeGrouper(freq='5D')).sum()
assert_frame_equal(result3, expected)
def test_groupby_with_timegrouper_methods(self):
# GH 3881
# make sure API of timegrouper conforms
import datetime as DT
df_original = pd.DataFrame({
'Branch' : 'A A A A A B'.split(),
'Buyer': 'Carl Mark Carl Joe Joe Carl'.split(),
'Quantity': [1,3,5,8,9,3],
'Date' : [
DT.datetime(2013,1,1,13,0),
DT.datetime(2013,1,1,13,5),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,12,2,12,0),
DT.datetime(2013,12,2,14,0),
]})
df_sorted = df_original.sort(columns='Quantity', ascending=False)
for df in [df_original, df_sorted]:
df = df.set_index('Date', drop=False)
g = df.groupby(pd.TimeGrouper('6M'))
self.assertTrue(g.group_keys)
self.assertTrue(isinstance(g.grouper,pd.core.groupby.BinGrouper))
groups = g.groups
self.assertTrue(isinstance(groups,dict))
self.assertTrue(len(groups) == 3)
def test_timegrouper_with_reg_groups(self):
# GH 3794
# allow combinateion of timegrouper/reg groups
import datetime as DT
df_original = DataFrame({
'Branch' : 'A A A A A A A B'.split(),
'Buyer': 'Carl Mark Carl Carl Joe Joe Joe Carl'.split(),
'Quantity': [1,3,5,1,8,1,9,3],
'Date' : [
DT.datetime(2013,1,1,13,0),
DT.datetime(2013,1,1,13,5),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,12,2,12,0),
DT.datetime(2013,12,2,14,0),
]}).set_index('Date')
df_sorted = df_original.sort(columns='Quantity', ascending=False)
for df in [df_original, df_sorted]:
expected = DataFrame({
'Buyer': 'Carl Joe Mark'.split(),
'Quantity': [10,18,3],
'Date' : [
DT.datetime(2013,12,31,0,0),
DT.datetime(2013,12,31,0,0),
DT.datetime(2013,12,31,0,0),
]}).set_index(['Date','Buyer'])
result = df.groupby([pd.Grouper(freq='A'),'Buyer']).sum()
assert_frame_equal(result,expected)
expected = DataFrame({
'Buyer': 'Carl Mark Carl Joe'.split(),
'Quantity': [1,3,9,18],
'Date' : [
DT.datetime(2013,1,1,0,0),
DT.datetime(2013,1,1,0,0),
DT.datetime(2013,7,1,0,0),
DT.datetime(2013,7,1,0,0),
]}).set_index(['Date','Buyer'])
result = df.groupby([pd.Grouper(freq='6MS'),'Buyer']).sum()
assert_frame_equal(result,expected)
df_original = DataFrame({
'Branch' : 'A A A A A A A B'.split(),
'Buyer': 'Carl Mark Carl Carl Joe Joe Joe Carl'.split(),
'Quantity': [1,3,5,1,8,1,9,3],
'Date' : [
DT.datetime(2013,10,1,13,0),
DT.datetime(2013,10,1,13,5),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,10,2,12,0),
DT.datetime(2013,10,2,14,0),
]}).set_index('Date')
df_sorted = df_original.sort(columns='Quantity', ascending=False)
for df in [df_original, df_sorted]:
expected = DataFrame({
'Buyer': 'Carl Joe Mark Carl Joe'.split(),
'Quantity': [6,8,3,4,10],
'Date' : [
DT.datetime(2013,10,1,0,0),
DT.datetime(2013,10,1,0,0),
DT.datetime(2013,10,1,0,0),
DT.datetime(2013,10,2,0,0),
DT.datetime(2013,10,2,0,0),
]}).set_index(['Date','Buyer'])
result = df.groupby([pd.Grouper(freq='1D'),'Buyer']).sum()
assert_frame_equal(result,expected)
result = df.groupby([pd.Grouper(freq='1M'),'Buyer']).sum()
expected = DataFrame({
'Buyer': 'Carl Joe Mark'.split(),
'Quantity': [10,18,3],
'Date' : [
DT.datetime(2013,10,31,0,0),
DT.datetime(2013,10,31,0,0),
DT.datetime(2013,10,31,0,0),
]}).set_index(['Date','Buyer'])
assert_frame_equal(result,expected)
# passing the name
df = df.reset_index()
result = df.groupby([pd.Grouper(freq='1M',key='Date'),'Buyer']).sum()
assert_frame_equal(result,expected)
self.assertRaises(KeyError, lambda : df.groupby([pd.Grouper(freq='1M',key='foo'),'Buyer']).sum())
# passing the level
df = df.set_index('Date')
result = df.groupby([pd.Grouper(freq='1M',level='Date'),'Buyer']).sum()
assert_frame_equal(result,expected)
result = df.groupby([pd.Grouper(freq='1M',level=0),'Buyer']).sum()
assert_frame_equal(result,expected)
self.assertRaises(ValueError, lambda : df.groupby([pd.Grouper(freq='1M',level='foo'),'Buyer']).sum())
# multi names
df = df.copy()
df['Date'] = df.index + pd.offsets.MonthEnd(2)
result = df.groupby([pd.Grouper(freq='1M',key='Date'),'Buyer']).sum()
expected = DataFrame({
'Buyer': 'Carl Joe Mark'.split(),
'Quantity': [10,18,3],
'Date' : [
DT.datetime(2013,11,30,0,0),
DT.datetime(2013,11,30,0,0),
DT.datetime(2013,11,30,0,0),
]}).set_index(['Date','Buyer'])
assert_frame_equal(result,expected)
# error as we have both a level and a name!
self.assertRaises(ValueError, lambda : df.groupby([pd.Grouper(freq='1M',key='Date',level='Date'),'Buyer']).sum())
# single groupers
expected = DataFrame({ 'Quantity' : [31],
'Date' : [DT.datetime(2013,10,31,0,0)] }).set_index('Date')
result = df.groupby(pd.Grouper(freq='1M')).sum()
assert_frame_equal(result, expected)
result = df.groupby([pd.Grouper(freq='1M')]).sum()
assert_frame_equal(result, expected)
expected = DataFrame({ 'Quantity' : [31],
'Date' : [DT.datetime(2013,11,30,0,0)] }).set_index('Date')
result = df.groupby(pd.Grouper(freq='1M',key='Date')).sum()
assert_frame_equal(result, expected)
result = df.groupby([pd.Grouper(freq='1M',key='Date')]).sum()
assert_frame_equal(result, expected)
# GH 6764 multiple grouping with/without sort
df = DataFrame({
'date' : pd.to_datetime([
'20121002','20121007','20130130','20130202','20130305','20121002',
'20121207','20130130','20130202','20130305','20130202','20130305']),
'user_id' : [1,1,1,1,1,3,3,3,5,5,5,5],
'whole_cost' : [1790,364,280,259,201,623,90,312,359,301,359,801],
'cost1' : [12,15,10,24,39,1,0,90,45,34,1,12] }).set_index('date')
for freq in ['D', 'M', 'A', 'Q-APR']:
expected = df.groupby('user_id')['whole_cost'].resample(
freq, how='sum').dropna().reorder_levels(
['date','user_id']).sortlevel().astype('int64')
expected.name = 'whole_cost'
result1 = df.sort_index().groupby([pd.TimeGrouper(freq=freq), 'user_id'])['whole_cost'].sum()
assert_series_equal(result1, expected)
result2 = df.groupby([pd.TimeGrouper(freq=freq), 'user_id'])['whole_cost'].sum()
assert_series_equal(result2, expected)
def test_timegrouper_get_group(self):
# GH 6914
df_original = DataFrame({
'Buyer': 'Carl Joe Joe Carl Joe Carl'.split(),
'Quantity': [18,3,5,1,9,3],
'Date' : [datetime(2013,9,1,13,0), datetime(2013,9,1,13,5),
datetime(2013,10,1,20,0), datetime(2013,10,3,10,0),
datetime(2013,12,2,12,0), datetime(2013,9,2,14,0),]})
df_reordered = df_original.sort(columns='Quantity')
# single grouping
expected_list = [df_original.iloc[[0, 1, 5]], df_original.iloc[[2, 3]],
df_original.iloc[[4]]]
dt_list = ['2013-09-30', '2013-10-31', '2013-12-31']
for df in [df_original, df_reordered]:
grouped = df.groupby(pd.Grouper(freq='M', key='Date'))
for t, expected in zip(dt_list, expected_list):
dt = pd.Timestamp(t)
result = grouped.get_group(dt)
assert_frame_equal(result, expected)
# multiple grouping
expected_list = [df_original.iloc[[1]], df_original.iloc[[3]],
df_original.iloc[[4]]]
g_list = [('Joe', '2013-09-30'), ('Carl', '2013-10-31'), ('Joe', '2013-12-31')]
for df in [df_original, df_reordered]:
grouped = df.groupby(['Buyer', pd.Grouper(freq='M', key='Date')])
for (b, t), expected in zip(g_list, expected_list):
dt = pd.Timestamp(t)
result = grouped.get_group((b, dt))
assert_frame_equal(result, expected)
# with index
df_original = df_original.set_index('Date')
df_reordered = df_original.sort(columns='Quantity')
expected_list = [df_original.iloc[[0, 1, 5]], df_original.iloc[[2, 3]],
df_original.iloc[[4]]]
for df in [df_original, df_reordered]:
grouped = df.groupby(pd.Grouper(freq='M'))
for t, expected in zip(dt_list, expected_list):
dt = pd.Timestamp(t)
result = grouped.get_group(dt)
assert_frame_equal(result, expected)
def test_cumcount(self):
df = DataFrame([['a'], ['a'], ['a'], ['b'], ['a']], columns=['A'])
g = df.groupby('A')
sg = g.A
expected = Series([0, 1, 2, 0, 3])
assert_series_equal(expected, g.cumcount())
assert_series_equal(expected, sg.cumcount())
def test_cumcount_empty(self):
ge = DataFrame().groupby(level=0)
se = Series().groupby(level=0)
e = Series(dtype='int64') # edge case, as this is usually considered float
assert_series_equal(e, ge.cumcount())
assert_series_equal(e, se.cumcount())
def test_cumcount_dupe_index(self):
df = DataFrame([['a'], ['a'], ['a'], ['b'], ['a']], columns=['A'], index=[0] * 5)
g = df.groupby('A')
sg = g.A
expected = Series([0, 1, 2, 0, 3], index=[0] * 5)
assert_series_equal(expected, g.cumcount())
assert_series_equal(expected, sg.cumcount())
def test_cumcount_mi(self):
mi = MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]])
df = DataFrame([['a'], ['a'], ['a'], ['b'], ['a']], columns=['A'], index=mi)
g = df.groupby('A')
sg = g.A
expected = Series([0, 1, 2, 0, 3], index=mi)
assert_series_equal(expected, g.cumcount())
assert_series_equal(expected, sg.cumcount())
def test_cumcount_groupby_not_col(self):
df = DataFrame([['a'], ['a'], ['a'], ['b'], ['a']], columns=['A'], index=[0] * 5)
g = df.groupby([0, 0, 0, 1, 0])
sg = g.A
expected = Series([0, 1, 2, 0, 3], index=[0] * 5)
assert_series_equal(expected, g.cumcount())
assert_series_equal(expected, sg.cumcount())
def test_filter_series(self):
import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
expected_odd = pd.Series([1, 3, 5, 7], index=[0, 1, 3, 6])
expected_even = pd.Series([20, 22, 24], index=[2, 4, 5])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
assert_series_equal(
grouped.filter(lambda x: x.mean() < 10), expected_odd)
assert_series_equal(
grouped.filter(lambda x: x.mean() > 10), expected_even)
# Test dropna=False.
assert_series_equal(
grouped.filter(lambda x: x.mean() < 10, dropna=False),
expected_odd.reindex(s.index))
assert_series_equal(
grouped.filter(lambda x: x.mean() > 10, dropna=False),
expected_even.reindex(s.index))
def test_filter_single_column_df(self):
import pandas as pd
df = pd.DataFrame([1, 3, 20, 5, 22, 24, 7])
expected_odd = pd.DataFrame([1, 3, 5, 7], index=[0, 1, 3, 6])
expected_even = pd.DataFrame([20, 22, 24], index=[2, 4, 5])
grouper = df[0].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
assert_frame_equal(
grouped.filter(lambda x: x.mean() < 10), expected_odd)
assert_frame_equal(
grouped.filter(lambda x: x.mean() > 10), expected_even)
# Test dropna=False.
assert_frame_equal(
grouped.filter(lambda x: x.mean() < 10, dropna=False),
expected_odd.reindex(df.index))
assert_frame_equal(
grouped.filter(lambda x: x.mean() > 10, dropna=False),
expected_even.reindex(df.index))
def test_filter_multi_column_df(self):
import pandas as pd
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': [1, 1, 1, 1]})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
expected = pd.DataFrame({'A': [12, 12], 'B': [1, 1]}, index=[1, 2])
assert_frame_equal(
grouped.filter(lambda x: x['A'].sum() - x['B'].sum() > 10), expected)
def test_filter_mixed_df(self):
import pandas as pd
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': 'a b c d'.split()})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
expected = pd.DataFrame({'A': [12, 12], 'B': ['b', 'c']},
index=[1, 2])
assert_frame_equal(
grouped.filter(lambda x: x['A'].sum() > 10), expected)
def test_filter_out_all_groups(self):
import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
assert_series_equal(
grouped.filter(lambda x: x.mean() > 1000), s[[]])
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': 'a b c d'.split()})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
assert_frame_equal(
grouped.filter(lambda x: x['A'].sum() > 1000), df.ix[[]])
def test_filter_out_no_groups(self):
import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
filtered = grouped.filter(lambda x: x.mean() > 0)
assert_series_equal(filtered, s)
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': 'a b c d'.split()})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
filtered = grouped.filter(lambda x: x['A'].mean() > 0)
assert_frame_equal(filtered, df)
def test_filter_condition_raises(self):
import pandas as pd
def raise_if_sum_is_zero(x):
if x.sum() == 0:
raise ValueError
else:
return x.sum() > 0
s = pd.Series([-1,0,1,2])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
self.assertRaises(TypeError,
lambda: grouped.filter(raise_if_sum_is_zero))
def test_filter_bad_shapes(self):
df = DataFrame({'A': np.arange(8), 'B': list('aabbbbcc'), 'C': np.arange(8)})
s = df['B']
g_df = df.groupby('B')
g_s = s.groupby(s)
f = lambda x: x
self.assertRaises(TypeError, lambda: g_df.filter(f))
self.assertRaises(TypeError, lambda: g_s.filter(f))
f = lambda x: x == 1
self.assertRaises(TypeError, lambda: g_df.filter(f))
self.assertRaises(TypeError, lambda: g_s.filter(f))
f = lambda x: np.outer(x, x)
self.assertRaises(TypeError, lambda: g_df.filter(f))
self.assertRaises(TypeError, lambda: g_s.filter(f))
def test_filter_nan_is_false(self):
df = DataFrame({'A': np.arange(8), 'B': list('aabbbbcc'), 'C': np.arange(8)})
s = df['B']
g_df = df.groupby(df['B'])
g_s = s.groupby(s)
f = lambda x: np.nan
assert_frame_equal(g_df.filter(f), df.loc[[]])
assert_series_equal(g_s.filter(f), s[[]])
def test_filter_against_workaround(self):
np.random.seed(0)
# Series of ints
s = Series(np.random.randint(0,100,1000))
grouper = s.apply(lambda x: np.round(x, -1))
grouped = s.groupby(grouper)
f = lambda x: x.mean() > 10
old_way = s[grouped.transform(f).astype('bool')]
new_way = grouped.filter(f)
assert_series_equal(new_way.order(), old_way.order())
# Series of floats
s = 100*Series(np.random.random(1000))
grouper = s.apply(lambda x: np.round(x, -1))
grouped = s.groupby(grouper)
f = lambda x: x.mean() > 10
old_way = s[grouped.transform(f).astype('bool')]
new_way = grouped.filter(f)
assert_series_equal(new_way.order(), old_way.order())
# Set up DataFrame of ints, floats, strings.
from string import ascii_lowercase
letters = np.array(list(ascii_lowercase))
N = 1000
random_letters = letters.take(np.random.randint(0, 26, N))
df = DataFrame({'ints': Series(np.random.randint(0, 100, N)),
'floats': N/10*Series(np.random.random(N)),
'letters': Series(random_letters)})
# Group by ints; filter on floats.
grouped = df.groupby('ints')
old_way = df[grouped.floats.\
transform(lambda x: x.mean() > N/20).astype('bool')]
new_way = grouped.filter(lambda x: x['floats'].mean() > N/20)
assert_frame_equal(new_way, old_way)
# Group by floats (rounded); filter on strings.
grouper = df.floats.apply(lambda x: np.round(x, -1))
grouped = df.groupby(grouper)
old_way = df[grouped.letters.\
transform(lambda x: len(x) < N/10).astype('bool')]
new_way = grouped.filter(
lambda x: len(x.letters) < N/10)
assert_frame_equal(new_way, old_way)
# Group by strings; filter on ints.
grouped = df.groupby('letters')
old_way = df[grouped.ints.\
transform(lambda x: x.mean() > N/20).astype('bool')]
new_way = grouped.filter(lambda x: x['ints'].mean() > N/20)
assert_frame_equal(new_way, old_way)
def test_filter_using_len(self):
# BUG GH4447
df = DataFrame({'A': np.arange(8), 'B': list('aabbbbcc'), 'C': np.arange(8)})
grouped = df.groupby('B')
actual = grouped.filter(lambda x: len(x) > 2)
expected = DataFrame({'A': np.arange(2, 6), 'B': list('bbbb'), 'C': np.arange(2, 6)}, index=np.arange(2, 6))
assert_frame_equal(actual, expected)
actual = grouped.filter(lambda x: len(x) > 4)
expected = df.ix[[]]
assert_frame_equal(actual, expected)
# Series have always worked properly, but we'll test anyway.
s = df['B']
grouped = s.groupby(s)
actual = grouped.filter(lambda x: len(x) > 2)
expected = Series(4*['b'], index=np.arange(2, 6))
assert_series_equal(actual, expected)
actual = grouped.filter(lambda x: len(x) > 4)
expected = s[[]]
assert_series_equal(actual, expected)
def test_filter_maintains_ordering(self):
# Simple case: index is sequential. #4621
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]})
s = df['pid']
grouped = df.groupby('tag')
actual = grouped.filter(lambda x: len(x) > 1)
expected = df.iloc[[1, 2, 4, 7]]
assert_frame_equal(actual, expected)
grouped = s.groupby(df['tag'])
actual = grouped.filter(lambda x: len(x) > 1)
expected = s.iloc[[1, 2, 4, 7]]
assert_series_equal(actual, expected)
# Now index is sequentially decreasing.
df.index = np.arange(len(df) - 1, -1, -1)
s = df['pid']
grouped = df.groupby('tag')
actual = grouped.filter(lambda x: len(x) > 1)
expected = df.iloc[[1, 2, 4, 7]]
assert_frame_equal(actual, expected)
grouped = s.groupby(df['tag'])
actual = grouped.filter(lambda x: len(x) > 1)
expected = s.iloc[[1, 2, 4, 7]]
assert_series_equal(actual, expected)
# Index is shuffled.
SHUFFLED = [4, 6, 7, 2, 1, 0, 5, 3]
df.index = df.index[SHUFFLED]
s = df['pid']
grouped = df.groupby('tag')
actual = grouped.filter(lambda x: len(x) > 1)
expected = df.iloc[[1, 2, 4, 7]]
assert_frame_equal(actual, expected)
grouped = s.groupby(df['tag'])
actual = grouped.filter(lambda x: len(x) > 1)
expected = s.iloc[[1, 2, 4, 7]]
assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_int_index(self):
# GH4620
index = [1, 1, 1, 2, 1, 1, 0, 1]
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_and_transform_with_multiple_non_unique_int_index(self):
# GH4620
index = [1, 1, 1, 2, 0, 0, 0, 1]
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_float_index(self):
# GH4620
index = np.array([1, 1, 1, 2, 1, 1, 0, 1], dtype=float)
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_float_index(self):
# GH4620
index = np.array([1, 1, 1, 2, 0, 0, 0, 1], dtype=float)
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_timestamp_index(self):
# GH4620
t0 = Timestamp('2013-09-30 00:05:00')
t1 = Timestamp('2013-10-30 00:05:00')
t2 = Timestamp('2013-11-30 00:05:00')
index = [t1, t1, t1, t2, t1, t1, t0, t1]
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_string_index(self):
# GH4620
index = list('bbbcbbab')
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_has_access_to_grouped_cols(self):
df = DataFrame([[1, 2], [1, 3], [5, 6]], columns=['A', 'B'])
g = df.groupby('A')
# previously didn't have access to col A #????
filt = g.filter(lambda x: x['A'].sum() == 2)
assert_frame_equal(filt, df.iloc[[0, 1]])
def test_filter_enforces_scalarness(self):
df = pd.DataFrame([
['best', 'a', 'x'],
['worst', 'b', 'y'],
['best', 'c', 'x'],
['best','d', 'y'],
['worst','d', 'y'],
['worst','d', 'y'],
['best','d', 'z'],
], columns=['a', 'b', 'c'])
with tm.assertRaisesRegexp(TypeError, 'filter function returned a.*'):
df.groupby('c').filter(lambda g: g['a'] == 'best')
def test_filter_non_bool_raises(self):
df = pd.DataFrame([
['best', 'a', 1],
['worst', 'b', 1],
['best', 'c', 1],
['best','d', 1],
['worst','d', 1],
['worst','d', 1],
['best','d', 1],
], columns=['a', 'b', 'c'])
with tm.assertRaisesRegexp(TypeError, 'filter function returned a.*'):
df.groupby('a').filter(lambda g: g.c.mean())
def test_fill_constistency(self):
# GH9221
# pass thru keyword arguments to the generated wrapper
# are set if the passed kw is None (only)
df = DataFrame(index=pd.MultiIndex.from_product([['value1','value2'],
date_range('2014-01-01','2014-01-06')]),
columns=Index(['1','2'], name='id'))
df['1'] = [np.nan, 1, np.nan, np.nan, 11, np.nan, np.nan, 2, np.nan, np.nan, 22, np.nan]
df['2'] = [np.nan, 3, np.nan, np.nan, 33, np.nan, np.nan, 4, np.nan, np.nan, 44, np.nan]
expected = df.groupby(level=0, axis=0).fillna(method='ffill')
result = df.T.groupby(level=0, axis=1).fillna(method='ffill').T
assert_frame_equal(result, expected)
def test_index_label_overlaps_location(self):
# checking we don't have any label/location confusion in the
# the wake of GH5375
df = DataFrame(list('ABCDE'), index=[2, 0, 2, 1, 1])
g = df.groupby(list('ababb'))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
assert_frame_equal(actual, expected)
ser = df[0]
g = ser.groupby(list('ababb'))
actual = g.filter(lambda x: len(x) > 2)
expected = ser.take([1, 3, 4])
assert_series_equal(actual, expected)
# ... and again, with a generic Index of floats
df.index = df.index.astype(float)
g = df.groupby(list('ababb'))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
assert_frame_equal(actual, expected)
ser = df[0]
g = ser.groupby(list('ababb'))
actual = g.filter(lambda x: len(x) > 2)
expected = ser.take([1, 3, 4])
assert_series_equal(actual, expected)
def test_groupby_selection_with_methods(self):
# some methods which require DatetimeIndex
rng = pd.date_range('2014', periods=len(self.df))
self.df.index = rng
g = self.df.groupby(['A'])[['C']]
g_exp = self.df[['C']].groupby(self.df['A'])
# TODO check groupby with > 1 col ?
# methods which are called as .foo()
methods = ['count',
'corr',
'cummax', 'cummin', 'cumprod',
'describe', 'rank',
'quantile',
'diff', 'shift',
'all', 'any',
'idxmin', 'idxmax',
'ffill', 'bfill',
'pct_change',
'tshift',
#'ohlc'
]
for m in methods:
res = getattr(g, m)()
exp = getattr(g_exp, m)()
assert_frame_equal(res, exp) # should always be frames!
# methods which aren't just .foo()
assert_frame_equal(g.fillna(0), g_exp.fillna(0))
assert_frame_equal(g.dtypes, g_exp.dtypes)
assert_frame_equal(g.apply(lambda x: x.sum()),
g_exp.apply(lambda x: x.sum()))
assert_frame_equal(g.resample('D'), g_exp.resample('D'))
assert_frame_equal(g.resample('D', how='ohlc'),
g_exp.resample('D', how='ohlc'))
assert_frame_equal(g.filter(lambda x: len(x) == 3),
g_exp.filter(lambda x: len(x) == 3))
def test_groupby_whitelist(self):
from string import ascii_lowercase
letters = np.array(list(ascii_lowercase))
N = 10
random_letters = letters.take(np.random.randint(0, 26, N))
df = DataFrame({'floats': N / 10 * Series(np.random.random(N)),
'letters': Series(random_letters)})
s = df.floats
df_whitelist = frozenset([
'last', 'first',
'mean', 'sum', 'min', 'max',
'head', 'tail',
'cumsum', 'cumprod', 'cummin', 'cummax', 'cumcount',
'resample',
'describe',
'rank', 'quantile', 'count',
'fillna',
'mad',
'any', 'all',
'irow', 'take',
'idxmax', 'idxmin',
'shift', 'tshift',
'ffill', 'bfill',
'pct_change', 'skew',
'plot', 'boxplot', 'hist',
'median', 'dtypes',
'corrwith', 'corr', 'cov',
'diff',
])
s_whitelist = frozenset([
'last', 'first',
'mean', 'sum', 'min', 'max',
'head', 'tail',
'cumsum', 'cumprod', 'cummin', 'cummax', 'cumcount',
'resample',
'describe',
'rank', 'quantile', 'count',
'fillna',
'mad',
'any', 'all',
'irow', 'take',
'idxmax', 'idxmin',
'shift', 'tshift',
'ffill', 'bfill',
'pct_change', 'skew',
'plot', 'hist',
'median', 'dtype',
'corr', 'cov',
'value_counts',
'diff',
'unique', 'nunique',
'nlargest', 'nsmallest',
])
for obj, whitelist in zip((df, s),
(df_whitelist, s_whitelist)):
gb = obj.groupby(df.letters)
self.assertEqual(whitelist, gb._apply_whitelist)
for m in whitelist:
getattr(type(gb), m)
AGG_FUNCTIONS = ['sum', 'prod', 'min', 'max', 'median', 'mean', 'skew',
'mad', 'std', 'var', 'sem']
AGG_FUNCTIONS_WITH_SKIPNA = ['skew', 'mad']
def test_regression_whitelist_methods(self) :
# GH6944
# explicity test the whitelest methods
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
['one', 'two', 'three']],
labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
[0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
names=['first', 'second'])
raw_frame = DataFrame(np.random.randn(10, 3), index=index,
columns=Index(['A', 'B', 'C'], name='exp'))
raw_frame.ix[1, [1, 2]] = np.nan
raw_frame.ix[7, [0, 1]] = np.nan
for op, level, axis, skipna in cart_product(self.AGG_FUNCTIONS,
lrange(2), lrange(2),
[True,False]) :
if axis == 0 :
frame = raw_frame
else :
frame = raw_frame.T
if op in self.AGG_FUNCTIONS_WITH_SKIPNA :
grouped = frame.groupby(level=level,axis=axis)
result = getattr(grouped,op)(skipna=skipna)
expected = getattr(frame,op)(level=level,axis=axis,skipna=skipna)
assert_frame_equal(result, expected)
else :
grouped = frame.groupby(level=level,axis=axis)
result = getattr(grouped,op)()
expected = getattr(frame,op)(level=level,axis=axis)
assert_frame_equal(result, expected)
def test_groupby_blacklist(self):
from string import ascii_lowercase
letters = np.array(list(ascii_lowercase))
N = 10
random_letters = letters.take(np.random.randint(0, 26, N))
df = DataFrame({'floats': N / 10 * Series(np.random.random(N)),
'letters': Series(random_letters)})
s = df.floats
blacklist = [
'eval', 'query', 'abs', 'where',
'mask', 'align', 'groupby', 'clip', 'astype',
'at', 'combine', 'consolidate', 'convert_objects',
]
to_methods = [method for method in dir(df) if method.startswith('to_')]
blacklist.extend(to_methods)
# e.g., to_csv
defined_but_not_allowed = ("(?:^Cannot.+{0!r}.+{1!r}.+try using the "
"'apply' method$)")
# e.g., query, eval
not_defined = "(?:^{1!r} object has no attribute {0!r}$)"
fmt = defined_but_not_allowed + '|' + not_defined
for bl in blacklist:
for obj in (df, s):
gb = obj.groupby(df.letters)
msg = fmt.format(bl, type(gb).__name__)
with tm.assertRaisesRegexp(AttributeError, msg):
getattr(gb, bl)
def test_tab_completion(self):
grp = self.mframe.groupby(level='second')
results = set([v for v in dir(grp) if not v.startswith('_')])
expected = set(['A','B','C',
'agg','aggregate','apply','boxplot','filter','first','get_group',
'groups','hist','indices','last','max','mean','median',
'min','name','ngroups','nth','ohlc','plot', 'prod',
'size', 'std', 'sum', 'transform', 'var', 'sem', 'count', 'head',
'describe', 'cummax', 'quantile', 'rank', 'cumprod', 'tail',
'resample', 'cummin', 'fillna', 'cumsum', 'cumcount',
'all', 'shift', 'skew', 'bfill', 'irow', 'ffill',
'take', 'tshift', 'pct_change', 'any', 'mad', 'corr', 'corrwith',
'cov', 'dtypes', 'diff', 'idxmax', 'idxmin'
])
self.assertEqual(results, expected)
def test_lexsort_indexer(self):
keys = [[nan]*5 + list(range(100)) + [nan]*5]
# orders=True, na_position='last'
result = _lexsort_indexer(keys, orders=True, na_position='last')
expected = list(range(5, 105)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# orders=True, na_position='first'
result = _lexsort_indexer(keys, orders=True, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(5, 105))
assert_equal(result, expected)
# orders=False, na_position='last'
result = _lexsort_indexer(keys, orders=False, na_position='last')
expected = list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# orders=False, na_position='first'
result = _lexsort_indexer(keys, orders=False, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1))
assert_equal(result, expected)
def test_nargsort(self):
# np.argsort(items) places NaNs last
items = [nan]*5 + list(range(100)) + [nan]*5
# np.argsort(items2) may not place NaNs first
items2 = np.array(items, dtype='O')
try:
# GH 2785; due to a regression in NumPy1.6.2
np.argsort(np.array([[1, 2], [1, 3], [1, 2]], dtype='i'))
np.argsort(items2, kind='mergesort')
except TypeError as err:
raise nose.SkipTest('requested sort not available for type')
# mergesort is the most difficult to get right because we want it to be stable.
# According to numpy/core/tests/test_multiarray, """The number
# of sorted items must be greater than ~50 to check the actual algorithm
# because quick and merge sort fall over to insertion sort for small
# arrays."""
# mergesort, ascending=True, na_position='last'
result = _nargsort(
items, kind='mergesort', ascending=True, na_position='last')
expected = list(range(5, 105)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# mergesort, ascending=True, na_position='first'
result = _nargsort(
items, kind='mergesort', ascending=True, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(5, 105))
assert_equal(result, expected)
# mergesort, ascending=False, na_position='last'
result = _nargsort(
items, kind='mergesort', ascending=False, na_position='last')
expected = list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# mergesort, ascending=False, na_position='first'
result = _nargsort(
items, kind='mergesort', ascending=False, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1))
assert_equal(result, expected)
# mergesort, ascending=True, na_position='last'
result = _nargsort(
items2, kind='mergesort', ascending=True, na_position='last')
expected = list(range(5, 105)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# mergesort, ascending=True, na_position='first'
result = _nargsort(
items2, kind='mergesort', ascending=True, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(5, 105))
assert_equal(result, expected)
# mergesort, ascending=False, na_position='last'
result = _nargsort(
items2, kind='mergesort', ascending=False, na_position='last')
expected = list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# mergesort, ascending=False, na_position='first'
result = _nargsort(
items2, kind='mergesort', ascending=False, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1))
assert_equal(result, expected)
def test_datetime_count(self):
df = DataFrame({'a': [1,2,3] * 2,
'dates': pd.date_range('now', periods=6, freq='T')})
result = df.groupby('a').dates.count()
expected = Series([2, 2, 2], index=Index([1, 2, 3], name='a'),
name='dates')
tm.assert_series_equal(result, expected)
def test_lower_int_prec_count(self):
df = DataFrame({'a': np.array([0, 1, 2, 100], np.int8),
'b': np.array([1, 2, 3, 6], np.uint32),
'c': np.array([4, 5, 6, 8], np.int16),
'grp': list('ab' * 2)})
result = df.groupby('grp').count()
expected = DataFrame({'a': [2, 2],
'b': [2, 2],
'c': [2, 2]}, index=pd.Index(list('ab'),
name='grp'))
tm.assert_frame_equal(result, expected)
def test_count_uses_size_on_exception(self):
class RaisingObjectException(Exception):
pass
class RaisingObject(object):
def __init__(self, msg='I will raise inside Cython'):
super(RaisingObject, self).__init__()
self.msg = msg
def __eq__(self, other):
# gets called in Cython to check that raising calls the method
raise RaisingObjectException(self.msg)
df = DataFrame({'a': [RaisingObject() for _ in range(4)],
'grp': list('ab' * 2)})
result = df.groupby('grp').count()
expected = DataFrame({'a': [2, 2]}, index=pd.Index(list('ab'),
name='grp'))
tm.assert_frame_equal(result, expected)
def test__cython_agg_general(self):
ops = [('mean', np.mean),
('median', np.median),
('var', np.var),
('add', np.sum),
('prod', np.prod),
('min', np.min),
('max', np.max),
('first', lambda x: x.iloc[0]),
('last', lambda x: x.iloc[-1]),
('count', np.size),
]
df = DataFrame(np.random.randn(1000))
labels = np.random.randint(0, 50, size=1000).astype(float)
for op, targop in ops:
result = df.groupby(labels)._cython_agg_general(op)
expected = df.groupby(labels).agg(targop)
try:
tm.assert_frame_equal(result, expected)
except BaseException as exc:
exc.args += ('operation: %s' % op,)
raise
def test_ops_general(self):
ops = [('mean', np.mean),
('median', np.median),
('std', np.std),
('var', np.var),
('sum', np.sum),
('prod', np.prod),
('min', np.min),
('max', np.max),
('first', lambda x: x.iloc[0]),
('last', lambda x: x.iloc[-1]),
('count', np.size),
]
try:
from scipy.stats import sem
except ImportError:
pass
else:
ops.append(('sem', sem))
df = DataFrame(np.random.randn(1000))
labels = np.random.randint(0, 50, size=1000).astype(float)
for op, targop in ops:
result = getattr(df.groupby(labels), op)().astype(float)
expected = df.groupby(labels).agg(targop)
try:
tm.assert_frame_equal(result, expected)
except BaseException as exc:
exc.args += ('operation: %s' % op,)
raise
def test_max_nan_bug(self):
raw = """,Date,app,File
2013-04-23,2013-04-23 00:00:00,,log080001.log
2013-05-06,2013-05-06 00:00:00,,log.log
2013-05-07,2013-05-07 00:00:00,OE,xlsx"""
df = pd.read_csv(StringIO(raw), parse_dates=[0])
gb = df.groupby('Date')
r = gb[['File']].max()
e = gb['File'].max().to_frame()
tm.assert_frame_equal(r, e)
self.assertFalse(r['File'].isnull().any())
def test_nlargest(self):
a = Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10])
b = Series(list('a' * 5 + 'b' * 5))
gb = a.groupby(b)
r = gb.nlargest(3)
e = Series([7, 5, 3, 10, 9, 6],
index=MultiIndex.from_arrays([list('aaabbb'),
[3, 2, 1, 9, 5, 8]]))
tm.assert_series_equal(r, e)
def test_nsmallest(self):
a = Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10])
b = Series(list('a' * 5 + 'b' * 5))
gb = a.groupby(b)
r = gb.nsmallest(3)
e = Series([1, 2, 3, 0, 4, 6],
index=MultiIndex.from_arrays([list('aaabbb'),
[0, 4, 1, 6, 7, 8]]))
tm.assert_series_equal(r, e)
def test_transform_doesnt_clobber_ints(self):
# GH 7972
n = 6
x = np.arange(n)
df = DataFrame({'a': x // 2, 'b': 2.0 * x, 'c': 3.0 * x})
df2 = DataFrame({'a': x // 2 * 1.0, 'b': 2.0 * x, 'c': 3.0 * x})
gb = df.groupby('a')
result = gb.transform('mean')
gb2 = df2.groupby('a')
expected = gb2.transform('mean')
tm.assert_frame_equal(result, expected)
def test_groupby_categorical_two_columns(self):
# https://github.com/pydata/pandas/issues/8138
d = {'cat': pd.Categorical(["a","b","a","b"], categories=["a", "b", "c"], ordered=True),
'ints': [1, 1, 2, 2],'val': [10, 20, 30, 40]}
test = pd.DataFrame(d)
# Grouping on a single column
groups_single_key = test.groupby("cat")
res = groups_single_key.agg('mean')
exp = DataFrame({"ints":[1.5,1.5,np.nan], "val":[20,30,np.nan]},
index=pd.Index(["a", "b", "c"], name="cat"))
tm.assert_frame_equal(res, exp)
# Grouping on two columns
groups_double_key = test.groupby(["cat","ints"])
res = groups_double_key.agg('mean')
exp = DataFrame({"val":[10,30,20,40,np.nan,np.nan],
"cat": ["a","a","b","b","c","c"],
"ints": [1,2,1,2,1,2]}).set_index(["cat","ints"])
tm.assert_frame_equal(res, exp)
d = {'C1': [3, 3, 4, 5], 'C2': [1, 2, 3, 4], 'C3': [10, 100, 200, 34]}
test = pd.DataFrame(d)
values = pd.cut(test['C1'], [1, 2, 3, 6])
values.name = "cat"
groups_double_key = test.groupby([values,'C2'])
res = groups_double_key.agg('mean')
nan = np.nan
idx = MultiIndex.from_product([["(1, 2]", "(2, 3]", "(3, 6]"],[1,2,3,4]],
names=["cat", "C2"])
exp = DataFrame({"C1":[nan,nan,nan,nan, 3, 3,nan,nan, nan,nan, 4, 5],
"C3":[nan,nan,nan,nan, 10,100,nan,nan, nan,nan,200,34]}, index=idx)
tm.assert_frame_equal(res, exp)
def assert_fp_equal(a, b):
assert (np.abs(a - b) < 1e-12).all()
def _check_groupby(df, result, keys, field, f=lambda x: x.sum()):
tups = lmap(tuple, df[keys].values)
tups = com._asarray_tuplesafe(tups)
expected = f(df.groupby(tups)[field])
for k, v in compat.iteritems(expected):
assert(result[k] == v)
def test_decons():
from pandas.core.groupby import decons_group_index, get_group_index
def testit(label_list, shape):
group_index = get_group_index(label_list, shape, sort=True, xnull=True)
label_list2 = decons_group_index(group_index, shape)
for a, b in zip(label_list, label_list2):
assert(np.array_equal(a, b))
shape = (4, 5, 6)
label_list = [np.tile([0, 1, 2, 3, 0, 1, 2, 3], 100),
np.tile([0, 2, 4, 3, 0, 1, 2, 3], 100),
np.tile([5, 1, 0, 2, 3, 0, 5, 4], 100)]
testit(label_list, shape)
shape = (10000, 10000)
label_list = [np.tile(np.arange(10000), 5),
np.tile(np.arange(10000), 5)]
testit(label_list, shape)
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure',
'-s'], exit=False)
| # -*- coding: utf-8 -*-
from __future__ import print_function
import nose
from numpy.testing.decorators import slow
from datetime import datetime
from numpy import nan
from pandas import date_range,bdate_range, Timestamp
from pandas.core.index import Index, MultiIndex, Int64Index
from pandas.core.api import Categorical, DataFrame
from pandas.core.groupby import (SpecificationError, DataError,
_nargsort, _lexsort_indexer)
from pandas.core.series import Series
from pandas.core.config import option_context
from pandas.util.testing import (assert_panel_equal, assert_frame_equal,
assert_series_equal, assert_almost_equal,
assert_index_equal, assertRaisesRegexp)
from pandas.compat import(
range, long, lrange, StringIO, lmap, lzip, map,
zip, builtins, OrderedDict, product as cart_product
)
from pandas import compat
from pandas.core.panel import Panel
from pandas.tools.merge import concat
from collections import defaultdict
from functools import partial
import pandas.core.common as com
import numpy as np
import pandas.core.nanops as nanops
import pandas.util.testing as tm
import pandas as pd
from numpy.testing import assert_equal
def commonSetUp(self):
self.dateRange = bdate_range('1/1/2005', periods=250)
self.stringIndex = Index([rands(8).upper() for x in range(250)])
self.groupId = Series([x[0] for x in self.stringIndex],
index=self.stringIndex)
self.groupDict = dict((k, v) for k, v in compat.iteritems(self.groupId))
self.columnIndex = Index(['A', 'B', 'C', 'D', 'E'])
randMat = np.random.randn(250, 5)
self.stringMatrix = DataFrame(randMat, columns=self.columnIndex,
index=self.stringIndex)
self.timeMatrix = DataFrame(randMat, columns=self.columnIndex,
index=self.dateRange)
class TestGroupBy(tm.TestCase):
_multiprocess_can_split_ = True
def setUp(self):
self.ts = tm.makeTimeSeries()
self.seriesd = tm.getSeriesData()
self.tsd = tm.getTimeSeriesData()
self.frame = DataFrame(self.seriesd)
self.tsframe = DataFrame(self.tsd)
self.df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8)})
self.df_mixed_floats = DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.array(np.random.randn(8),
dtype='float32')})
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
['one', 'two', 'three']],
labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
[0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
names=['first', 'second'])
self.mframe = DataFrame(np.random.randn(10, 3), index=index,
columns=['A', 'B', 'C'])
self.three_group = DataFrame({'A': ['foo', 'foo', 'foo', 'foo',
'bar', 'bar', 'bar', 'bar',
'foo', 'foo', 'foo'],
'B': ['one', 'one', 'one', 'two',
'one', 'one', 'one', 'two',
'two', 'two', 'one'],
'C': ['dull', 'dull', 'shiny', 'dull',
'dull', 'shiny', 'shiny', 'dull',
'shiny', 'shiny', 'shiny'],
'D': np.random.randn(11),
'E': np.random.randn(11),
'F': np.random.randn(11)})
def test_basic(self):
def checkit(dtype):
data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype)
index = np.arange(9)
np.random.shuffle(index)
data = data.reindex(index)
grouped = data.groupby(lambda x: x // 3)
for k, v in grouped:
self.assertEqual(len(v), 3)
agged = grouped.aggregate(np.mean)
self.assertEqual(agged[1], 1)
assert_series_equal(agged, grouped.agg(np.mean)) # shorthand
assert_series_equal(agged, grouped.mean())
assert_series_equal(grouped.agg(np.sum), grouped.sum())
expected = grouped.apply(lambda x: x * x.sum())
transformed = grouped.transform(lambda x: x * x.sum())
self.assertEqual(transformed[7], 12)
assert_series_equal(transformed, expected)
value_grouped = data.groupby(data)
assert_series_equal(value_grouped.aggregate(np.mean), agged)
# complex agg
agged = grouped.aggregate([np.mean, np.std])
agged = grouped.aggregate({'one': np.mean,
'two': np.std})
group_constants = {
0: 10,
1: 20,
2: 30
}
agged = grouped.agg(lambda x: group_constants[x.name] + x.mean())
self.assertEqual(agged[1], 21)
# corner cases
self.assertRaises(Exception, grouped.aggregate, lambda x: x * 2)
for dtype in ['int64', 'int32', 'float64', 'float32']:
checkit(dtype)
def test_select_bad_cols(self):
df = DataFrame([[1, 2]], columns=['A', 'B'])
g = df.groupby('A')
self.assertRaises(KeyError, g.__getitem__, ['C']) # g[['C']]
self.assertRaises(KeyError, g.__getitem__, ['A', 'C']) # g[['A', 'C']]
with assertRaisesRegexp(KeyError, '^[^A]+$'):
# A should not be referenced as a bad column...
# will have to rethink regex if you change message!
g[['A', 'C']]
def test_first_last_nth(self):
# tests for first / last / nth
grouped = self.df.groupby('A')
first = grouped.first()
expected = self.df.ix[[1, 0], ['B','C','D']]
expected.index = Index(['bar', 'foo'],name='A')
expected = expected.sort_index()
assert_frame_equal(first, expected)
nth = grouped.nth(0)
assert_frame_equal(nth, expected)
last = grouped.last()
expected = self.df.ix[[5, 7], ['B','C','D']]
expected.index = Index(['bar', 'foo'],name='A')
assert_frame_equal(last, expected)
nth = grouped.nth(-1)
assert_frame_equal(nth, expected)
nth = grouped.nth(1)
expected = self.df.ix[[2, 3],['B','C','D']].copy()
expected.index = Index(['foo', 'bar'],name='A')
expected = expected.sort_index()
assert_frame_equal(nth, expected)
# it works!
grouped['B'].first()
grouped['B'].last()
grouped['B'].nth(0)
self.df.loc[self.df['A'] == 'foo', 'B'] = np.nan
self.assertTrue(com.isnull(grouped['B'].first()['foo']))
self.assertTrue(com.isnull(grouped['B'].last()['foo']))
self.assertTrue(com.isnull(grouped['B'].nth(0)[0])) # not sure what this is testing
# v0.14.0 whatsnew
df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
g = df.groupby('A')
result = g.first()
expected = df.iloc[[1,2]].set_index('A')
assert_frame_equal(result, expected)
expected = df.iloc[[1,2]].set_index('A')
result = g.nth(0,dropna='any')
assert_frame_equal(result, expected)
def test_first_last_nth_dtypes(self):
df = self.df_mixed_floats.copy()
df['E'] = True
df['F'] = 1
# tests for first / last / nth
grouped = df.groupby('A')
first = grouped.first()
expected = df.ix[[1, 0], ['B', 'C', 'D', 'E', 'F']]
expected.index = Index(['bar', 'foo'], name='A')
expected = expected.sort_index()
assert_frame_equal(first, expected)
last = grouped.last()
expected = df.ix[[5, 7], ['B', 'C', 'D', 'E', 'F']]
expected.index = Index(['bar', 'foo'], name='A')
expected = expected.sort_index()
assert_frame_equal(last, expected)
nth = grouped.nth(1)
expected = df.ix[[3, 2],['B', 'C', 'D', 'E', 'F']]
expected.index = Index(['bar', 'foo'], name='A')
expected = expected.sort_index()
assert_frame_equal(nth, expected)
# GH 2763, first/last shifting dtypes
idx = lrange(10)
idx.append(9)
s = Series(data=lrange(11), index=idx, name='IntCol')
self.assertEqual(s.dtype, 'int64')
f = s.groupby(level=0).first()
self.assertEqual(f.dtype, 'int64')
def test_nth(self):
df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
g = df.groupby('A')
assert_frame_equal(g.nth(0), df.iloc[[0, 2]].set_index('A'))
assert_frame_equal(g.nth(1), df.iloc[[1]].set_index('A'))
assert_frame_equal(g.nth(2), df.loc[[],['B']])
assert_frame_equal(g.nth(-1), df.iloc[[1, 2]].set_index('A'))
assert_frame_equal(g.nth(-2), df.iloc[[0]].set_index('A'))
assert_frame_equal(g.nth(-3), df.loc[[],['B']])
assert_series_equal(g.B.nth(0), df.B.iloc[[0, 2]])
assert_series_equal(g.B.nth(1), df.B.iloc[[1]])
assert_frame_equal(g[['B']].nth(0), df.ix[[0, 2], ['A', 'B']].set_index('A'))
exp = df.set_index('A')
assert_frame_equal(g.nth(0, dropna='any'), exp.iloc[[1, 2]])
assert_frame_equal(g.nth(-1, dropna='any'), exp.iloc[[1, 2]])
exp['B'] = np.nan
assert_frame_equal(g.nth(7, dropna='any'), exp.iloc[[1, 2]])
assert_frame_equal(g.nth(2, dropna='any'), exp.iloc[[1, 2]])
# out of bounds, regression from 0.13.1
# GH 6621
df = DataFrame({'color': {0: 'green', 1: 'green', 2: 'red', 3: 'red', 4: 'red'},
'food': {0: 'ham', 1: 'eggs', 2: 'eggs', 3: 'ham', 4: 'pork'},
'two': {0: 1.5456590000000001, 1: -0.070345000000000005, 2: -2.4004539999999999, 3: 0.46206000000000003, 4: 0.52350799999999997},
'one': {0: 0.56573799999999996, 1: -0.9742360000000001, 2: 1.033801, 3: -0.78543499999999999, 4: 0.70422799999999997}}).set_index(['color', 'food'])
result = df.groupby(level=0).nth(2)
expected = df.iloc[[-1]]
assert_frame_equal(result,expected)
result = df.groupby(level=0).nth(3)
expected = df.loc[[]]
assert_frame_equal(result,expected)
# GH 7559
# from the vbench
df = DataFrame(np.random.randint(1, 10, (100, 2)),dtype='int64')
s = df[1]
g = df[0]
expected = s.groupby(g).first()
expected2 = s.groupby(g).apply(lambda x: x.iloc[0])
assert_series_equal(expected2,expected)
# validate first
v = s[g==1].iloc[0]
self.assertEqual(expected.iloc[0],v)
self.assertEqual(expected2.iloc[0],v)
# this is NOT the same as .first (as sorted is default!)
# as it keeps the order in the series (and not the group order)
# related GH 7287
expected = s.groupby(g,sort=False).first()
expected.index = range(1,10)
result = s.groupby(g).nth(0,dropna='all')
assert_series_equal(result,expected)
# doc example
df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
g = df.groupby('A')
result = g.B.nth(0, dropna=True)
expected = g.B.first()
assert_series_equal(result,expected)
# test multiple nth values
df = DataFrame([[1, np.nan], [1, 3], [1, 4], [5, 6], [5, 7]],
columns=['A', 'B'])
g = df.groupby('A')
assert_frame_equal(g.nth(0), df.iloc[[0, 3]].set_index('A'))
assert_frame_equal(g.nth([0]), df.iloc[[0, 3]].set_index('A'))
assert_frame_equal(g.nth([0, 1]), df.iloc[[0, 1, 3, 4]].set_index('A'))
assert_frame_equal(g.nth([0, -1]), df.iloc[[0, 2, 3, 4]].set_index('A'))
assert_frame_equal(g.nth([0, 1, 2]), df.iloc[[0, 1, 2, 3, 4]].set_index('A'))
assert_frame_equal(g.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]].set_index('A'))
assert_frame_equal(g.nth([2]), df.iloc[[2]].set_index('A'))
assert_frame_equal(g.nth([3, 4]), df.loc[[],['B']])
business_dates = pd.date_range(start='4/1/2014', end='6/30/2014', freq='B')
df = DataFrame(1, index=business_dates, columns=['a', 'b'])
# get the first, fourth and last two business days for each month
result = df.groupby((df.index.year, df.index.month)).nth([0, 3, -2, -1])
expected_dates = pd.to_datetime(['2014/4/1', '2014/4/4', '2014/4/29', '2014/4/30',
'2014/5/1', '2014/5/6', '2014/5/29', '2014/5/30',
'2014/6/2', '2014/6/5', '2014/6/27', '2014/6/30'])
expected = DataFrame(1, columns=['a', 'b'], index=expected_dates)
assert_frame_equal(result, expected)
def test_nth_multi_index(self):
# PR 9090, related to issue 8979
# test nth on MultiIndex, should match .first()
grouped = self.three_group.groupby(['A', 'B'])
result = grouped.nth(0)
expected = grouped.first()
assert_frame_equal(result, expected)
def test_nth_multi_index_as_expected(self):
# PR 9090, related to issue 8979
# test nth on MultiIndex
three_group = DataFrame({'A': ['foo', 'foo', 'foo', 'foo',
'bar', 'bar', 'bar', 'bar',
'foo', 'foo', 'foo'],
'B': ['one', 'one', 'one', 'two',
'one', 'one', 'one', 'two',
'two', 'two', 'one'],
'C': ['dull', 'dull', 'shiny', 'dull',
'dull', 'shiny', 'shiny', 'dull',
'shiny', 'shiny', 'shiny']})
grouped = three_group.groupby(['A', 'B'])
result = grouped.nth(0)
expected = DataFrame({'C': ['dull', 'dull', 'dull', 'dull']},
index=MultiIndex.from_arrays([['bar', 'bar', 'foo', 'foo'], ['one', 'two', 'one', 'two']],
names=['A', 'B']))
assert_frame_equal(result, expected)
def test_grouper_index_types(self):
# related GH5375
# groupby misbehaving when using a Floatlike index
df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))
for index in [ tm.makeFloatIndex, tm.makeStringIndex,
tm.makeUnicodeIndex, tm.makeIntIndex,
tm.makeDateIndex, tm.makePeriodIndex ]:
df.index = index(len(df))
df.groupby(list('abcde')).apply(lambda x: x)
df.index = list(reversed(df.index.tolist()))
df.groupby(list('abcde')).apply(lambda x: x)
def test_grouper_multilevel_freq(self):
# GH 7885
# with level and freq specified in a pd.Grouper
from datetime import date, timedelta
d0 = date.today() - timedelta(days=14)
dates = date_range(d0, date.today())
date_index = pd.MultiIndex.from_product([dates, dates], names=['foo', 'bar'])
df = pd.DataFrame(np.random.randint(0, 100, 225), index=date_index)
# Check string level
expected = df.reset_index().groupby([pd.Grouper(key='foo', freq='W'),
pd.Grouper(key='bar', freq='W')]).sum()
result = df.groupby([pd.Grouper(level='foo', freq='W'),
pd.Grouper(level='bar', freq='W')]).sum()
assert_frame_equal(result, expected)
# Check integer level
result = df.groupby([pd.Grouper(level=0, freq='W'),
pd.Grouper(level=1, freq='W')]).sum()
assert_frame_equal(result, expected)
def test_grouper_creation_bug(self):
# GH 8795
df = DataFrame({'A':[0,0,1,1,2,2], 'B':[1,2,3,4,5,6]})
g = df.groupby('A')
expected = g.sum()
g = df.groupby(pd.Grouper(key='A'))
result = g.sum()
assert_frame_equal(result, expected)
result = g.apply(lambda x: x.sum())
assert_frame_equal(result, expected)
g = df.groupby(pd.Grouper(key='A',axis=0))
result = g.sum()
assert_frame_equal(result, expected)
# GH8866
s = Series(np.arange(8,dtype='int64'),
index=pd.MultiIndex.from_product([list('ab'),
range(2),
date_range('20130101',periods=2)],
names=['one','two','three']))
result = s.groupby(pd.Grouper(level='three',freq='M')).sum()
expected = Series([28],index=Index([Timestamp('2013-01-31')],freq='M',name='three'))
assert_series_equal(result, expected)
# just specifying a level breaks
result = s.groupby(pd.Grouper(level='one')).sum()
expected = s.groupby(level='one').sum()
assert_series_equal(result, expected)
def test_grouper_iter(self):
self.assertEqual(sorted(self.df.groupby('A').grouper), ['bar', 'foo'])
def test_empty_groups(self):
# GH # 1048
self.assertRaises(ValueError, self.df.groupby, [])
def test_groupby_grouper(self):
grouped = self.df.groupby('A')
result = self.df.groupby(grouped.grouper).mean()
expected = grouped.mean()
assert_frame_equal(result, expected)
def test_groupby_duplicated_column_errormsg(self):
# GH7511
df = DataFrame(columns=['A','B','A','C'], \
data=[range(4), range(2,6), range(0, 8, 2)])
self.assertRaises(ValueError, df.groupby, 'A')
self.assertRaises(ValueError, df.groupby, ['A', 'B'])
grouped = df.groupby('B')
c = grouped.count()
self.assertTrue(c.columns.nlevels == 1)
self.assertTrue(c.columns.size == 3)
def test_groupby_dict_mapping(self):
# GH #679
from pandas import Series
s = Series({'T1': 5})
result = s.groupby({'T1': 'T2'}).agg(sum)
expected = s.groupby(['T2']).agg(sum)
assert_series_equal(result, expected)
s = Series([1., 2., 3., 4.], index=list('abcd'))
mapping = {'a': 0, 'b': 0, 'c': 1, 'd': 1}
result = s.groupby(mapping).mean()
result2 = s.groupby(mapping).agg(np.mean)
expected = s.groupby([0, 0, 1, 1]).mean()
expected2 = s.groupby([0, 0, 1, 1]).mean()
assert_series_equal(result, expected)
assert_series_equal(result, result2)
assert_series_equal(result, expected2)
def test_groupby_bounds_check(self):
import pandas as pd
# groupby_X is code-generated, so if one variant
# does, the rest probably do to
a = np.array([1,2],dtype='object')
b = np.array([1,2,3],dtype='object')
self.assertRaises(AssertionError, pd.algos.groupby_object,a, b)
def test_groupby_grouper_f_sanity_checked(self):
import pandas as pd
dates = date_range('01-Jan-2013', periods=12, freq='MS')
ts = pd.TimeSeries(np.random.randn(12), index=dates)
# GH3035
# index.map is used to apply grouper to the index
# if it fails on the elements, map tries it on the entire index as
# a sequence. That can yield invalid results that cause trouble
# down the line.
# the surprise comes from using key[0:6] rather then str(key)[0:6]
# when the elements are Timestamp.
# the result is Index[0:6], very confusing.
self.assertRaises(AssertionError, ts.groupby,lambda key: key[0:6])
def test_groupby_nonobject_dtype(self):
key = self.mframe.index.labels[0]
grouped = self.mframe.groupby(key)
result = grouped.sum()
expected = self.mframe.groupby(key.astype('O')).sum()
assert_frame_equal(result, expected)
# GH 3911, mixed frame non-conversion
df = self.df_mixed_floats.copy()
df['value'] = lrange(len(df))
def max_value(group):
return group.ix[group['value'].idxmax()]
applied = df.groupby('A').apply(max_value)
result = applied.get_dtype_counts()
result.sort()
expected = Series({ 'object' : 2, 'float64' : 2, 'int64' : 1 })
expected.sort()
assert_series_equal(result,expected)
def test_groupby_return_type(self):
# GH2893, return a reduced type
df1 = DataFrame([{"val1": 1, "val2" : 20}, {"val1":1, "val2": 19},
{"val1":2, "val2": 27}, {"val1":2, "val2": 12}])
def func(dataf):
return dataf["val2"] - dataf["val2"].mean()
result = df1.groupby("val1", squeeze=True).apply(func)
tm.assert_isinstance(result,Series)
df2 = DataFrame([{"val1": 1, "val2" : 20}, {"val1":1, "val2": 19},
{"val1":1, "val2": 27}, {"val1":1, "val2": 12}])
def func(dataf):
return dataf["val2"] - dataf["val2"].mean()
result = df2.groupby("val1", squeeze=True).apply(func)
tm.assert_isinstance(result,Series)
# GH3596, return a consistent type (regression in 0.11 from 0.10.1)
df = DataFrame([[1,1],[1,1]],columns=['X','Y'])
result = df.groupby('X',squeeze=False).count()
tm.assert_isinstance(result,DataFrame)
# GH5592
# inconcistent return type
df = DataFrame(dict(A = [ 'Tiger', 'Tiger', 'Tiger', 'Lamb', 'Lamb', 'Pony', 'Pony' ],
B = Series(np.arange(7),dtype='int64'),
C = date_range('20130101',periods=7)))
def f(grp):
return grp.iloc[0]
expected = df.groupby('A').first()[['B']]
result = df.groupby('A').apply(f)[['B']]
assert_frame_equal(result,expected)
def f(grp):
if grp.name == 'Tiger':
return None
return grp.iloc[0]
result = df.groupby('A').apply(f)[['B']]
e = expected.copy()
e.loc['Tiger'] = np.nan
assert_frame_equal(result,e)
def f(grp):
if grp.name == 'Pony':
return None
return grp.iloc[0]
result = df.groupby('A').apply(f)[['B']]
e = expected.copy()
e.loc['Pony'] = np.nan
assert_frame_equal(result,e)
# 5592 revisited, with datetimes
def f(grp):
if grp.name == 'Pony':
return None
return grp.iloc[0]
result = df.groupby('A').apply(f)[['C']]
e = df.groupby('A').first()[['C']]
e.loc['Pony'] = np.nan
assert_frame_equal(result,e)
# scalar outputs
def f(grp):
if grp.name == 'Pony':
return None
return grp.iloc[0].loc['C']
result = df.groupby('A').apply(f)
e = df.groupby('A').first()['C'].copy()
e.loc['Pony'] = np.nan
e.name = None
assert_series_equal(result,e)
def test_agg_api(self):
# GH 6337
# http://stackoverflow.com/questions/21706030/pandas-groupby-agg-function-column-dtype-error
# different api for agg when passed custom function with mixed frame
df = DataFrame({'data1':np.random.randn(5),
'data2':np.random.randn(5),
'key1':['a','a','b','b','a'],
'key2':['one','two','one','two','one']})
grouped = df.groupby('key1')
def peak_to_peak(arr):
return arr.max() - arr.min()
expected = grouped.agg([peak_to_peak])
expected.columns=['data1','data2']
result = grouped.agg(peak_to_peak)
assert_frame_equal(result,expected)
def test_agg_regression1(self):
grouped = self.tsframe.groupby([lambda x: x.year, lambda x: x.month])
result = grouped.agg(np.mean)
expected = grouped.mean()
assert_frame_equal(result, expected)
def test_agg_datetimes_mixed(self):
data = [[1, '2012-01-01', 1.0],
[2, '2012-01-02', 2.0],
[3, None, 3.0]]
df1 = DataFrame({'key': [x[0] for x in data],
'date': [x[1] for x in data],
'value': [x[2] for x in data]})
data = [[row[0], datetime.strptime(row[1], '%Y-%m-%d').date()
if row[1] else None, row[2]] for row in data]
df2 = DataFrame({'key': [x[0] for x in data],
'date': [x[1] for x in data],
'value': [x[2] for x in data]})
df1['weights'] = df1['value'] / df1['value'].sum()
gb1 = df1.groupby('date').aggregate(np.sum)
df2['weights'] = df1['value'] / df1['value'].sum()
gb2 = df2.groupby('date').aggregate(np.sum)
assert(len(gb1) == len(gb2))
def test_agg_period_index(self):
from pandas import period_range, PeriodIndex
prng = period_range('2012-1-1', freq='M', periods=3)
df = DataFrame(np.random.randn(3, 2), index=prng)
rs = df.groupby(level=0).sum()
tm.assert_isinstance(rs.index, PeriodIndex)
# GH 3579
index = period_range(start='1999-01', periods=5, freq='M')
s1 = Series(np.random.rand(len(index)), index=index)
s2 = Series(np.random.rand(len(index)), index=index)
series = [('s1', s1), ('s2',s2)]
df = DataFrame.from_items(series)
grouped = df.groupby(df.index.month)
list(grouped)
def test_agg_must_agg(self):
grouped = self.df.groupby('A')['C']
self.assertRaises(Exception, grouped.agg, lambda x: x.describe())
self.assertRaises(Exception, grouped.agg, lambda x: x.index[:2])
def test_agg_ser_multi_key(self):
ser = self.df.C
f = lambda x: x.sum()
results = self.df.C.groupby([self.df.A, self.df.B]).aggregate(f)
expected = self.df.groupby(['A', 'B']).sum()['C']
assert_series_equal(results, expected)
def test_get_group(self):
wp = tm.makePanel()
grouped = wp.groupby(lambda x: x.month, axis='major')
gp = grouped.get_group(1)
expected = wp.reindex(major=[x for x in wp.major_axis if x.month == 1])
assert_panel_equal(gp, expected)
# GH 5267
# be datelike friendly
df = DataFrame({'DATE' : pd.to_datetime(['10-Oct-2013', '10-Oct-2013', '10-Oct-2013',
'11-Oct-2013', '11-Oct-2013', '11-Oct-2013']),
'label' : ['foo','foo','bar','foo','foo','bar'],
'VAL' : [1,2,3,4,5,6]})
g = df.groupby('DATE')
key = list(g.groups)[0]
result1 = g.get_group(key)
result2 = g.get_group(Timestamp(key).to_datetime())
result3 = g.get_group(str(Timestamp(key)))
assert_frame_equal(result1,result2)
assert_frame_equal(result1,result3)
g = df.groupby(['DATE','label'])
key = list(g.groups)[0]
result1 = g.get_group(key)
result2 = g.get_group((Timestamp(key[0]).to_datetime(),key[1]))
result3 = g.get_group((str(Timestamp(key[0])),key[1]))
assert_frame_equal(result1,result2)
assert_frame_equal(result1,result3)
# must pass a same-length tuple with multiple keys
self.assertRaises(ValueError, lambda : g.get_group('foo'))
self.assertRaises(ValueError, lambda : g.get_group(('foo')))
self.assertRaises(ValueError, lambda : g.get_group(('foo','bar','baz')))
def test_get_group_grouped_by_tuple(self):
# GH 8121
df = DataFrame([[(1,), (1, 2), (1,), (1, 2)]],
index=['ids']).T
gr = df.groupby('ids')
expected = DataFrame({'ids': [(1,), (1,)]}, index=[0, 2])
result = gr.get_group((1,))
assert_frame_equal(result, expected)
dt = pd.to_datetime(['2010-01-01', '2010-01-02', '2010-01-01',
'2010-01-02'])
df = DataFrame({'ids': [(x,) for x in dt]})
gr = df.groupby('ids')
result = gr.get_group(('2010-01-01',))
expected = DataFrame({'ids': [(dt[0],), (dt[0],)]}, index=[0, 2])
assert_frame_equal(result, expected)
def test_agg_apply_corner(self):
# nothing to group, all NA
grouped = self.ts.groupby(self.ts * np.nan)
assert_series_equal(grouped.sum(), Series([]))
assert_series_equal(grouped.agg(np.sum), Series([]))
assert_series_equal(grouped.apply(np.sum), Series([]))
# DataFrame
grouped = self.tsframe.groupby(self.tsframe['A'] * np.nan)
exp_df = DataFrame(columns=self.tsframe.columns, dtype=float)
assert_frame_equal(grouped.sum(), exp_df, check_names=False)
assert_frame_equal(grouped.agg(np.sum), exp_df, check_names=False)
assert_frame_equal(grouped.apply(np.sum), DataFrame({}, dtype=float))
def test_agg_grouping_is_list_tuple(self):
from pandas.core.groupby import Grouping
df = tm.makeTimeDataFrame()
grouped = df.groupby(lambda x: x.year)
grouper = grouped.grouper.groupings[0].grouper
grouped.grouper.groupings[0] = Grouping(self.ts.index, list(grouper))
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
grouped.grouper.groupings[0] = Grouping(self.ts.index, tuple(grouper))
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_grouping_error_on_multidim_input(self):
from pandas.core.groupby import Grouping
self.assertRaises(ValueError, \
Grouping, self.df.index, self.df[['A','A']])
def test_agg_python_multiindex(self):
grouped = self.mframe.groupby(['A', 'B'])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_apply_describe_bug(self):
grouped = self.mframe.groupby(level='first')
result = grouped.describe() # it works!
def test_apply_issues(self):
# GH 5788
s="""2011.05.16,00:00,1.40893
2011.05.16,01:00,1.40760
2011.05.16,02:00,1.40750
2011.05.16,03:00,1.40649
2011.05.17,02:00,1.40893
2011.05.17,03:00,1.40760
2011.05.17,04:00,1.40750
2011.05.17,05:00,1.40649
2011.05.18,02:00,1.40893
2011.05.18,03:00,1.40760
2011.05.18,04:00,1.40750
2011.05.18,05:00,1.40649"""
df = pd.read_csv(StringIO(s), header=None, names=['date', 'time', 'value'], parse_dates=[['date', 'time']])
df = df.set_index('date_time')
expected = df.groupby(df.index.date).idxmax()
result = df.groupby(df.index.date).apply(lambda x: x.idxmax())
assert_frame_equal(result,expected)
# GH 5789
# don't auto coerce dates
df = pd.read_csv(StringIO(s), header=None, names=['date', 'time', 'value'])
expected = Series(['00:00','02:00','02:00'],index=['2011.05.16','2011.05.17','2011.05.18'])
result = df.groupby('date').apply(lambda x: x['time'][x['value'].idxmax()])
assert_series_equal(result,expected)
def test_len(self):
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year,
lambda x: x.month,
lambda x: x.day])
self.assertEqual(len(grouped), len(df))
grouped = df.groupby([lambda x: x.year,
lambda x: x.month])
expected = len(set([(x.year, x.month) for x in df.index]))
self.assertEqual(len(grouped), expected)
def test_groups(self):
grouped = self.df.groupby(['A'])
groups = grouped.groups
self.assertIs(groups, grouped.groups) # caching works
for k, v in compat.iteritems(grouped.groups):
self.assertTrue((self.df.ix[v]['A'] == k).all())
grouped = self.df.groupby(['A', 'B'])
groups = grouped.groups
self.assertIs(groups, grouped.groups) # caching works
for k, v in compat.iteritems(grouped.groups):
self.assertTrue((self.df.ix[v]['A'] == k[0]).all())
self.assertTrue((self.df.ix[v]['B'] == k[1]).all())
def test_aggregate_str_func(self):
def _check_results(grouped):
# single series
result = grouped['A'].agg('std')
expected = grouped['A'].std()
assert_series_equal(result, expected)
# group frame by function name
result = grouped.aggregate('var')
expected = grouped.var()
assert_frame_equal(result, expected)
# group frame by function dict
result = grouped.agg(OrderedDict([['A', 'var'],
['B', 'std'],
['C', 'mean'],
['D', 'sem']]))
expected = DataFrame(OrderedDict([['A', grouped['A'].var()],
['B', grouped['B'].std()],
['C', grouped['C'].mean()],
['D', grouped['D'].sem()]]))
assert_frame_equal(result, expected)
by_weekday = self.tsframe.groupby(lambda x: x.weekday())
_check_results(by_weekday)
by_mwkday = self.tsframe.groupby([lambda x: x.month,
lambda x: x.weekday()])
_check_results(by_mwkday)
def test_aggregate_item_by_item(self):
df = self.df.copy()
df['E'] = ['a'] * len(self.df)
grouped = self.df.groupby('A')
# API change in 0.11
# def aggfun(ser):
# return len(ser + 'a')
# result = grouped.agg(aggfun)
# self.assertEqual(len(result.columns), 1)
aggfun = lambda ser: ser.size
result = grouped.agg(aggfun)
foo = (self.df.A == 'foo').sum()
bar = (self.df.A == 'bar').sum()
K = len(result.columns)
# GH5782
# odd comparisons can result here, so cast to make easy
assert_almost_equal(result.xs('foo'), np.array([foo] * K).astype('float64'))
assert_almost_equal(result.xs('bar'), np.array([bar] * K).astype('float64'))
def aggfun(ser):
return ser.size
result = DataFrame().groupby(self.df.A).agg(aggfun)
tm.assert_isinstance(result, DataFrame)
self.assertEqual(len(result), 0)
def test_agg_item_by_item_raise_typeerror(self):
from numpy.random import randint
df = DataFrame(randint(10, size=(20, 10)))
def raiseException(df):
com.pprint_thing('----------------------------------------')
com.pprint_thing(df.to_string())
raise TypeError
self.assertRaises(TypeError, df.groupby(0).agg,
raiseException)
def test_basic_regression(self):
# regression
T = [1.0 * x for x in lrange(1, 10) * 10][:1095]
result = Series(T, lrange(0, len(T)))
groupings = np.random.random((1100,))
groupings = Series(groupings, lrange(0, len(groupings))) * 10.
grouped = result.groupby(groupings)
grouped.mean()
def test_transform(self):
data = Series(np.arange(9) // 3, index=np.arange(9))
index = np.arange(9)
np.random.shuffle(index)
data = data.reindex(index)
grouped = data.groupby(lambda x: x // 3)
transformed = grouped.transform(lambda x: x * x.sum())
self.assertEqual(transformed[7], 12)
# GH 8046
# make sure that we preserve the input order
df = DataFrame(np.arange(6,dtype='int64').reshape(3,2), columns=["a","b"], index=[0,2,1])
key = [0,0,1]
expected = df.sort_index().groupby(key).transform(lambda x: x-x.mean()).groupby(key).mean()
result = df.groupby(key).transform(lambda x: x-x.mean()).groupby(key).mean()
assert_frame_equal(result, expected)
def demean(arr):
return arr - arr.mean()
people = DataFrame(np.random.randn(5, 5),
columns=['a', 'b', 'c', 'd', 'e'],
index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])
key = ['one', 'two', 'one', 'two', 'one']
result = people.groupby(key).transform(demean).groupby(key).mean()
expected = people.groupby(key).apply(demean).groupby(key).mean()
assert_frame_equal(result, expected)
# GH 8430
df = tm.makeTimeDataFrame()
g = df.groupby(pd.TimeGrouper('M'))
g.transform(lambda x: x-1)
def test_transform_fast(self):
df = DataFrame( { 'id' : np.arange( 100000 ) / 3,
'val': np.random.randn( 100000) } )
grp=df.groupby('id')['val']
values = np.repeat(grp.mean().values, com._ensure_platform_int(grp.count().values))
expected = pd.Series(values,index=df.index)
result = grp.transform(np.mean)
assert_series_equal(result,expected)
result = grp.transform('mean')
assert_series_equal(result,expected)
def test_transform_broadcast(self):
grouped = self.ts.groupby(lambda x: x.month)
result = grouped.transform(np.mean)
self.assertTrue(result.index.equals(self.ts.index))
for _, gp in grouped:
assert_fp_equal(result.reindex(gp.index), gp.mean())
grouped = self.tsframe.groupby(lambda x: x.month)
result = grouped.transform(np.mean)
self.assertTrue(result.index.equals(self.tsframe.index))
for _, gp in grouped:
agged = gp.mean()
res = result.reindex(gp.index)
for col in self.tsframe:
assert_fp_equal(res[col], agged[col])
# group columns
grouped = self.tsframe.groupby({'A': 0, 'B': 0, 'C': 1, 'D': 1},
axis=1)
result = grouped.transform(np.mean)
self.assertTrue(result.index.equals(self.tsframe.index))
self.assertTrue(result.columns.equals(self.tsframe.columns))
for _, gp in grouped:
agged = gp.mean(1)
res = result.reindex(columns=gp.columns)
for idx in gp.index:
assert_fp_equal(res.xs(idx), agged[idx])
def test_transform_bug(self):
# GH 5712
# transforming on a datetime column
df = DataFrame(dict(A = Timestamp('20130101'), B = np.arange(5)))
result = df.groupby('A')['B'].transform(lambda x: x.rank(ascending=False))
expected = Series(np.arange(5,0,step=-1),name='B')
assert_series_equal(result,expected)
def test_transform_multiple(self):
grouped = self.ts.groupby([lambda x: x.year, lambda x: x.month])
transformed = grouped.transform(lambda x: x * 2)
broadcasted = grouped.transform(np.mean)
def test_dispatch_transform(self):
df = self.tsframe[::5].reindex(self.tsframe.index)
grouped = df.groupby(lambda x: x.month)
filled = grouped.fillna(method='pad')
fillit = lambda x: x.fillna(method='pad')
expected = df.groupby(lambda x: x.month).transform(fillit)
assert_frame_equal(filled, expected)
def test_transform_select_columns(self):
f = lambda x: x.mean()
result = self.df.groupby('A')['C', 'D'].transform(f)
selection = self.df[['C', 'D']]
expected = selection.groupby(self.df['A']).transform(f)
assert_frame_equal(result, expected)
def test_transform_exclude_nuisance(self):
# this also tests orderings in transform between
# series/frame to make sure it's consistent
expected = {}
grouped = self.df.groupby('A')
expected['C'] = grouped['C'].transform(np.mean)
expected['D'] = grouped['D'].transform(np.mean)
expected = DataFrame(expected)
result = self.df.groupby('A').transform(np.mean)
assert_frame_equal(result, expected)
def test_transform_function_aliases(self):
result = self.df.groupby('A').transform('mean')
expected = self.df.groupby('A').transform(np.mean)
assert_frame_equal(result, expected)
result = self.df.groupby('A')['C'].transform('mean')
expected = self.df.groupby('A')['C'].transform(np.mean)
assert_series_equal(result, expected)
def test_with_na(self):
index = Index(np.arange(10))
for dtype in ['float64','float32','int64','int32','int16','int8']:
values = Series(np.ones(10), index, dtype=dtype)
labels = Series([nan, 'foo', 'bar', 'bar', nan, nan, 'bar',
'bar', nan, 'foo'], index=index)
# this SHOULD be an int
grouped = values.groupby(labels)
agged = grouped.agg(len)
expected = Series([4, 2], index=['bar', 'foo'])
assert_series_equal(agged, expected, check_dtype=False)
#self.assertTrue(issubclass(agged.dtype.type, np.integer))
# explicity return a float from my function
def f(x):
return float(len(x))
agged = grouped.agg(f)
expected = Series([4, 2], index=['bar', 'foo'])
assert_series_equal(agged, expected, check_dtype=False)
self.assertTrue(issubclass(agged.dtype.type, np.dtype(dtype).type))
def test_groupby_transform_with_int(self):
# GH 3740, make sure that we might upcast on item-by-item transform
# floats
df = DataFrame(dict(A = [1,1,1,2,2,2], B = Series(1,dtype='float64'), C = Series([1,2,3,1,2,3],dtype='float64'), D = 'foo'))
result = df.groupby('A').transform(lambda x: (x-x.mean())/x.std())
expected = DataFrame(dict(B = np.nan, C = Series([-1,0,1,-1,0,1],dtype='float64')))
assert_frame_equal(result,expected)
# int case
df = DataFrame(dict(A = [1,1,1,2,2,2], B = 1, C = [1,2,3,1,2,3], D = 'foo'))
result = df.groupby('A').transform(lambda x: (x-x.mean())/x.std())
expected = DataFrame(dict(B = np.nan, C = [-1,0,1,-1,0,1]))
assert_frame_equal(result,expected)
# int that needs float conversion
s = Series([2,3,4,10,5,-1])
df = DataFrame(dict(A = [1,1,1,2,2,2], B = 1, C = s, D = 'foo'))
result = df.groupby('A').transform(lambda x: (x-x.mean())/x.std())
s1 = s.iloc[0:3]
s1 = (s1-s1.mean())/s1.std()
s2 = s.iloc[3:6]
s2 = (s2-s2.mean())/s2.std()
expected = DataFrame(dict(B = np.nan, C = concat([s1,s2])))
assert_frame_equal(result,expected)
# int downcasting
result = df.groupby('A').transform(lambda x: x*2/2)
expected = DataFrame(dict(B = 1, C = [2,3,4,10,5,-1]))
assert_frame_equal(result,expected)
def test_indices_concatenation_order(self):
# GH 2808
def f1(x):
y = x[(x.b % 2) == 1]**2
if y.empty:
multiindex = MultiIndex(
levels = [[]]*2,
labels = [[]]*2,
names = ['b', 'c']
)
res = DataFrame(None,
columns=['a'],
index=multiindex)
return res
else:
y = y.set_index(['b','c'])
return y
def f2(x):
y = x[(x.b % 2) == 1]**2
if y.empty:
return DataFrame()
else:
y = y.set_index(['b','c'])
return y
def f3(x):
y = x[(x.b % 2) == 1]**2
if y.empty:
multiindex = MultiIndex(
levels = [[]]*2,
labels = [[]]*2,
names = ['foo', 'bar']
)
res = DataFrame(None,
columns=['a','b'],
index=multiindex)
return res
else:
return y
df = DataFrame({'a':[1,2,2,2],
'b':lrange(4),
'c':lrange(5,9)})
df2 = DataFrame({'a':[3,2,2,2],
'b':lrange(4),
'c':lrange(5,9)})
# correct result
result1 = df.groupby('a').apply(f1)
result2 = df2.groupby('a').apply(f1)
assert_frame_equal(result1, result2)
# should fail (not the same number of levels)
self.assertRaises(AssertionError, df.groupby('a').apply, f2)
self.assertRaises(AssertionError, df2.groupby('a').apply, f2)
# should fail (incorrect shape)
self.assertRaises(AssertionError, df.groupby('a').apply, f3)
self.assertRaises(AssertionError, df2.groupby('a').apply, f3)
def test_attr_wrapper(self):
grouped = self.ts.groupby(lambda x: x.weekday())
result = grouped.std()
expected = grouped.agg(lambda x: np.std(x, ddof=1))
assert_series_equal(result, expected)
# this is pretty cool
result = grouped.describe()
expected = {}
for name, gp in grouped:
expected[name] = gp.describe()
expected = DataFrame(expected).T
assert_frame_equal(result.unstack(), expected)
# get attribute
result = grouped.dtype
expected = grouped.agg(lambda x: x.dtype)
# make sure raises error
self.assertRaises(AttributeError, getattr, grouped, 'foo')
def test_series_describe_multikey(self):
ts = tm.makeTimeSeries()
grouped = ts.groupby([lambda x: x.year, lambda x: x.month])
result = grouped.describe().unstack()
assert_series_equal(result['mean'], grouped.mean())
assert_series_equal(result['std'], grouped.std())
assert_series_equal(result['min'], grouped.min())
def test_series_describe_single(self):
ts = tm.makeTimeSeries()
grouped = ts.groupby(lambda x: x.month)
result = grouped.apply(lambda x: x.describe())
expected = grouped.describe()
assert_series_equal(result, expected)
def test_series_agg_multikey(self):
ts = tm.makeTimeSeries()
grouped = ts.groupby([lambda x: x.year, lambda x: x.month])
result = grouped.agg(np.sum)
expected = grouped.sum()
assert_series_equal(result, expected)
def test_series_agg_multi_pure_python(self):
data = DataFrame({'A': ['foo', 'foo', 'foo', 'foo',
'bar', 'bar', 'bar', 'bar',
'foo', 'foo', 'foo'],
'B': ['one', 'one', 'one', 'two',
'one', 'one', 'one', 'two',
'two', 'two', 'one'],
'C': ['dull', 'dull', 'shiny', 'dull',
'dull', 'shiny', 'shiny', 'dull',
'shiny', 'shiny', 'shiny'],
'D': np.random.randn(11),
'E': np.random.randn(11),
'F': np.random.randn(11)})
def bad(x):
assert(len(x.base) > 0)
return 'foo'
result = data.groupby(['A', 'B']).agg(bad)
expected = data.groupby(['A', 'B']).agg(lambda x: 'foo')
assert_frame_equal(result, expected)
def test_series_index_name(self):
grouped = self.df.ix[:, ['C']].groupby(self.df['A'])
result = grouped.agg(lambda x: x.mean())
self.assertEqual(result.index.name, 'A')
def test_frame_describe_multikey(self):
grouped = self.tsframe.groupby([lambda x: x.year,
lambda x: x.month])
result = grouped.describe()
for col in self.tsframe:
expected = grouped[col].describe()
assert_series_equal(result[col], expected)
groupedT = self.tsframe.groupby({'A': 0, 'B': 0,
'C': 1, 'D': 1}, axis=1)
result = groupedT.describe()
for name, group in groupedT:
assert_frame_equal(result[name], group.describe())
def test_frame_groupby(self):
grouped = self.tsframe.groupby(lambda x: x.weekday())
# aggregate
aggregated = grouped.aggregate(np.mean)
self.assertEqual(len(aggregated), 5)
self.assertEqual(len(aggregated.columns), 4)
# by string
tscopy = self.tsframe.copy()
tscopy['weekday'] = [x.weekday() for x in tscopy.index]
stragged = tscopy.groupby('weekday').aggregate(np.mean)
assert_frame_equal(stragged, aggregated, check_names=False)
# transform
grouped = self.tsframe.head(30).groupby(lambda x: x.weekday())
transformed = grouped.transform(lambda x: x - x.mean())
self.assertEqual(len(transformed), 30)
self.assertEqual(len(transformed.columns), 4)
# transform propagate
transformed = grouped.transform(lambda x: x.mean())
for name, group in grouped:
mean = group.mean()
for idx in group.index:
assert_almost_equal(transformed.xs(idx), mean)
# iterate
for weekday, group in grouped:
self.assertEqual(group.index[0].weekday(), weekday)
# groups / group_indices
groups = grouped.groups
indices = grouped.indices
for k, v in compat.iteritems(groups):
samething = self.tsframe.index.take(indices[k])
self.assertTrue((samething == v).all())
def test_grouping_is_iterable(self):
# this code path isn't used anywhere else
# not sure it's useful
grouped = self.tsframe.groupby([lambda x: x.weekday(),
lambda x: x.year])
# test it works
for g in grouped.grouper.groupings[0]:
pass
def test_frame_groupby_columns(self):
mapping = {
'A': 0, 'B': 0, 'C': 1, 'D': 1
}
grouped = self.tsframe.groupby(mapping, axis=1)
# aggregate
aggregated = grouped.aggregate(np.mean)
self.assertEqual(len(aggregated), len(self.tsframe))
self.assertEqual(len(aggregated.columns), 2)
# transform
tf = lambda x: x - x.mean()
groupedT = self.tsframe.T.groupby(mapping, axis=0)
assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf))
# iterate
for k, v in grouped:
self.assertEqual(len(v.columns), 2)
def test_frame_set_name_single(self):
grouped = self.df.groupby('A')
result = grouped.mean()
self.assertEqual(result.index.name, 'A')
result = self.df.groupby('A', as_index=False).mean()
self.assertNotEqual(result.index.name, 'A')
result = grouped.agg(np.mean)
self.assertEqual(result.index.name, 'A')
result = grouped.agg({'C': np.mean, 'D': np.std})
self.assertEqual(result.index.name, 'A')
result = grouped['C'].mean()
self.assertEqual(result.index.name, 'A')
result = grouped['C'].agg(np.mean)
self.assertEqual(result.index.name, 'A')
result = grouped['C'].agg([np.mean, np.std])
self.assertEqual(result.index.name, 'A')
result = grouped['C'].agg({'foo': np.mean, 'bar': np.std})
self.assertEqual(result.index.name, 'A')
def test_multi_iter(self):
s = Series(np.arange(6))
k1 = np.array(['a', 'a', 'a', 'b', 'b', 'b'])
k2 = np.array(['1', '2', '1', '2', '1', '2'])
grouped = s.groupby([k1, k2])
iterated = list(grouped)
expected = [('a', '1', s[[0, 2]]),
('a', '2', s[[1]]),
('b', '1', s[[4]]),
('b', '2', s[[3, 5]])]
for i, ((one, two), three) in enumerate(iterated):
e1, e2, e3 = expected[i]
self.assertEqual(e1, one)
self.assertEqual(e2, two)
assert_series_equal(three, e3)
def test_multi_iter_frame(self):
k1 = np.array(['b', 'b', 'b', 'a', 'a', 'a'])
k2 = np.array(['1', '2', '1', '2', '1', '2'])
df = DataFrame({'v1': np.random.randn(6),
'v2': np.random.randn(6),
'k1': k1, 'k2': k2},
index=['one', 'two', 'three', 'four', 'five', 'six'])
grouped = df.groupby(['k1', 'k2'])
# things get sorted!
iterated = list(grouped)
idx = df.index
expected = [('a', '1', df.ix[idx[[4]]]),
('a', '2', df.ix[idx[[3, 5]]]),
('b', '1', df.ix[idx[[0, 2]]]),
('b', '2', df.ix[idx[[1]]])]
for i, ((one, two), three) in enumerate(iterated):
e1, e2, e3 = expected[i]
self.assertEqual(e1, one)
self.assertEqual(e2, two)
assert_frame_equal(three, e3)
# don't iterate through groups with no data
df['k1'] = np.array(['b', 'b', 'b', 'a', 'a', 'a'])
df['k2'] = np.array(['1', '1', '1', '2', '2', '2'])
grouped = df.groupby(['k1', 'k2'])
groups = {}
for key, gp in grouped:
groups[key] = gp
self.assertEqual(len(groups), 2)
# axis = 1
three_levels = self.three_group.groupby(['A', 'B', 'C']).mean()
grouped = three_levels.T.groupby(axis=1, level=(1, 2))
for key, group in grouped:
pass
def test_multi_iter_panel(self):
wp = tm.makePanel()
grouped = wp.groupby([lambda x: x.month, lambda x: x.weekday()],
axis=1)
for (month, wd), group in grouped:
exp_axis = [x for x in wp.major_axis
if x.month == month and x.weekday() == wd]
expected = wp.reindex(major=exp_axis)
assert_panel_equal(group, expected)
def test_multi_func(self):
col1 = self.df['A']
col2 = self.df['B']
grouped = self.df.groupby([col1.get, col2.get])
agged = grouped.mean()
expected = self.df.groupby(['A', 'B']).mean()
assert_frame_equal(agged.ix[:, ['C', 'D']],
expected.ix[:, ['C', 'D']],
check_names=False) # TODO groupby get drops names
# some "groups" with no data
df = DataFrame({'v1': np.random.randn(6),
'v2': np.random.randn(6),
'k1': np.array(['b', 'b', 'b', 'a', 'a', 'a']),
'k2': np.array(['1', '1', '1', '2', '2', '2'])},
index=['one', 'two', 'three', 'four', 'five', 'six'])
# only verify that it works for now
grouped = df.groupby(['k1', 'k2'])
grouped.agg(np.sum)
def test_multi_key_multiple_functions(self):
grouped = self.df.groupby(['A', 'B'])['C']
agged = grouped.agg([np.mean, np.std])
expected = DataFrame({'mean': grouped.agg(np.mean),
'std': grouped.agg(np.std)})
assert_frame_equal(agged, expected)
def test_frame_multi_key_function_list(self):
data = DataFrame({'A': ['foo', 'foo', 'foo', 'foo',
'bar', 'bar', 'bar', 'bar',
'foo', 'foo', 'foo'],
'B': ['one', 'one', 'one', 'two',
'one', 'one', 'one', 'two',
'two', 'two', 'one'],
'C': ['dull', 'dull', 'shiny', 'dull',
'dull', 'shiny', 'shiny', 'dull',
'shiny', 'shiny', 'shiny'],
'D': np.random.randn(11),
'E': np.random.randn(11),
'F': np.random.randn(11)})
grouped = data.groupby(['A', 'B'])
funcs = [np.mean, np.std]
agged = grouped.agg(funcs)
expected = concat([grouped['D'].agg(funcs), grouped['E'].agg(funcs),
grouped['F'].agg(funcs)],
keys=['D', 'E', 'F'], axis=1)
assert(isinstance(agged.index, MultiIndex))
assert(isinstance(expected.index, MultiIndex))
assert_frame_equal(agged, expected)
def test_groupby_multiple_columns(self):
data = self.df
grouped = data.groupby(['A', 'B'])
def _check_op(op):
result1 = op(grouped)
expected = defaultdict(dict)
for n1, gp1 in data.groupby('A'):
for n2, gp2 in gp1.groupby('B'):
expected[n1][n2] = op(gp2.ix[:, ['C', 'D']])
expected = dict((k, DataFrame(v)) for k, v in compat.iteritems(expected))
expected = Panel.fromDict(expected).swapaxes(0, 1)
expected.major_axis.name, expected.minor_axis.name = 'A', 'B'
# a little bit crude
for col in ['C', 'D']:
result_col = op(grouped[col])
exp = expected[col]
pivoted = result1[col].unstack()
pivoted2 = result_col.unstack()
assert_frame_equal(pivoted.reindex_like(exp), exp)
assert_frame_equal(pivoted2.reindex_like(exp), exp)
_check_op(lambda x: x.sum())
_check_op(lambda x: x.mean())
# test single series works the same
result = data['C'].groupby([data['A'], data['B']]).mean()
expected = data.groupby(['A', 'B']).mean()['C']
assert_series_equal(result, expected)
def test_groupby_as_index_agg(self):
grouped = self.df.groupby('A', as_index=False)
# single-key
result = grouped.agg(np.mean)
expected = grouped.mean()
assert_frame_equal(result, expected)
result2 = grouped.agg(OrderedDict([['C', np.mean], ['D', np.sum]]))
expected2 = grouped.mean()
expected2['D'] = grouped.sum()['D']
assert_frame_equal(result2, expected2)
grouped = self.df.groupby('A', as_index=True)
expected3 = grouped['C'].sum()
expected3 = DataFrame(expected3).rename(columns={'C': 'Q'})
result3 = grouped['C'].agg({'Q': np.sum})
assert_frame_equal(result3, expected3)
# multi-key
grouped = self.df.groupby(['A', 'B'], as_index=False)
result = grouped.agg(np.mean)
expected = grouped.mean()
assert_frame_equal(result, expected)
result2 = grouped.agg(OrderedDict([['C', np.mean], ['D', np.sum]]))
expected2 = grouped.mean()
expected2['D'] = grouped.sum()['D']
assert_frame_equal(result2, expected2)
expected3 = grouped['C'].sum()
expected3 = DataFrame(expected3).rename(columns={'C': 'Q'})
result3 = grouped['C'].agg({'Q': np.sum})
assert_frame_equal(result3, expected3)
# GH7115 & GH8112 & GH8582
df = DataFrame(np.random.randint(0, 100, (50, 3)),
columns=['jim', 'joe', 'jolie'])
ts = Series(np.random.randint(5, 10, 50), name='jim')
gr = df.groupby(ts)
_ = gr.nth(0) # invokes _set_selection_from_grouper internally
assert_frame_equal(gr.apply(sum), df.groupby(ts).apply(sum))
for attr in ['mean', 'max', 'count', 'idxmax', 'cumsum', 'all']:
gr = df.groupby(ts, as_index=False)
left = getattr(gr, attr)()
gr = df.groupby(ts.values, as_index=True)
right = getattr(gr, attr)().reset_index(drop=True)
assert_frame_equal(left, right)
def test_mulitindex_passthru(self):
# GH 7997
# regression from 0.14.1
df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
df.columns = pd.MultiIndex.from_tuples([(0,1),(1,1),(2,1)])
result = df.groupby(axis=1, level=[0,1]).first()
assert_frame_equal(result, df)
def test_multifunc_select_col_integer_cols(self):
df = self.df
df.columns = np.arange(len(df.columns))
# it works!
result = df.groupby(1, as_index=False)[2].agg({'Q': np.mean})
def test_as_index_series_return_frame(self):
grouped = self.df.groupby('A', as_index=False)
grouped2 = self.df.groupby(['A', 'B'], as_index=False)
result = grouped['C'].agg(np.sum)
expected = grouped.agg(np.sum).ix[:, ['A', 'C']]
tm.assert_isinstance(result, DataFrame)
assert_frame_equal(result, expected)
result2 = grouped2['C'].agg(np.sum)
expected2 = grouped2.agg(np.sum).ix[:, ['A', 'B', 'C']]
tm.assert_isinstance(result2, DataFrame)
assert_frame_equal(result2, expected2)
result = grouped['C'].sum()
expected = grouped.sum().ix[:, ['A', 'C']]
tm.assert_isinstance(result, DataFrame)
assert_frame_equal(result, expected)
result2 = grouped2['C'].sum()
expected2 = grouped2.sum().ix[:, ['A', 'B', 'C']]
tm.assert_isinstance(result2, DataFrame)
assert_frame_equal(result2, expected2)
# corner case
self.assertRaises(Exception, grouped['C'].__getitem__,
'D')
def test_groupby_as_index_cython(self):
data = self.df
# single-key
grouped = data.groupby('A', as_index=False)
result = grouped.mean()
expected = data.groupby(['A']).mean()
expected.insert(0, 'A', expected.index)
expected.index = np.arange(len(expected))
assert_frame_equal(result, expected)
# multi-key
grouped = data.groupby(['A', 'B'], as_index=False)
result = grouped.mean()
expected = data.groupby(['A', 'B']).mean()
arrays = lzip(*expected.index._tuple_index)
expected.insert(0, 'A', arrays[0])
expected.insert(1, 'B', arrays[1])
expected.index = np.arange(len(expected))
assert_frame_equal(result, expected)
def test_groupby_as_index_series_scalar(self):
grouped = self.df.groupby(['A', 'B'], as_index=False)
# GH #421
result = grouped['C'].agg(len)
expected = grouped.agg(len).ix[:, ['A', 'B', 'C']]
assert_frame_equal(result, expected)
def test_groupby_as_index_corner(self):
self.assertRaises(TypeError, self.ts.groupby,
lambda x: x.weekday(), as_index=False)
self.assertRaises(ValueError, self.df.groupby,
lambda x: x.lower(), as_index=False, axis=1)
def test_groupby_as_index_apply(self):
# GH #4648 and #3417
df = DataFrame({'item_id': ['b', 'b', 'a', 'c', 'a', 'b'],
'user_id': [1,2,1,1,3,1],
'time': range(6)})
g_as = df.groupby('user_id', as_index=True)
g_not_as = df.groupby('user_id', as_index=False)
res_as = g_as.head(2).index
res_not_as = g_not_as.head(2).index
exp = Index([0, 1, 2, 4])
assert_index_equal(res_as, exp)
assert_index_equal(res_not_as, exp)
res_as_apply = g_as.apply(lambda x: x.head(2)).index
res_not_as_apply = g_not_as.apply(lambda x: x.head(2)).index
# apply doesn't maintain the original ordering
# changed in GH5610 as the as_index=False returns a MI here
exp_not_as_apply = MultiIndex.from_tuples([(0, 0), (0, 2), (1, 1), (2, 4)])
exp_as_apply = MultiIndex.from_tuples([(1, 0), (1, 2), (2, 1), (3, 4)])
assert_index_equal(res_as_apply, exp_as_apply)
assert_index_equal(res_not_as_apply, exp_not_as_apply)
ind = Index(list('abcde'))
df = DataFrame([[1, 2], [2, 3], [1, 4], [1, 5], [2, 6]], index=ind)
res = df.groupby(0, as_index=False).apply(lambda x: x).index
assert_index_equal(res, ind)
def test_groupby_head_tail(self):
df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])
g_as = df.groupby('A', as_index=True)
g_not_as = df.groupby('A', as_index=False)
# as_index= False, much easier
assert_frame_equal(df.loc[[0, 2]], g_not_as.head(1))
assert_frame_equal(df.loc[[1, 2]], g_not_as.tail(1))
empty_not_as = DataFrame(columns=df.columns)
assert_frame_equal(empty_not_as, g_not_as.head(0))
assert_frame_equal(empty_not_as, g_not_as.tail(0))
assert_frame_equal(empty_not_as, g_not_as.head(-1))
assert_frame_equal(empty_not_as, g_not_as.tail(-1))
assert_frame_equal(df, g_not_as.head(7)) # contains all
assert_frame_equal(df, g_not_as.tail(7))
# as_index=True, (used to be different)
df_as = df
assert_frame_equal(df_as.loc[[0, 2]], g_as.head(1))
assert_frame_equal(df_as.loc[[1, 2]], g_as.tail(1))
empty_as = DataFrame(index=df_as.index[:0], columns=df.columns)
assert_frame_equal(empty_as, g_as.head(0))
assert_frame_equal(empty_as, g_as.tail(0))
assert_frame_equal(empty_as, g_as.head(-1))
assert_frame_equal(empty_as, g_as.tail(-1))
assert_frame_equal(df_as, g_as.head(7)) # contains all
assert_frame_equal(df_as, g_as.tail(7))
# test with selection
assert_frame_equal(g_as[[]].head(1), df_as.loc[[0,2], []])
assert_frame_equal(g_as[['A']].head(1), df_as.loc[[0,2], ['A']])
assert_frame_equal(g_as[['B']].head(1), df_as.loc[[0,2], ['B']])
assert_frame_equal(g_as[['A', 'B']].head(1), df_as.loc[[0,2]])
assert_frame_equal(g_not_as[[]].head(1), df_as.loc[[0,2], []])
assert_frame_equal(g_not_as[['A']].head(1), df_as.loc[[0,2], ['A']])
assert_frame_equal(g_not_as[['B']].head(1), df_as.loc[[0,2], ['B']])
assert_frame_equal(g_not_as[['A', 'B']].head(1), df_as.loc[[0,2]])
def test_groupby_multiple_key(self):
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year,
lambda x: x.month,
lambda x: x.day])
agged = grouped.sum()
assert_almost_equal(df.values, agged.values)
grouped = df.T.groupby([lambda x: x.year,
lambda x: x.month,
lambda x: x.day], axis=1)
agged = grouped.agg(lambda x: x.sum())
self.assertTrue(agged.index.equals(df.columns))
assert_almost_equal(df.T.values, agged.values)
agged = grouped.agg(lambda x: x.sum())
assert_almost_equal(df.T.values, agged.values)
def test_groupby_multi_corner(self):
# test that having an all-NA column doesn't mess you up
df = self.df.copy()
df['bad'] = np.nan
agged = df.groupby(['A', 'B']).mean()
expected = self.df.groupby(['A', 'B']).mean()
expected['bad'] = np.nan
assert_frame_equal(agged, expected)
def test_omit_nuisance(self):
grouped = self.df.groupby('A')
result = grouped.mean()
expected = self.df.ix[:, ['A', 'C', 'D']].groupby('A').mean()
assert_frame_equal(result, expected)
agged = grouped.agg(np.mean)
exp = grouped.mean()
assert_frame_equal(agged, exp)
df = self.df.ix[:, ['A', 'C', 'D']]
df['E'] = datetime.now()
grouped = df.groupby('A')
result = grouped.agg(np.sum)
expected = grouped.sum()
assert_frame_equal(result, expected)
# won't work with axis = 1
grouped = df.groupby({'A': 0, 'C': 0, 'D': 1, 'E': 1}, axis=1)
result = self.assertRaises(TypeError, grouped.agg,
lambda x: x.sum(0, numeric_only=False))
def test_omit_nuisance_python_multiple(self):
grouped = self.three_group.groupby(['A', 'B'])
agged = grouped.agg(np.mean)
exp = grouped.mean()
assert_frame_equal(agged, exp)
def test_empty_groups_corner(self):
# handle empty groups
df = DataFrame({'k1': np.array(['b', 'b', 'b', 'a', 'a', 'a']),
'k2': np.array(['1', '1', '1', '2', '2', '2']),
'k3': ['foo', 'bar'] * 3,
'v1': np.random.randn(6),
'v2': np.random.randn(6)})
grouped = df.groupby(['k1', 'k2'])
result = grouped.agg(np.mean)
expected = grouped.mean()
assert_frame_equal(result, expected)
grouped = self.mframe[3:5].groupby(level=0)
agged = grouped.apply(lambda x: x.mean())
agged_A = grouped['A'].apply(np.mean)
assert_series_equal(agged['A'], agged_A)
self.assertEqual(agged.index.name, 'first')
def test_apply_concat_preserve_names(self):
grouped = self.three_group.groupby(['A', 'B'])
def desc(group):
result = group.describe()
result.index.name = 'stat'
return result
def desc2(group):
result = group.describe()
result.index.name = 'stat'
result = result[:len(group)]
# weirdo
return result
def desc3(group):
result = group.describe()
# names are different
result.index.name = 'stat_%d' % len(group)
result = result[:len(group)]
# weirdo
return result
result = grouped.apply(desc)
self.assertEqual(result.index.names, ('A', 'B', 'stat'))
result2 = grouped.apply(desc2)
self.assertEqual(result2.index.names, ('A', 'B', 'stat'))
result3 = grouped.apply(desc3)
self.assertEqual(result3.index.names, ('A', 'B', None))
def test_nonsense_func(self):
df = DataFrame([0])
self.assertRaises(Exception, df.groupby, lambda x: x + 'foo')
def test_builtins_apply(self): # GH8155
df = pd.DataFrame(np.random.randint(1, 50, (1000, 2)),
columns=['jim', 'joe'])
df['jolie'] = np.random.randn(1000)
print(df.head())
for keys in ['jim', ['jim', 'joe']]: # single key & multi-key
if keys == 'jim': continue
for f in [max, min, sum]:
fname = f.__name__
result = df.groupby(keys).apply(f)
_shape = result.shape
ngroups = len(df.drop_duplicates(subset=keys))
assert result.shape == (ngroups, 3), 'invalid frame shape: '\
'{} (expected ({}, 3))'.format(result.shape, ngroups)
assert_frame_equal(result, # numpy's equivalent function
df.groupby(keys).apply(getattr(np, fname)))
if f != sum:
expected = df.groupby(keys).agg(fname).reset_index()
expected.set_index(keys, inplace=True, drop=False)
assert_frame_equal(result, expected, check_dtype=False)
assert_series_equal(getattr(result, fname)(),
getattr(df, fname)())
def test_cythonized_aggers(self):
data = {'A': [0, 0, 0, 0, 1, 1, 1, 1, 1, 1., nan, nan],
'B': ['A', 'B'] * 6,
'C': np.random.randn(12)}
df = DataFrame(data)
df.loc[2:10:2,'C'] = nan
def _testit(op):
# single column
grouped = df.drop(['B'], axis=1).groupby('A')
exp = {}
for cat, group in grouped:
exp[cat] = op(group['C'])
exp = DataFrame({'C': exp})
exp.index.name = 'A'
result = op(grouped)
assert_frame_equal(result, exp)
# multiple columns
grouped = df.groupby(['A', 'B'])
expd = {}
for (cat1, cat2), group in grouped:
expd.setdefault(cat1, {})[cat2] = op(group['C'])
exp = DataFrame(expd).T.stack(dropna=False)
result = op(grouped)['C']
assert_series_equal(result, exp)
_testit(lambda x: x.count())
_testit(lambda x: x.sum())
_testit(lambda x: x.std())
_testit(lambda x: x.var())
_testit(lambda x: x.sem())
_testit(lambda x: x.mean())
_testit(lambda x: x.median())
_testit(lambda x: x.prod())
_testit(lambda x: x.min())
_testit(lambda x: x.max())
def test_max_min_non_numeric(self):
# #2700
aa = DataFrame({'nn':[11,11,22,22],'ii':[1,2,3,4],'ss':4*['mama']})
result = aa.groupby('nn').max()
self.assertTrue('ss' in result)
result = aa.groupby('nn').min()
self.assertTrue('ss' in result)
def test_cython_agg_boolean(self):
frame = DataFrame({'a': np.random.randint(0, 5, 50),
'b': np.random.randint(0, 2, 50).astype('bool')})
result = frame.groupby('a')['b'].mean()
expected = frame.groupby('a')['b'].agg(np.mean)
assert_series_equal(result, expected)
def test_cython_agg_nothing_to_agg(self):
frame = DataFrame({'a': np.random.randint(0, 5, 50),
'b': ['foo', 'bar'] * 25})
self.assertRaises(DataError, frame.groupby('a')['b'].mean)
frame = DataFrame({'a': np.random.randint(0, 5, 50),
'b': ['foo', 'bar'] * 25})
self.assertRaises(DataError, frame[['b']].groupby(frame['a']).mean)
def test_cython_agg_nothing_to_agg_with_dates(self):
frame = DataFrame({'a': np.random.randint(0, 5, 50),
'b': ['foo', 'bar'] * 25,
'dates': pd.date_range('now', periods=50,
freq='T')})
with tm.assertRaisesRegexp(DataError, "No numeric types to aggregate"):
frame.groupby('b').dates.mean()
def test_groupby_timedelta_cython_count(self):
df = DataFrame({'g': list('ab' * 2),
'delt': np.arange(4).astype('timedelta64[ns]')})
expected = Series([2, 2], index=['a', 'b'], name='delt')
result = df.groupby('g').delt.count()
tm.assert_series_equal(expected, result)
def test_cython_agg_frame_columns(self):
# #2113
df = DataFrame({'x': [1, 2, 3], 'y': [3, 4, 5]})
result = df.groupby(level=0, axis='columns').mean()
result = df.groupby(level=0, axis='columns').mean()
result = df.groupby(level=0, axis='columns').mean()
_ = df.groupby(level=0, axis='columns').mean()
def test_wrap_aggregated_output_multindex(self):
df = self.mframe.T
df['baz', 'two'] = 'peekaboo'
keys = [np.array([0, 0, 1]), np.array([0, 0, 1])]
agged = df.groupby(keys).agg(np.mean)
tm.assert_isinstance(agged.columns, MultiIndex)
def aggfun(ser):
if ser.name == ('foo', 'one'):
raise TypeError
else:
return ser.sum()
agged2 = df.groupby(keys).aggregate(aggfun)
self.assertEqual(len(agged2.columns) + 1, len(df.columns))
def test_groupby_level(self):
frame = self.mframe
deleveled = frame.reset_index()
result0 = frame.groupby(level=0).sum()
result1 = frame.groupby(level=1).sum()
expected0 = frame.groupby(deleveled['first'].values).sum()
expected1 = frame.groupby(deleveled['second'].values).sum()
expected0 = expected0.reindex(frame.index.levels[0])
expected1 = expected1.reindex(frame.index.levels[1])
self.assertEqual(result0.index.name, 'first')
self.assertEqual(result1.index.name, 'second')
assert_frame_equal(result0, expected0)
assert_frame_equal(result1, expected1)
self.assertEqual(result0.index.name, frame.index.names[0])
self.assertEqual(result1.index.name, frame.index.names[1])
# groupby level name
result0 = frame.groupby(level='first').sum()
result1 = frame.groupby(level='second').sum()
assert_frame_equal(result0, expected0)
assert_frame_equal(result1, expected1)
# axis=1
result0 = frame.T.groupby(level=0, axis=1).sum()
result1 = frame.T.groupby(level=1, axis=1).sum()
assert_frame_equal(result0, expected0.T)
assert_frame_equal(result1, expected1.T)
# raise exception for non-MultiIndex
self.assertRaises(ValueError, self.df.groupby, level=1)
def test_groupby_level_index_names(self):
## GH4014 this used to raise ValueError since 'exp'>1 (in py2)
df = DataFrame({'exp' : ['A']*3 + ['B']*3, 'var1' : lrange(6),}).set_index('exp')
df.groupby(level='exp')
self.assertRaises(ValueError, df.groupby, level='foo')
def test_groupby_level_with_nas(self):
index = MultiIndex(levels=[[1, 0], [0, 1, 2, 3]],
labels=[[1, 1, 1, 1, 0, 0, 0, 0],
[0, 1, 2, 3, 0, 1, 2, 3]])
# factorizing doesn't confuse things
s = Series(np.arange(8.), index=index)
result = s.groupby(level=0).sum()
expected = Series([22., 6.], index=[1, 0])
assert_series_equal(result, expected)
index = MultiIndex(levels=[[1, 0], [0, 1, 2, 3]],
labels=[[1, 1, 1, 1, -1, 0, 0, 0],
[0, 1, 2, 3, 0, 1, 2, 3]])
# factorizing doesn't confuse things
s = Series(np.arange(8.), index=index)
result = s.groupby(level=0).sum()
expected = Series([18., 6.], index=[1, 0])
assert_series_equal(result, expected)
def test_groupby_level_apply(self):
frame = self.mframe
result = frame.groupby(level=0).count()
self.assertEqual(result.index.name, 'first')
result = frame.groupby(level=1).count()
self.assertEqual(result.index.name, 'second')
result = frame['A'].groupby(level=0).count()
self.assertEqual(result.index.name, 'first')
def test_groupby_args(self):
#PR8618 and issue 8015
frame = self.mframe
def j():
frame.groupby()
self.assertRaisesRegexp(TypeError, "You have to supply one of 'by' and 'level'", j)
def k():
frame.groupby(by=None, level=None)
self.assertRaisesRegexp(TypeError, "You have to supply one of 'by' and 'level'", k)
def test_groupby_level_mapper(self):
frame = self.mframe
deleveled = frame.reset_index()
mapper0 = {'foo': 0, 'bar': 0,
'baz': 1, 'qux': 1}
mapper1 = {'one': 0, 'two': 0, 'three': 1}
result0 = frame.groupby(mapper0, level=0).sum()
result1 = frame.groupby(mapper1, level=1).sum()
mapped_level0 = np.array([mapper0.get(x) for x in deleveled['first']])
mapped_level1 = np.array([mapper1.get(x) for x in deleveled['second']])
expected0 = frame.groupby(mapped_level0).sum()
expected1 = frame.groupby(mapped_level1).sum()
expected0.index.name, expected1.index.name = 'first', 'second'
assert_frame_equal(result0, expected0)
assert_frame_equal(result1, expected1)
def test_groupby_level_0_nonmulti(self):
# #1313
a = Series([1, 2, 3, 10, 4, 5, 20, 6], Index([1, 2, 3, 1,
4, 5, 2, 6], name='foo'))
result = a.groupby(level=0).sum()
self.assertEqual(result.index.name, a.index.name)
def test_level_preserve_order(self):
grouped = self.mframe.groupby(level=0)
exp_labels = np.array([0, 0, 0, 1, 1, 2, 2, 3, 3, 3])
assert_almost_equal(grouped.grouper.labels[0], exp_labels)
def test_grouping_labels(self):
grouped = self.mframe.groupby(self.mframe.index.get_level_values(0))
exp_labels = np.array([2, 2, 2, 0, 0, 1, 1, 3, 3, 3])
assert_almost_equal(grouped.grouper.labels[0], exp_labels)
def test_cython_fail_agg(self):
dr = bdate_range('1/1/2000', periods=50)
ts = Series(['A', 'B', 'C', 'D', 'E'] * 10, index=dr)
grouped = ts.groupby(lambda x: x.month)
summed = grouped.sum()
expected = grouped.agg(np.sum)
assert_series_equal(summed, expected)
def test_apply_series_to_frame(self):
def f(piece):
return DataFrame({'value': piece,
'demeaned': piece - piece.mean(),
'logged': np.log(piece)})
dr = bdate_range('1/1/2000', periods=100)
ts = Series(np.random.randn(100), index=dr)
grouped = ts.groupby(lambda x: x.month)
result = grouped.apply(f)
tm.assert_isinstance(result, DataFrame)
self.assertTrue(result.index.equals(ts.index))
def test_apply_series_yield_constant(self):
result = self.df.groupby(['A', 'B'])['C'].apply(len)
self.assertEqual(result.index.names[:2], ('A', 'B'))
def test_apply_frame_to_series(self):
grouped = self.df.groupby(['A', 'B'])
result = grouped.apply(len)
expected = grouped.count()['C']
self.assertTrue(result.index.equals(expected.index))
self.assert_numpy_array_equal(result.values, expected.values)
def test_apply_frame_concat_series(self):
def trans(group):
return group.groupby('B')['C'].sum().order()[:2]
def trans2(group):
grouped = group.groupby(df.reindex(group.index)['B'])
return grouped.sum().order()[:2]
df = DataFrame({'A': np.random.randint(0, 5, 1000),
'B': np.random.randint(0, 5, 1000),
'C': np.random.randn(1000)})
result = df.groupby('A').apply(trans)
exp = df.groupby('A')['C'].apply(trans2)
assert_series_equal(result, exp)
def test_apply_transform(self):
grouped = self.ts.groupby(lambda x: x.month)
result = grouped.apply(lambda x: x * 2)
expected = grouped.transform(lambda x: x * 2)
assert_series_equal(result, expected)
def test_apply_multikey_corner(self):
grouped = self.tsframe.groupby([lambda x: x.year,
lambda x: x.month])
def f(group):
return group.sort('A')[-5:]
result = grouped.apply(f)
for key, group in grouped:
assert_frame_equal(result.ix[key], f(group))
def test_mutate_groups(self):
# GH3380
mydf = DataFrame({
'cat1' : ['a'] * 8 + ['b'] * 6,
'cat2' : ['c'] * 2 + ['d'] * 2 + ['e'] * 2 + ['f'] * 2 + ['c'] * 2 + ['d'] * 2 + ['e'] * 2,
'cat3' : lmap(lambda x: 'g%s' % x, lrange(1,15)),
'val' : np.random.randint(100, size=14),
})
def f_copy(x):
x = x.copy()
x['rank'] = x.val.rank(method='min')
return x.groupby('cat2')['rank'].min()
def f_no_copy(x):
x['rank'] = x.val.rank(method='min')
return x.groupby('cat2')['rank'].min()
grpby_copy = mydf.groupby('cat1').apply(f_copy)
grpby_no_copy = mydf.groupby('cat1').apply(f_no_copy)
assert_series_equal(grpby_copy,grpby_no_copy)
def test_no_mutate_but_looks_like(self):
# GH 8467
# first show's mutation indicator
# second does not, but should yield the same results
df = DataFrame({'key': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'value': range(9)})
result1 = df.groupby('key', group_keys=True).apply(lambda x: x[:].key)
result2 = df.groupby('key', group_keys=True).apply(lambda x: x.key)
assert_series_equal(result1, result2)
def test_apply_chunk_view(self):
# Low level tinkering could be unsafe, make sure not
df = DataFrame({'key': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'value': lrange(9)})
# return view
f = lambda x: x[:2]
result = df.groupby('key', group_keys=False).apply(f)
expected = df.take([0, 1, 3, 4, 6, 7])
assert_frame_equal(result, expected)
def test_apply_no_name_column_conflict(self):
df = DataFrame({'name': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2],
'name2': [0, 0, 0, 1, 1, 1, 0, 0, 1, 1],
'value': lrange(10)[::-1]})
# it works! #2605
grouped = df.groupby(['name', 'name2'])
grouped.apply(lambda x: x.sort('value'))
def test_groupby_series_indexed_differently(self):
s1 = Series([5.0, -9.0, 4.0, 100., -5., 55., 6.7],
index=Index(['a', 'b', 'c', 'd', 'e', 'f', 'g']))
s2 = Series([1.0, 1.0, 4.0, 5.0, 5.0, 7.0],
index=Index(['a', 'b', 'd', 'f', 'g', 'h']))
grouped = s1.groupby(s2)
agged = grouped.mean()
exp = s1.groupby(s2.reindex(s1.index).get).mean()
assert_series_equal(agged, exp)
def test_groupby_with_hier_columns(self):
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two',
'one', 'two', 'one', 'two']]))
index = MultiIndex.from_tuples(tuples)
columns = MultiIndex.from_tuples([('A', 'cat'), ('B', 'dog'),
('B', 'cat'), ('A', 'dog')])
df = DataFrame(np.random.randn(8, 4), index=index,
columns=columns)
result = df.groupby(level=0).mean()
self.assertTrue(result.columns.equals(columns))
result = df.groupby(level=0, axis=1).mean()
self.assertTrue(result.index.equals(df.index))
result = df.groupby(level=0).agg(np.mean)
self.assertTrue(result.columns.equals(columns))
result = df.groupby(level=0).apply(lambda x: x.mean())
self.assertTrue(result.columns.equals(columns))
result = df.groupby(level=0, axis=1).agg(lambda x: x.mean(1))
self.assertTrue(result.columns.equals(Index(['A', 'B'])))
self.assertTrue(result.index.equals(df.index))
# add a nuisance column
sorted_columns, _ = columns.sortlevel(0)
df['A', 'foo'] = 'bar'
result = df.groupby(level=0).mean()
self.assertTrue(result.columns.equals(df.columns[:-1]))
def test_pass_args_kwargs(self):
from numpy import percentile
def f(x, q=None, axis=0):
return percentile(x, q, axis=axis)
g = lambda x: percentile(x, 80, axis=0)
# Series
ts_grouped = self.ts.groupby(lambda x: x.month)
agg_result = ts_grouped.agg(percentile, 80, axis=0)
apply_result = ts_grouped.apply(percentile, 80, axis=0)
trans_result = ts_grouped.transform(percentile, 80, axis=0)
agg_expected = ts_grouped.quantile(.8)
trans_expected = ts_grouped.transform(g)
assert_series_equal(apply_result, agg_expected)
assert_series_equal(agg_result, agg_expected)
assert_series_equal(trans_result, trans_expected)
agg_result = ts_grouped.agg(f, q=80)
apply_result = ts_grouped.apply(f, q=80)
trans_result = ts_grouped.transform(f, q=80)
assert_series_equal(agg_result, agg_expected)
assert_series_equal(apply_result, agg_expected)
assert_series_equal(trans_result, trans_expected)
# DataFrame
df_grouped = self.tsframe.groupby(lambda x: x.month)
agg_result = df_grouped.agg(percentile, 80, axis=0)
apply_result = df_grouped.apply(DataFrame.quantile, .8)
expected = df_grouped.quantile(.8)
assert_frame_equal(apply_result, expected)
assert_frame_equal(agg_result, expected)
agg_result = df_grouped.agg(f, q=80)
apply_result = df_grouped.apply(DataFrame.quantile, q=.8)
assert_frame_equal(agg_result, expected)
assert_frame_equal(apply_result, expected)
# def test_cython_na_bug(self):
# values = np.random.randn(10)
# shape = (5, 5)
# label_list = [np.array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2], dtype=np.int32),
# np.array([1, 2, 3, 4, 0, 1, 2, 3, 3, 4], dtype=np.int32)]
# lib.group_aggregate(values, label_list, shape)
def test_size(self):
grouped = self.df.groupby(['A', 'B'])
result = grouped.size()
for key, group in grouped:
self.assertEqual(result[key], len(group))
grouped = self.df.groupby('A')
result = grouped.size()
for key, group in grouped:
self.assertEqual(result[key], len(group))
grouped = self.df.groupby('B')
result = grouped.size()
for key, group in grouped:
self.assertEqual(result[key], len(group))
def test_count(self):
# GH5610
# count counts non-nulls
df = pd.DataFrame([[1, 2, 'foo'], [1, nan, 'bar'], [3, nan, nan]],
columns=['A', 'B', 'C'])
count_as = df.groupby('A').count()
count_not_as = df.groupby('A', as_index=False).count()
expected = DataFrame([[1, 2], [0, 0]], columns=['B', 'C'], index=[1,3])
expected.index.name='A'
assert_frame_equal(count_not_as, expected.reset_index())
assert_frame_equal(count_as, expected)
count_B = df.groupby('A')['B'].count()
assert_series_equal(count_B, expected['B'])
def test_count_object(self):
df = pd.DataFrame({'a': ['a'] * 3 + ['b'] * 3,
'c': [2] * 3 + [3] * 3})
result = df.groupby('c').a.count()
expected = pd.Series([3, 3], index=[2, 3], name='a')
tm.assert_series_equal(result, expected)
df = pd.DataFrame({'a': ['a', np.nan, np.nan] + ['b'] * 3,
'c': [2] * 3 + [3] * 3})
result = df.groupby('c').a.count()
expected = pd.Series([1, 3], index=[2, 3], name='a')
tm.assert_series_equal(result, expected)
def test_count_cross_type(self): # GH8169
vals = np.hstack((np.random.randint(0,5,(100,2)),
np.random.randint(0,2,(100,2))))
df = pd.DataFrame(vals, columns=['a', 'b', 'c', 'd'])
df[df==2] = np.nan
expected = df.groupby(['c', 'd']).count()
for t in ['float32', 'object']:
df['a'] = df['a'].astype(t)
df['b'] = df['b'].astype(t)
result = df.groupby(['c', 'd']).count()
tm.assert_frame_equal(result, expected)
def test_non_cython_api(self):
# GH5610
# non-cython calls should not include the grouper
df = DataFrame([[1, 2, 'foo'], [1, nan, 'bar',], [3, nan, 'baz']], columns=['A', 'B','C'])
g = df.groupby('A')
gni = df.groupby('A',as_index=False)
# mad
expected = DataFrame([[0],[nan]],columns=['B'],index=[1,3])
expected.index.name = 'A'
result = g.mad()
assert_frame_equal(result,expected)
expected = DataFrame([[0.,0.],[0,nan]],columns=['A','B'],index=[0,1])
result = gni.mad()
assert_frame_equal(result,expected)
# describe
expected = DataFrame(dict(B = concat([df.loc[[0,1],'B'].describe(),df.loc[[2],'B'].describe()],keys=[1,3])))
expected.index.names = ['A',None]
result = g.describe()
assert_frame_equal(result,expected)
expected = concat([df.loc[[0,1],['A','B']].describe(),df.loc[[2],['A','B']].describe()],keys=[0,1])
result = gni.describe()
assert_frame_equal(result,expected)
# any
expected = DataFrame([[True, True],[False, True]],columns=['B','C'],index=[1,3])
expected.index.name = 'A'
result = g.any()
assert_frame_equal(result,expected)
# idxmax
expected = DataFrame([[0],[nan]],columns=['B'],index=[1,3])
expected.index.name = 'A'
result = g.idxmax()
assert_frame_equal(result,expected)
def test_cython_api2(self):
# this takes the fast apply path
# cumsum (GH5614)
df = DataFrame([[1, 2, np.nan], [1, np.nan, 9], [3, 4, 9]], columns=['A', 'B', 'C'])
expected = DataFrame([[2, np.nan], [np.nan, 9], [4, 9]], columns=['B', 'C'])
result = df.groupby('A').cumsum()
assert_frame_equal(result,expected)
expected = DataFrame([[1, 2, np.nan], [2, np.nan, 9], [3, 4, 9]], columns=['A', 'B', 'C']).astype('float64')
result = df.groupby('A', as_index=False).cumsum()
assert_frame_equal(result,expected)
def test_grouping_ndarray(self):
grouped = self.df.groupby(self.df['A'].values)
result = grouped.sum()
expected = self.df.groupby('A').sum()
assert_frame_equal(result, expected, check_names=False) # Note: no names when grouping by value
def test_agg_consistency(self):
# agg with ([]) and () not consistent
# GH 6715
def P1(a):
try:
return np.percentile(a.dropna(), q=1)
except:
return np.nan
import datetime as dt
df = DataFrame({'col1':[1,2,3,4],
'col2':[10,25,26,31],
'date':[dt.date(2013,2,10),dt.date(2013,2,10),dt.date(2013,2,11),dt.date(2013,2,11)]})
g = df.groupby('date')
expected = g.agg([P1])
expected.columns = expected.columns.levels[0]
result = g.agg(P1)
assert_frame_equal(result, expected)
def test_apply_typecast_fail(self):
df = DataFrame({'d': [1., 1., 1., 2., 2., 2.],
'c': np.tile(['a', 'b', 'c'], 2),
'v': np.arange(1., 7.)})
def f(group):
v = group['v']
group['v2'] = (v - v.min()) / (v.max() - v.min())
return group
result = df.groupby('d').apply(f)
expected = df.copy()
expected['v2'] = np.tile([0., 0.5, 1], 2)
assert_frame_equal(result, expected)
def test_apply_multiindex_fail(self):
index = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1],
[1, 2, 3, 1, 2, 3]])
df = DataFrame({'d': [1., 1., 1., 2., 2., 2.],
'c': np.tile(['a', 'b', 'c'], 2),
'v': np.arange(1., 7.)}, index=index)
def f(group):
v = group['v']
group['v2'] = (v - v.min()) / (v.max() - v.min())
return group
result = df.groupby('d').apply(f)
expected = df.copy()
expected['v2'] = np.tile([0., 0.5, 1], 2)
assert_frame_equal(result, expected)
def test_apply_corner(self):
result = self.tsframe.groupby(lambda x: x.year).apply(lambda x: x * 2)
expected = self.tsframe * 2
assert_frame_equal(result, expected)
def test_apply_without_copy(self):
# GH 5545
# returning a non-copy in an applied function fails
data = DataFrame({'id_field' : [100, 100, 200, 300], 'category' : ['a','b','c','c'], 'value' : [1,2,3,4]})
def filt1(x):
if x.shape[0] == 1:
return x.copy()
else:
return x[x.category == 'c']
def filt2(x):
if x.shape[0] == 1:
return x
else:
return x[x.category == 'c']
expected = data.groupby('id_field').apply(filt1)
result = data.groupby('id_field').apply(filt2)
assert_frame_equal(result,expected)
def test_apply_use_categorical_name(self):
from pandas import qcut
cats = qcut(self.df.C, 4)
def get_stats(group):
return {'min': group.min(), 'max': group.max(),
'count': group.count(), 'mean': group.mean()}
result = self.df.groupby(cats).D.apply(get_stats)
self.assertEqual(result.index.names[0], 'C')
def test_apply_corner_cases(self):
# #535, can't use sliding iterator
N = 1000
labels = np.random.randint(0, 100, size=N)
df = DataFrame({'key': labels,
'value1': np.random.randn(N),
'value2': ['foo', 'bar', 'baz', 'qux'] * (N // 4)})
grouped = df.groupby('key')
def f(g):
g['value3'] = g['value1'] * 2
return g
result = grouped.apply(f)
self.assertTrue('value3' in result)
def test_transform_mixed_type(self):
index = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1],
[1, 2, 3, 1, 2, 3]])
df = DataFrame({'d': [1., 1., 1., 2., 2., 2.],
'c': np.tile(['a', 'b', 'c'], 2),
'v': np.arange(1., 7.)}, index=index)
def f(group):
group['g'] = group['d'] * 2
return group[:1]
grouped = df.groupby('c')
result = grouped.apply(f)
self.assertEqual(result['d'].dtype, np.float64)
# this is by definition a mutating operation!
with option_context('mode.chained_assignment',None):
for key, group in grouped:
res = f(group)
assert_frame_equal(res, result.ix[key])
def test_groupby_wrong_multi_labels(self):
from pandas import read_csv
data = """index,foo,bar,baz,spam,data
0,foo1,bar1,baz1,spam2,20
1,foo1,bar2,baz1,spam3,30
2,foo2,bar2,baz1,spam2,40
3,foo1,bar1,baz2,spam1,50
4,foo3,bar1,baz2,spam1,60"""
data = read_csv(StringIO(data), index_col=0)
grouped = data.groupby(['foo', 'bar', 'baz', 'spam'])
result = grouped.agg(np.mean)
expected = grouped.mean()
assert_frame_equal(result, expected)
def test_groupby_series_with_name(self):
result = self.df.groupby(self.df['A']).mean()
result2 = self.df.groupby(self.df['A'], as_index=False).mean()
self.assertEqual(result.index.name, 'A')
self.assertIn('A', result2)
result = self.df.groupby([self.df['A'], self.df['B']]).mean()
result2 = self.df.groupby([self.df['A'], self.df['B']],
as_index=False).mean()
self.assertEqual(result.index.names, ('A', 'B'))
self.assertIn('A', result2)
self.assertIn('B', result2)
def test_seriesgroupby_name_attr(self):
# GH 6265
result = self.df.groupby('A')['C']
self.assertEqual(result.count().name, 'C')
self.assertEqual(result.mean().name, 'C')
testFunc = lambda x: np.sum(x)*2
self.assertEqual(result.agg(testFunc).name, 'C')
def test_groupby_name_propagation(self):
# GH 6124
def summarize(df, name=None):
return Series({
'count': 1,
'mean': 2,
'omissions': 3,
}, name=name)
def summarize_random_name(df):
# Provide a different name for each Series. In this case, groupby
# should not attempt to propagate the Series name since they are
# inconsistent.
return Series({
'count': 1,
'mean': 2,
'omissions': 3,
}, name=df.iloc[0]['A'])
metrics = self.df.groupby('A').apply(summarize)
self.assertEqual(metrics.columns.name, None)
metrics = self.df.groupby('A').apply(summarize, 'metrics')
self.assertEqual(metrics.columns.name, 'metrics')
metrics = self.df.groupby('A').apply(summarize_random_name)
self.assertEqual(metrics.columns.name, None)
def test_groupby_nonstring_columns(self):
df = DataFrame([np.arange(10) for x in range(10)])
grouped = df.groupby(0)
result = grouped.mean()
expected = df.groupby(df[0]).mean()
assert_frame_equal(result, expected)
def test_cython_grouper_series_bug_noncontig(self):
arr = np.empty((100, 100))
arr.fill(np.nan)
obj = Series(arr[:, 0], index=lrange(100))
inds = np.tile(lrange(10), 10)
result = obj.groupby(inds).agg(Series.median)
self.assertTrue(result.isnull().all())
def test_series_grouper_noncontig_index(self):
index = Index(tm.rands_array(10, 100))
values = Series(np.random.randn(50), index=index[::2])
labels = np.random.randint(0, 5, 50)
# it works!
grouped = values.groupby(labels)
# accessing the index elements causes segfault
f = lambda x: len(set(map(id, x.index)))
grouped.agg(f)
def test_convert_objects_leave_decimal_alone(self):
from decimal import Decimal
s = Series(lrange(5))
labels = np.array(['a', 'b', 'c', 'd', 'e'], dtype='O')
def convert_fast(x):
return Decimal(str(x.mean()))
def convert_force_pure(x):
# base will be length 0
assert(len(x.base) > 0)
return Decimal(str(x.mean()))
grouped = s.groupby(labels)
result = grouped.agg(convert_fast)
self.assertEqual(result.dtype, np.object_)
tm.assert_isinstance(result[0], Decimal)
result = grouped.agg(convert_force_pure)
self.assertEqual(result.dtype, np.object_)
tm.assert_isinstance(result[0], Decimal)
def test_fast_apply(self):
# make sure that fast apply is correctly called
# rather than raising any kind of error
# otherwise the python path will be callsed
# which slows things down
N = 1000
labels = np.random.randint(0, 2000, size=N)
labels2 = np.random.randint(0, 3, size=N)
df = DataFrame({'key': labels,
'key2': labels2,
'value1': np.random.randn(N),
'value2': ['foo', 'bar', 'baz', 'qux'] * (N // 4)})
def f(g):
return 1
g = df.groupby(['key', 'key2'])
grouper = g.grouper
splitter = grouper._get_splitter(g._selected_obj, axis=g.axis)
group_keys = grouper._get_group_keys()
values, mutated = splitter.fast_apply(f, group_keys)
self.assertFalse(mutated)
def test_apply_with_mixed_dtype(self):
# GH3480, apply with mixed dtype on axis=1 breaks in 0.11
df = DataFrame({'foo1' : ['one', 'two', 'two', 'three', 'one', 'two'],
'foo2' : np.random.randn(6)})
result = df.apply(lambda x: x, axis=1)
assert_series_equal(df.get_dtype_counts(), result.get_dtype_counts())
# GH 3610 incorrect dtype conversion with as_index=False
df = DataFrame({"c1" : [1,2,6,6,8]})
df["c2"] = df.c1/2.0
result1 = df.groupby("c2").mean().reset_index().c2
result2 = df.groupby("c2", as_index=False).mean().c2
assert_series_equal(result1,result2)
def test_groupby_aggregation_mixed_dtype(self):
# GH 6212
expected = DataFrame({
'v1': [5,5,7,np.nan,3,3,4,1],
'v2': [55,55,77,np.nan,33,33,44,11]},
index=MultiIndex.from_tuples([(1,95),(1,99),(2,95),(2,99),('big','damp'),
('blue','dry'),('red','red'),('red','wet')],
names=['by1','by2']))
df = DataFrame({
'v1': [1,3,5,7,8,3,5,np.nan,4,5,7,9],
'v2': [11,33,55,77,88,33,55,np.nan,44,55,77,99],
'by1': ["red", "blue", 1, 2, np.nan, "big", 1, 2, "red", 1, np.nan, 12],
'by2': ["wet", "dry", 99, 95, np.nan, "damp", 95, 99, "red", 99, np.nan,
np.nan]
})
g = df.groupby(['by1','by2'])
result = g[['v1','v2']].mean()
assert_frame_equal(result,expected)
def test_groupby_dtype_inference_empty(self):
# GH 6733
df = DataFrame({'x': [], 'range': np.arange(0,dtype='int64')})
result = df.groupby('x').first()
expected = DataFrame({'range' : Series([],index=Index([],name='x'),dtype='int64') })
assert_frame_equal(result,expected,by_blocks=True)
def test_groupby_list_infer_array_like(self):
result = self.df.groupby(list(self.df['A'])).mean()
expected = self.df.groupby(self.df['A']).mean()
assert_frame_equal(result, expected, check_names=False)
self.assertRaises(Exception, self.df.groupby, list(self.df['A'][:-1]))
# pathological case of ambiguity
df = DataFrame({'foo': [0, 1], 'bar': [3, 4],
'val': np.random.randn(2)})
result = df.groupby(['foo', 'bar']).mean()
expected = df.groupby([df['foo'], df['bar']]).mean()[['val']]
def test_dictify(self):
dict(iter(self.df.groupby('A')))
dict(iter(self.df.groupby(['A', 'B'])))
dict(iter(self.df['C'].groupby(self.df['A'])))
dict(iter(self.df['C'].groupby([self.df['A'], self.df['B']])))
dict(iter(self.df.groupby('A')['C']))
dict(iter(self.df.groupby(['A', 'B'])['C']))
def test_sparse_friendly(self):
sdf = self.df[['C', 'D']].to_sparse()
panel = tm.makePanel()
tm.add_nans(panel)
def _check_work(gp):
gp.mean()
gp.agg(np.mean)
dict(iter(gp))
# it works!
_check_work(sdf.groupby(lambda x: x // 2))
_check_work(sdf['C'].groupby(lambda x: x // 2))
_check_work(sdf.groupby(self.df['A']))
# do this someday
# _check_work(panel.groupby(lambda x: x.month, axis=1))
def test_panel_groupby(self):
self.panel = tm.makePanel()
tm.add_nans(self.panel)
grouped = self.panel.groupby({'ItemA': 0, 'ItemB': 0, 'ItemC': 1},
axis='items')
agged = grouped.mean()
agged2 = grouped.agg(lambda x: x.mean('items'))
tm.assert_panel_equal(agged, agged2)
self.assert_numpy_array_equal(agged.items, [0, 1])
grouped = self.panel.groupby(lambda x: x.month, axis='major')
agged = grouped.mean()
self.assert_numpy_array_equal(agged.major_axis, sorted(list(set(self.panel.major_axis.month))))
grouped = self.panel.groupby({'A': 0, 'B': 0, 'C': 1, 'D': 1},
axis='minor')
agged = grouped.mean()
self.assert_numpy_array_equal(agged.minor_axis, [0, 1])
def test_numpy_groupby(self):
from pandas.core.groupby import numpy_groupby
data = np.random.randn(100, 100)
labels = np.random.randint(0, 10, size=100)
df = DataFrame(data)
result = df.groupby(labels).sum().values
expected = numpy_groupby(data, labels)
assert_almost_equal(result, expected)
result = df.groupby(labels, axis=1).sum().values
expected = numpy_groupby(data, labels, axis=1)
assert_almost_equal(result, expected)
def test_groupby_2d_malformed(self):
d = DataFrame(index=lrange(2))
d['group'] = ['g1', 'g2']
d['zeros'] = [0, 0]
d['ones'] = [1, 1]
d['label'] = ['l1', 'l2']
tmp = d.groupby(['group']).mean()
res_values = np.array([[0., 1.], [0., 1.]])
self.assert_numpy_array_equal(tmp.columns, ['zeros', 'ones'])
self.assert_numpy_array_equal(tmp.values, res_values)
def test_int32_overflow(self):
B = np.concatenate((np.arange(10000), np.arange(10000),
np.arange(5000)))
A = np.arange(25000)
df = DataFrame({'A': A, 'B': B,
'C': A, 'D': B,
'E': np.random.randn(25000)})
left = df.groupby(['A', 'B', 'C', 'D']).sum()
right = df.groupby(['D', 'C', 'B', 'A']).sum()
self.assertEqual(len(left), len(right))
def test_int64_overflow(self):
from pandas.core.groupby import _int64_overflow_possible
B = np.concatenate((np.arange(1000), np.arange(1000),
np.arange(500)))
A = np.arange(2500)
df = DataFrame({'A': A, 'B': B,
'C': A, 'D': B,
'E': A, 'F': B,
'G': A, 'H': B,
'values': np.random.randn(2500)})
lg = df.groupby(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'])
rg = df.groupby(['H', 'G', 'F', 'E', 'D', 'C', 'B', 'A'])
left = lg.sum()['values']
right = rg.sum()['values']
exp_index, _ = left.index.sortlevel(0)
self.assertTrue(left.index.equals(exp_index))
exp_index, _ = right.index.sortlevel(0)
self.assertTrue(right.index.equals(exp_index))
tups = list(map(tuple, df[['A', 'B', 'C', 'D',
'E', 'F', 'G', 'H']].values))
tups = com._asarray_tuplesafe(tups)
expected = df.groupby(tups).sum()['values']
for k, v in compat.iteritems(expected):
self.assertEqual(left[k], right[k[::-1]])
self.assertEqual(left[k], v)
self.assertEqual(len(left), len(right))
# GH9096
values = range(55109)
data = pd.DataFrame.from_dict({'a': values, 'b': values,
'c': values, 'd': values})
grouped = data.groupby(['a', 'b', 'c', 'd'])
self.assertEqual(len(grouped), len(values))
arr = np.random.randint(- 1 << 12, 1 << 12, (1 << 15, 5))
i = np.random.choice(len(arr), len(arr) * 4)
arr = np.vstack((arr, arr[i])) # add sume duplicate rows
i = np.random.permutation(len(arr))
arr = arr[i] # shuffle rows
df = DataFrame(arr, columns=list('abcde'))
df['jim'], df['joe'] = np.random.randn(2, len(df)) * 10
gr = df.groupby(list('abcde'))
# verify this is testing what it is supposed to test!
self.assertTrue(_int64_overflow_possible(gr.grouper.shape))
# mannually compute groupings
jim, joe = defaultdict(list), defaultdict(list)
for key, a, b in zip(map(tuple, arr), df['jim'], df['joe']):
jim[key].append(a)
joe[key].append(b)
self.assertEqual(len(gr), len(jim))
mi = MultiIndex.from_tuples(jim.keys(), names=list('abcde'))
def aggr(func):
f = lambda a: np.fromiter(map(func, a), dtype='f8')
arr = np.vstack((f(jim.values()), f(joe.values()))).T
res = DataFrame(arr, columns=['jim', 'joe'], index=mi)
return res.sort_index()
assert_frame_equal(gr.mean(), aggr(np.mean))
assert_frame_equal(gr.median(), aggr(np.median))
def test_groupby_sort_multi(self):
df = DataFrame({'a': ['foo', 'bar', 'baz'],
'b': [3, 2, 1],
'c': [0, 1, 2],
'd': np.random.randn(3)})
tups = lmap(tuple, df[['a', 'b', 'c']].values)
tups = com._asarray_tuplesafe(tups)
result = df.groupby(['a', 'b', 'c'], sort=True).sum()
self.assert_numpy_array_equal(result.index.values,
tups[[1, 2, 0]])
tups = lmap(tuple, df[['c', 'a', 'b']].values)
tups = com._asarray_tuplesafe(tups)
result = df.groupby(['c', 'a', 'b'], sort=True).sum()
self.assert_numpy_array_equal(result.index.values, tups)
tups = lmap(tuple, df[['b', 'c', 'a']].values)
tups = com._asarray_tuplesafe(tups)
result = df.groupby(['b', 'c', 'a'], sort=True).sum()
self.assert_numpy_array_equal(result.index.values,
tups[[2, 1, 0]])
df = DataFrame({'a': [0, 1, 2, 0, 1, 2],
'b': [0, 0, 0, 1, 1, 1],
'd': np.random.randn(6)})
grouped = df.groupby(['a', 'b'])['d']
result = grouped.sum()
_check_groupby(df, result, ['a', 'b'], 'd')
def test_intercept_builtin_sum(self):
s = Series([1., 2., np.nan, 3.])
grouped = s.groupby([0, 1, 2, 2])
result = grouped.agg(builtins.sum)
result2 = grouped.apply(builtins.sum)
expected = grouped.sum()
assert_series_equal(result, expected)
assert_series_equal(result2, expected)
def test_column_select_via_attr(self):
result = self.df.groupby('A').C.sum()
expected = self.df.groupby('A')['C'].sum()
assert_series_equal(result, expected)
self.df['mean'] = 1.5
result = self.df.groupby('A').mean()
expected = self.df.groupby('A').agg(np.mean)
assert_frame_equal(result, expected)
def test_rank_apply(self):
lev1 = tm.rands_array(10, 100)
lev2 = tm.rands_array(10, 130)
lab1 = np.random.randint(0, 100, size=500)
lab2 = np.random.randint(0, 130, size=500)
df = DataFrame({'value': np.random.randn(500),
'key1': lev1.take(lab1),
'key2': lev2.take(lab2)})
result = df.groupby(['key1', 'key2']).value.rank()
expected = []
for key, piece in df.groupby(['key1', 'key2']):
expected.append(piece.value.rank())
expected = concat(expected, axis=0)
expected = expected.reindex(result.index)
assert_series_equal(result, expected)
result = df.groupby(['key1', 'key2']).value.rank(pct=True)
expected = []
for key, piece in df.groupby(['key1', 'key2']):
expected.append(piece.value.rank(pct=True))
expected = concat(expected, axis=0)
expected = expected.reindex(result.index)
assert_series_equal(result, expected)
def test_dont_clobber_name_column(self):
df = DataFrame({'key': ['a', 'a', 'a', 'b', 'b', 'b'],
'name': ['foo', 'bar', 'baz'] * 2})
result = df.groupby('key').apply(lambda x: x)
assert_frame_equal(result, df)
def test_skip_group_keys(self):
from pandas import concat
tsf = tm.makeTimeDataFrame()
grouped = tsf.groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.sort_index(by='A')[:3])
pieces = []
for key, group in grouped:
pieces.append(group.sort_index(by='A')[:3])
expected = concat(pieces)
assert_frame_equal(result, expected)
grouped = tsf['A'].groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.order()[:3])
pieces = []
for key, group in grouped:
pieces.append(group.order()[:3])
expected = concat(pieces)
assert_series_equal(result, expected)
def test_no_nonsense_name(self):
# GH #995
s = self.frame['C'].copy()
s.name = None
result = s.groupby(self.frame['A']).agg(np.sum)
self.assertIsNone(result.name)
def test_wrap_agg_out(self):
grouped = self.three_group.groupby(['A', 'B'])
def func(ser):
if ser.dtype == np.object:
raise TypeError
else:
return ser.sum()
result = grouped.aggregate(func)
exp_grouped = self.three_group.ix[:, self.three_group.columns != 'C']
expected = exp_grouped.groupby(['A', 'B']).aggregate(func)
assert_frame_equal(result, expected)
def test_multifunc_sum_bug(self):
# GH #1065
x = DataFrame(np.arange(9).reshape(3, 3))
x['test'] = 0
x['fl'] = [1.3, 1.5, 1.6]
grouped = x.groupby('test')
result = grouped.agg({'fl': 'sum', 2: 'size'})
self.assertEqual(result['fl'].dtype, np.float64)
def test_handle_dict_return_value(self):
def f(group):
return {'min': group.min(), 'max': group.max()}
def g(group):
return Series({'min': group.min(), 'max': group.max()})
result = self.df.groupby('A')['C'].apply(f)
expected = self.df.groupby('A')['C'].apply(g)
tm.assert_isinstance(result, Series)
assert_series_equal(result, expected)
def test_getitem_list_of_columns(self):
df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8),
'E': np.random.randn(8)})
result = df.groupby('A')[['C', 'D']].mean()
result2 = df.groupby('A')['C', 'D'].mean()
result3 = df.groupby('A')[df.columns[2:4]].mean()
expected = df.ix[:, ['A', 'C', 'D']].groupby('A').mean()
assert_frame_equal(result, expected)
assert_frame_equal(result2, expected)
assert_frame_equal(result3, expected)
def test_agg_multiple_functions_maintain_order(self):
# GH #610
funcs = [('mean', np.mean), ('max', np.max), ('min', np.min)]
result = self.df.groupby('A')['C'].agg(funcs)
exp_cols = ['mean', 'max', 'min']
self.assert_numpy_array_equal(result.columns, exp_cols)
def test_multiple_functions_tuples_and_non_tuples(self):
# #1359
funcs = [('foo', 'mean'), 'std']
ex_funcs = [('foo', 'mean'), ('std', 'std')]
result = self.df.groupby('A')['C'].agg(funcs)
expected = self.df.groupby('A')['C'].agg(ex_funcs)
assert_frame_equal(result, expected)
result = self.df.groupby('A').agg(funcs)
expected = self.df.groupby('A').agg(ex_funcs)
assert_frame_equal(result, expected)
def test_agg_multiple_functions_too_many_lambdas(self):
grouped = self.df.groupby('A')
funcs = ['mean', lambda x: x.mean(), lambda x: x.std()]
self.assertRaises(SpecificationError, grouped.agg, funcs)
def test_more_flexible_frame_multi_function(self):
from pandas import concat
grouped = self.df.groupby('A')
exmean = grouped.agg(OrderedDict([['C', np.mean], ['D', np.mean]]))
exstd = grouped.agg(OrderedDict([['C', np.std], ['D', np.std]]))
expected = concat([exmean, exstd], keys=['mean', 'std'], axis=1)
expected = expected.swaplevel(0, 1, axis=1).sortlevel(0, axis=1)
d = OrderedDict([['C', [np.mean, np.std]], ['D', [np.mean, np.std]]])
result = grouped.aggregate(d)
assert_frame_equal(result, expected)
# be careful
result = grouped.aggregate(OrderedDict([['C', np.mean],
['D', [np.mean, np.std]]]))
expected = grouped.aggregate(OrderedDict([['C', np.mean],
['D', [np.mean, np.std]]]))
assert_frame_equal(result, expected)
def foo(x):
return np.mean(x)
def bar(x):
return np.std(x, ddof=1)
d = OrderedDict([['C', np.mean],
['D', OrderedDict([['foo', np.mean],
['bar', np.std]])]])
result = grouped.aggregate(d)
d = OrderedDict([['C', [np.mean]], ['D', [foo, bar]]])
expected = grouped.aggregate(d)
assert_frame_equal(result, expected)
def test_multi_function_flexible_mix(self):
# GH #1268
grouped = self.df.groupby('A')
d = OrderedDict([['C', OrderedDict([['foo', 'mean'],
[
'bar', 'std']])],
['D', 'sum']])
result = grouped.aggregate(d)
d2 = OrderedDict([['C', OrderedDict([['foo', 'mean'],
[
'bar', 'std']])],
['D', ['sum']]])
result2 = grouped.aggregate(d2)
d3 = OrderedDict([['C', OrderedDict([['foo', 'mean'],
[
'bar', 'std']])],
['D', {'sum': 'sum'}]])
expected = grouped.aggregate(d3)
assert_frame_equal(result, expected)
assert_frame_equal(result2, expected)
def test_agg_callables(self):
# GH 7929
df = DataFrame({'foo' : [1,2], 'bar' :[3,4]}).astype(np.int64)
class fn_class(object):
def __call__(self, x):
return sum(x)
equiv_callables = [sum, np.sum,
lambda x: sum(x),
lambda x: x.sum(),
partial(sum), fn_class()]
expected = df.groupby("foo").agg(sum)
for ecall in equiv_callables:
result = df.groupby('foo').agg(ecall)
assert_frame_equal(result, expected)
def test_set_group_name(self):
def f(group):
assert group.name is not None
return group
def freduce(group):
assert group.name is not None
return group.sum()
def foo(x):
return freduce(x)
def _check_all(grouped):
# make sure all these work
grouped.apply(f)
grouped.aggregate(freduce)
grouped.aggregate({'C': freduce, 'D': freduce})
grouped.transform(f)
grouped['C'].apply(f)
grouped['C'].aggregate(freduce)
grouped['C'].aggregate([freduce, foo])
grouped['C'].transform(f)
_check_all(self.df.groupby('A'))
_check_all(self.df.groupby(['A', 'B']))
def test_no_dummy_key_names(self):
# GH #1291
result = self.df.groupby(self.df['A'].values).sum()
self.assertIsNone(result.index.name)
result = self.df.groupby([self.df['A'].values,
self.df['B'].values]).sum()
self.assertEqual(result.index.names, (None, None))
def test_groupby_sort_categorical(self):
# dataframe groupby sort was being ignored # GH 8868
df = DataFrame([['(7.5, 10]', 10, 10],
['(7.5, 10]', 8, 20],
['(2.5, 5]', 5, 30],
['(5, 7.5]', 6, 40],
['(2.5, 5]', 4, 50],
['(0, 2.5]', 1, 60],
['(5, 7.5]', 7, 70]], columns=['range', 'foo', 'bar'])
df['range'] = Categorical(df['range'],ordered=True)
index = Index(['(0, 2.5]', '(2.5, 5]', '(5, 7.5]', '(7.5, 10]'], dtype='object')
index.name = 'range'
result_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]], columns=['foo', 'bar'])
result_sort.index = index
index = Index(['(7.5, 10]', '(2.5, 5]', '(5, 7.5]', '(0, 2.5]'], dtype='object')
index.name = 'range'
result_nosort = DataFrame([[10, 10], [5, 30], [6, 40], [1, 60]], index=index, columns=['foo', 'bar'])
result_nosort.index = index
col = 'range'
assert_frame_equal(result_sort, df.groupby(col, sort=True).first())
assert_frame_equal(result_nosort, df.groupby(col, sort=False).first())
df['range'] = Categorical(df['range'],ordered=False)
index = Index(['(0, 2.5]', '(2.5, 5]', '(5, 7.5]', '(7.5, 10]'], dtype='object')
index.name = 'range'
result_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]], columns=['foo', 'bar'])
result_sort.index = index
index = Index(['(7.5, 10]', '(2.5, 5]', '(5, 7.5]', '(0, 2.5]'], dtype='object')
index.name = 'range'
result_nosort = DataFrame([[10, 10], [5, 30], [6, 40], [1, 60]], index=index, columns=['foo', 'bar'])
result_nosort.index = index
col = 'range'
#### this is an unordered categorical, but we allow this ####
assert_frame_equal(result_sort, df.groupby(col, sort=True).first())
assert_frame_equal(result_nosort, df.groupby(col, sort=False).first())
def test_groupby_sort_multiindex_series(self):
# series multiindex groupby sort argument was not being passed through _compress_group_index
# GH 9444
index = MultiIndex(levels=[[1, 2], [1, 2]],
labels=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]],
names=['a', 'b'])
mseries = Series([0, 1, 2, 3, 4, 5], index=index)
index = MultiIndex(levels=[[1, 2], [1, 2]],
labels=[[0, 0, 1], [1, 0, 0]],
names=['a', 'b'])
mseries_result = Series([0, 2, 4], index=index)
result = mseries.groupby(level=['a', 'b'], sort=False).first()
assert_series_equal(result, mseries_result)
result = mseries.groupby(level=['a', 'b'], sort=True).first()
assert_series_equal(result, mseries_result.sort_index())
def test_groupby_categorical(self):
levels = ['foo', 'bar', 'baz', 'qux']
codes = np.random.randint(0, 4, size=100)
cats = Categorical.from_codes(codes, levels, name='myfactor', ordered=True)
data = DataFrame(np.random.randn(100, 4))
result = data.groupby(cats).mean()
expected = data.groupby(np.asarray(cats)).mean()
expected = expected.reindex(levels)
expected.index.name = 'myfactor'
assert_frame_equal(result, expected)
self.assertEqual(result.index.name, cats.name)
grouped = data.groupby(cats)
desc_result = grouped.describe()
idx = cats.codes.argsort()
ord_labels = np.asarray(cats).take(idx)
ord_data = data.take(idx)
expected = ord_data.groupby(ord_labels, sort=False).describe()
expected.index.names = ['myfactor', None]
assert_frame_equal(desc_result, expected)
def test_groupby_datetime_categorical(self):
# GH9049: ensure backward compatibility
levels = pd.date_range('2014-01-01', periods=4)
codes = np.random.randint(0, 4, size=100)
cats = Categorical.from_codes(codes, levels, name='myfactor', ordered=True)
data = DataFrame(np.random.randn(100, 4))
result = data.groupby(cats).mean()
expected = data.groupby(np.asarray(cats)).mean()
expected = expected.reindex(levels)
expected.index.name = 'myfactor'
assert_frame_equal(result, expected)
self.assertEqual(result.index.name, cats.name)
grouped = data.groupby(cats)
desc_result = grouped.describe()
idx = cats.codes.argsort()
ord_labels = np.asarray(cats).take(idx)
ord_data = data.take(idx)
expected = ord_data.groupby(ord_labels, sort=False).describe()
expected.index.names = ['myfactor', None]
assert_frame_equal(desc_result, expected)
def test_groupby_groups_datetimeindex(self):
# #1430
from pandas.tseries.api import DatetimeIndex
periods = 1000
ind = DatetimeIndex(start='2012/1/1', freq='5min', periods=periods)
df = DataFrame({'high': np.arange(periods),
'low': np.arange(periods)}, index=ind)
grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))
# it works!
groups = grouped.groups
tm.assert_isinstance(list(groups.keys())[0], datetime)
def test_groupby_groups_datetimeindex_tz(self):
# GH 3950
dates = ['2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00',
'2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00']
df = DataFrame({'label': ['a', 'a', 'a', 'b', 'b', 'b'],
'datetime': dates,
'value1': np.arange(6,dtype='int64'),
'value2': [1, 2] * 3})
df['datetime'] = df['datetime'].apply(lambda d: Timestamp(d, tz='US/Pacific'))
exp_idx1 = pd.DatetimeIndex(['2011-07-19 07:00:00', '2011-07-19 07:00:00',
'2011-07-19 08:00:00', '2011-07-19 08:00:00',
'2011-07-19 09:00:00', '2011-07-19 09:00:00'],
tz='US/Pacific', name='datetime')
exp_idx2 = Index(['a', 'b'] * 3, name='label')
exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2])
expected = DataFrame({'value1': [0, 3, 1, 4, 2, 5], 'value2': [1, 2, 2, 1, 1, 2]},
index=exp_idx, columns=['value1', 'value2'])
result = df.groupby(['datetime', 'label']).sum()
assert_frame_equal(result, expected)
# by level
didx = pd.DatetimeIndex(dates, tz='Asia/Tokyo')
df = DataFrame({'value1': np.arange(6,dtype='int64'),
'value2': [1, 2, 3, 1, 2, 3]},
index=didx)
exp_idx = pd.DatetimeIndex(['2011-07-19 07:00:00', '2011-07-19 08:00:00',
'2011-07-19 09:00:00'], tz='Asia/Tokyo')
expected = DataFrame({'value1': [3, 5, 7], 'value2': [2, 4, 6]},
index=exp_idx, columns=['value1', 'value2'])
result = df.groupby(level=0).sum()
assert_frame_equal(result, expected)
def test_groupby_reindex_inside_function(self):
from pandas.tseries.api import DatetimeIndex
periods = 1000
ind = DatetimeIndex(start='2012/1/1', freq='5min', periods=periods)
df = DataFrame({'high': np.arange(
periods), 'low': np.arange(periods)}, index=ind)
def agg_before(hour, func, fix=False):
"""
Run an aggregate func on the subset of data.
"""
def _func(data):
d = data.select(lambda x: x.hour < 11).dropna()
if fix:
data[data.index[0]]
if len(d) == 0:
return None
return func(d)
return _func
def afunc(data):
d = data.select(lambda x: x.hour < 11).dropna()
return np.max(d)
grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))
closure_bad = grouped.agg({'high': agg_before(11, np.max)})
closure_good = grouped.agg({'high': agg_before(11, np.max, True)})
assert_frame_equal(closure_bad, closure_good)
def test_multiindex_columns_empty_level(self):
l = [['count', 'values'], ['to filter', '']]
midx = MultiIndex.from_tuples(l)
df = DataFrame([[long(1), 'A']], columns=midx)
grouped = df.groupby('to filter').groups
self.assert_numpy_array_equal(grouped['A'], [0])
grouped = df.groupby([('to filter', '')]).groups
self.assert_numpy_array_equal(grouped['A'], [0])
df = DataFrame([[long(1), 'A'], [long(2), 'B']], columns=midx)
expected = df.groupby('to filter').groups
result = df.groupby([('to filter', '')]).groups
self.assertEqual(result, expected)
df = DataFrame([[long(1), 'A'], [long(2), 'A']], columns=midx)
expected = df.groupby('to filter').groups
result = df.groupby([('to filter', '')]).groups
self.assertEqual(result, expected)
def test_cython_median(self):
df = DataFrame(np.random.randn(1000))
df.values[::2] = np.nan
labels = np.random.randint(0, 50, size=1000).astype(float)
labels[::17] = np.nan
result = df.groupby(labels).median()
exp = df.groupby(labels).agg(nanops.nanmedian)
assert_frame_equal(result, exp)
df = DataFrame(np.random.randn(1000, 5))
rs = df.groupby(labels).agg(np.median)
xp = df.groupby(labels).median()
assert_frame_equal(rs, xp)
def test_groupby_categorical_no_compress(self):
data = Series(np.random.randn(9))
codes = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])
cats = Categorical.from_codes(codes, [0, 1, 2], ordered=True)
result = data.groupby(cats).mean()
exp = data.groupby(codes).mean()
assert_series_equal(result, exp)
codes = np.array([0, 0, 0, 1, 1, 1, 3, 3, 3])
cats = Categorical.from_codes(codes, [0, 1, 2, 3], ordered=True)
result = data.groupby(cats).mean()
exp = data.groupby(codes).mean().reindex(cats.categories)
assert_series_equal(result, exp)
cats = Categorical(["a", "a", "a", "b", "b", "b", "c", "c", "c"],
categories=["a","b","c","d"], ordered=True)
data = DataFrame({"a":[1,1,1,2,2,2,3,4,5], "b":cats})
result = data.groupby("b").mean()
result = result["a"].values
exp = np.array([1,2,4,np.nan])
self.assert_numpy_array_equivalent(result, exp)
def test_groupby_non_arithmetic_agg_types(self):
# GH9311, GH6620
df = pd.DataFrame([{'a': 1, 'b': 1},
{'a': 1, 'b': 2},
{'a': 2, 'b': 3},
{'a': 2, 'b': 4}])
dtypes = ['int8', 'int16', 'int32', 'int64',
'float32', 'float64']
grp_exp = {'first': {'df': [{'a': 1, 'b': 1}, {'a': 2, 'b': 3}]},
'last': {'df': [{'a': 1, 'b': 2}, {'a': 2, 'b': 4}]},
'min': {'df': [{'a': 1, 'b': 1}, {'a': 2, 'b': 3}]},
'max': {'df': [{'a': 1, 'b': 2}, {'a': 2, 'b': 4}]},
'nth': {'df': [{'a': 1, 'b': 2}, {'a': 2, 'b': 4}],
'args': [1]},
'count': {'df': [{'a': 1, 'b': 2}, {'a': 2, 'b': 2}],
'out_type': 'int64'}}
for dtype in dtypes:
df_in = df.copy()
df_in['b'] = df_in.b.astype(dtype)
for method, data in compat.iteritems(grp_exp):
if 'args' not in data:
data['args'] = []
if 'out_type' in data:
out_type = data['out_type']
else:
out_type = dtype
exp = data['df']
df_out = pd.DataFrame(exp)
df_out['b'] = df_out.b.astype(out_type)
df_out.set_index('a', inplace=True)
grpd = df_in.groupby('a')
t = getattr(grpd, method)(*data['args'])
assert_frame_equal(t, df_out)
def test_groupby_non_arithmetic_agg_intlike_precision(self):
# GH9311, GH6620
c = 24650000000000000
inputs = ((Timestamp('2011-01-15 12:50:28.502376'),
Timestamp('2011-01-20 12:50:28.593448')),
(1 + c, 2 + c))
for i in inputs:
df = pd.DataFrame([{'a': 1,
'b': i[0]},
{'a': 1,
'b': i[1]}])
grp_exp = {'first': {'expected': i[0]},
'last': {'expected': i[1]},
'min': {'expected': i[0]},
'max': {'expected': i[1]},
'nth': {'expected': i[1], 'args': [1]},
'count': {'expected': 2}}
for method, data in compat.iteritems(grp_exp):
if 'args' not in data:
data['args'] = []
grpd = df.groupby('a')
res = getattr(grpd, method)(*data['args'])
self.assertEqual(res.iloc[0].b, data['expected'])
def test_groupby_first_datetime64(self):
df = DataFrame([(1, 1351036800000000000), (2, 1351036800000000000)])
df[1] = df[1].view('M8[ns]')
self.assertTrue(issubclass(df[1].dtype.type, np.datetime64))
result = df.groupby(level=0).first()
got_dt = result[1].dtype
self.assertTrue(issubclass(got_dt.type, np.datetime64))
result = df[1].groupby(level=0).first()
got_dt = result.dtype
self.assertTrue(issubclass(got_dt.type, np.datetime64))
def test_groupby_max_datetime64(self):
# GH 5869
# datetimelike dtype conversion from int
df = DataFrame(dict(A = Timestamp('20130101'), B = np.arange(5)))
expected = df.groupby('A')['A'].apply(lambda x: x.max())
result = df.groupby('A')['A'].max()
assert_series_equal(result,expected)
def test_groupby_datetime64_32_bit(self):
# GH 6410 / numpy 4328
# 32-bit under 1.9-dev indexing issue
df = DataFrame({"A": range(2), "B": [pd.Timestamp('2000-01-1')]*2})
result = df.groupby("A")["B"].transform(min)
expected = Series([pd.Timestamp('2000-01-1')]*2)
assert_series_equal(result,expected)
def test_groupby_categorical_unequal_len(self):
import pandas as pd
#GH3011
series = Series([np.nan, np.nan, 1, 1, 2, 2, 3, 3, 4, 4])
# The raises only happens with categorical, not with series of types category
bins = pd.cut(series.dropna().values, 4)
# len(bins) != len(series) here
self.assertRaises(ValueError,lambda : series.groupby(bins).mean())
def test_groupby_multiindex_missing_pair(self):
# GH9049
df = DataFrame({'group1': ['a','a','a','b'],
'group2': ['c','c','d','c'],
'value': [1,1,1,5]})
df = df.set_index(['group1', 'group2'])
df_grouped = df.groupby(level=['group1','group2'], sort=True)
res = df_grouped.agg('sum')
idx = MultiIndex.from_tuples([('a','c'), ('a','d'), ('b','c')], names=['group1', 'group2'])
exp = DataFrame([[2], [1], [5]], index=idx, columns=['value'])
tm.assert_frame_equal(res, exp)
def test_groupby_levels_and_columns(self):
# GH9344, GH9049
idx_names = ['x', 'y']
idx = pd.MultiIndex.from_tuples([(1, 1), (1, 2), (3, 4), (5, 6)], names=idx_names)
df = pd.DataFrame(np.arange(12).reshape(-1, 3), index=idx)
by_levels = df.groupby(level=idx_names).mean()
by_columns = df.reset_index().groupby(idx_names).mean()
tm.assert_frame_equal(by_levels, by_columns)
def test_gb_apply_list_of_unequal_len_arrays(self):
# GH1738
df = DataFrame({'group1': ['a','a','a','b','b','b','a','a','a','b','b','b'],
'group2': ['c','c','d','d','d','e','c','c','d','d','d','e'],
'weight': [1.1,2,3,4,5,6,2,4,6,8,1,2],
'value': [7.1,8,9,10,11,12,8,7,6,5,4,3]
})
df = df.set_index(['group1', 'group2'])
df_grouped = df.groupby(level=['group1','group2'], sort=True)
def noddy(value, weight):
out = np.array( value * weight ).repeat(3)
return out
# the kernel function returns arrays of unequal length
# pandas sniffs the first one, sees it's an array and not
# a list, and assumed the rest are of equal length
# and so tries a vstack
# don't die
no_toes = df_grouped.apply(lambda x: noddy(x.value, x.weight ))
def test_groupby_with_empty(self):
import pandas as pd
index = pd.DatetimeIndex(())
data = ()
series = pd.Series(data, index)
grouper = pd.tseries.resample.TimeGrouper('D')
grouped = series.groupby(grouper)
assert next(iter(grouped), None) is None
def test_groupby_with_timegrouper(self):
# GH 4161
# TimeGrouper requires a sorted index
# also verifies that the resultant index has the correct name
import datetime as DT
df_original = DataFrame({
'Buyer': 'Carl Carl Carl Carl Joe Carl'.split(),
'Quantity': [18,3,5,1,9,3],
'Date' : [
DT.datetime(2013,9,1,13,0),
DT.datetime(2013,9,1,13,5),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,3,10,0),
DT.datetime(2013,12,2,12,0),
DT.datetime(2013,9,2,14,0),
]})
# GH 6908 change target column's order
df_reordered = df_original.sort(columns='Quantity')
for df in [df_original, df_reordered]:
df = df.set_index(['Date'])
expected = DataFrame({ 'Quantity' : np.nan },
index=date_range('20130901 13:00:00','20131205 13:00:00',
freq='5D',name='Date',closed='left'))
expected.iloc[[0,6,18],0] = np.array([24.,6.,9.],dtype='float64')
result1 = df.resample('5D',how=sum)
assert_frame_equal(result1, expected)
df_sorted = df.sort_index()
result2 = df_sorted.groupby(pd.TimeGrouper(freq='5D')).sum()
assert_frame_equal(result2, expected)
result3 = df.groupby(pd.TimeGrouper(freq='5D')).sum()
assert_frame_equal(result3, expected)
def test_groupby_with_timegrouper_methods(self):
# GH 3881
# make sure API of timegrouper conforms
import datetime as DT
df_original = pd.DataFrame({
'Branch' : 'A A A A A B'.split(),
'Buyer': 'Carl Mark Carl Joe Joe Carl'.split(),
'Quantity': [1,3,5,8,9,3],
'Date' : [
DT.datetime(2013,1,1,13,0),
DT.datetime(2013,1,1,13,5),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,12,2,12,0),
DT.datetime(2013,12,2,14,0),
]})
df_sorted = df_original.sort(columns='Quantity', ascending=False)
for df in [df_original, df_sorted]:
df = df.set_index('Date', drop=False)
g = df.groupby(pd.TimeGrouper('6M'))
self.assertTrue(g.group_keys)
self.assertTrue(isinstance(g.grouper,pd.core.groupby.BinGrouper))
groups = g.groups
self.assertTrue(isinstance(groups,dict))
self.assertTrue(len(groups) == 3)
def test_timegrouper_with_reg_groups(self):
# GH 3794
# allow combinateion of timegrouper/reg groups
import datetime as DT
df_original = DataFrame({
'Branch' : 'A A A A A A A B'.split(),
'Buyer': 'Carl Mark Carl Carl Joe Joe Joe Carl'.split(),
'Quantity': [1,3,5,1,8,1,9,3],
'Date' : [
DT.datetime(2013,1,1,13,0),
DT.datetime(2013,1,1,13,5),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,12,2,12,0),
DT.datetime(2013,12,2,14,0),
]}).set_index('Date')
df_sorted = df_original.sort(columns='Quantity', ascending=False)
for df in [df_original, df_sorted]:
expected = DataFrame({
'Buyer': 'Carl Joe Mark'.split(),
'Quantity': [10,18,3],
'Date' : [
DT.datetime(2013,12,31,0,0),
DT.datetime(2013,12,31,0,0),
DT.datetime(2013,12,31,0,0),
]}).set_index(['Date','Buyer'])
result = df.groupby([pd.Grouper(freq='A'),'Buyer']).sum()
assert_frame_equal(result,expected)
expected = DataFrame({
'Buyer': 'Carl Mark Carl Joe'.split(),
'Quantity': [1,3,9,18],
'Date' : [
DT.datetime(2013,1,1,0,0),
DT.datetime(2013,1,1,0,0),
DT.datetime(2013,7,1,0,0),
DT.datetime(2013,7,1,0,0),
]}).set_index(['Date','Buyer'])
result = df.groupby([pd.Grouper(freq='6MS'),'Buyer']).sum()
assert_frame_equal(result,expected)
df_original = DataFrame({
'Branch' : 'A A A A A A A B'.split(),
'Buyer': 'Carl Mark Carl Carl Joe Joe Joe Carl'.split(),
'Quantity': [1,3,5,1,8,1,9,3],
'Date' : [
DT.datetime(2013,10,1,13,0),
DT.datetime(2013,10,1,13,5),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,10,2,12,0),
DT.datetime(2013,10,2,14,0),
]}).set_index('Date')
df_sorted = df_original.sort(columns='Quantity', ascending=False)
for df in [df_original, df_sorted]:
expected = DataFrame({
'Buyer': 'Carl Joe Mark Carl Joe'.split(),
'Quantity': [6,8,3,4,10],
'Date' : [
DT.datetime(2013,10,1,0,0),
DT.datetime(2013,10,1,0,0),
DT.datetime(2013,10,1,0,0),
DT.datetime(2013,10,2,0,0),
DT.datetime(2013,10,2,0,0),
]}).set_index(['Date','Buyer'])
result = df.groupby([pd.Grouper(freq='1D'),'Buyer']).sum()
assert_frame_equal(result,expected)
result = df.groupby([pd.Grouper(freq='1M'),'Buyer']).sum()
expected = DataFrame({
'Buyer': 'Carl Joe Mark'.split(),
'Quantity': [10,18,3],
'Date' : [
DT.datetime(2013,10,31,0,0),
DT.datetime(2013,10,31,0,0),
DT.datetime(2013,10,31,0,0),
]}).set_index(['Date','Buyer'])
assert_frame_equal(result,expected)
# passing the name
df = df.reset_index()
result = df.groupby([pd.Grouper(freq='1M',key='Date'),'Buyer']).sum()
assert_frame_equal(result,expected)
self.assertRaises(KeyError, lambda : df.groupby([pd.Grouper(freq='1M',key='foo'),'Buyer']).sum())
# passing the level
df = df.set_index('Date')
result = df.groupby([pd.Grouper(freq='1M',level='Date'),'Buyer']).sum()
assert_frame_equal(result,expected)
result = df.groupby([pd.Grouper(freq='1M',level=0),'Buyer']).sum()
assert_frame_equal(result,expected)
self.assertRaises(ValueError, lambda : df.groupby([pd.Grouper(freq='1M',level='foo'),'Buyer']).sum())
# multi names
df = df.copy()
df['Date'] = df.index + pd.offsets.MonthEnd(2)
result = df.groupby([pd.Grouper(freq='1M',key='Date'),'Buyer']).sum()
expected = DataFrame({
'Buyer': 'Carl Joe Mark'.split(),
'Quantity': [10,18,3],
'Date' : [
DT.datetime(2013,11,30,0,0),
DT.datetime(2013,11,30,0,0),
DT.datetime(2013,11,30,0,0),
]}).set_index(['Date','Buyer'])
assert_frame_equal(result,expected)
# error as we have both a level and a name!
self.assertRaises(ValueError, lambda : df.groupby([pd.Grouper(freq='1M',key='Date',level='Date'),'Buyer']).sum())
# single groupers
expected = DataFrame({ 'Quantity' : [31],
'Date' : [DT.datetime(2013,10,31,0,0)] }).set_index('Date')
result = df.groupby(pd.Grouper(freq='1M')).sum()
assert_frame_equal(result, expected)
result = df.groupby([pd.Grouper(freq='1M')]).sum()
assert_frame_equal(result, expected)
expected = DataFrame({ 'Quantity' : [31],
'Date' : [DT.datetime(2013,11,30,0,0)] }).set_index('Date')
result = df.groupby(pd.Grouper(freq='1M',key='Date')).sum()
assert_frame_equal(result, expected)
result = df.groupby([pd.Grouper(freq='1M',key='Date')]).sum()
assert_frame_equal(result, expected)
# GH 6764 multiple grouping with/without sort
df = DataFrame({
'date' : pd.to_datetime([
'20121002','20121007','20130130','20130202','20130305','20121002',
'20121207','20130130','20130202','20130305','20130202','20130305']),
'user_id' : [1,1,1,1,1,3,3,3,5,5,5,5],
'whole_cost' : [1790,364,280,259,201,623,90,312,359,301,359,801],
'cost1' : [12,15,10,24,39,1,0,90,45,34,1,12] }).set_index('date')
for freq in ['D', 'M', 'A', 'Q-APR']:
expected = df.groupby('user_id')['whole_cost'].resample(
freq, how='sum').dropna().reorder_levels(
['date','user_id']).sortlevel().astype('int64')
expected.name = 'whole_cost'
result1 = df.sort_index().groupby([pd.TimeGrouper(freq=freq), 'user_id'])['whole_cost'].sum()
assert_series_equal(result1, expected)
result2 = df.groupby([pd.TimeGrouper(freq=freq), 'user_id'])['whole_cost'].sum()
assert_series_equal(result2, expected)
def test_timegrouper_get_group(self):
# GH 6914
df_original = DataFrame({
'Buyer': 'Carl Joe Joe Carl Joe Carl'.split(),
'Quantity': [18,3,5,1,9,3],
'Date' : [datetime(2013,9,1,13,0), datetime(2013,9,1,13,5),
datetime(2013,10,1,20,0), datetime(2013,10,3,10,0),
datetime(2013,12,2,12,0), datetime(2013,9,2,14,0),]})
df_reordered = df_original.sort(columns='Quantity')
# single grouping
expected_list = [df_original.iloc[[0, 1, 5]], df_original.iloc[[2, 3]],
df_original.iloc[[4]]]
dt_list = ['2013-09-30', '2013-10-31', '2013-12-31']
for df in [df_original, df_reordered]:
grouped = df.groupby(pd.Grouper(freq='M', key='Date'))
for t, expected in zip(dt_list, expected_list):
dt = pd.Timestamp(t)
result = grouped.get_group(dt)
assert_frame_equal(result, expected)
# multiple grouping
expected_list = [df_original.iloc[[1]], df_original.iloc[[3]],
df_original.iloc[[4]]]
g_list = [('Joe', '2013-09-30'), ('Carl', '2013-10-31'), ('Joe', '2013-12-31')]
for df in [df_original, df_reordered]:
grouped = df.groupby(['Buyer', pd.Grouper(freq='M', key='Date')])
for (b, t), expected in zip(g_list, expected_list):
dt = pd.Timestamp(t)
result = grouped.get_group((b, dt))
assert_frame_equal(result, expected)
# with index
df_original = df_original.set_index('Date')
df_reordered = df_original.sort(columns='Quantity')
expected_list = [df_original.iloc[[0, 1, 5]], df_original.iloc[[2, 3]],
df_original.iloc[[4]]]
for df in [df_original, df_reordered]:
grouped = df.groupby(pd.Grouper(freq='M'))
for t, expected in zip(dt_list, expected_list):
dt = pd.Timestamp(t)
result = grouped.get_group(dt)
assert_frame_equal(result, expected)
def test_cumcount(self):
df = DataFrame([['a'], ['a'], ['a'], ['b'], ['a']], columns=['A'])
g = df.groupby('A')
sg = g.A
expected = Series([0, 1, 2, 0, 3])
assert_series_equal(expected, g.cumcount())
assert_series_equal(expected, sg.cumcount())
def test_cumcount_empty(self):
ge = DataFrame().groupby(level=0)
se = Series().groupby(level=0)
e = Series(dtype='int64') # edge case, as this is usually considered float
assert_series_equal(e, ge.cumcount())
assert_series_equal(e, se.cumcount())
def test_cumcount_dupe_index(self):
df = DataFrame([['a'], ['a'], ['a'], ['b'], ['a']], columns=['A'], index=[0] * 5)
g = df.groupby('A')
sg = g.A
expected = Series([0, 1, 2, 0, 3], index=[0] * 5)
assert_series_equal(expected, g.cumcount())
assert_series_equal(expected, sg.cumcount())
def test_cumcount_mi(self):
mi = MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]])
df = DataFrame([['a'], ['a'], ['a'], ['b'], ['a']], columns=['A'], index=mi)
g = df.groupby('A')
sg = g.A
expected = Series([0, 1, 2, 0, 3], index=mi)
assert_series_equal(expected, g.cumcount())
assert_series_equal(expected, sg.cumcount())
def test_cumcount_groupby_not_col(self):
df = DataFrame([['a'], ['a'], ['a'], ['b'], ['a']], columns=['A'], index=[0] * 5)
g = df.groupby([0, 0, 0, 1, 0])
sg = g.A
expected = Series([0, 1, 2, 0, 3], index=[0] * 5)
assert_series_equal(expected, g.cumcount())
assert_series_equal(expected, sg.cumcount())
def test_filter_series(self):
import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
expected_odd = pd.Series([1, 3, 5, 7], index=[0, 1, 3, 6])
expected_even = pd.Series([20, 22, 24], index=[2, 4, 5])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
assert_series_equal(
grouped.filter(lambda x: x.mean() < 10), expected_odd)
assert_series_equal(
grouped.filter(lambda x: x.mean() > 10), expected_even)
# Test dropna=False.
assert_series_equal(
grouped.filter(lambda x: x.mean() < 10, dropna=False),
expected_odd.reindex(s.index))
assert_series_equal(
grouped.filter(lambda x: x.mean() > 10, dropna=False),
expected_even.reindex(s.index))
def test_filter_single_column_df(self):
import pandas as pd
df = pd.DataFrame([1, 3, 20, 5, 22, 24, 7])
expected_odd = pd.DataFrame([1, 3, 5, 7], index=[0, 1, 3, 6])
expected_even = pd.DataFrame([20, 22, 24], index=[2, 4, 5])
grouper = df[0].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
assert_frame_equal(
grouped.filter(lambda x: x.mean() < 10), expected_odd)
assert_frame_equal(
grouped.filter(lambda x: x.mean() > 10), expected_even)
# Test dropna=False.
assert_frame_equal(
grouped.filter(lambda x: x.mean() < 10, dropna=False),
expected_odd.reindex(df.index))
assert_frame_equal(
grouped.filter(lambda x: x.mean() > 10, dropna=False),
expected_even.reindex(df.index))
def test_filter_multi_column_df(self):
import pandas as pd
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': [1, 1, 1, 1]})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
expected = pd.DataFrame({'A': [12, 12], 'B': [1, 1]}, index=[1, 2])
assert_frame_equal(
grouped.filter(lambda x: x['A'].sum() - x['B'].sum() > 10), expected)
def test_filter_mixed_df(self):
import pandas as pd
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': 'a b c d'.split()})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
expected = pd.DataFrame({'A': [12, 12], 'B': ['b', 'c']},
index=[1, 2])
assert_frame_equal(
grouped.filter(lambda x: x['A'].sum() > 10), expected)
def test_filter_out_all_groups(self):
import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
assert_series_equal(
grouped.filter(lambda x: x.mean() > 1000), s[[]])
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': 'a b c d'.split()})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
assert_frame_equal(
grouped.filter(lambda x: x['A'].sum() > 1000), df.ix[[]])
def test_filter_out_no_groups(self):
import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
filtered = grouped.filter(lambda x: x.mean() > 0)
assert_series_equal(filtered, s)
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': 'a b c d'.split()})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
filtered = grouped.filter(lambda x: x['A'].mean() > 0)
assert_frame_equal(filtered, df)
def test_filter_condition_raises(self):
import pandas as pd
def raise_if_sum_is_zero(x):
if x.sum() == 0:
raise ValueError
else:
return x.sum() > 0
s = pd.Series([-1,0,1,2])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
self.assertRaises(TypeError,
lambda: grouped.filter(raise_if_sum_is_zero))
def test_filter_bad_shapes(self):
df = DataFrame({'A': np.arange(8), 'B': list('aabbbbcc'), 'C': np.arange(8)})
s = df['B']
g_df = df.groupby('B')
g_s = s.groupby(s)
f = lambda x: x
self.assertRaises(TypeError, lambda: g_df.filter(f))
self.assertRaises(TypeError, lambda: g_s.filter(f))
f = lambda x: x == 1
self.assertRaises(TypeError, lambda: g_df.filter(f))
self.assertRaises(TypeError, lambda: g_s.filter(f))
f = lambda x: np.outer(x, x)
self.assertRaises(TypeError, lambda: g_df.filter(f))
self.assertRaises(TypeError, lambda: g_s.filter(f))
def test_filter_nan_is_false(self):
df = DataFrame({'A': np.arange(8), 'B': list('aabbbbcc'), 'C': np.arange(8)})
s = df['B']
g_df = df.groupby(df['B'])
g_s = s.groupby(s)
f = lambda x: np.nan
assert_frame_equal(g_df.filter(f), df.loc[[]])
assert_series_equal(g_s.filter(f), s[[]])
def test_filter_against_workaround(self):
np.random.seed(0)
# Series of ints
s = Series(np.random.randint(0,100,1000))
grouper = s.apply(lambda x: np.round(x, -1))
grouped = s.groupby(grouper)
f = lambda x: x.mean() > 10
old_way = s[grouped.transform(f).astype('bool')]
new_way = grouped.filter(f)
assert_series_equal(new_way.order(), old_way.order())
# Series of floats
s = 100*Series(np.random.random(1000))
grouper = s.apply(lambda x: np.round(x, -1))
grouped = s.groupby(grouper)
f = lambda x: x.mean() > 10
old_way = s[grouped.transform(f).astype('bool')]
new_way = grouped.filter(f)
assert_series_equal(new_way.order(), old_way.order())
# Set up DataFrame of ints, floats, strings.
from string import ascii_lowercase
letters = np.array(list(ascii_lowercase))
N = 1000
random_letters = letters.take(np.random.randint(0, 26, N))
df = DataFrame({'ints': Series(np.random.randint(0, 100, N)),
'floats': N/10*Series(np.random.random(N)),
'letters': Series(random_letters)})
# Group by ints; filter on floats.
grouped = df.groupby('ints')
old_way = df[grouped.floats.\
transform(lambda x: x.mean() > N/20).astype('bool')]
new_way = grouped.filter(lambda x: x['floats'].mean() > N/20)
assert_frame_equal(new_way, old_way)
# Group by floats (rounded); filter on strings.
grouper = df.floats.apply(lambda x: np.round(x, -1))
grouped = df.groupby(grouper)
old_way = df[grouped.letters.\
transform(lambda x: len(x) < N/10).astype('bool')]
new_way = grouped.filter(
lambda x: len(x.letters) < N/10)
assert_frame_equal(new_way, old_way)
# Group by strings; filter on ints.
grouped = df.groupby('letters')
old_way = df[grouped.ints.\
transform(lambda x: x.mean() > N/20).astype('bool')]
new_way = grouped.filter(lambda x: x['ints'].mean() > N/20)
assert_frame_equal(new_way, old_way)
def test_filter_using_len(self):
# BUG GH4447
df = DataFrame({'A': np.arange(8), 'B': list('aabbbbcc'), 'C': np.arange(8)})
grouped = df.groupby('B')
actual = grouped.filter(lambda x: len(x) > 2)
expected = DataFrame({'A': np.arange(2, 6), 'B': list('bbbb'), 'C': np.arange(2, 6)}, index=np.arange(2, 6))
assert_frame_equal(actual, expected)
actual = grouped.filter(lambda x: len(x) > 4)
expected = df.ix[[]]
assert_frame_equal(actual, expected)
# Series have always worked properly, but we'll test anyway.
s = df['B']
grouped = s.groupby(s)
actual = grouped.filter(lambda x: len(x) > 2)
expected = Series(4*['b'], index=np.arange(2, 6))
assert_series_equal(actual, expected)
actual = grouped.filter(lambda x: len(x) > 4)
expected = s[[]]
assert_series_equal(actual, expected)
def test_filter_maintains_ordering(self):
# Simple case: index is sequential. #4621
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]})
s = df['pid']
grouped = df.groupby('tag')
actual = grouped.filter(lambda x: len(x) > 1)
expected = df.iloc[[1, 2, 4, 7]]
assert_frame_equal(actual, expected)
grouped = s.groupby(df['tag'])
actual = grouped.filter(lambda x: len(x) > 1)
expected = s.iloc[[1, 2, 4, 7]]
assert_series_equal(actual, expected)
# Now index is sequentially decreasing.
df.index = np.arange(len(df) - 1, -1, -1)
s = df['pid']
grouped = df.groupby('tag')
actual = grouped.filter(lambda x: len(x) > 1)
expected = df.iloc[[1, 2, 4, 7]]
assert_frame_equal(actual, expected)
grouped = s.groupby(df['tag'])
actual = grouped.filter(lambda x: len(x) > 1)
expected = s.iloc[[1, 2, 4, 7]]
assert_series_equal(actual, expected)
# Index is shuffled.
SHUFFLED = [4, 6, 7, 2, 1, 0, 5, 3]
df.index = df.index[SHUFFLED]
s = df['pid']
grouped = df.groupby('tag')
actual = grouped.filter(lambda x: len(x) > 1)
expected = df.iloc[[1, 2, 4, 7]]
assert_frame_equal(actual, expected)
grouped = s.groupby(df['tag'])
actual = grouped.filter(lambda x: len(x) > 1)
expected = s.iloc[[1, 2, 4, 7]]
assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_int_index(self):
# GH4620
index = [1, 1, 1, 2, 1, 1, 0, 1]
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_and_transform_with_multiple_non_unique_int_index(self):
# GH4620
index = [1, 1, 1, 2, 0, 0, 0, 1]
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_float_index(self):
# GH4620
index = np.array([1, 1, 1, 2, 1, 1, 0, 1], dtype=float)
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_float_index(self):
# GH4620
index = np.array([1, 1, 1, 2, 0, 0, 0, 1], dtype=float)
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_timestamp_index(self):
# GH4620
t0 = Timestamp('2013-09-30 00:05:00')
t1 = Timestamp('2013-10-30 00:05:00')
t2 = Timestamp('2013-11-30 00:05:00')
index = [t1, t1, t1, t2, t1, t1, t0, t1]
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_string_index(self):
# GH4620
index = list('bbbcbbab')
df = DataFrame({'pid' : [1,1,1,2,2,3,3,3],
'tag' : [23,45,62,24,45,34,25,62]}, index=index)
grouped_df = df.groupby('tag')
ser = df['pid']
grouped_ser = ser.groupby(df['tag'])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA,1,1,NA,2,NA,NA,3], index, name='pid')
# ^ made manually because this can get confusing!
assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index)
assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
assert_series_equal(actual, expected)
def test_filter_has_access_to_grouped_cols(self):
df = DataFrame([[1, 2], [1, 3], [5, 6]], columns=['A', 'B'])
g = df.groupby('A')
# previously didn't have access to col A #????
filt = g.filter(lambda x: x['A'].sum() == 2)
assert_frame_equal(filt, df.iloc[[0, 1]])
def test_filter_enforces_scalarness(self):
df = pd.DataFrame([
['best', 'a', 'x'],
['worst', 'b', 'y'],
['best', 'c', 'x'],
['best','d', 'y'],
['worst','d', 'y'],
['worst','d', 'y'],
['best','d', 'z'],
], columns=['a', 'b', 'c'])
with tm.assertRaisesRegexp(TypeError, 'filter function returned a.*'):
df.groupby('c').filter(lambda g: g['a'] == 'best')
def test_filter_non_bool_raises(self):
df = pd.DataFrame([
['best', 'a', 1],
['worst', 'b', 1],
['best', 'c', 1],
['best','d', 1],
['worst','d', 1],
['worst','d', 1],
['best','d', 1],
], columns=['a', 'b', 'c'])
with tm.assertRaisesRegexp(TypeError, 'filter function returned a.*'):
df.groupby('a').filter(lambda g: g.c.mean())
def test_fill_constistency(self):
# GH9221
# pass thru keyword arguments to the generated wrapper
# are set if the passed kw is None (only)
df = DataFrame(index=pd.MultiIndex.from_product([['value1','value2'],
date_range('2014-01-01','2014-01-06')]),
columns=Index(['1','2'], name='id'))
df['1'] = [np.nan, 1, np.nan, np.nan, 11, np.nan, np.nan, 2, np.nan, np.nan, 22, np.nan]
df['2'] = [np.nan, 3, np.nan, np.nan, 33, np.nan, np.nan, 4, np.nan, np.nan, 44, np.nan]
expected = df.groupby(level=0, axis=0).fillna(method='ffill')
result = df.T.groupby(level=0, axis=1).fillna(method='ffill').T
assert_frame_equal(result, expected)
def test_index_label_overlaps_location(self):
# checking we don't have any label/location confusion in the
# the wake of GH5375
df = DataFrame(list('ABCDE'), index=[2, 0, 2, 1, 1])
g = df.groupby(list('ababb'))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
assert_frame_equal(actual, expected)
ser = df[0]
g = ser.groupby(list('ababb'))
actual = g.filter(lambda x: len(x) > 2)
expected = ser.take([1, 3, 4])
assert_series_equal(actual, expected)
# ... and again, with a generic Index of floats
df.index = df.index.astype(float)
g = df.groupby(list('ababb'))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
assert_frame_equal(actual, expected)
ser = df[0]
g = ser.groupby(list('ababb'))
actual = g.filter(lambda x: len(x) > 2)
expected = ser.take([1, 3, 4])
assert_series_equal(actual, expected)
def test_groupby_selection_with_methods(self):
# some methods which require DatetimeIndex
rng = pd.date_range('2014', periods=len(self.df))
self.df.index = rng
g = self.df.groupby(['A'])[['C']]
g_exp = self.df[['C']].groupby(self.df['A'])
# TODO check groupby with > 1 col ?
# methods which are called as .foo()
methods = ['count',
'corr',
'cummax', 'cummin', 'cumprod',
'describe', 'rank',
'quantile',
'diff', 'shift',
'all', 'any',
'idxmin', 'idxmax',
'ffill', 'bfill',
'pct_change',
'tshift',
#'ohlc'
]
for m in methods:
res = getattr(g, m)()
exp = getattr(g_exp, m)()
assert_frame_equal(res, exp) # should always be frames!
# methods which aren't just .foo()
assert_frame_equal(g.fillna(0), g_exp.fillna(0))
assert_frame_equal(g.dtypes, g_exp.dtypes)
assert_frame_equal(g.apply(lambda x: x.sum()),
g_exp.apply(lambda x: x.sum()))
assert_frame_equal(g.resample('D'), g_exp.resample('D'))
assert_frame_equal(g.resample('D', how='ohlc'),
g_exp.resample('D', how='ohlc'))
assert_frame_equal(g.filter(lambda x: len(x) == 3),
g_exp.filter(lambda x: len(x) == 3))
def test_groupby_whitelist(self):
from string import ascii_lowercase
letters = np.array(list(ascii_lowercase))
N = 10
random_letters = letters.take(np.random.randint(0, 26, N))
df = DataFrame({'floats': N / 10 * Series(np.random.random(N)),
'letters': Series(random_letters)})
s = df.floats
df_whitelist = frozenset([
'last', 'first',
'mean', 'sum', 'min', 'max',
'head', 'tail',
'cumsum', 'cumprod', 'cummin', 'cummax', 'cumcount',
'resample',
'describe',
'rank', 'quantile', 'count',
'fillna',
'mad',
'any', 'all',
'irow', 'take',
'idxmax', 'idxmin',
'shift', 'tshift',
'ffill', 'bfill',
'pct_change', 'skew',
'plot', 'boxplot', 'hist',
'median', 'dtypes',
'corrwith', 'corr', 'cov',
'diff',
])
s_whitelist = frozenset([
'last', 'first',
'mean', 'sum', 'min', 'max',
'head', 'tail',
'cumsum', 'cumprod', 'cummin', 'cummax', 'cumcount',
'resample',
'describe',
'rank', 'quantile', 'count',
'fillna',
'mad',
'any', 'all',
'irow', 'take',
'idxmax', 'idxmin',
'shift', 'tshift',
'ffill', 'bfill',
'pct_change', 'skew',
'plot', 'hist',
'median', 'dtype',
'corr', 'cov',
'value_counts',
'diff',
'unique', 'nunique',
'nlargest', 'nsmallest',
])
for obj, whitelist in zip((df, s),
(df_whitelist, s_whitelist)):
gb = obj.groupby(df.letters)
self.assertEqual(whitelist, gb._apply_whitelist)
for m in whitelist:
getattr(type(gb), m)
AGG_FUNCTIONS = ['sum', 'prod', 'min', 'max', 'median', 'mean', 'skew',
'mad', 'std', 'var', 'sem']
AGG_FUNCTIONS_WITH_SKIPNA = ['skew', 'mad']
def test_regression_whitelist_methods(self) :
# GH6944
# explicity test the whitelest methods
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
['one', 'two', 'three']],
labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
[0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
names=['first', 'second'])
raw_frame = DataFrame(np.random.randn(10, 3), index=index,
columns=Index(['A', 'B', 'C'], name='exp'))
raw_frame.ix[1, [1, 2]] = np.nan
raw_frame.ix[7, [0, 1]] = np.nan
for op, level, axis, skipna in cart_product(self.AGG_FUNCTIONS,
lrange(2), lrange(2),
[True,False]) :
if axis == 0 :
frame = raw_frame
else :
frame = raw_frame.T
if op in self.AGG_FUNCTIONS_WITH_SKIPNA :
grouped = frame.groupby(level=level,axis=axis)
result = getattr(grouped,op)(skipna=skipna)
expected = getattr(frame,op)(level=level,axis=axis,skipna=skipna)
assert_frame_equal(result, expected)
else :
grouped = frame.groupby(level=level,axis=axis)
result = getattr(grouped,op)()
expected = getattr(frame,op)(level=level,axis=axis)
assert_frame_equal(result, expected)
def test_groupby_blacklist(self):
from string import ascii_lowercase
letters = np.array(list(ascii_lowercase))
N = 10
random_letters = letters.take(np.random.randint(0, 26, N))
df = DataFrame({'floats': N / 10 * Series(np.random.random(N)),
'letters': Series(random_letters)})
s = df.floats
blacklist = [
'eval', 'query', 'abs', 'where',
'mask', 'align', 'groupby', 'clip', 'astype',
'at', 'combine', 'consolidate', 'convert_objects',
]
to_methods = [method for method in dir(df) if method.startswith('to_')]
blacklist.extend(to_methods)
# e.g., to_csv
defined_but_not_allowed = ("(?:^Cannot.+{0!r}.+{1!r}.+try using the "
"'apply' method$)")
# e.g., query, eval
not_defined = "(?:^{1!r} object has no attribute {0!r}$)"
fmt = defined_but_not_allowed + '|' + not_defined
for bl in blacklist:
for obj in (df, s):
gb = obj.groupby(df.letters)
msg = fmt.format(bl, type(gb).__name__)
with tm.assertRaisesRegexp(AttributeError, msg):
getattr(gb, bl)
def test_tab_completion(self):
grp = self.mframe.groupby(level='second')
results = set([v for v in dir(grp) if not v.startswith('_')])
expected = set(['A','B','C',
'agg','aggregate','apply','boxplot','filter','first','get_group',
'groups','hist','indices','last','max','mean','median',
'min','name','ngroups','nth','ohlc','plot', 'prod',
'size', 'std', 'sum', 'transform', 'var', 'sem', 'count', 'head',
'describe', 'cummax', 'quantile', 'rank', 'cumprod', 'tail',
'resample', 'cummin', 'fillna', 'cumsum', 'cumcount',
'all', 'shift', 'skew', 'bfill', 'irow', 'ffill',
'take', 'tshift', 'pct_change', 'any', 'mad', 'corr', 'corrwith',
'cov', 'dtypes', 'diff', 'idxmax', 'idxmin'
])
self.assertEqual(results, expected)
def test_lexsort_indexer(self):
keys = [[nan]*5 + list(range(100)) + [nan]*5]
# orders=True, na_position='last'
result = _lexsort_indexer(keys, orders=True, na_position='last')
expected = list(range(5, 105)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# orders=True, na_position='first'
result = _lexsort_indexer(keys, orders=True, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(5, 105))
assert_equal(result, expected)
# orders=False, na_position='last'
result = _lexsort_indexer(keys, orders=False, na_position='last')
expected = list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# orders=False, na_position='first'
result = _lexsort_indexer(keys, orders=False, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1))
assert_equal(result, expected)
def test_nargsort(self):
# np.argsort(items) places NaNs last
items = [nan]*5 + list(range(100)) + [nan]*5
# np.argsort(items2) may not place NaNs first
items2 = np.array(items, dtype='O')
try:
# GH 2785; due to a regression in NumPy1.6.2
np.argsort(np.array([[1, 2], [1, 3], [1, 2]], dtype='i'))
np.argsort(items2, kind='mergesort')
except TypeError as err:
raise nose.SkipTest('requested sort not available for type')
# mergesort is the most difficult to get right because we want it to be stable.
# According to numpy/core/tests/test_multiarray, """The number
# of sorted items must be greater than ~50 to check the actual algorithm
# because quick and merge sort fall over to insertion sort for small
# arrays."""
# mergesort, ascending=True, na_position='last'
result = _nargsort(
items, kind='mergesort', ascending=True, na_position='last')
expected = list(range(5, 105)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# mergesort, ascending=True, na_position='first'
result = _nargsort(
items, kind='mergesort', ascending=True, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(5, 105))
assert_equal(result, expected)
# mergesort, ascending=False, na_position='last'
result = _nargsort(
items, kind='mergesort', ascending=False, na_position='last')
expected = list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# mergesort, ascending=False, na_position='first'
result = _nargsort(
items, kind='mergesort', ascending=False, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1))
assert_equal(result, expected)
# mergesort, ascending=True, na_position='last'
result = _nargsort(
items2, kind='mergesort', ascending=True, na_position='last')
expected = list(range(5, 105)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# mergesort, ascending=True, na_position='first'
result = _nargsort(
items2, kind='mergesort', ascending=True, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(5, 105))
assert_equal(result, expected)
# mergesort, ascending=False, na_position='last'
result = _nargsort(
items2, kind='mergesort', ascending=False, na_position='last')
expected = list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110))
assert_equal(result, expected)
# mergesort, ascending=False, na_position='first'
result = _nargsort(
items2, kind='mergesort', ascending=False, na_position='first')
expected = list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1))
assert_equal(result, expected)
def test_datetime_count(self):
df = DataFrame({'a': [1,2,3] * 2,
'dates': pd.date_range('now', periods=6, freq='T')})
result = df.groupby('a').dates.count()
expected = Series([2, 2, 2], index=Index([1, 2, 3], name='a'),
name='dates')
tm.assert_series_equal(result, expected)
def test_lower_int_prec_count(self):
df = DataFrame({'a': np.array([0, 1, 2, 100], np.int8),
'b': np.array([1, 2, 3, 6], np.uint32),
'c': np.array([4, 5, 6, 8], np.int16),
'grp': list('ab' * 2)})
result = df.groupby('grp').count()
expected = DataFrame({'a': [2, 2],
'b': [2, 2],
'c': [2, 2]}, index=pd.Index(list('ab'),
name='grp'))
tm.assert_frame_equal(result, expected)
def test_count_uses_size_on_exception(self):
class RaisingObjectException(Exception):
pass
class RaisingObject(object):
def __init__(self, msg='I will raise inside Cython'):
super(RaisingObject, self).__init__()
self.msg = msg
def __eq__(self, other):
# gets called in Cython to check that raising calls the method
raise RaisingObjectException(self.msg)
df = DataFrame({'a': [RaisingObject() for _ in range(4)],
'grp': list('ab' * 2)})
result = df.groupby('grp').count()
expected = DataFrame({'a': [2, 2]}, index=pd.Index(list('ab'),
name='grp'))
tm.assert_frame_equal(result, expected)
def test__cython_agg_general(self):
ops = [('mean', np.mean),
('median', np.median),
('var', np.var),
('add', np.sum),
('prod', np.prod),
('min', np.min),
('max', np.max),
('first', lambda x: x.iloc[0]),
('last', lambda x: x.iloc[-1]),
('count', np.size),
]
df = DataFrame(np.random.randn(1000))
labels = np.random.randint(0, 50, size=1000).astype(float)
for op, targop in ops:
result = df.groupby(labels)._cython_agg_general(op)
expected = df.groupby(labels).agg(targop)
try:
tm.assert_frame_equal(result, expected)
except BaseException as exc:
exc.args += ('operation: %s' % op,)
raise
def test_ops_general(self):
ops = [('mean', np.mean),
('median', np.median),
('std', np.std),
('var', np.var),
('sum', np.sum),
('prod', np.prod),
('min', np.min),
('max', np.max),
('first', lambda x: x.iloc[0]),
('last', lambda x: x.iloc[-1]),
('count', np.size),
]
try:
from scipy.stats import sem
except ImportError:
pass
else:
ops.append(('sem', sem))
df = DataFrame(np.random.randn(1000))
labels = np.random.randint(0, 50, size=1000).astype(float)
for op, targop in ops:
result = getattr(df.groupby(labels), op)().astype(float)
expected = df.groupby(labels).agg(targop)
try:
tm.assert_frame_equal(result, expected)
except BaseException as exc:
exc.args += ('operation: %s' % op,)
raise
def test_max_nan_bug(self):
raw = """,Date,app,File
2013-04-23,2013-04-23 00:00:00,,log080001.log
2013-05-06,2013-05-06 00:00:00,,log.log
2013-05-07,2013-05-07 00:00:00,OE,xlsx"""
df = pd.read_csv(StringIO(raw), parse_dates=[0])
gb = df.groupby('Date')
r = gb[['File']].max()
e = gb['File'].max().to_frame()
tm.assert_frame_equal(r, e)
self.assertFalse(r['File'].isnull().any())
def test_nlargest(self):
a = Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10])
b = Series(list('a' * 5 + 'b' * 5))
gb = a.groupby(b)
r = gb.nlargest(3)
e = Series([7, 5, 3, 10, 9, 6],
index=MultiIndex.from_arrays([list('aaabbb'),
[3, 2, 1, 9, 5, 8]]))
tm.assert_series_equal(r, e)
def test_nsmallest(self):
a = Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10])
b = Series(list('a' * 5 + 'b' * 5))
gb = a.groupby(b)
r = gb.nsmallest(3)
e = Series([1, 2, 3, 0, 4, 6],
index=MultiIndex.from_arrays([list('aaabbb'),
[0, 4, 1, 6, 7, 8]]))
tm.assert_series_equal(r, e)
def test_transform_doesnt_clobber_ints(self):
# GH 7972
n = 6
x = np.arange(n)
df = DataFrame({'a': x // 2, 'b': 2.0 * x, 'c': 3.0 * x})
df2 = DataFrame({'a': x // 2 * 1.0, 'b': 2.0 * x, 'c': 3.0 * x})
gb = df.groupby('a')
result = gb.transform('mean')
gb2 = df2.groupby('a')
expected = gb2.transform('mean')
tm.assert_frame_equal(result, expected)
def test_groupby_categorical_two_columns(self):
# https://github.com/pydata/pandas/issues/8138
d = {'cat': pd.Categorical(["a","b","a","b"], categories=["a", "b", "c"], ordered=True),
'ints': [1, 1, 2, 2],'val': [10, 20, 30, 40]}
test = pd.DataFrame(d)
# Grouping on a single column
groups_single_key = test.groupby("cat")
res = groups_single_key.agg('mean')
exp = DataFrame({"ints":[1.5,1.5,np.nan], "val":[20,30,np.nan]},
index=pd.Index(["a", "b", "c"], name="cat"))
tm.assert_frame_equal(res, exp)
# Grouping on two columns
groups_double_key = test.groupby(["cat","ints"])
res = groups_double_key.agg('mean')
exp = DataFrame({"val":[10,30,20,40,np.nan,np.nan],
"cat": ["a","a","b","b","c","c"],
"ints": [1,2,1,2,1,2]}).set_index(["cat","ints"])
tm.assert_frame_equal(res, exp)
d = {'C1': [3, 3, 4, 5], 'C2': [1, 2, 3, 4], 'C3': [10, 100, 200, 34]}
test = pd.DataFrame(d)
values = pd.cut(test['C1'], [1, 2, 3, 6])
values.name = "cat"
groups_double_key = test.groupby([values,'C2'])
res = groups_double_key.agg('mean')
nan = np.nan
idx = MultiIndex.from_product([["(1, 2]", "(2, 3]", "(3, 6]"],[1,2,3,4]],
names=["cat", "C2"])
exp = DataFrame({"C1":[nan,nan,nan,nan, 3, 3,nan,nan, nan,nan, 4, 5],
"C3":[nan,nan,nan,nan, 10,100,nan,nan, nan,nan,200,34]}, index=idx)
tm.assert_frame_equal(res, exp)
def assert_fp_equal(a, b):
assert (np.abs(a - b) < 1e-12).all()
def _check_groupby(df, result, keys, field, f=lambda x: x.sum()):
tups = lmap(tuple, df[keys].values)
tups = com._asarray_tuplesafe(tups)
expected = f(df.groupby(tups)[field])
for k, v in compat.iteritems(expected):
assert(result[k] == v)
def test_decons():
from pandas.core.groupby import decons_group_index, get_group_index
def testit(label_list, shape):
group_index = get_group_index(label_list, shape, sort=True, xnull=True)
label_list2 = decons_group_index(group_index, shape)
for a, b in zip(label_list, label_list2):
assert(np.array_equal(a, b))
shape = (4, 5, 6)
label_list = [np.tile([0, 1, 2, 3, 0, 1, 2, 3], 100),
np.tile([0, 2, 4, 3, 0, 1, 2, 3], 100),
np.tile([5, 1, 0, 2, 3, 0, 5, 4], 100)]
testit(label_list, shape)
shape = (10000, 10000)
label_list = [np.tile(np.arange(10000), 5),
np.tile(np.arange(10000), 5)]
testit(label_list, shape)
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure',
'-s'], exit=False)
|
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" AutoFeatureExtractor class."""
import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union
# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module
from ...feature_extraction_utils import FeatureExtractionMixin
from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
CONFIG_MAPPING_NAMES,
AutoConfig,
model_type_to_module_name,
replace_list_option_in_docstrings,
)
logger = logging.get_logger(__name__)
FEATURE_EXTRACTOR_MAPPING_NAMES = OrderedDict(
[
("beit", "BeitFeatureExtractor"),
("detr", "DetrFeatureExtractor"),
("deit", "DeiTFeatureExtractor"),
("hubert", "Wav2Vec2FeatureExtractor"),
("speech_to_text", "Speech2TextFeatureExtractor"),
("vit", "ViTFeatureExtractor"),
("wav2vec2", "Wav2Vec2FeatureExtractor"),
("detr", "DetrFeatureExtractor"),
("layoutlmv2", "LayoutLMv2FeatureExtractor"),
("clip", "CLIPFeatureExtractor"),
("perceiver", "PerceiverFeatureExtractor"),
("swin", "ViTFeatureExtractor"),
("vit_mae", "ViTFeatureExtractor"),
("segformer", "SegformerFeatureExtractor"),
("convnext", "ConvNextFeatureExtractor"),
("van", "ConvNextFeatureExtractor"),
("resnet", "ConvNextFeatureExtractor"),
("regnet", "ConvNextFeatureExtractor"),
("poolformer", "PoolFormerFeatureExtractor"),
("maskformer", "MaskFormerFeatureExtractor"),
("data2vec-audio", "Wav2Vec2FeatureExtractor"),
("data2vec-vision", "BeitFeatureExtractor"),
("dpt", "DPTFeatureExtractor"),
("glpn", "GLPNFeatureExtractor"),
]
)
FEATURE_EXTRACTOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)
def feature_extractor_class_from_name(class_name: str):
for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
if class_name in extractors:
module_name = model_type_to_module_name(module_name)
module = importlib.import_module(f".{module_name}", "transformers.models")
return getattr(module, class_name)
break
for config, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
if getattr(extractor, "__name__", None) == class_name:
return extractor
return None
def get_feature_extractor_config(
pretrained_model_name_or_path: Union[str, os.PathLike],
cache_dir: Optional[Union[str, os.PathLike]] = None,
force_download: bool = False,
resume_download: bool = False,
proxies: Optional[Dict[str, str]] = None,
use_auth_token: Optional[Union[bool, str]] = None,
revision: Optional[str] = None,
local_files_only: bool = False,
**kwargs,
):
"""
Loads the tokenizer configuration from a pretrained model tokenizer configuration.
Args:
pretrained_model_name_or_path (`str` or `os.PathLike`):
This can be either:
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced
under a user or organization name, like `dbmdz/bert-base-german-cased`.
- a path to a *directory* containing a configuration file saved using the
[`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
cache_dir (`str` or `os.PathLike`, *optional*):
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
cache should not be used.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to force to (re-)download the configuration files and override the cached versions if they
exist.
resume_download (`bool`, *optional*, defaults to `False`):
Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists.
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
use_auth_token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `transformers-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
identifier allowed by git.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, will only try to load the tokenizer configuration from local files.
<Tip>
Passing `use_auth_token=True` is required when you want to use a private model.
</Tip>
Returns:
`Dict`: The configuration of the tokenizer.
Examples:
```python
# Download configuration from huggingface.co and cache.
tokenizer_config = get_tokenizer_config("bert-base-uncased")
# This model does not have a tokenizer config so the result will be an empty dict.
tokenizer_config = get_tokenizer_config("xlm-roberta-base")
# Save a pretrained tokenizer locally and you can reload its config
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
tokenizer.save_pretrained("tokenizer-test")
tokenizer_config = get_tokenizer_config("tokenizer-test")
```"""
resolved_config_file = get_file_from_repo(
pretrained_model_name_or_path,
FEATURE_EXTRACTOR_NAME,
cache_dir=cache_dir,
force_download=force_download,
resume_download=resume_download,
proxies=proxies,
use_auth_token=use_auth_token,
revision=revision,
local_files_only=local_files_only,
)
if resolved_config_file is None:
logger.info(
"Could not locate the feature extractor configuration file, will try to use the model config instead."
)
return {}
with open(resolved_config_file, encoding="utf-8") as reader:
return json.load(reader)
class AutoFeatureExtractor:
r"""
This is a generic feature extractor class that will be instantiated as one of the feature extractor classes of the
library when created with the [`AutoFeatureExtractor.from_pretrained`] class method.
This class cannot be instantiated directly using `__init__()` (throws an error).
"""
def __init__(self):
raise EnvironmentError(
"AutoFeatureExtractor is designed to be instantiated "
"using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method."
)
@classmethod
@replace_list_option_in_docstrings(FEATURE_EXTRACTOR_MAPPING_NAMES)
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
r"""
Instantiate one of the feature extractor classes of the library from a pretrained model vocabulary.
The feature extractor class to instantiate is selected based on the `model_type` property of the config object
(either passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's
missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
List options
Params:
pretrained_model_name_or_path (`str` or `os.PathLike`):
This can be either:
- a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or
namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
- a path to a *directory* containing a feature extractor file saved using the
[`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] method, e.g.,
`./my_model_directory/`.
- a path or url to a saved feature extractor JSON *file*, e.g.,
`./my_model_directory/preprocessor_config.json`.
cache_dir (`str` or `os.PathLike`, *optional*):
Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
standard cache should not be used.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to force to (re-)download the feature extractor files and override the cached versions
if they exist.
resume_download (`bool`, *optional*, defaults to `False`):
Whether or not to delete incompletely received file. Attempts to resume the download if such a file
exists.
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
use_auth_token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `transformers-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
identifier allowed by git.
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
If `False`, then this function returns just the final feature extractor object. If `True`, then this
functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
`kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
trust_remote_code (`bool`, *optional*, defaults to `False`):
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
should only be set to `True` for repositories you trust and in which you have read the code, as it will
execute code present on the Hub on your local machine.
kwargs (`Dict[str, Any]`, *optional*):
The values in kwargs of any keys which are feature extractor attributes will be used to override the
loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
controlled by the `return_unused_kwargs` keyword parameter.
<Tip>
Passing `use_auth_token=True` is required when you want to use a private model.
</Tip>
Examples:
```python
>>> from transformers import AutoFeatureExtractor
>>> # Download feature extractor from huggingface.co and cache.
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h")
>>> # If feature extractor files are in a directory (e.g. feature extractor was saved using *save_pretrained('./test/saved_model/')*)
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("./test/saved_model/")
```"""
config = kwargs.pop("config", None)
trust_remote_code = kwargs.pop("trust_remote_code", False)
kwargs["_from_auto"] = True
config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs)
feature_extractor_class = config_dict.get("feature_extractor_type", None)
feature_extractor_auto_map = None
if "AutoFeatureExtractor" in config_dict.get("auto_map", {}):
feature_extractor_auto_map = config_dict["auto_map"]["AutoFeatureExtractor"]
# If we don't find the feature extractor class in the feature extractor config, let's try the model config.
if feature_extractor_class is None and feature_extractor_auto_map is None:
if not isinstance(config, PretrainedConfig):
config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
# It could be in `config.feature_extractor_type``
feature_extractor_class = getattr(config, "feature_extractor_type", None)
if hasattr(config, "auto_map") and "AutoFeatureExtractor" in config.auto_map:
feature_extractor_auto_map = config.auto_map["AutoFeatureExtractor"]
if feature_extractor_class is not None:
# If we have custom code for a feature extractor, we get the proper class.
if feature_extractor_auto_map is not None:
if not trust_remote_code:
raise ValueError(
f"Loading {pretrained_model_name_or_path} requires you to execute the feature extractor file "
"in that repo on your local machine. Make sure you have read the code there to avoid "
"malicious use, then set the option `trust_remote_code=True` to remove this error."
)
if kwargs.get("revision", None) is None:
logger.warning(
"Explicitly passing a `revision` is encouraged when loading a feature extractor with custom "
"code to ensure no malicious code has been contributed in a newer revision."
)
module_file, class_name = feature_extractor_auto_map.split(".")
feature_extractor_class = get_class_from_dynamic_module(
pretrained_model_name_or_path, module_file + ".py", class_name, **kwargs
)
else:
feature_extractor_class = feature_extractor_class_from_name(feature_extractor_class)
return feature_extractor_class.from_dict(config_dict, **kwargs)
# Last try: we use the FEATURE_EXTRACTOR_MAPPING.
elif type(config) in FEATURE_EXTRACTOR_MAPPING:
feature_extractor_class = FEATURE_EXTRACTOR_MAPPING[type(config)]
return feature_extractor_class.from_dict(config_dict, **kwargs)
raise ValueError(
f"Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a "
f"`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following "
f"`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys())}"
)
@staticmethod
def register(config_class, feature_extractor_class):
"""
Register a new feature extractor for this class.
Args:
config_class ([`PretrainedConfig`]):
The configuration corresponding to the model to register.
feature_extractor_class ([`FeatureExtractorMixin`]): The feature extractor to register.
"""
FEATURE_EXTRACTOR_MAPPING.register(config_class, feature_extractor_class)
| # coding=utf-8
# Copyright 2021 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" AutoFeatureExtractor class."""
import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union
# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module
from ...feature_extraction_utils import FeatureExtractionMixin
from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
CONFIG_MAPPING_NAMES,
AutoConfig,
model_type_to_module_name,
replace_list_option_in_docstrings,
)
logger = logging.get_logger(__name__)
FEATURE_EXTRACTOR_MAPPING_NAMES = OrderedDict(
[
("beit", "BeitFeatureExtractor"),
("detr", "DetrFeatureExtractor"),
("deit", "DeiTFeatureExtractor"),
("hubert", "Wav2Vec2FeatureExtractor"),
("speech_to_text", "Speech2TextFeatureExtractor"),
("vit", "ViTFeatureExtractor"),
("wav2vec2", "Wav2Vec2FeatureExtractor"),
("detr", "DetrFeatureExtractor"),
("layoutlmv2", "LayoutLMv2FeatureExtractor"),
("clip", "CLIPFeatureExtractor"),
("perceiver", "PerceiverFeatureExtractor"),
("swin", "ViTFeatureExtractor"),
("vit_mae", "ViTFeatureExtractor"),
("segformer", "SegformerFeatureExtractor"),
("convnext", "ConvNextFeatureExtractor"),
("van", "ConvNextFeatureExtractor"),
("resnet", "ConvNextFeatureExtractor"),
("regnet", "ConvNextFeatureExtractor"),
("poolformer", "PoolFormerFeatureExtractor"),
("maskformer", "MaskFormerFeatureExtractor"),
("data2vec-audio", "Wav2Vec2FeatureExtractor"),
("data2vec-vision", "BeitFeatureExtractor"),
("dpt", "DPTFeatureExtractor"),
("glpn", "GLPNFeatureExtractor"),
]
)
FEATURE_EXTRACTOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)
def feature_extractor_class_from_name(class_name: str):
for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
if class_name in extractors:
module_name = model_type_to_module_name(module_name)
module = importlib.import_module(f".{module_name}", "transformers.models")
return getattr(module, class_name)
break
for config, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
if getattr(extractor, "__name__", None) == class_name:
return extractor
return None
def get_feature_extractor_config(
pretrained_model_name_or_path: Union[str, os.PathLike],
cache_dir: Optional[Union[str, os.PathLike]] = None,
force_download: bool = False,
resume_download: bool = False,
proxies: Optional[Dict[str, str]] = None,
use_auth_token: Optional[Union[bool, str]] = None,
revision: Optional[str] = None,
local_files_only: bool = False,
**kwargs,
):
"""
Loads the tokenizer configuration from a pretrained model tokenizer configuration.
Args:
pretrained_model_name_or_path (`str` or `os.PathLike`):
This can be either:
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced
under a user or organization name, like `dbmdz/bert-base-german-cased`.
- a path to a *directory* containing a configuration file saved using the
[`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
cache_dir (`str` or `os.PathLike`, *optional*):
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
cache should not be used.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to force to (re-)download the configuration files and override the cached versions if they
exist.
resume_download (`bool`, *optional*, defaults to `False`):
Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists.
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
use_auth_token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `transformers-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
identifier allowed by git.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, will only try to load the tokenizer configuration from local files.
<Tip>
Passing `use_auth_token=True` is required when you want to use a private model.
</Tip>
Returns:
`Dict`: The configuration of the tokenizer.
Examples:
```python
# Download configuration from huggingface.co and cache.
tokenizer_config = get_tokenizer_config("bert-base-uncased")
# This model does not have a tokenizer config so the result will be an empty dict.
tokenizer_config = get_tokenizer_config("xlm-roberta-base")
# Save a pretrained tokenizer locally and you can reload its config
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
tokenizer.save_pretrained("tokenizer-test")
tokenizer_config = get_tokenizer_config("tokenizer-test")
```"""
resolved_config_file = get_file_from_repo(
pretrained_model_name_or_path,
FEATURE_EXTRACTOR_NAME,
cache_dir=cache_dir,
force_download=force_download,
resume_download=resume_download,
proxies=proxies,
use_auth_token=use_auth_token,
revision=revision,
local_files_only=local_files_only,
)
if resolved_config_file is None:
logger.info(
"Could not locate the feature extractor configuration file, will try to use the model config instead."
)
return {}
with open(resolved_config_file, encoding="utf-8") as reader:
return json.load(reader)
class AutoFeatureExtractor:
r"""
This is a generic feature extractor class that will be instantiated as one of the feature extractor classes of the
library when created with the [`AutoFeatureExtractor.from_pretrained`] class method.
This class cannot be instantiated directly using `__init__()` (throws an error).
"""
def __init__(self):
raise EnvironmentError(
"AutoFeatureExtractor is designed to be instantiated "
"using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method."
)
@classmethod
@replace_list_option_in_docstrings(FEATURE_EXTRACTOR_MAPPING_NAMES)
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
r"""
Instantiate one of the feature extractor classes of the library from a pretrained model vocabulary.
The feature extractor class to instantiate is selected based on the `model_type` property of the config object
(either passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's
missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
List options
Params:
pretrained_model_name_or_path (`str` or `os.PathLike`):
This can be either:
- a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or
namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
- a path to a *directory* containing a feature extractor file saved using the
[`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] method, e.g.,
`./my_model_directory/`.
- a path or url to a saved feature extractor JSON *file*, e.g.,
`./my_model_directory/preprocessor_config.json`.
cache_dir (`str` or `os.PathLike`, *optional*):
Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
standard cache should not be used.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to force to (re-)download the feature extractor files and override the cached versions
if they exist.
resume_download (`bool`, *optional*, defaults to `False`):
Whether or not to delete incompletely received file. Attempts to resume the download if such a file
exists.
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
use_auth_token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `transformers-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
identifier allowed by git.
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
If `False`, then this function returns just the final feature extractor object. If `True`, then this
functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
`kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
trust_remote_code (`bool`, *optional*, defaults to `False`):
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
should only be set to `True` for repositories you trust and in which you have read the code, as it will
execute code present on the Hub on your local machine.
kwargs (`Dict[str, Any]`, *optional*):
The values in kwargs of any keys which are feature extractor attributes will be used to override the
loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
controlled by the `return_unused_kwargs` keyword parameter.
<Tip>
Passing `use_auth_token=True` is required when you want to use a private model.
</Tip>
Examples:
```python
>>> from transformers import AutoFeatureExtractor
>>> # Download feature extractor from huggingface.co and cache.
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h")
>>> # If feature extractor files are in a directory (e.g. feature extractor was saved using *save_pretrained('./test/saved_model/')*)
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("./test/saved_model/")
```"""
config = kwargs.pop("config", None)
trust_remote_code = kwargs.pop("trust_remote_code", False)
kwargs["_from_auto"] = True
config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs)
feature_extractor_class = config_dict.get("feature_extractor_type", None)
feature_extractor_auto_map = None
if "AutoFeatureExtractor" in config_dict.get("auto_map", {}):
feature_extractor_auto_map = config_dict["auto_map"]["AutoFeatureExtractor"]
# If we don't find the feature extractor class in the feature extractor config, let's try the model config.
if feature_extractor_class is None and feature_extractor_auto_map is None:
if not isinstance(config, PretrainedConfig):
config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
# It could be in `config.feature_extractor_type``
feature_extractor_class = getattr(config, "feature_extractor_type", None)
if hasattr(config, "auto_map") and "AutoFeatureExtractor" in config.auto_map:
feature_extractor_auto_map = config.auto_map["AutoFeatureExtractor"]
if feature_extractor_class is not None:
# If we have custom code for a feature extractor, we get the proper class.
if feature_extractor_auto_map is not None:
if not trust_remote_code:
raise ValueError(
f"Loading {pretrained_model_name_or_path} requires you to execute the feature extractor file "
"in that repo on your local machine. Make sure you have read the code there to avoid "
"malicious use, then set the option `trust_remote_code=True` to remove this error."
)
if kwargs.get("revision", None) is None:
logger.warning(
"Explicitly passing a `revision` is encouraged when loading a feature extractor with custom "
"code to ensure no malicious code has been contributed in a newer revision."
)
module_file, class_name = feature_extractor_auto_map.split(".")
feature_extractor_class = get_class_from_dynamic_module(
pretrained_model_name_or_path, module_file + ".py", class_name, **kwargs
)
else:
feature_extractor_class = feature_extractor_class_from_name(feature_extractor_class)
return feature_extractor_class.from_dict(config_dict, **kwargs)
# Last try: we use the FEATURE_EXTRACTOR_MAPPING.
elif type(config) in FEATURE_EXTRACTOR_MAPPING:
feature_extractor_class = FEATURE_EXTRACTOR_MAPPING[type(config)]
return feature_extractor_class.from_dict(config_dict, **kwargs)
raise ValueError(
f"Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a "
f"`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following "
f"`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys())}"
)
@staticmethod
def register(config_class, feature_extractor_class):
"""
Register a new feature extractor for this class.
Args:
config_class ([`PretrainedConfig`]):
The configuration corresponding to the model to register.
feature_extractor_class ([`FeatureExtractorMixin`]): The feature extractor to register.
"""
FEATURE_EXTRACTOR_MAPPING.register(config_class, feature_extractor_class)
|
import base64
import json
import logging
from html.parser import HTMLParser
from http.client import HTTPConnection
from markupsafe import escape
from sqlalchemy import and_
from sqlalchemy.orm import eagerload, joinedload, lazyload, undefer
from sqlalchemy.sql import expression
from galaxy import (
model,
util,
web
)
from galaxy.managers.workflows import (
MissingToolsException,
WorkflowUpdateOptions,
)
from galaxy.model.item_attrs import UsesItemRatings
from galaxy.model.mapping import desc
from galaxy.security.validate_user_input import validate_publicname
from galaxy.tools.parameters.basic import workflow_building_modes
from galaxy.util import (
FILENAME_VALID_CHARS,
unicodify
)
from galaxy.util.sanitize_html import sanitize_html
from galaxy.web import error, url_for
from galaxy.web.framework.helpers import (
grids,
time_ago,
)
from galaxy.webapps.base.controller import (
BaseUIController,
SharableMixin,
UsesStoredWorkflowMixin
)
from galaxy.workflow.extract import (
extract_workflow,
summarize
)
from galaxy.workflow.modules import (
load_module_sections,
module_factory
)
from galaxy.workflow.render import (
STANDALONE_SVG_TEMPLATE,
WorkflowCanvas
)
log = logging.getLogger(__name__)
class StoredWorkflowListGrid(grids.Grid):
class StepsColumn(grids.GridColumn):
def get_value(self, trans, grid, workflow):
return len(workflow.latest_workflow.steps)
# Grid definition
use_panels = True
title = "Saved Workflows"
model_class = model.StoredWorkflow
default_filter = {"name": "All", "tags": "All"}
default_sort_key = "-update_time"
columns = [
grids.TextColumn("Name", key="name", attach_popup=True, filterable="advanced"),
grids.IndividualTagsColumn("Tags",
"tags",
model_tag_association_class=model.StoredWorkflowTagAssociation,
filterable="advanced",
grid_name="StoredWorkflowListGrid"),
StepsColumn("Steps"),
grids.GridColumn("Created", key="create_time", format=time_ago),
grids.GridColumn("Last Updated", key="update_time", format=time_ago),
]
columns.append(
grids.MulticolFilterColumn(
"Search",
cols_to_filter=[columns[0], columns[1]],
key="free-text-search", visible=False, filterable="standard"
)
)
operations = [
grids.GridOperation("Edit", allow_multiple=False, condition=(lambda item: not item.deleted), async_compatible=False),
grids.GridOperation("Run", condition=(lambda item: not item.deleted), async_compatible=False),
grids.GridOperation("Copy", condition=(lambda item: not item.deleted), async_compatible=False),
grids.GridOperation("Rename", condition=(lambda item: not item.deleted), async_compatible=False),
grids.GridOperation("Sharing", condition=(lambda item: not item.deleted), async_compatible=False),
grids.GridOperation("Delete", condition=(lambda item: item.deleted), async_compatible=True),
]
def apply_query_filter(self, trans, query, **kwargs):
return query.filter_by(user=trans.user, deleted=False)
class StoredWorkflowAllPublishedGrid(grids.Grid):
title = "Published Workflows"
model_class = model.StoredWorkflow
default_sort_key = "update_time"
default_filter = dict(public_url="All", username="All", tags="All")
columns = [
grids.PublicURLColumn("Name", key="name", filterable="advanced", attach_popup=True),
grids.OwnerAnnotationColumn("Annotation",
key="annotation",
model_annotation_association_class=model.StoredWorkflowAnnotationAssociation,
filterable="advanced"),
grids.OwnerColumn("Owner", key="username", model_class=model.User, filterable="advanced"),
grids.CommunityRatingColumn("Community Rating", key="rating"),
grids.CommunityTagsColumn("Community Tags", key="tags",
model_tag_association_class=model.StoredWorkflowTagAssociation,
filterable="advanced", grid_name="PublicWorkflowListGrid"),
grids.ReverseSortColumn("Last Updated", key="update_time", format=time_ago)
]
columns.append(
grids.MulticolFilterColumn(
"Search name, annotation, owner, and tags",
cols_to_filter=[columns[0], columns[1], columns[2], columns[4]],
key="free-text-search", visible=False, filterable="standard"
)
)
operations = [
grids.GridOperation(
'Run',
condition=(lambda item: not item.deleted),
allow_multiple=False,
url_args=dict(controller='workflows', action="run")
),
grids.GridOperation(
"Import",
condition=(lambda item: not item.deleted),
allow_multiple=False,
url_args=dict(action="imp")
),
grids.GridOperation(
"Save as File",
condition=(lambda item: not item.deleted),
allow_multiple=False,
url_args=dict(action="export_to_file")
),
]
num_rows_per_page = 50
use_paging = True
def build_initial_query(self, trans, **kwargs):
# See optimization description comments and TODO for tags in matching public histories query.
# In addition to that - be sure to lazyload the latest_workflow - it isn't needed and it causes all
# of its steps to be eagerly loaded.
return trans.sa_session.query(self.model_class).join("user").options(lazyload("latest_workflow"), eagerload("user").load_only("username"), eagerload("annotations"), undefer("average_rating"))
def apply_query_filter(self, trans, query, **kwargs):
# A public workflow is published, has a slug, and is not deleted.
return query.filter(
self.model_class.published == expression.true()).filter(
self.model_class.slug.isnot(None)).filter(
self.model_class.deleted == expression.false())
# Simple HTML parser to get all content in a single tag.
class SingleTagContentsParser(HTMLParser):
def __init__(self, target_tag):
# Cannot use super() because HTMLParser is an old-style class in Python2
HTMLParser.__init__(self)
self.target_tag = target_tag
self.cur_tag = None
self.tag_content = ""
def handle_starttag(self, tag, attrs):
""" Called for each start tag. """
self.cur_tag = tag
def handle_data(self, text):
""" Called for each block of plain text. """
if self.cur_tag == self.target_tag:
self.tag_content += text
class WorkflowController(BaseUIController, SharableMixin, UsesStoredWorkflowMixin, UsesItemRatings):
stored_list_grid = StoredWorkflowListGrid()
published_list_grid = StoredWorkflowAllPublishedGrid()
@web.expose
@web.require_login("use Galaxy workflows")
def list_grid(self, trans, **kwargs):
""" List user's stored workflows. """
# status = message = None
if 'operation' in kwargs:
operation = kwargs['operation'].lower()
if operation == "rename":
return self.rename(trans, **kwargs)
history_ids = util.listify(kwargs.get('id', []))
if operation == "sharing":
return self.sharing(trans, id=history_ids)
return self.stored_list_grid(trans, **kwargs)
@web.expose
@web.require_login("use Galaxy workflows", use_panels=True)
def list(self, trans):
"""
Render workflow main page (management of existing workflows)
"""
# Take care of proxy prefix in url as well
redirect_url = url_for('/') + 'workflow'
return trans.response.send_redirect(redirect_url)
@web.expose
@web.json
def list_published(self, trans, **kwargs):
return self.published_list_grid(trans, **kwargs)
@web.expose
def display_by_username_and_slug(self, trans, username, slug, format='html'):
"""
Display workflow based on a username and slug. Format can be html, json, or json-download.
"""
# Get workflow by username and slug. Security is handled by the display methods below.
session = trans.sa_session
user = session.query(model.User).filter_by(username=username).first()
if not user:
raise web.httpexceptions.HTTPNotFound()
stored_workflow = trans.sa_session.query(model.StoredWorkflow).filter_by(user=user, slug=slug, deleted=False).first()
if not stored_workflow:
raise web.httpexceptions.HTTPNotFound()
encoded_id = trans.security.encode_id(stored_workflow.id)
# Display workflow in requested format.
if format == 'html':
return self._display(trans, stored_workflow)
elif format == 'json':
return self.for_direct_import(trans, encoded_id)
elif format == 'json-download':
return self.export_to_file(trans, encoded_id)
@web.expose
def display_by_id(self, trans, id):
""" Display workflow based on id. """
# Get workflow.
stored_workflow = self.get_stored_workflow(trans, id)
return self._display(trans, stored_workflow)
def _display(self, trans, stored_workflow):
""" Diplay workflow as HTML page. """
if stored_workflow is None:
raise web.httpexceptions.HTTPNotFound()
# Security check raises error if user cannot access workflow.
self.security_check(trans, stored_workflow, False, True)
# Get data for workflow's steps.
self.get_stored_workflow_steps(trans, stored_workflow)
# Get annotations.
stored_workflow.annotation = self.get_item_annotation_str(trans.sa_session, stored_workflow.user, stored_workflow)
for step in stored_workflow.latest_workflow.steps:
step.annotation = self.get_item_annotation_str(trans.sa_session, stored_workflow.user, step)
user_is_owner = True if trans.user == stored_workflow.user else False
# Get rating data.
user_item_rating = 0
if trans.get_user():
user_item_rating = self.get_user_item_rating(trans.sa_session, trans.get_user(), stored_workflow)
if user_item_rating:
user_item_rating = user_item_rating.rating
else:
user_item_rating = 0
ave_item_rating, num_ratings = self.get_ave_item_rating_data(trans.sa_session, stored_workflow)
return trans.fill_template_mako("workflow/display.mako",
item=stored_workflow,
item_data=stored_workflow.latest_workflow.steps,
user_item_rating=user_item_rating,
ave_item_rating=ave_item_rating,
num_ratings=num_ratings,
user_is_owner=user_is_owner)
@web.expose
def get_item_content_async(self, trans, id):
""" Returns item content in HTML format. """
stored = self.get_stored_workflow(trans, id, False, True)
if stored is None:
raise web.httpexceptions.HTTPNotFound()
# Get data for workflow's steps.
self.get_stored_workflow_steps(trans, stored)
# Get annotations.
stored.annotation = self.get_item_annotation_str(trans.sa_session, stored.user, stored)
for step in stored.latest_workflow.steps:
step.annotation = self.get_item_annotation_str(trans.sa_session, stored.user, step)
return trans.stream_template_mako("/workflow/item_content.mako", item=stored, item_data=stored.latest_workflow.steps)
@web.expose
@web.require_login("use Galaxy workflows")
def share(self, trans, id, email="", use_panels=False):
msg = mtype = None
# Load workflow from database
stored = self.get_stored_workflow(trans, id)
if email:
other = trans.sa_session.query(model.User) \
.filter(and_(model.User.table.c.email == email,
model.User.table.c.deleted == expression.false())) \
.first()
if not other:
mtype = "error"
msg = ("User '%s' does not exist" % escape(email))
elif other == trans.get_user():
mtype = "error"
msg = ("You cannot share a workflow with yourself")
elif trans.sa_session.query(model.StoredWorkflowUserShareAssociation) \
.filter_by(user=other, stored_workflow=stored).count() > 0:
mtype = "error"
msg = ("Workflow already shared with '%s'" % escape(email))
else:
share = model.StoredWorkflowUserShareAssociation()
share.stored_workflow = stored
share.user = other
session = trans.sa_session
session.add(share)
session.flush()
trans.set_message("Workflow '{}' shared with user '{}'".format(escape(stored.name), escape(other.email)))
return trans.response.send_redirect(url_for(controller='workflow', action='sharing', id=id))
return trans.fill_template("/ind_share_base.mako",
message=msg,
messagetype=mtype,
item=stored,
email=email,
use_panels=use_panels)
@web.expose
@web.require_login("Share or export Galaxy workflows")
def sharing(self, trans, id, **kwargs):
""" Handle workflow sharing. """
session = trans.sa_session
if 'unshare_me' in kwargs:
# Remove self from shared associations with workflow.
stored = self.get_stored_workflow(trans, id, False, True)
association = session.query(model.StoredWorkflowUserShareAssociation) \
.filter_by(user=trans.user, stored_workflow=stored).one()
session.delete(association)
session.flush()
return self.list(trans)
else:
# Get session and workflow.
stored = self.get_stored_workflow(trans, id)
session.add(stored)
# Do operation on workflow.
if 'make_accessible_via_link' in kwargs:
self._make_item_accessible(trans.sa_session, stored)
elif 'make_accessible_and_publish' in kwargs:
self._make_item_accessible(trans.sa_session, stored)
stored.published = True
elif 'publish' in kwargs:
stored.published = True
elif 'disable_link_access' in kwargs:
stored.importable = False
elif 'unpublish' in kwargs:
stored.published = False
elif 'disable_link_access_and_unpublish' in kwargs:
stored.importable = stored.published = False
elif 'unshare_user' in kwargs:
user = session.query(model.User).get(trans.security.decode_id(kwargs['unshare_user']))
if not user:
error("User not found for provided id")
association = session.query(model.StoredWorkflowUserShareAssociation) \
.filter_by(user=user, stored_workflow=stored).one()
session.delete(association)
# Legacy issue: workflows made accessible before recent updates may not have a slug. Create slug for any workflows that need them.
if stored.importable and not stored.slug:
self._make_item_accessible(trans.sa_session, stored)
session.flush()
return trans.fill_template("/workflow/sharing.mako", use_panels=True, item=stored)
@web.expose
@web.require_login("share Galaxy items")
def set_public_username(self, trans, id, username, **kwargs):
""" Set user's public username and delegate to sharing() """
user = trans.get_user()
# message from validate_publicname does not contain input, no need
# to escape.
message = validate_publicname(trans, username, user)
if message:
return trans.fill_template("/workflow/sharing.mako", item=self.get_item(trans, id), message=message, status="error")
user.username = username
trans.sa_session.flush()
return self.sharing(trans, id, **kwargs)
@web.expose
@web.require_login("to import a workflow", use_panels=True)
def imp(self, trans, id, **kwargs):
"""Imports a workflow shared by other users."""
# Set referer message.
referer = trans.request.referer
if referer:
referer_message = "<a href='%s'>return to the previous page</a>" % escape(referer)
else:
referer_message = "<a href='%s'>go to Galaxy's start page</a>" % url_for('/')
# Do import.
stored = self.get_stored_workflow(trans, id, check_ownership=False)
if stored.importable is False:
return trans.show_error_message("The owner of this workflow has disabled imports via this link.<br>You can %s" % referer_message, use_panels=True)
elif stored.deleted:
return trans.show_error_message("You can't import this workflow because it has been deleted.<br>You can %s" % referer_message, use_panels=True)
self._import_shared_workflow(trans, stored)
# Redirect to load galaxy frames.
return trans.show_ok_message(
message="""Workflow "%s" has been imported. <br>You can <a href="%s">start using this workflow</a> or %s."""
% (stored.name, web.url_for('/workflows/list'), referer_message))
@web.expose
@web.require_login("use Galaxy workflows")
def rename_async(self, trans, id, new_name=None, **kwargs):
stored = self.get_stored_workflow(trans, id)
if new_name:
san_new_name = sanitize_html(new_name)
stored.name = san_new_name
stored.latest_workflow.name = san_new_name
trans.sa_session.flush()
return stored.name
@web.expose
@web.require_login("use Galaxy workflows")
def annotate_async(self, trans, id, new_annotation=None, **kwargs):
stored = self.get_stored_workflow(trans, id)
if new_annotation:
# Sanitize annotation before adding it.
new_annotation = sanitize_html(new_annotation)
self.add_item_annotation(trans.sa_session, trans.get_user(), stored, new_annotation)
trans.sa_session.flush()
return new_annotation
@web.expose
@web.require_login("rate items")
@web.json
def rate_async(self, trans, id, rating):
""" Rate a workflow asynchronously and return updated community data. """
stored = self.get_stored_workflow(trans, id, check_ownership=False, check_accessible=True)
if not stored:
return trans.show_error_message("The specified workflow does not exist.")
# Rate workflow.
self.rate_item(trans.sa_session, trans.get_user(), stored, rating)
return self.get_ave_item_rating_data(trans.sa_session, stored)
@web.expose
@web.require_login("use Galaxy workflows")
def set_accessible_async(self, trans, id=None, accessible=False):
""" Set workflow's importable attribute and slug. """
stored = self.get_stored_workflow(trans, id)
# Only set if importable value would change; this prevents a change in the update_time unless attribute really changed.
importable = accessible in ['True', 'true', 't', 'T']
if stored and stored.importable != importable:
if importable:
self._make_item_accessible(trans.sa_session, stored)
else:
stored.importable = importable
trans.sa_session.flush()
return
@web.expose
def get_embed_html_async(self, trans, id):
""" Returns HTML for embedding a workflow in a page. """
# TODO: user should be able to embed any item he has access to. see display_by_username_and_slug for security code.
stored = self.get_stored_workflow(trans, id)
if stored:
return "Embedded Workflow '%s'" % stored.name
@web.expose
@web.json
@web.require_login("use Galaxy workflows")
def get_name_and_link_async(self, trans, id=None):
""" Returns workflow's name and link. """
stored = self.get_stored_workflow(trans, id)
return_dict = {"name": stored.name,
"link": url_for(controller='workflow',
action="display_by_username_and_slug",
username=stored.user.username,
slug=stored.slug)}
return return_dict
@web.expose
@web.require_login("use Galaxy workflows")
def gen_image(self, trans, id):
stored = self.get_stored_workflow(trans, id, check_ownership=True)
try:
svg = self._workflow_to_svg_canvas(trans, stored)
except Exception:
status = 'error'
message = 'Galaxy is unable to create the SVG image. Please check your workflow, there might be missing tools.'
return trans.fill_template("/workflow/sharing.mako", use_panels=True, item=stored, status=status, message=message)
trans.response.set_content_type("image/svg+xml")
s = STANDALONE_SVG_TEMPLATE % svg.tostring()
return s.encode('utf-8')
@web.expose
@web.require_login("use Galaxy workflows")
def copy(self, trans, id, save_as_name=None):
# Get workflow to copy.
stored = self.get_stored_workflow(trans, id, check_ownership=False)
user = trans.get_user()
if stored.user == user:
owner = True
else:
if trans.sa_session.query(model.StoredWorkflowUserShareAssociation) \
.filter_by(user=user, stored_workflow=stored).count() == 0:
error("Workflow is not owned by or shared with current user")
owner = False
# Copy.
new_stored = model.StoredWorkflow()
if (save_as_name):
new_stored.name = '%s' % save_as_name
else:
new_stored.name = "Copy of %s" % stored.name
new_stored.latest_workflow = stored.latest_workflow
# Copy annotation.
annotation_obj = self.get_item_annotation_obj(trans.sa_session, stored.user, stored)
if annotation_obj:
self.add_item_annotation(trans.sa_session, trans.get_user(), new_stored, annotation_obj.annotation)
new_stored.copy_tags_from(trans.user, stored)
if not owner:
new_stored.name += " shared by %s" % stored.user.email
new_stored.user = user
# Persist
session = trans.sa_session
session.add(new_stored)
session.flush()
# Display the management page
message = 'Created new workflow with name: %s' % escape(new_stored.name)
trans.set_message(message)
return_url = url_for('/') + 'workflow?status=done&message=%s' % escape(message)
trans.response.send_redirect(return_url)
@web.legacy_expose_api
def create(self, trans, payload=None, **kwd):
if trans.request.method == 'GET':
return {
'title' : 'Create Workflow',
'inputs' : [{
'name' : 'workflow_name',
'label' : 'Name',
'value' : 'Unnamed workflow'
}, {
'name' : 'workflow_annotation',
'label' : 'Annotation',
'help' : 'A description of the workflow; annotation is shown alongside shared or published workflows.'
}]}
else:
user = trans.get_user()
workflow_name = payload.get('workflow_name')
workflow_annotation = payload.get('workflow_annotation')
if not workflow_name:
return self.message_exception(trans, 'Please provide a workflow name.')
# Create the new stored workflow
stored_workflow = model.StoredWorkflow()
stored_workflow.name = workflow_name
stored_workflow.user = user
self.create_item_slug(trans.sa_session, stored_workflow)
# And the first (empty) workflow revision
workflow = model.Workflow()
workflow.name = workflow_name
workflow.stored_workflow = stored_workflow
stored_workflow.latest_workflow = workflow
# Add annotation.
workflow_annotation = sanitize_html(workflow_annotation)
self.add_item_annotation(trans.sa_session, trans.get_user(), stored_workflow, workflow_annotation)
# Persist
session = trans.sa_session
session.add(stored_workflow)
session.flush()
return {'id': trans.security.encode_id(stored_workflow.id), 'message': 'Workflow %s has been created.' % workflow_name}
@web.json
def save_workflow_as(self, trans, workflow_name, workflow_data, workflow_annotation="", from_tool_form=False):
"""
Creates a new workflow based on Save As command. It is a new workflow, but
is created with workflow_data already present.
"""
user = trans.get_user()
if workflow_name is not None:
workflow_contents_manager = self.app.workflow_contents_manager
stored_workflow = model.StoredWorkflow()
stored_workflow.name = workflow_name
stored_workflow.user = user
self.create_item_slug(trans.sa_session, stored_workflow)
workflow = model.Workflow()
workflow.name = workflow_name
workflow.stored_workflow = stored_workflow
stored_workflow.latest_workflow = workflow
# Add annotation.
workflow_annotation = sanitize_html(workflow_annotation)
self.add_item_annotation(trans.sa_session, trans.get_user(), stored_workflow, workflow_annotation)
# Persist
session = trans.sa_session
session.add(stored_workflow)
session.flush()
workflow_update_options = WorkflowUpdateOptions(
update_stored_workflow_attributes=False, # taken care of above
from_tool_form=from_tool_form,
)
try:
workflow, errors = workflow_contents_manager.update_workflow_from_raw_description(
trans,
stored_workflow,
workflow_data,
workflow_update_options,
)
except MissingToolsException as e:
return dict(
name=e.workflow.name,
message=("This workflow includes missing or invalid tools. "
"It cannot be saved until the following steps are removed or the missing tools are enabled."),
errors=e.errors,
)
return (trans.security.encode_id(stored_workflow.id))
else:
# This is an error state, 'save as' must have a workflow_name
log.exception("Error in Save As workflow: no name.")
@web.expose
def delete(self, trans, id=None):
"""
Mark a workflow as deleted
"""
# Load workflow from database
stored = self.get_stored_workflow(trans, id)
# Mark as deleted and save
stored.deleted = True
trans.user.stored_workflow_menu_entries = [entry for entry in trans.user.stored_workflow_menu_entries if entry.stored_workflow != stored]
trans.sa_session.add(stored)
trans.sa_session.flush()
# Display the management page
message = "Workflow deleted: %s" % escape(stored.name)
trans.set_message(message)
return trans.response.send_redirect(url_for('/') + 'workflow?status=done&message=%s' % escape(message))
@web.expose
@web.require_login("edit workflows")
def editor(self, trans, id=None, workflow_id=None, version=None):
"""
Render the main workflow editor interface. The canvas is embedded as
an iframe (necessary for scrolling to work properly), which is
rendered by `editor_canvas`.
"""
if not id:
if workflow_id:
workflow = trans.sa_session.query(model.Workflow).get(trans.security.decode_id(workflow_id))
stored_workflow = workflow.stored_workflow
self.security_check(trans, stored_workflow, True, False)
stored_workflow_id = trans.security.encode_id(stored_workflow.id)
return trans.response.send_redirect(f'{url_for('/')}workflow/editor?id={stored_workflow_id}')
error("Invalid workflow id")
stored = self.get_stored_workflow(trans, id)
# The following query loads all user-owned workflows,
# So that they can be copied or inserted in the workflow editor.
workflows = trans.sa_session.query(model.StoredWorkflow) \
.filter_by(user=trans.user, deleted=False, hidden=False) \
.order_by(desc(model.StoredWorkflow.table.c.update_time)) \
.options(joinedload('latest_workflow').joinedload('steps')) \
.all()
if version is None:
version = len(stored.workflows) - 1
else:
version = int(version)
# create workflow module models
module_sections = []
for module_section in load_module_sections(trans).values():
module_sections.append({
"title": module_section.get("title"),
"name": module_section.get("name"),
"elems": [{
"name": elem.get("name"),
"title": elem.get("title"),
"description": elem.get("description")
} for elem in module_section.get("modules")]
})
# create data manager tool models
data_managers = []
if trans.user_is_admin and trans.app.data_managers.data_managers:
for data_manager_val in trans.app.data_managers.data_managers.values():
tool = data_manager_val.tool
if not tool.hidden:
data_managers.append({
"id": tool.id,
"name": tool.name,
"hidden": tool.hidden,
"description": tool.description,
"is_workflow_compatible": tool.is_workflow_compatible
})
# create workflow models
workflows = [{
'id' : trans.security.encode_id(workflow.id),
'latest_id' : trans.security.encode_id(workflow.latest_workflow.id),
'step_count' : len(workflow.latest_workflow.steps),
'name' : workflow.name
} for workflow in workflows if workflow.id != stored.id]
# identify item tags
item_tags = [tag for tag in stored.tags if tag.user == trans.user]
item_tag_names = []
for ta in item_tags:
item_tag_names.append(escape(ta.tag.name))
# build workflow editor model
editor_config = {
'id' : trans.security.encode_id(stored.id),
'name' : stored.name,
'tags' : item_tag_names,
'version' : version,
'annotation' : self.get_item_annotation_str(trans.sa_session, trans.user, stored),
'toolbox' : trans.app.toolbox.to_dict(trans),
'moduleSections' : module_sections,
'dataManagers' : data_managers,
'workflows' : workflows
}
# parse to mako
return trans.fill_template("workflow/editor.mako", editor_config=editor_config)
@web.json
def load_workflow(self, trans, id, version=None):
"""
Get the latest Workflow for the StoredWorkflow identified by `id` and
encode it as a json string that can be read by the workflow editor
web interface.
"""
trans.workflow_building_mode = workflow_building_modes.ENABLED
stored = self.get_stored_workflow(trans, id, check_ownership=True, check_accessible=False)
workflow_contents_manager = self.app.workflow_contents_manager
return workflow_contents_manager.workflow_to_dict(trans, stored, style="editor", version=version)
@web.expose
@web.require_login("use workflows")
def export_to_myexp(self, trans, id, myexp_username, myexp_password):
"""
Exports a workflow to myExperiment website.
"""
trans.workflow_building_mode = workflow_building_modes.ENABLED
stored = self.get_stored_workflow(trans, id, check_ownership=False, check_accessible=True)
# Convert workflow to dict.
workflow_dict = self._workflow_to_dict(trans, stored)
#
# Create and submit workflow myExperiment request.
#
# Create workflow content JSON.
workflow_content = json.dumps(workflow_dict, indent=4, sort_keys=True)
# Create myExperiment request.
request_raw = trans.fill_template(
"workflow/myexp_export.mako",
workflow_name=workflow_dict['name'],
workflow_description=workflow_dict['annotation'],
workflow_content=workflow_content,
workflow_svg=self._workflow_to_svg_canvas(trans, stored).tostring()
)
# strip() b/c myExperiment XML parser doesn't allow white space before XML; utf-8 handles unicode characters.
request = unicodify(request_raw.strip(), 'utf-8')
# Do request and get result.
auth_header = base64.b64encode(f'{myexp_username}:{myexp_password}')
headers = {"Content-type": "text/xml", "Accept": "text/xml", "Authorization": "Basic %s" % auth_header}
myexp_url = trans.app.config.myexperiment_target_url
conn = HTTPConnection(myexp_url)
# NOTE: blocks web thread.
conn.request("POST", "/workflow.xml", request, headers)
response = conn.getresponse()
response_data = response.read()
conn.close()
# Do simple parse of response to see if export successful and provide user feedback.
parser = SingleTagContentsParser('id')
parser.feed(response_data)
myexp_workflow_id = parser.tag_content
workflow_list_str = " <br>Return to <a href='%s'>workflow list." % url_for(controller='workflows', action='list')
if myexp_workflow_id:
return trans.show_message(
"""Workflow '{}' successfully exported to myExperiment. <br/>
<a href="http://{}/workflows/{}">Click here to view the workflow on myExperiment</a> {}
""".format(stored.name, myexp_url, myexp_workflow_id, workflow_list_str),
use_panels=True)
else:
return trans.show_error_message(
"Workflow '%s' could not be exported to myExperiment. Error: %s %s" %
(stored.name, response_data, workflow_list_str), use_panels=True)
@web.json_pretty
def for_direct_import(self, trans, id):
"""
Get the latest Workflow for the StoredWorkflow identified by `id` and
encode it as a json string that can be imported back into Galaxy
This has slightly different information than the above. In particular,
it does not attempt to decode forms and build UIs, it just stores
the raw state.
"""
stored = self.get_stored_workflow(trans, id, check_ownership=False, check_accessible=True)
return self._workflow_to_dict(trans, stored)
@web.json_pretty
def export_to_file(self, trans, id):
"""
Get the latest Workflow for the StoredWorkflow identified by `id` and
encode it as a json string that can be imported back into Galaxy
This has slightly different information than the above. In particular,
it does not attempt to decode forms and build UIs, it just stores
the raw state.
"""
# Get workflow.
stored = self.get_stored_workflow(trans, id, check_ownership=False, check_accessible=True)
# Stream workflow to file.
stored_dict = self._workflow_to_dict(trans, stored)
if not stored_dict:
# This workflow has a tool that's missing from the distribution
trans.response.status = 400
return "Workflow cannot be exported due to missing tools."
sname = stored.name
sname = ''.join(c in FILENAME_VALID_CHARS and c or '_' for c in sname)[0:150]
trans.response.headers["Content-Disposition"] = 'attachment; filename="Galaxy-Workflow-%s.ga"' % (sname)
trans.response.set_content_type('application/galaxy-archive')
return stored_dict
@web.expose
def build_from_current_history(self, trans, job_ids=None, dataset_ids=None, dataset_collection_ids=None, workflow_name=None, dataset_names=None, dataset_collection_names=None):
user = trans.get_user()
history = trans.get_history()
if not user:
return trans.show_error_message("Must be logged in to create workflows")
if (job_ids is None and dataset_ids is None) or workflow_name is None:
jobs, warnings = summarize(trans)
# Render
return trans.fill_template(
"workflow/build_from_current_history.mako",
jobs=jobs,
warnings=warnings,
history=history
)
else:
# If there is just one dataset name selected or one dataset collection, these
# come through as string types instead of lists. xref #3247.
dataset_names = util.listify(dataset_names)
dataset_collection_names = util.listify(dataset_collection_names)
stored_workflow = extract_workflow(
trans,
user=user,
job_ids=job_ids,
dataset_ids=dataset_ids,
dataset_collection_ids=dataset_collection_ids,
workflow_name=workflow_name,
dataset_names=dataset_names,
dataset_collection_names=dataset_collection_names
)
# Index page with message
workflow_id = trans.security.encode_id(stored_workflow.id)
return trans.show_message('Workflow "%s" created from current history. '
'You can <a href="%s" target="_parent">edit</a> or <a href="%s" target="_parent">run</a> the workflow.'
% (escape(workflow_name), url_for(controller='workflow', action='editor', id=workflow_id),
url_for(controller='workflows', action='run', id=workflow_id)))
def get_item(self, trans, id):
return self.get_stored_workflow(trans, id)
def _workflow_to_svg_canvas(self, trans, stored):
workflow = stored.latest_workflow
workflow_canvas = WorkflowCanvas()
for step in workflow.steps:
# Load from database representation
module = module_factory.from_workflow_step(trans, step)
module_name = module.get_name()
module_data_inputs = module.get_data_inputs()
module_data_outputs = module.get_data_outputs()
workflow_canvas.populate_data_for_step(
step,
module_name,
module_data_inputs,
module_data_outputs,
)
workflow_canvas.add_steps()
return workflow_canvas.finish()
def _build_workflow_on_str(instance_ds_names):
# Returns suffix for new histories based on multi input iteration
num_multi_inputs = len(instance_ds_names)
if num_multi_inputs == 0:
return ""
elif num_multi_inputs == 1:
return " on %s" % instance_ds_names[0]
else:
return " on {} and {}".format(", ".join(instance_ds_names[0:-1]), instance_ds_names[-1])
def _expand_multiple_inputs(kwargs):
(single_inputs, matched_multi_inputs, multiplied_multi_inputs) = _split_inputs(kwargs)
# Build up every combination of inputs to be run together.
input_combos = _extend_with_matched_combos(single_inputs, matched_multi_inputs)
input_combos = _extend_with_multiplied_combos(input_combos, multiplied_multi_inputs)
# Input name that are multiply specified
multi_input_keys = list(matched_multi_inputs.keys()) + list(multiplied_multi_inputs.keys())
for input_combo in input_combos:
for key, value in input_combo.items():
kwargs[key] = value
yield (kwargs, multi_input_keys)
def _extend_with_matched_combos(single_inputs, multi_inputs):
if len(multi_inputs) == 0:
return [single_inputs]
matched_multi_inputs = []
first_multi_input_key = next(iter(multi_inputs.keys()))
first_multi_value = multi_inputs.get(first_multi_input_key)
for value in first_multi_value:
new_inputs = _copy_and_extend_inputs(single_inputs, first_multi_input_key, value)
matched_multi_inputs.append(new_inputs)
for multi_input_key, multi_input_values in multi_inputs.items():
if multi_input_key == first_multi_input_key:
continue
if len(multi_input_values) != len(first_multi_value):
raise Exception("Failed to match up multi-select inputs, must select equal number of data files in each multiselect")
for index, value in enumerate(multi_input_values):
matched_multi_inputs[index][multi_input_key] = value
return matched_multi_inputs
def _extend_with_multiplied_combos(input_combos, multi_inputs):
combos = input_combos
for multi_input_key, multi_input_value in multi_inputs.items():
iter_combos = []
for combo in combos:
for input_value in multi_input_value:
iter_combos.append(_copy_and_extend_inputs(combo, multi_input_key, input_value))
combos = iter_combos
return combos
def _copy_and_extend_inputs(inputs, key, value):
new_inputs = dict(inputs)
new_inputs[key] = value
return new_inputs
def _split_inputs(kwargs):
"""
"""
input_keys = [a for a in kwargs if a.endswith('|input')]
single_inputs = {}
matched_multi_inputs = {}
multiplied_multi_inputs = {}
for input_key in input_keys:
input_val = kwargs[input_key]
if isinstance(input_val, list):
input_base = input_key[:-len("|input")]
mode_key = "%s|multi_mode" % input_base
mode = kwargs.get(mode_key, "matched")
if mode == "matched":
matched_multi_inputs[input_key] = input_val
else:
multiplied_multi_inputs[input_key] = input_val
else:
single_inputs[input_key] = input_val
return (single_inputs, matched_multi_inputs, multiplied_multi_inputs)
| import base64
import json
import logging
from html.parser import HTMLParser
from http.client import HTTPConnection
from markupsafe import escape
from sqlalchemy import and_
from sqlalchemy.orm import eagerload, joinedload, lazyload, undefer
from sqlalchemy.sql import expression
from galaxy import (
model,
util,
web
)
from galaxy.managers.workflows import (
MissingToolsException,
WorkflowUpdateOptions,
)
from galaxy.model.item_attrs import UsesItemRatings
from galaxy.model.mapping import desc
from galaxy.security.validate_user_input import validate_publicname
from galaxy.tools.parameters.basic import workflow_building_modes
from galaxy.util import (
FILENAME_VALID_CHARS,
unicodify
)
from galaxy.util.sanitize_html import sanitize_html
from galaxy.web import error, url_for
from galaxy.web.framework.helpers import (
grids,
time_ago,
)
from galaxy.webapps.base.controller import (
BaseUIController,
SharableMixin,
UsesStoredWorkflowMixin
)
from galaxy.workflow.extract import (
extract_workflow,
summarize
)
from galaxy.workflow.modules import (
load_module_sections,
module_factory
)
from galaxy.workflow.render import (
STANDALONE_SVG_TEMPLATE,
WorkflowCanvas
)
log = logging.getLogger(__name__)
class StoredWorkflowListGrid(grids.Grid):
class StepsColumn(grids.GridColumn):
def get_value(self, trans, grid, workflow):
return len(workflow.latest_workflow.steps)
# Grid definition
use_panels = True
title = "Saved Workflows"
model_class = model.StoredWorkflow
default_filter = {"name": "All", "tags": "All"}
default_sort_key = "-update_time"
columns = [
grids.TextColumn("Name", key="name", attach_popup=True, filterable="advanced"),
grids.IndividualTagsColumn("Tags",
"tags",
model_tag_association_class=model.StoredWorkflowTagAssociation,
filterable="advanced",
grid_name="StoredWorkflowListGrid"),
StepsColumn("Steps"),
grids.GridColumn("Created", key="create_time", format=time_ago),
grids.GridColumn("Last Updated", key="update_time", format=time_ago),
]
columns.append(
grids.MulticolFilterColumn(
"Search",
cols_to_filter=[columns[0], columns[1]],
key="free-text-search", visible=False, filterable="standard"
)
)
operations = [
grids.GridOperation("Edit", allow_multiple=False, condition=(lambda item: not item.deleted), async_compatible=False),
grids.GridOperation("Run", condition=(lambda item: not item.deleted), async_compatible=False),
grids.GridOperation("Copy", condition=(lambda item: not item.deleted), async_compatible=False),
grids.GridOperation("Rename", condition=(lambda item: not item.deleted), async_compatible=False),
grids.GridOperation("Sharing", condition=(lambda item: not item.deleted), async_compatible=False),
grids.GridOperation("Delete", condition=(lambda item: item.deleted), async_compatible=True),
]
def apply_query_filter(self, trans, query, **kwargs):
return query.filter_by(user=trans.user, deleted=False)
class StoredWorkflowAllPublishedGrid(grids.Grid):
title = "Published Workflows"
model_class = model.StoredWorkflow
default_sort_key = "update_time"
default_filter = dict(public_url="All", username="All", tags="All")
columns = [
grids.PublicURLColumn("Name", key="name", filterable="advanced", attach_popup=True),
grids.OwnerAnnotationColumn("Annotation",
key="annotation",
model_annotation_association_class=model.StoredWorkflowAnnotationAssociation,
filterable="advanced"),
grids.OwnerColumn("Owner", key="username", model_class=model.User, filterable="advanced"),
grids.CommunityRatingColumn("Community Rating", key="rating"),
grids.CommunityTagsColumn("Community Tags", key="tags",
model_tag_association_class=model.StoredWorkflowTagAssociation,
filterable="advanced", grid_name="PublicWorkflowListGrid"),
grids.ReverseSortColumn("Last Updated", key="update_time", format=time_ago)
]
columns.append(
grids.MulticolFilterColumn(
"Search name, annotation, owner, and tags",
cols_to_filter=[columns[0], columns[1], columns[2], columns[4]],
key="free-text-search", visible=False, filterable="standard"
)
)
operations = [
grids.GridOperation(
'Run',
condition=(lambda item: not item.deleted),
allow_multiple=False,
url_args=dict(controller='workflows', action="run")
),
grids.GridOperation(
"Import",
condition=(lambda item: not item.deleted),
allow_multiple=False,
url_args=dict(action="imp")
),
grids.GridOperation(
"Save as File",
condition=(lambda item: not item.deleted),
allow_multiple=False,
url_args=dict(action="export_to_file")
),
]
num_rows_per_page = 50
use_paging = True
def build_initial_query(self, trans, **kwargs):
# See optimization description comments and TODO for tags in matching public histories query.
# In addition to that - be sure to lazyload the latest_workflow - it isn't needed and it causes all
# of its steps to be eagerly loaded.
return trans.sa_session.query(self.model_class).join("user").options(lazyload("latest_workflow"), eagerload("user").load_only("username"), eagerload("annotations"), undefer("average_rating"))
def apply_query_filter(self, trans, query, **kwargs):
# A public workflow is published, has a slug, and is not deleted.
return query.filter(
self.model_class.published == expression.true()).filter(
self.model_class.slug.isnot(None)).filter(
self.model_class.deleted == expression.false())
# Simple HTML parser to get all content in a single tag.
class SingleTagContentsParser(HTMLParser):
def __init__(self, target_tag):
# Cannot use super() because HTMLParser is an old-style class in Python2
HTMLParser.__init__(self)
self.target_tag = target_tag
self.cur_tag = None
self.tag_content = ""
def handle_starttag(self, tag, attrs):
""" Called for each start tag. """
self.cur_tag = tag
def handle_data(self, text):
""" Called for each block of plain text. """
if self.cur_tag == self.target_tag:
self.tag_content += text
class WorkflowController(BaseUIController, SharableMixin, UsesStoredWorkflowMixin, UsesItemRatings):
stored_list_grid = StoredWorkflowListGrid()
published_list_grid = StoredWorkflowAllPublishedGrid()
@web.expose
@web.require_login("use Galaxy workflows")
def list_grid(self, trans, **kwargs):
""" List user's stored workflows. """
# status = message = None
if 'operation' in kwargs:
operation = kwargs['operation'].lower()
if operation == "rename":
return self.rename(trans, **kwargs)
history_ids = util.listify(kwargs.get('id', []))
if operation == "sharing":
return self.sharing(trans, id=history_ids)
return self.stored_list_grid(trans, **kwargs)
@web.expose
@web.require_login("use Galaxy workflows", use_panels=True)
def list(self, trans):
"""
Render workflow main page (management of existing workflows)
"""
# Take care of proxy prefix in url as well
redirect_url = url_for('/') + 'workflow'
return trans.response.send_redirect(redirect_url)
@web.expose
@web.json
def list_published(self, trans, **kwargs):
return self.published_list_grid(trans, **kwargs)
@web.expose
def display_by_username_and_slug(self, trans, username, slug, format='html'):
"""
Display workflow based on a username and slug. Format can be html, json, or json-download.
"""
# Get workflow by username and slug. Security is handled by the display methods below.
session = trans.sa_session
user = session.query(model.User).filter_by(username=username).first()
if not user:
raise web.httpexceptions.HTTPNotFound()
stored_workflow = trans.sa_session.query(model.StoredWorkflow).filter_by(user=user, slug=slug, deleted=False).first()
if not stored_workflow:
raise web.httpexceptions.HTTPNotFound()
encoded_id = trans.security.encode_id(stored_workflow.id)
# Display workflow in requested format.
if format == 'html':
return self._display(trans, stored_workflow)
elif format == 'json':
return self.for_direct_import(trans, encoded_id)
elif format == 'json-download':
return self.export_to_file(trans, encoded_id)
@web.expose
def display_by_id(self, trans, id):
""" Display workflow based on id. """
# Get workflow.
stored_workflow = self.get_stored_workflow(trans, id)
return self._display(trans, stored_workflow)
def _display(self, trans, stored_workflow):
""" Diplay workflow as HTML page. """
if stored_workflow is None:
raise web.httpexceptions.HTTPNotFound()
# Security check raises error if user cannot access workflow.
self.security_check(trans, stored_workflow, False, True)
# Get data for workflow's steps.
self.get_stored_workflow_steps(trans, stored_workflow)
# Get annotations.
stored_workflow.annotation = self.get_item_annotation_str(trans.sa_session, stored_workflow.user, stored_workflow)
for step in stored_workflow.latest_workflow.steps:
step.annotation = self.get_item_annotation_str(trans.sa_session, stored_workflow.user, step)
user_is_owner = True if trans.user == stored_workflow.user else False
# Get rating data.
user_item_rating = 0
if trans.get_user():
user_item_rating = self.get_user_item_rating(trans.sa_session, trans.get_user(), stored_workflow)
if user_item_rating:
user_item_rating = user_item_rating.rating
else:
user_item_rating = 0
ave_item_rating, num_ratings = self.get_ave_item_rating_data(trans.sa_session, stored_workflow)
return trans.fill_template_mako("workflow/display.mako",
item=stored_workflow,
item_data=stored_workflow.latest_workflow.steps,
user_item_rating=user_item_rating,
ave_item_rating=ave_item_rating,
num_ratings=num_ratings,
user_is_owner=user_is_owner)
@web.expose
def get_item_content_async(self, trans, id):
""" Returns item content in HTML format. """
stored = self.get_stored_workflow(trans, id, False, True)
if stored is None:
raise web.httpexceptions.HTTPNotFound()
# Get data for workflow's steps.
self.get_stored_workflow_steps(trans, stored)
# Get annotations.
stored.annotation = self.get_item_annotation_str(trans.sa_session, stored.user, stored)
for step in stored.latest_workflow.steps:
step.annotation = self.get_item_annotation_str(trans.sa_session, stored.user, step)
return trans.stream_template_mako("/workflow/item_content.mako", item=stored, item_data=stored.latest_workflow.steps)
@web.expose
@web.require_login("use Galaxy workflows")
def share(self, trans, id, email="", use_panels=False):
msg = mtype = None
# Load workflow from database
stored = self.get_stored_workflow(trans, id)
if email:
other = trans.sa_session.query(model.User) \
.filter(and_(model.User.table.c.email == email,
model.User.table.c.deleted == expression.false())) \
.first()
if not other:
mtype = "error"
msg = ("User '%s' does not exist" % escape(email))
elif other == trans.get_user():
mtype = "error"
msg = ("You cannot share a workflow with yourself")
elif trans.sa_session.query(model.StoredWorkflowUserShareAssociation) \
.filter_by(user=other, stored_workflow=stored).count() > 0:
mtype = "error"
msg = ("Workflow already shared with '%s'" % escape(email))
else:
share = model.StoredWorkflowUserShareAssociation()
share.stored_workflow = stored
share.user = other
session = trans.sa_session
session.add(share)
session.flush()
trans.set_message("Workflow '{}' shared with user '{}'".format(escape(stored.name), escape(other.email)))
return trans.response.send_redirect(url_for(controller='workflow', action='sharing', id=id))
return trans.fill_template("/ind_share_base.mako",
message=msg,
messagetype=mtype,
item=stored,
email=email,
use_panels=use_panels)
@web.expose
@web.require_login("Share or export Galaxy workflows")
def sharing(self, trans, id, **kwargs):
""" Handle workflow sharing. """
session = trans.sa_session
if 'unshare_me' in kwargs:
# Remove self from shared associations with workflow.
stored = self.get_stored_workflow(trans, id, False, True)
association = session.query(model.StoredWorkflowUserShareAssociation) \
.filter_by(user=trans.user, stored_workflow=stored).one()
session.delete(association)
session.flush()
return self.list(trans)
else:
# Get session and workflow.
stored = self.get_stored_workflow(trans, id)
session.add(stored)
# Do operation on workflow.
if 'make_accessible_via_link' in kwargs:
self._make_item_accessible(trans.sa_session, stored)
elif 'make_accessible_and_publish' in kwargs:
self._make_item_accessible(trans.sa_session, stored)
stored.published = True
elif 'publish' in kwargs:
stored.published = True
elif 'disable_link_access' in kwargs:
stored.importable = False
elif 'unpublish' in kwargs:
stored.published = False
elif 'disable_link_access_and_unpublish' in kwargs:
stored.importable = stored.published = False
elif 'unshare_user' in kwargs:
user = session.query(model.User).get(trans.security.decode_id(kwargs['unshare_user']))
if not user:
error("User not found for provided id")
association = session.query(model.StoredWorkflowUserShareAssociation) \
.filter_by(user=user, stored_workflow=stored).one()
session.delete(association)
# Legacy issue: workflows made accessible before recent updates may not have a slug. Create slug for any workflows that need them.
if stored.importable and not stored.slug:
self._make_item_accessible(trans.sa_session, stored)
session.flush()
return trans.fill_template("/workflow/sharing.mako", use_panels=True, item=stored)
@web.expose
@web.require_login("share Galaxy items")
def set_public_username(self, trans, id, username, **kwargs):
""" Set user's public username and delegate to sharing() """
user = trans.get_user()
# message from validate_publicname does not contain input, no need
# to escape.
message = validate_publicname(trans, username, user)
if message:
return trans.fill_template("/workflow/sharing.mako", item=self.get_item(trans, id), message=message, status="error")
user.username = username
trans.sa_session.flush()
return self.sharing(trans, id, **kwargs)
@web.expose
@web.require_login("to import a workflow", use_panels=True)
def imp(self, trans, id, **kwargs):
"""Imports a workflow shared by other users."""
# Set referer message.
referer = trans.request.referer
if referer:
referer_message = "<a href='%s'>return to the previous page</a>" % escape(referer)
else:
referer_message = "<a href='%s'>go to Galaxy's start page</a>" % url_for('/')
# Do import.
stored = self.get_stored_workflow(trans, id, check_ownership=False)
if stored.importable is False:
return trans.show_error_message("The owner of this workflow has disabled imports via this link.<br>You can %s" % referer_message, use_panels=True)
elif stored.deleted:
return trans.show_error_message("You can't import this workflow because it has been deleted.<br>You can %s" % referer_message, use_panels=True)
self._import_shared_workflow(trans, stored)
# Redirect to load galaxy frames.
return trans.show_ok_message(
message="""Workflow "%s" has been imported. <br>You can <a href="%s">start using this workflow</a> or %s."""
% (stored.name, web.url_for('/workflows/list'), referer_message))
@web.expose
@web.require_login("use Galaxy workflows")
def rename_async(self, trans, id, new_name=None, **kwargs):
stored = self.get_stored_workflow(trans, id)
if new_name:
san_new_name = sanitize_html(new_name)
stored.name = san_new_name
stored.latest_workflow.name = san_new_name
trans.sa_session.flush()
return stored.name
@web.expose
@web.require_login("use Galaxy workflows")
def annotate_async(self, trans, id, new_annotation=None, **kwargs):
stored = self.get_stored_workflow(trans, id)
if new_annotation:
# Sanitize annotation before adding it.
new_annotation = sanitize_html(new_annotation)
self.add_item_annotation(trans.sa_session, trans.get_user(), stored, new_annotation)
trans.sa_session.flush()
return new_annotation
@web.expose
@web.require_login("rate items")
@web.json
def rate_async(self, trans, id, rating):
""" Rate a workflow asynchronously and return updated community data. """
stored = self.get_stored_workflow(trans, id, check_ownership=False, check_accessible=True)
if not stored:
return trans.show_error_message("The specified workflow does not exist.")
# Rate workflow.
self.rate_item(trans.sa_session, trans.get_user(), stored, rating)
return self.get_ave_item_rating_data(trans.sa_session, stored)
@web.expose
@web.require_login("use Galaxy workflows")
def set_accessible_async(self, trans, id=None, accessible=False):
""" Set workflow's importable attribute and slug. """
stored = self.get_stored_workflow(trans, id)
# Only set if importable value would change; this prevents a change in the update_time unless attribute really changed.
importable = accessible in ['True', 'true', 't', 'T']
if stored and stored.importable != importable:
if importable:
self._make_item_accessible(trans.sa_session, stored)
else:
stored.importable = importable
trans.sa_session.flush()
return
@web.expose
def get_embed_html_async(self, trans, id):
""" Returns HTML for embedding a workflow in a page. """
# TODO: user should be able to embed any item he has access to. see display_by_username_and_slug for security code.
stored = self.get_stored_workflow(trans, id)
if stored:
return "Embedded Workflow '%s'" % stored.name
@web.expose
@web.json
@web.require_login("use Galaxy workflows")
def get_name_and_link_async(self, trans, id=None):
""" Returns workflow's name and link. """
stored = self.get_stored_workflow(trans, id)
return_dict = {"name": stored.name,
"link": url_for(controller='workflow',
action="display_by_username_and_slug",
username=stored.user.username,
slug=stored.slug)}
return return_dict
@web.expose
@web.require_login("use Galaxy workflows")
def gen_image(self, trans, id):
stored = self.get_stored_workflow(trans, id, check_ownership=True)
try:
svg = self._workflow_to_svg_canvas(trans, stored)
except Exception:
status = 'error'
message = 'Galaxy is unable to create the SVG image. Please check your workflow, there might be missing tools.'
return trans.fill_template("/workflow/sharing.mako", use_panels=True, item=stored, status=status, message=message)
trans.response.set_content_type("image/svg+xml")
s = STANDALONE_SVG_TEMPLATE % svg.tostring()
return s.encode('utf-8')
@web.expose
@web.require_login("use Galaxy workflows")
def copy(self, trans, id, save_as_name=None):
# Get workflow to copy.
stored = self.get_stored_workflow(trans, id, check_ownership=False)
user = trans.get_user()
if stored.user == user:
owner = True
else:
if trans.sa_session.query(model.StoredWorkflowUserShareAssociation) \
.filter_by(user=user, stored_workflow=stored).count() == 0:
error("Workflow is not owned by or shared with current user")
owner = False
# Copy.
new_stored = model.StoredWorkflow()
if (save_as_name):
new_stored.name = '%s' % save_as_name
else:
new_stored.name = "Copy of %s" % stored.name
new_stored.latest_workflow = stored.latest_workflow
# Copy annotation.
annotation_obj = self.get_item_annotation_obj(trans.sa_session, stored.user, stored)
if annotation_obj:
self.add_item_annotation(trans.sa_session, trans.get_user(), new_stored, annotation_obj.annotation)
new_stored.copy_tags_from(trans.user, stored)
if not owner:
new_stored.name += " shared by %s" % stored.user.email
new_stored.user = user
# Persist
session = trans.sa_session
session.add(new_stored)
session.flush()
# Display the management page
message = 'Created new workflow with name: %s' % escape(new_stored.name)
trans.set_message(message)
return_url = url_for('/') + 'workflow?status=done&message=%s' % escape(message)
trans.response.send_redirect(return_url)
@web.legacy_expose_api
def create(self, trans, payload=None, **kwd):
if trans.request.method == 'GET':
return {
'title' : 'Create Workflow',
'inputs' : [{
'name' : 'workflow_name',
'label' : 'Name',
'value' : 'Unnamed workflow'
}, {
'name' : 'workflow_annotation',
'label' : 'Annotation',
'help' : 'A description of the workflow; annotation is shown alongside shared or published workflows.'
}]}
else:
user = trans.get_user()
workflow_name = payload.get('workflow_name')
workflow_annotation = payload.get('workflow_annotation')
if not workflow_name:
return self.message_exception(trans, 'Please provide a workflow name.')
# Create the new stored workflow
stored_workflow = model.StoredWorkflow()
stored_workflow.name = workflow_name
stored_workflow.user = user
self.create_item_slug(trans.sa_session, stored_workflow)
# And the first (empty) workflow revision
workflow = model.Workflow()
workflow.name = workflow_name
workflow.stored_workflow = stored_workflow
stored_workflow.latest_workflow = workflow
# Add annotation.
workflow_annotation = sanitize_html(workflow_annotation)
self.add_item_annotation(trans.sa_session, trans.get_user(), stored_workflow, workflow_annotation)
# Persist
session = trans.sa_session
session.add(stored_workflow)
session.flush()
return {'id': trans.security.encode_id(stored_workflow.id), 'message': 'Workflow %s has been created.' % workflow_name}
@web.json
def save_workflow_as(self, trans, workflow_name, workflow_data, workflow_annotation="", from_tool_form=False):
"""
Creates a new workflow based on Save As command. It is a new workflow, but
is created with workflow_data already present.
"""
user = trans.get_user()
if workflow_name is not None:
workflow_contents_manager = self.app.workflow_contents_manager
stored_workflow = model.StoredWorkflow()
stored_workflow.name = workflow_name
stored_workflow.user = user
self.create_item_slug(trans.sa_session, stored_workflow)
workflow = model.Workflow()
workflow.name = workflow_name
workflow.stored_workflow = stored_workflow
stored_workflow.latest_workflow = workflow
# Add annotation.
workflow_annotation = sanitize_html(workflow_annotation)
self.add_item_annotation(trans.sa_session, trans.get_user(), stored_workflow, workflow_annotation)
# Persist
session = trans.sa_session
session.add(stored_workflow)
session.flush()
workflow_update_options = WorkflowUpdateOptions(
update_stored_workflow_attributes=False, # taken care of above
from_tool_form=from_tool_form,
)
try:
workflow, errors = workflow_contents_manager.update_workflow_from_raw_description(
trans,
stored_workflow,
workflow_data,
workflow_update_options,
)
except MissingToolsException as e:
return dict(
name=e.workflow.name,
message=("This workflow includes missing or invalid tools. "
"It cannot be saved until the following steps are removed or the missing tools are enabled."),
errors=e.errors,
)
return (trans.security.encode_id(stored_workflow.id))
else:
# This is an error state, 'save as' must have a workflow_name
log.exception("Error in Save As workflow: no name.")
@web.expose
def delete(self, trans, id=None):
"""
Mark a workflow as deleted
"""
# Load workflow from database
stored = self.get_stored_workflow(trans, id)
# Mark as deleted and save
stored.deleted = True
trans.user.stored_workflow_menu_entries = [entry for entry in trans.user.stored_workflow_menu_entries if entry.stored_workflow != stored]
trans.sa_session.add(stored)
trans.sa_session.flush()
# Display the management page
message = "Workflow deleted: %s" % escape(stored.name)
trans.set_message(message)
return trans.response.send_redirect(url_for('/') + 'workflow?status=done&message=%s' % escape(message))
@web.expose
@web.require_login("edit workflows")
def editor(self, trans, id=None, workflow_id=None, version=None):
"""
Render the main workflow editor interface. The canvas is embedded as
an iframe (necessary for scrolling to work properly), which is
rendered by `editor_canvas`.
"""
if not id:
if workflow_id:
workflow = trans.sa_session.query(model.Workflow).get(trans.security.decode_id(workflow_id))
stored_workflow = workflow.stored_workflow
self.security_check(trans, stored_workflow, True, False)
stored_workflow_id = trans.security.encode_id(stored_workflow.id)
return trans.response.send_redirect(f'{url_for("/")}workflow/editor?id={stored_workflow_id}')
error("Invalid workflow id")
stored = self.get_stored_workflow(trans, id)
# The following query loads all user-owned workflows,
# So that they can be copied or inserted in the workflow editor.
workflows = trans.sa_session.query(model.StoredWorkflow) \
.filter_by(user=trans.user, deleted=False, hidden=False) \
.order_by(desc(model.StoredWorkflow.table.c.update_time)) \
.options(joinedload('latest_workflow').joinedload('steps')) \
.all()
if version is None:
version = len(stored.workflows) - 1
else:
version = int(version)
# create workflow module models
module_sections = []
for module_section in load_module_sections(trans).values():
module_sections.append({
"title": module_section.get("title"),
"name": module_section.get("name"),
"elems": [{
"name": elem.get("name"),
"title": elem.get("title"),
"description": elem.get("description")
} for elem in module_section.get("modules")]
})
# create data manager tool models
data_managers = []
if trans.user_is_admin and trans.app.data_managers.data_managers:
for data_manager_val in trans.app.data_managers.data_managers.values():
tool = data_manager_val.tool
if not tool.hidden:
data_managers.append({
"id": tool.id,
"name": tool.name,
"hidden": tool.hidden,
"description": tool.description,
"is_workflow_compatible": tool.is_workflow_compatible
})
# create workflow models
workflows = [{
'id' : trans.security.encode_id(workflow.id),
'latest_id' : trans.security.encode_id(workflow.latest_workflow.id),
'step_count' : len(workflow.latest_workflow.steps),
'name' : workflow.name
} for workflow in workflows if workflow.id != stored.id]
# identify item tags
item_tags = [tag for tag in stored.tags if tag.user == trans.user]
item_tag_names = []
for ta in item_tags:
item_tag_names.append(escape(ta.tag.name))
# build workflow editor model
editor_config = {
'id' : trans.security.encode_id(stored.id),
'name' : stored.name,
'tags' : item_tag_names,
'version' : version,
'annotation' : self.get_item_annotation_str(trans.sa_session, trans.user, stored),
'toolbox' : trans.app.toolbox.to_dict(trans),
'moduleSections' : module_sections,
'dataManagers' : data_managers,
'workflows' : workflows
}
# parse to mako
return trans.fill_template("workflow/editor.mako", editor_config=editor_config)
@web.json
def load_workflow(self, trans, id, version=None):
"""
Get the latest Workflow for the StoredWorkflow identified by `id` and
encode it as a json string that can be read by the workflow editor
web interface.
"""
trans.workflow_building_mode = workflow_building_modes.ENABLED
stored = self.get_stored_workflow(trans, id, check_ownership=True, check_accessible=False)
workflow_contents_manager = self.app.workflow_contents_manager
return workflow_contents_manager.workflow_to_dict(trans, stored, style="editor", version=version)
@web.expose
@web.require_login("use workflows")
def export_to_myexp(self, trans, id, myexp_username, myexp_password):
"""
Exports a workflow to myExperiment website.
"""
trans.workflow_building_mode = workflow_building_modes.ENABLED
stored = self.get_stored_workflow(trans, id, check_ownership=False, check_accessible=True)
# Convert workflow to dict.
workflow_dict = self._workflow_to_dict(trans, stored)
#
# Create and submit workflow myExperiment request.
#
# Create workflow content JSON.
workflow_content = json.dumps(workflow_dict, indent=4, sort_keys=True)
# Create myExperiment request.
request_raw = trans.fill_template(
"workflow/myexp_export.mako",
workflow_name=workflow_dict['name'],
workflow_description=workflow_dict['annotation'],
workflow_content=workflow_content,
workflow_svg=self._workflow_to_svg_canvas(trans, stored).tostring()
)
# strip() b/c myExperiment XML parser doesn't allow white space before XML; utf-8 handles unicode characters.
request = unicodify(request_raw.strip(), 'utf-8')
# Do request and get result.
auth_header = base64.b64encode(f'{myexp_username}:{myexp_password}')
headers = {"Content-type": "text/xml", "Accept": "text/xml", "Authorization": "Basic %s" % auth_header}
myexp_url = trans.app.config.myexperiment_target_url
conn = HTTPConnection(myexp_url)
# NOTE: blocks web thread.
conn.request("POST", "/workflow.xml", request, headers)
response = conn.getresponse()
response_data = response.read()
conn.close()
# Do simple parse of response to see if export successful and provide user feedback.
parser = SingleTagContentsParser('id')
parser.feed(response_data)
myexp_workflow_id = parser.tag_content
workflow_list_str = " <br>Return to <a href='%s'>workflow list." % url_for(controller='workflows', action='list')
if myexp_workflow_id:
return trans.show_message(
"""Workflow '{}' successfully exported to myExperiment. <br/>
<a href="http://{}/workflows/{}">Click here to view the workflow on myExperiment</a> {}
""".format(stored.name, myexp_url, myexp_workflow_id, workflow_list_str),
use_panels=True)
else:
return trans.show_error_message(
"Workflow '%s' could not be exported to myExperiment. Error: %s %s" %
(stored.name, response_data, workflow_list_str), use_panels=True)
@web.json_pretty
def for_direct_import(self, trans, id):
"""
Get the latest Workflow for the StoredWorkflow identified by `id` and
encode it as a json string that can be imported back into Galaxy
This has slightly different information than the above. In particular,
it does not attempt to decode forms and build UIs, it just stores
the raw state.
"""
stored = self.get_stored_workflow(trans, id, check_ownership=False, check_accessible=True)
return self._workflow_to_dict(trans, stored)
@web.json_pretty
def export_to_file(self, trans, id):
"""
Get the latest Workflow for the StoredWorkflow identified by `id` and
encode it as a json string that can be imported back into Galaxy
This has slightly different information than the above. In particular,
it does not attempt to decode forms and build UIs, it just stores
the raw state.
"""
# Get workflow.
stored = self.get_stored_workflow(trans, id, check_ownership=False, check_accessible=True)
# Stream workflow to file.
stored_dict = self._workflow_to_dict(trans, stored)
if not stored_dict:
# This workflow has a tool that's missing from the distribution
trans.response.status = 400
return "Workflow cannot be exported due to missing tools."
sname = stored.name
sname = ''.join(c in FILENAME_VALID_CHARS and c or '_' for c in sname)[0:150]
trans.response.headers["Content-Disposition"] = 'attachment; filename="Galaxy-Workflow-%s.ga"' % (sname)
trans.response.set_content_type('application/galaxy-archive')
return stored_dict
@web.expose
def build_from_current_history(self, trans, job_ids=None, dataset_ids=None, dataset_collection_ids=None, workflow_name=None, dataset_names=None, dataset_collection_names=None):
user = trans.get_user()
history = trans.get_history()
if not user:
return trans.show_error_message("Must be logged in to create workflows")
if (job_ids is None and dataset_ids is None) or workflow_name is None:
jobs, warnings = summarize(trans)
# Render
return trans.fill_template(
"workflow/build_from_current_history.mako",
jobs=jobs,
warnings=warnings,
history=history
)
else:
# If there is just one dataset name selected or one dataset collection, these
# come through as string types instead of lists. xref #3247.
dataset_names = util.listify(dataset_names)
dataset_collection_names = util.listify(dataset_collection_names)
stored_workflow = extract_workflow(
trans,
user=user,
job_ids=job_ids,
dataset_ids=dataset_ids,
dataset_collection_ids=dataset_collection_ids,
workflow_name=workflow_name,
dataset_names=dataset_names,
dataset_collection_names=dataset_collection_names
)
# Index page with message
workflow_id = trans.security.encode_id(stored_workflow.id)
return trans.show_message('Workflow "%s" created from current history. '
'You can <a href="%s" target="_parent">edit</a> or <a href="%s" target="_parent">run</a> the workflow.'
% (escape(workflow_name), url_for(controller='workflow', action='editor', id=workflow_id),
url_for(controller='workflows', action='run', id=workflow_id)))
def get_item(self, trans, id):
return self.get_stored_workflow(trans, id)
def _workflow_to_svg_canvas(self, trans, stored):
workflow = stored.latest_workflow
workflow_canvas = WorkflowCanvas()
for step in workflow.steps:
# Load from database representation
module = module_factory.from_workflow_step(trans, step)
module_name = module.get_name()
module_data_inputs = module.get_data_inputs()
module_data_outputs = module.get_data_outputs()
workflow_canvas.populate_data_for_step(
step,
module_name,
module_data_inputs,
module_data_outputs,
)
workflow_canvas.add_steps()
return workflow_canvas.finish()
def _build_workflow_on_str(instance_ds_names):
# Returns suffix for new histories based on multi input iteration
num_multi_inputs = len(instance_ds_names)
if num_multi_inputs == 0:
return ""
elif num_multi_inputs == 1:
return " on %s" % instance_ds_names[0]
else:
return " on {} and {}".format(", ".join(instance_ds_names[0:-1]), instance_ds_names[-1])
def _expand_multiple_inputs(kwargs):
(single_inputs, matched_multi_inputs, multiplied_multi_inputs) = _split_inputs(kwargs)
# Build up every combination of inputs to be run together.
input_combos = _extend_with_matched_combos(single_inputs, matched_multi_inputs)
input_combos = _extend_with_multiplied_combos(input_combos, multiplied_multi_inputs)
# Input name that are multiply specified
multi_input_keys = list(matched_multi_inputs.keys()) + list(multiplied_multi_inputs.keys())
for input_combo in input_combos:
for key, value in input_combo.items():
kwargs[key] = value
yield (kwargs, multi_input_keys)
def _extend_with_matched_combos(single_inputs, multi_inputs):
if len(multi_inputs) == 0:
return [single_inputs]
matched_multi_inputs = []
first_multi_input_key = next(iter(multi_inputs.keys()))
first_multi_value = multi_inputs.get(first_multi_input_key)
for value in first_multi_value:
new_inputs = _copy_and_extend_inputs(single_inputs, first_multi_input_key, value)
matched_multi_inputs.append(new_inputs)
for multi_input_key, multi_input_values in multi_inputs.items():
if multi_input_key == first_multi_input_key:
continue
if len(multi_input_values) != len(first_multi_value):
raise Exception("Failed to match up multi-select inputs, must select equal number of data files in each multiselect")
for index, value in enumerate(multi_input_values):
matched_multi_inputs[index][multi_input_key] = value
return matched_multi_inputs
def _extend_with_multiplied_combos(input_combos, multi_inputs):
combos = input_combos
for multi_input_key, multi_input_value in multi_inputs.items():
iter_combos = []
for combo in combos:
for input_value in multi_input_value:
iter_combos.append(_copy_and_extend_inputs(combo, multi_input_key, input_value))
combos = iter_combos
return combos
def _copy_and_extend_inputs(inputs, key, value):
new_inputs = dict(inputs)
new_inputs[key] = value
return new_inputs
def _split_inputs(kwargs):
"""
"""
input_keys = [a for a in kwargs if a.endswith('|input')]
single_inputs = {}
matched_multi_inputs = {}
multiplied_multi_inputs = {}
for input_key in input_keys:
input_val = kwargs[input_key]
if isinstance(input_val, list):
input_base = input_key[:-len("|input")]
mode_key = "%s|multi_mode" % input_base
mode = kwargs.get(mode_key, "matched")
if mode == "matched":
matched_multi_inputs[input_key] = input_val
else:
multiplied_multi_inputs[input_key] = input_val
else:
single_inputs[input_key] = input_val
return (single_inputs, matched_multi_inputs, multiplied_multi_inputs)
|
import requests
import datetime
from lxml import html
headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0"}
class EFG():
def __init__(self):
self.data = requests.get(
"https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions"
).json()
def get_games(self) -> list:
""" Return text with free games available now on epicgamesstore and next
update """
# Так як у python немає мутабельних stringʼів, а метод зберає результат
# із шматочків, то вирішив юзати список рядків. Тим більше що "\n".join()
# працює швидко та ефективно.
result = [f"Update time is: {self.next_update().ctime()}", "\n"]
for item in self.data["data"]["Catalog"]["searchStore"]["elements"]:
# if originalPrice == discount game is available for free
tmp = item['price']['totalPrice']
if tmp['originalPrice'] == tmp['discount']:
if tmp['originalPrice'] != 0:
result.append(f"**{item["title"]}**")
url = self._get_url(item)
print(f"[get_games] {url}")
result.append(url)
result.append(f"{self._get_description(url)}\n")
return "\n".join(result)
def next_update(self) -> datetime:
""" Return datetime object which represent next update on epicgamesstore """
for item in self.data["data"]["Catalog"]["searchStore"]["elements"]:
# if originalPrice == discount game is available for free
tmp = item['price']['totalPrice']
if tmp['originalPrice'] == tmp['discount']:
if tmp['originalPrice'] != 0:
nu = item["promotions"]["promotionalOffers"][0]["promotionalOffers"][0]["endDate"]
nu = nu.split('.')[:-1][0]
return datetime.datetime.fromisoformat(nu)
def _get_description(self, url):
try:
resp = requests.get(url, headers=headers)
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
print("ERROR")
print(e)
data = html.fromstring(resp.text).cssselect('div.css-pfxkyb')
if data:
return data[0].text
return "Description not found. Please check manualy."
def _get_url(self, item):
base = "https://www.epicgames.com/store/en-US/p/"
url_slug = base + item['urlSlug']
product_slug = base + item['productSlug']
print(url_slug, product_slug)
if url_slug == product_slug:
return url_slug
for i in (item['urlSlug'], item['productSlug']):
result = self._probe(base + i, i)
if result:
return result
def _probe(self, url, name):
resp = requests.get(url, headers=headers)
data = html.fromstring(resp.text)
for probe_url in data.findall('head')[0].findall("link"):
print(probe_url.attrib.get('href'))
page = probe_url.attrib.get('href')
if "not-found" in page:
return ''
if name in page:
return page
if __name__ == "__main__":
efg = EFG()
print(efg.get_games())
| import requests
import datetime
from lxml import html
headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0"}
class EFG():
def __init__(self):
self.data = requests.get(
"https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions"
).json()
def get_games(self) -> list:
""" Return text with free games available now on epicgamesstore and next
update """
# Так як у python немає мутабельних stringʼів, а метод зберає результат
# із шматочків, то вирішив юзати список рядків. Тим більше що "\n".join()
# працює швидко та ефективно.
result = [f"Update time is: {self.next_update().ctime()}", "\n"]
for item in self.data["data"]["Catalog"]["searchStore"]["elements"]:
# if originalPrice == discount game is available for free
tmp = item['price']['totalPrice']
if tmp['originalPrice'] == tmp['discount']:
if tmp['originalPrice'] != 0:
result.append(f"**{item['title']}**")
url = self._get_url(item)
print(f"[get_games] {url}")
result.append(url)
result.append(f"{self._get_description(url)}\n")
return "\n".join(result)
def next_update(self) -> datetime:
""" Return datetime object which represent next update on epicgamesstore """
for item in self.data["data"]["Catalog"]["searchStore"]["elements"]:
# if originalPrice == discount game is available for free
tmp = item['price']['totalPrice']
if tmp['originalPrice'] == tmp['discount']:
if tmp['originalPrice'] != 0:
nu = item["promotions"]["promotionalOffers"][0]["promotionalOffers"][0]["endDate"]
nu = nu.split('.')[:-1][0]
return datetime.datetime.fromisoformat(nu)
def _get_description(self, url):
try:
resp = requests.get(url, headers=headers)
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
print("ERROR")
print(e)
data = html.fromstring(resp.text).cssselect('div.css-pfxkyb')
if data:
return data[0].text
return "Description not found. Please check manualy."
def _get_url(self, item):
base = "https://www.epicgames.com/store/en-US/p/"
url_slug = base + item['urlSlug']
product_slug = base + item['productSlug']
print(url_slug, product_slug)
if url_slug == product_slug:
return url_slug
for i in (item['urlSlug'], item['productSlug']):
result = self._probe(base + i, i)
if result:
return result
def _probe(self, url, name):
resp = requests.get(url, headers=headers)
data = html.fromstring(resp.text)
for probe_url in data.findall('head')[0].findall("link"):
print(probe_url.attrib.get('href'))
page = probe_url.attrib.get('href')
if "not-found" in page:
return ''
if name in page:
return page
if __name__ == "__main__":
efg = EFG()
print(efg.get_games())
|
import asyncio
import pathlib
import sys
import time
from datetime import datetime
from decimal import Decimal
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Union
import aiohttp
from chia.cmds.cmds_util import transaction_status_msg, transaction_submitted_msg
from chia.cmds.show import print_connections
from chia.cmds.units import units
from chia.rpc.wallet_rpc_client import WalletRpcClient
from chia.server.start_wallet import SERVICE_NAME
from chia.types.blockchain_format.sized_bytes import bytes32
from chia.util.bech32m import encode_puzzle_hash
from chia.util.config import load_config
from chia.util.default_root import DEFAULT_ROOT_PATH
from chia.util.ints import uint16, uint32, uint64
from chia.wallet.trade_record import TradeRecord
from chia.wallet.trading.offer import Offer
from chia.wallet.trading.trade_status import TradeStatus
from chia.wallet.transaction_record import TransactionRecord
from chia.wallet.util.transaction_type import TransactionType
from chia.wallet.util.wallet_types import WalletType
CATNameResolver = Callable[[bytes32], Awaitable[Optional[Tuple[Optional[uint32], str]]]]
transaction_type_descriptions = {
TransactionType.INCOMING_TX: "received",
TransactionType.OUTGOING_TX: "sent",
TransactionType.COINBASE_REWARD: "rewarded",
TransactionType.FEE_REWARD: "rewarded",
TransactionType.INCOMING_TRADE: "received in trade",
TransactionType.OUTGOING_TRADE: "sent in trade",
}
def transaction_description_from_type(tx: TransactionRecord) -> str:
return transaction_type_descriptions.get(TransactionType(tx.type), "(unknown reason)")
def print_transaction(tx: TransactionRecord, verbose: bool, name, address_prefix: str, mojo_per_unit: int) -> None:
if verbose:
print(tx)
else:
chia_amount = Decimal(int(tx.amount)) / mojo_per_unit
to_address = encode_puzzle_hash(tx.to_puzzle_hash, address_prefix)
print(f"Transaction {tx.name}")
print(f"Status: {"Confirmed" if tx.confirmed else ("In mempool" if tx.is_in_mempool() else "Pending")}")
description = transaction_description_from_type(tx)
print(f"Amount {description}: {chia_amount} {name}")
print(f"To address: {to_address}")
print("Created at:", datetime.fromtimestamp(tx.created_at_time).strftime("%Y-%m-%d %H:%M:%S"))
print("")
def get_mojo_per_unit(wallet_type: WalletType) -> int:
mojo_per_unit: int
if wallet_type == WalletType.STANDARD_WALLET or wallet_type == WalletType.POOLING_WALLET:
mojo_per_unit = units["chia"]
elif wallet_type == WalletType.CAT:
mojo_per_unit = units["cat"]
else:
raise LookupError("Only standard wallet, CAT wallets, and Plot NFTs are supported")
return mojo_per_unit
async def get_wallet_type(wallet_id: int, wallet_client: WalletRpcClient) -> WalletType:
summaries_response = await wallet_client.get_wallets()
for summary in summaries_response:
summary_id: int = summary["id"]
summary_type: int = summary["type"]
if wallet_id == summary_id:
return WalletType(summary_type)
raise LookupError(f"Wallet ID not found: {wallet_id}")
async def get_name_for_wallet_id(
config: Dict[str, Any],
wallet_type: WalletType,
wallet_id: int,
wallet_client: WalletRpcClient,
):
if wallet_type == WalletType.STANDARD_WALLET or wallet_type == WalletType.POOLING_WALLET:
name = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"].upper()
elif wallet_type == WalletType.CAT:
name = await wallet_client.get_cat_name(wallet_id=str(wallet_id))
else:
raise LookupError("Only standard wallet, CAT wallets, and Plot NFTs are supported")
return name
async def get_transaction(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
transaction_id = bytes32.from_hexstr(args["tx_id"])
config = load_config(DEFAULT_ROOT_PATH, "config.yaml", SERVICE_NAME)
address_prefix = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"]
tx: TransactionRecord = await wallet_client.get_transaction("this is unused", transaction_id=transaction_id)
try:
wallet_type = await get_wallet_type(wallet_id=tx.wallet_id, wallet_client=wallet_client)
mojo_per_unit = get_mojo_per_unit(wallet_type=wallet_type)
name = await get_name_for_wallet_id(
config=config,
wallet_type=wallet_type,
wallet_id=tx.wallet_id,
wallet_client=wallet_client,
)
except LookupError as e:
print(e.args[0])
return
print_transaction(
tx,
verbose=(args["verbose"] > 0),
name=name,
address_prefix=address_prefix,
mojo_per_unit=mojo_per_unit,
)
async def get_transactions(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["id"]
paginate = args["paginate"]
if paginate is None:
paginate = sys.stdout.isatty()
offset = args["offset"]
limit = args["limit"]
sort_key = args["sort_key"]
reverse = args["reverse"]
txs: List[TransactionRecord] = await wallet_client.get_transactions(
wallet_id, start=offset, end=(offset + limit), sort_key=sort_key, reverse=reverse
)
config = load_config(DEFAULT_ROOT_PATH, "config.yaml", SERVICE_NAME)
address_prefix = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"]
if len(txs) == 0:
print("There are no transactions to this address")
try:
wallet_type = await get_wallet_type(wallet_id=wallet_id, wallet_client=wallet_client)
mojo_per_unit = get_mojo_per_unit(wallet_type=wallet_type)
name = await get_name_for_wallet_id(
config=config,
wallet_type=wallet_type,
wallet_id=wallet_id,
wallet_client=wallet_client,
)
except LookupError as e:
print(e.args[0])
return
num_per_screen = 5 if paginate else len(txs)
for i in range(0, len(txs), num_per_screen):
for j in range(0, num_per_screen):
if i + j >= len(txs):
break
print_transaction(
txs[i + j],
verbose=(args["verbose"] > 0),
name=name,
address_prefix=address_prefix,
mojo_per_unit=mojo_per_unit,
)
if i + num_per_screen >= len(txs):
return None
print("Press q to quit, or c to continue")
while True:
entered_key = sys.stdin.read(1)
if entered_key == "q":
return None
elif entered_key == "c":
break
def check_unusual_transaction(amount: Decimal, fee: Decimal):
return fee >= amount
async def send(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id: int = args["id"]
amount = Decimal(args["amount"])
fee = Decimal(args["fee"])
address = args["address"]
override = args["override"]
memo = args["memo"]
if memo is None:
memos = None
else:
memos = [memo]
if not override and check_unusual_transaction(amount, fee):
print(
f"A transaction of amount {amount} and fee {fee} is unusual.\n"
f"Pass in --override if you are sure you mean to do this."
)
return
try:
typ = await get_wallet_type(wallet_id=wallet_id, wallet_client=wallet_client)
except LookupError:
print(f"Wallet id: {wallet_id} not found.")
return
final_fee = uint64(int(fee * units["chia"]))
final_amount: uint64
if typ == WalletType.STANDARD_WALLET:
final_amount = uint64(int(amount * units["chia"]))
print("Submitting transaction...")
res = await wallet_client.send_transaction(str(wallet_id), final_amount, address, final_fee, memos)
elif typ == WalletType.CAT:
final_amount = uint64(int(amount * units["cat"]))
print("Submitting transaction...")
res = await wallet_client.cat_spend(str(wallet_id), final_amount, address, final_fee, memos)
else:
print("Only standard wallet and CAT wallets are supported")
return
tx_id = res.name
start = time.time()
while time.time() - start < 10:
await asyncio.sleep(0.1)
tx = await wallet_client.get_transaction(str(wallet_id), tx_id)
if len(tx.sent_to) > 0:
print(transaction_submitted_msg(tx))
print(transaction_status_msg(fingerprint, tx_id))
return None
print("Transaction not yet submitted to nodes")
print(f"To get status, use command: chia wallet get_transaction -f {fingerprint} -tx 0x{tx_id}")
async def get_address(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["id"]
new_address: bool = args.get("new_address", False)
res = await wallet_client.get_next_address(wallet_id, new_address)
print(res)
async def delete_unconfirmed_transactions(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["id"]
await wallet_client.delete_unconfirmed_transactions(wallet_id)
print(f"Successfully deleted all unconfirmed transactions for wallet id {wallet_id} on key {fingerprint}")
async def add_token(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
asset_id = args["asset_id"]
token_name = args["token_name"]
try:
asset_id_bytes: bytes32 = bytes32.from_hexstr(asset_id)
existing_info: Optional[Tuple[Optional[uint32], str]] = await wallet_client.cat_asset_id_to_name(asset_id_bytes)
if existing_info is None or existing_info[0] is None:
response = await wallet_client.create_wallet_for_existing_cat(asset_id_bytes)
wallet_id = response["wallet_id"]
await wallet_client.set_cat_name(wallet_id, token_name)
print(f"Successfully added {token_name} with wallet id {wallet_id} on key {fingerprint}")
else:
wallet_id, old_name = existing_info
await wallet_client.set_cat_name(wallet_id, token_name)
print(f"Successfully renamed {old_name} with wallet_id {wallet_id} on key {fingerprint} to {token_name}")
except ValueError as e:
if "fromhex()" in str(e):
print(f"{asset_id} is not a valid Asset ID")
else:
raise e
async def make_offer(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
offers: List[str] = args["offers"]
requests: List[str] = args["requests"]
filepath: str = args["filepath"]
fee: int = int(Decimal(args["fee"]) * units["chia"])
if [] in [offers, requests]:
print("Not creating offer: Must be offering and requesting at least one asset")
else:
offer_dict: Dict[Union[uint32, str], int] = {}
printable_dict: Dict[str, Tuple[str, int, int]] = {} # Dict[asset_name, Tuple[amount, unit, multiplier]]
for item in [*offers, *requests]:
wallet_id, amount = tuple(item.split(":")[0:2])
if int(wallet_id) == 1:
name: str = "XCH"
unit: int = units["chia"]
else:
name = await wallet_client.get_cat_name(wallet_id)
unit = units["cat"]
multiplier: int = -1 if item in offers else 1
printable_dict[name] = (amount, unit, multiplier)
if uint32(int(wallet_id)) in offer_dict:
print("Not creating offer: Cannot offer and request the same asset in a trade")
break
else:
offer_dict[uint32(int(wallet_id))] = int(Decimal(amount) * unit) * multiplier
else:
print("Creating Offer")
print("--------------")
print()
print("OFFERING:")
for name, info in printable_dict.items():
amount, unit, multiplier = info
if multiplier < 0:
print(f" - {amount} {name} ({int(Decimal(amount) * unit)} mojos)")
print("REQUESTING:")
for name, info in printable_dict.items():
amount, unit, multiplier = info
if multiplier > 0:
print(f" - {amount} {name} ({int(Decimal(amount) * unit)} mojos)")
confirmation = input("Confirm (y/n): ")
if confirmation not in ["y", "yes"]:
print("Not creating offer...")
else:
offer, trade_record = await wallet_client.create_offer_for_ids(offer_dict, fee=fee)
if offer is not None:
with open(pathlib.Path(filepath), "w") as file:
file.write(offer.to_bech32())
print(f"Created offer with ID {trade_record.trade_id}")
print(f"Use chia wallet get_offers --id {trade_record.trade_id} -f {fingerprint} to view status")
else:
print("Error creating offer")
def timestamp_to_time(timestamp):
return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
async def print_offer_summary(cat_name_resolver: CATNameResolver, sum_dict: Dict[str, int], has_fee: bool = False):
for asset_id, amount in sum_dict.items():
description: str = ""
unit: int = units["chia"]
wid: str = "1" if asset_id == "xch" else ""
mojo_amount: int = int(Decimal(amount))
name: str = "XCH"
if asset_id != "xch":
name = asset_id
if asset_id == "unknown":
name = "Unknown"
unit = units["mojo"]
if has_fee:
description = " [Typically represents change returned from the included fee]"
else:
unit = units["cat"]
result = await cat_name_resolver(bytes32.from_hexstr(asset_id))
if result is not None:
wid = str(result[0])
name = result[1]
output: str = f" - {name}"
mojo_str: str = f"{mojo_amount} {"mojo" if mojo_amount == 1 else "mojos"}"
if len(wid) > 0:
output += f" (Wallet ID: {wid})"
if unit == units["mojo"]:
output += f": {mojo_str}"
else:
output += f": {mojo_amount / unit} ({mojo_str})"
if len(description) > 0:
output += f" {description}"
print(output)
async def print_trade_record(record, wallet_client: WalletRpcClient, summaries: bool = False) -> None:
print()
print(f"Record with id: {record.trade_id}")
print("---------------")
print(f"Created at: {timestamp_to_time(record.created_at_time)}")
print(f"Confirmed at: {record.confirmed_at_index}")
print(f"Accepted at: {timestamp_to_time(record.accepted_at_time) if record.accepted_at_time else "N/A"}")
print(f"Status: {TradeStatus(record.status).name}")
if summaries:
print("Summary:")
offer = Offer.from_bytes(record.offer)
offered, requested, _ = offer.summary()
outbound_balances: Dict[str, int] = offer.get_pending_amounts()
fees: Decimal = Decimal(offer.bundle.fees())
cat_name_resolver = wallet_client.cat_asset_id_to_name
print(" OFFERED:")
await print_offer_summary(cat_name_resolver, offered)
print(" REQUESTED:")
await print_offer_summary(cat_name_resolver, requested)
print("Pending Outbound Balances:")
await print_offer_summary(cat_name_resolver, outbound_balances, has_fee=(fees > 0))
print(f"Included Fees: {fees / units["chia"]}")
print("---------------")
async def get_offers(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
id: Optional[str] = args.get("id", None)
filepath: Optional[str] = args.get("filepath", None)
exclude_my_offers: bool = args.get("exclude_my_offers", False)
exclude_taken_offers: bool = args.get("exclude_taken_offers", False)
include_completed: bool = args.get("include_completed", False)
summaries: bool = args.get("summaries", False)
reverse: bool = args.get("reverse", False)
file_contents: bool = (filepath is not None) or summaries
records: List[TradeRecord] = []
if id is None:
batch_size: int = 10
start: int = 0
end: int = start + batch_size
# Traverse offers page by page
while True:
new_records: List[TradeRecord] = await wallet_client.get_all_offers(
start,
end,
reverse=reverse,
file_contents=file_contents,
exclude_my_offers=exclude_my_offers,
exclude_taken_offers=exclude_taken_offers,
include_completed=include_completed,
)
records.extend(new_records)
# If fewer records were returned than requested, we're done
if len(new_records) < batch_size:
break
start = end
end += batch_size
else:
records = [await wallet_client.get_offer(bytes32.from_hexstr(id), file_contents)]
if filepath is not None:
with open(pathlib.Path(filepath), "w") as file:
file.write(Offer.from_bytes(records[0].offer).to_bech32())
file.close()
for record in records:
await print_trade_record(record, wallet_client, summaries=summaries)
async def take_offer(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
if "." in args["file"]:
filepath = pathlib.Path(args["file"])
with open(filepath, "r") as file:
offer_hex: str = file.read()
file.close()
else:
offer_hex = args["file"]
examine_only: bool = args["examine_only"]
fee: int = int(Decimal(args["fee"]) * units["chia"])
try:
offer = Offer.from_bech32(offer_hex)
except ValueError:
print("Please enter a valid offer file or hex blob")
return
offered, requested, _ = offer.summary()
cat_name_resolver = wallet_client.cat_asset_id_to_name
print("Summary:")
print(" OFFERED:")
await print_offer_summary(cat_name_resolver, offered)
print(" REQUESTED:")
await print_offer_summary(cat_name_resolver, requested)
print(f"Included Fees: {Decimal(offer.bundle.fees()) / units["chia"]}")
if not examine_only:
confirmation = input("Would you like to take this offer? (y/n): ")
if confirmation in ["y", "yes"]:
trade_record = await wallet_client.take_offer(offer, fee=fee)
print(f"Accepted offer with ID {trade_record.trade_id}")
print(f"Use chia wallet get_offers --id {trade_record.trade_id} -f {fingerprint} to view its status")
async def cancel_offer(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
id = bytes32.from_hexstr(args["id"])
secure: bool = not args["insecure"]
fee: int = int(Decimal(args["fee"]) * units["chia"])
trade_record = await wallet_client.get_offer(id, file_contents=True)
await print_trade_record(trade_record, wallet_client, summaries=True)
confirmation = input(f"Are you sure you wish to cancel offer with ID: {trade_record.trade_id}? (y/n): ")
if confirmation in ["y", "yes"]:
await wallet_client.cancel_offer(id, secure=secure, fee=fee)
print(f"Cancelled offer with ID {trade_record.trade_id}")
if secure:
print(f"Use chia wallet get_offers --id {trade_record.trade_id} -f {fingerprint} to view cancel status")
def wallet_coin_unit(typ: WalletType, address_prefix: str) -> Tuple[str, int]:
if typ == WalletType.CAT:
return "", units["cat"]
if typ in [WalletType.STANDARD_WALLET, WalletType.POOLING_WALLET, WalletType.MULTI_SIG, WalletType.RATE_LIMITED]:
return address_prefix, units["chia"]
return "", units["mojo"]
def print_balance(amount: int, scale: int, address_prefix: str) -> str:
ret = f"{amount/scale} {address_prefix} "
if scale > 1:
ret += f"({amount} mojo)"
return ret
async def print_balances(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_type: Optional[WalletType] = None
if "type" in args:
wallet_type = WalletType(args["type"])
summaries_response = await wallet_client.get_wallets(wallet_type)
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
address_prefix = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"]
is_synced: bool = await wallet_client.get_synced()
is_syncing: bool = await wallet_client.get_sync_status()
print(f"Wallet height: {await wallet_client.get_height_info()}")
if is_syncing:
print("Sync status: Syncing...")
elif is_synced:
print("Sync status: Synced")
else:
print("Sync status: Not synced")
if not is_syncing and is_synced:
if len(summaries_response) == 0:
type_hint = " " if wallet_type is None else f" from type {wallet_type.name} "
print(f"\nNo wallets{type_hint}available for fingerprint: {fingerprint}")
else:
print(f"Balances, fingerprint: {fingerprint}")
for summary in summaries_response:
indent: str = " "
# asset_id currently contains both the asset ID and TAIL program bytes concatenated together.
# A future RPC update may split them apart, but for now we'll show the first 32 bytes (64 chars)
asset_id = summary["data"][:64]
wallet_id = summary["id"]
balances = await wallet_client.get_wallet_balance(wallet_id)
typ = WalletType(int(summary["type"]))
address_prefix, scale = wallet_coin_unit(typ, address_prefix)
total_balance: str = print_balance(balances["confirmed_wallet_balance"], scale, address_prefix)
unconfirmed_wallet_balance: str = print_balance(
balances["unconfirmed_wallet_balance"], scale, address_prefix
)
spendable_balance: str = print_balance(balances["spendable_balance"], scale, address_prefix)
print()
print(f"{summary["name"]}:")
print(f"{indent}{"-Total Balance:".ljust(23)} {total_balance}")
print(f"{indent}{"-Pending Total Balance:".ljust(23)} " f"{unconfirmed_wallet_balance}")
print(f"{indent}{"-Spendable:".ljust(23)} {spendable_balance}")
print(f"{indent}{"-Type:".ljust(23)} {typ.name}")
if len(asset_id) > 0:
print(f"{indent}{"-Asset ID:".ljust(23)} {asset_id}")
print(f"{indent}{"-Wallet ID:".ljust(23)} {wallet_id}")
print(" ")
trusted_peers: Dict = config["wallet"].get("trusted_peers", {})
await print_connections(wallet_client, trusted_peers)
async def get_wallet(wallet_client: WalletRpcClient, fingerprint: int = None) -> Optional[Tuple[WalletRpcClient, int]]:
if fingerprint is not None:
fingerprints = [fingerprint]
else:
fingerprints = await wallet_client.get_public_keys()
if len(fingerprints) == 0:
print("No keys loaded. Run 'chia keys generate' or import a key")
return None
if len(fingerprints) == 1:
fingerprint = fingerprints[0]
if fingerprint is not None:
log_in_response = await wallet_client.log_in(fingerprint)
else:
logged_in_fingerprint: Optional[int] = await wallet_client.get_logged_in_fingerprint()
spacing: str = " " if logged_in_fingerprint is not None else ""
current_sync_status: str = ""
if logged_in_fingerprint is not None:
if await wallet_client.get_synced():
current_sync_status = "Synced"
elif await wallet_client.get_sync_status():
current_sync_status = "Syncing"
else:
current_sync_status = "Not Synced"
print("Wallet keys:")
for i, fp in enumerate(fingerprints):
row: str = f"{i+1}) "
row += "* " if fp == logged_in_fingerprint else spacing
row += f"{fp}"
if fp == logged_in_fingerprint and len(current_sync_status) > 0:
row += f" ({current_sync_status})"
print(row)
val = None
prompt: str = (
f"Choose a wallet key [1-{len(fingerprints)}] ('q' to quit, or Enter to use {logged_in_fingerprint}): "
)
while val is None:
val = input(prompt)
if val == "q":
return None
elif val == "" and logged_in_fingerprint is not None:
fingerprint = logged_in_fingerprint
break
elif not val.isdigit():
val = None
else:
index = int(val) - 1
if index < 0 or index >= len(fingerprints):
print("Invalid value")
val = None
continue
else:
fingerprint = fingerprints[index]
assert fingerprint is not None
log_in_response = await wallet_client.log_in(fingerprint)
if log_in_response["success"] is False:
print(f"Login failed: {log_in_response}")
return None
return wallet_client, fingerprint
async def execute_with_wallet(
wallet_rpc_port: Optional[int], fingerprint: int, extra_params: Dict, function: Callable
) -> None:
try:
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
self_hostname = config["self_hostname"]
if wallet_rpc_port is None:
wallet_rpc_port = config["wallet"]["rpc_port"]
wallet_client = await WalletRpcClient.create(self_hostname, uint16(wallet_rpc_port), DEFAULT_ROOT_PATH, config)
wallet_client_f = await get_wallet(wallet_client, fingerprint=fingerprint)
if wallet_client_f is None:
wallet_client.close()
await wallet_client.await_closed()
return None
wallet_client, fingerprint = wallet_client_f
await function(extra_params, wallet_client, fingerprint)
except KeyboardInterrupt:
pass
except Exception as e:
if isinstance(e, aiohttp.ClientConnectorError):
print(
f"Connection error. Check if the wallet is running at {wallet_rpc_port}. "
"You can run the wallet via:\n\tchia start wallet"
)
else:
print(f"Exception from 'wallet' {e}")
wallet_client.close()
await wallet_client.await_closed()
async def create_did_wallet(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
amount = args["amount"]
fee = args["fee"]
name = args["name"]
try:
response = await wallet_client.create_new_did_wallet(amount, fee, name)
wallet_id = response["wallet_id"]
my_did = response["my_did"]
print(f"Successfully created a DID wallet with name {name} and id {wallet_id} on key {fingerprint}")
print(f"Successfully created a DID {my_did} in the newly created DID wallet")
except Exception as e:
print(f"Failed to create DID wallet: {e}")
async def did_set_wallet_name(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["wallet_id"]
name = args["name"]
try:
await wallet_client.did_set_wallet_name(wallet_id, name)
print(f"Successfully set a new name for DID wallet with id {wallet_id}: {name}")
except Exception as e:
print(f"Failed to set DID wallet name: {e}")
async def get_did(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
did_wallet_id: int = args["did_wallet_id"]
try:
response = await wallet_client.get_did_id(did_wallet_id)
my_did = response["my_did"]
coin_id = response["coin_id"]
print(f"{"DID:".ljust(23)} {my_did}")
print(f"{"Coin ID:".ljust(23)} {coin_id}")
except Exception as e:
print(f"Failed to get DID: {e}")
async def create_nft_wallet(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
try:
response = await wallet_client.create_new_nft_wallet(None)
wallet_id = response["wallet_id"]
print(f"Successfully created an NFT wallet with id {wallet_id} on key {fingerprint}")
except Exception as e:
print(f"Failed to create NFT wallet: {e}")
async def mint_nft(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["wallet_id"]
royalty_address = args["royalty_address"]
target_address = args["target_address"]
hash = args["hash"]
uris = args["uris"]
metadata_hash = args["metadata_hash"]
metadata_uris = args["metadata_uris"]
license_hash = args["license_hash"]
license_uris = args["license_uris"]
series_total = args["series_total"]
series_number = args["series_number"]
fee = args["fee"]
try:
response = await wallet_client.mint_nft(
wallet_id,
royalty_address,
target_address,
hash,
uris,
metadata_hash,
metadata_uris,
license_hash,
license_uris,
series_total,
series_number,
fee,
)
spend_bundle = response["spend_bundle"]
print(f"NFT minted Successfully with spend bundle: {spend_bundle}")
except Exception as e:
print(f"Failed to mint NFT: {e}")
async def add_uri_to_nft(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
try:
wallet_id = args["wallet_id"]
nft_coin_id = args["nft_coin_id"]
uri = args["uri"]
fee = args["fee"]
key = args.get("meta_uri", "u")
response = await wallet_client.add_uri_to_nft(wallet_id, nft_coin_id, key, uri, fee)
spend_bundle = response["spend_bundle"]
print(f"URI added successfully with spend bundle: {spend_bundle}")
except Exception as e:
print(f"Failed to add URI to NFT: {e}")
async def transfer_nft(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
try:
wallet_id = args["wallet_id"]
nft_coin_id = args["nft_coin_id"]
target_address = args["target_address"]
fee = args["fee"]
response = await wallet_client.transfer_nft(wallet_id, nft_coin_id, target_address, fee)
spend_bundle = response["spend_bundle"]
print(f"NFT transferred successfully with spend bundle: {spend_bundle}")
except Exception as e:
print(f"Failed to transfer NFT: {e}")
async def list_nfts(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["wallet_id"]
try:
response = await wallet_client.list_nfts(wallet_id)
nft_list = response["nft_list"]
if len(nft_list) > 0:
from chia.wallet.nft_wallet.nft_info import NFTInfo
indent: str = " "
for n in nft_list:
nft = NFTInfo.from_json_dict(n)
print()
print(f"{"Launcher coin ID:".ljust(26)} {nft.launcher_id}")
print(f"{"Launcher puzhash:".ljust(26)} {nft.launcher_puzhash}")
print(f"{"Current NFT coin ID:".ljust(26)} {nft.nft_coin_id}")
print(f"{"On-chain data/info:".ljust(26)} {nft.chain_info}")
print(f"{"Owner DID:".ljust(26)} {nft.owner_did}")
print(f"{"Owner pubkey:".ljust(26)} {nft.owner_pubkey}")
print(f"{"Royalty percentage:".ljust(26)} {nft.royalty_percentage}")
print(f"{"Royalty puzhash:".ljust(26)} {nft.royalty_puzzle_hash}")
print(f"{"NFT content hash:".ljust(26)} {nft.data_hash.hex()}")
print(f"{"Metadata hash:".ljust(26)} {nft.metadata_hash.hex()}")
print(f"{"License hash:".ljust(26)} {nft.license_hash.hex()}")
print(f"{"NFT series total:".ljust(26)} {nft.series_total}")
print(f"{"Current NFT number in the series:".ljust(26)} {nft.series_number}")
print(f"{"Metadata updater puzhash:".ljust(26)} {nft.updater_puzhash}")
print(f"{"NFT minting block height:".ljust(26)} {nft.mint_height}")
print(f"{"Inner puzzle supports DID:".ljust(26)} {nft.supports_did}")
print(f"{"NFT is pending for a transaction:".ljust(26)} {nft.pending_transaction}")
print()
print("URIs:")
for uri in nft.data_uris:
print(f"{indent}{uri}")
print()
print("Metadata URIs:")
for metadata_uri in nft.metadata_uris:
print(f"{indent}{metadata_uri}")
print()
print("License URIs:")
for license_uri in nft.license_uris:
print(f"{indent}{license_uri}")
else:
print(f"No NFTs found for wallet with id {wallet_id} on key {fingerprint}")
except Exception as e:
print(f"Failed to list NFTs for wallet with id {wallet_id} on key {fingerprint}: {e}")
| import asyncio
import pathlib
import sys
import time
from datetime import datetime
from decimal import Decimal
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Union
import aiohttp
from chia.cmds.cmds_util import transaction_status_msg, transaction_submitted_msg
from chia.cmds.show import print_connections
from chia.cmds.units import units
from chia.rpc.wallet_rpc_client import WalletRpcClient
from chia.server.start_wallet import SERVICE_NAME
from chia.types.blockchain_format.sized_bytes import bytes32
from chia.util.bech32m import encode_puzzle_hash
from chia.util.config import load_config
from chia.util.default_root import DEFAULT_ROOT_PATH
from chia.util.ints import uint16, uint32, uint64
from chia.wallet.trade_record import TradeRecord
from chia.wallet.trading.offer import Offer
from chia.wallet.trading.trade_status import TradeStatus
from chia.wallet.transaction_record import TransactionRecord
from chia.wallet.util.transaction_type import TransactionType
from chia.wallet.util.wallet_types import WalletType
CATNameResolver = Callable[[bytes32], Awaitable[Optional[Tuple[Optional[uint32], str]]]]
transaction_type_descriptions = {
TransactionType.INCOMING_TX: "received",
TransactionType.OUTGOING_TX: "sent",
TransactionType.COINBASE_REWARD: "rewarded",
TransactionType.FEE_REWARD: "rewarded",
TransactionType.INCOMING_TRADE: "received in trade",
TransactionType.OUTGOING_TRADE: "sent in trade",
}
def transaction_description_from_type(tx: TransactionRecord) -> str:
return transaction_type_descriptions.get(TransactionType(tx.type), "(unknown reason)")
def print_transaction(tx: TransactionRecord, verbose: bool, name, address_prefix: str, mojo_per_unit: int) -> None:
if verbose:
print(tx)
else:
chia_amount = Decimal(int(tx.amount)) / mojo_per_unit
to_address = encode_puzzle_hash(tx.to_puzzle_hash, address_prefix)
print(f"Transaction {tx.name}")
print(f"Status: {'Confirmed' if tx.confirmed else ('In mempool' if tx.is_in_mempool() else 'Pending')}")
description = transaction_description_from_type(tx)
print(f"Amount {description}: {chia_amount} {name}")
print(f"To address: {to_address}")
print("Created at:", datetime.fromtimestamp(tx.created_at_time).strftime("%Y-%m-%d %H:%M:%S"))
print("")
def get_mojo_per_unit(wallet_type: WalletType) -> int:
mojo_per_unit: int
if wallet_type == WalletType.STANDARD_WALLET or wallet_type == WalletType.POOLING_WALLET:
mojo_per_unit = units["chia"]
elif wallet_type == WalletType.CAT:
mojo_per_unit = units["cat"]
else:
raise LookupError("Only standard wallet, CAT wallets, and Plot NFTs are supported")
return mojo_per_unit
async def get_wallet_type(wallet_id: int, wallet_client: WalletRpcClient) -> WalletType:
summaries_response = await wallet_client.get_wallets()
for summary in summaries_response:
summary_id: int = summary["id"]
summary_type: int = summary["type"]
if wallet_id == summary_id:
return WalletType(summary_type)
raise LookupError(f"Wallet ID not found: {wallet_id}")
async def get_name_for_wallet_id(
config: Dict[str, Any],
wallet_type: WalletType,
wallet_id: int,
wallet_client: WalletRpcClient,
):
if wallet_type == WalletType.STANDARD_WALLET or wallet_type == WalletType.POOLING_WALLET:
name = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"].upper()
elif wallet_type == WalletType.CAT:
name = await wallet_client.get_cat_name(wallet_id=str(wallet_id))
else:
raise LookupError("Only standard wallet, CAT wallets, and Plot NFTs are supported")
return name
async def get_transaction(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
transaction_id = bytes32.from_hexstr(args["tx_id"])
config = load_config(DEFAULT_ROOT_PATH, "config.yaml", SERVICE_NAME)
address_prefix = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"]
tx: TransactionRecord = await wallet_client.get_transaction("this is unused", transaction_id=transaction_id)
try:
wallet_type = await get_wallet_type(wallet_id=tx.wallet_id, wallet_client=wallet_client)
mojo_per_unit = get_mojo_per_unit(wallet_type=wallet_type)
name = await get_name_for_wallet_id(
config=config,
wallet_type=wallet_type,
wallet_id=tx.wallet_id,
wallet_client=wallet_client,
)
except LookupError as e:
print(e.args[0])
return
print_transaction(
tx,
verbose=(args["verbose"] > 0),
name=name,
address_prefix=address_prefix,
mojo_per_unit=mojo_per_unit,
)
async def get_transactions(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["id"]
paginate = args["paginate"]
if paginate is None:
paginate = sys.stdout.isatty()
offset = args["offset"]
limit = args["limit"]
sort_key = args["sort_key"]
reverse = args["reverse"]
txs: List[TransactionRecord] = await wallet_client.get_transactions(
wallet_id, start=offset, end=(offset + limit), sort_key=sort_key, reverse=reverse
)
config = load_config(DEFAULT_ROOT_PATH, "config.yaml", SERVICE_NAME)
address_prefix = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"]
if len(txs) == 0:
print("There are no transactions to this address")
try:
wallet_type = await get_wallet_type(wallet_id=wallet_id, wallet_client=wallet_client)
mojo_per_unit = get_mojo_per_unit(wallet_type=wallet_type)
name = await get_name_for_wallet_id(
config=config,
wallet_type=wallet_type,
wallet_id=wallet_id,
wallet_client=wallet_client,
)
except LookupError as e:
print(e.args[0])
return
num_per_screen = 5 if paginate else len(txs)
for i in range(0, len(txs), num_per_screen):
for j in range(0, num_per_screen):
if i + j >= len(txs):
break
print_transaction(
txs[i + j],
verbose=(args["verbose"] > 0),
name=name,
address_prefix=address_prefix,
mojo_per_unit=mojo_per_unit,
)
if i + num_per_screen >= len(txs):
return None
print("Press q to quit, or c to continue")
while True:
entered_key = sys.stdin.read(1)
if entered_key == "q":
return None
elif entered_key == "c":
break
def check_unusual_transaction(amount: Decimal, fee: Decimal):
return fee >= amount
async def send(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id: int = args["id"]
amount = Decimal(args["amount"])
fee = Decimal(args["fee"])
address = args["address"]
override = args["override"]
memo = args["memo"]
if memo is None:
memos = None
else:
memos = [memo]
if not override and check_unusual_transaction(amount, fee):
print(
f"A transaction of amount {amount} and fee {fee} is unusual.\n"
f"Pass in --override if you are sure you mean to do this."
)
return
try:
typ = await get_wallet_type(wallet_id=wallet_id, wallet_client=wallet_client)
except LookupError:
print(f"Wallet id: {wallet_id} not found.")
return
final_fee = uint64(int(fee * units["chia"]))
final_amount: uint64
if typ == WalletType.STANDARD_WALLET:
final_amount = uint64(int(amount * units["chia"]))
print("Submitting transaction...")
res = await wallet_client.send_transaction(str(wallet_id), final_amount, address, final_fee, memos)
elif typ == WalletType.CAT:
final_amount = uint64(int(amount * units["cat"]))
print("Submitting transaction...")
res = await wallet_client.cat_spend(str(wallet_id), final_amount, address, final_fee, memos)
else:
print("Only standard wallet and CAT wallets are supported")
return
tx_id = res.name
start = time.time()
while time.time() - start < 10:
await asyncio.sleep(0.1)
tx = await wallet_client.get_transaction(str(wallet_id), tx_id)
if len(tx.sent_to) > 0:
print(transaction_submitted_msg(tx))
print(transaction_status_msg(fingerprint, tx_id))
return None
print("Transaction not yet submitted to nodes")
print(f"To get status, use command: chia wallet get_transaction -f {fingerprint} -tx 0x{tx_id}")
async def get_address(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["id"]
new_address: bool = args.get("new_address", False)
res = await wallet_client.get_next_address(wallet_id, new_address)
print(res)
async def delete_unconfirmed_transactions(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["id"]
await wallet_client.delete_unconfirmed_transactions(wallet_id)
print(f"Successfully deleted all unconfirmed transactions for wallet id {wallet_id} on key {fingerprint}")
async def add_token(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
asset_id = args["asset_id"]
token_name = args["token_name"]
try:
asset_id_bytes: bytes32 = bytes32.from_hexstr(asset_id)
existing_info: Optional[Tuple[Optional[uint32], str]] = await wallet_client.cat_asset_id_to_name(asset_id_bytes)
if existing_info is None or existing_info[0] is None:
response = await wallet_client.create_wallet_for_existing_cat(asset_id_bytes)
wallet_id = response["wallet_id"]
await wallet_client.set_cat_name(wallet_id, token_name)
print(f"Successfully added {token_name} with wallet id {wallet_id} on key {fingerprint}")
else:
wallet_id, old_name = existing_info
await wallet_client.set_cat_name(wallet_id, token_name)
print(f"Successfully renamed {old_name} with wallet_id {wallet_id} on key {fingerprint} to {token_name}")
except ValueError as e:
if "fromhex()" in str(e):
print(f"{asset_id} is not a valid Asset ID")
else:
raise e
async def make_offer(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
offers: List[str] = args["offers"]
requests: List[str] = args["requests"]
filepath: str = args["filepath"]
fee: int = int(Decimal(args["fee"]) * units["chia"])
if [] in [offers, requests]:
print("Not creating offer: Must be offering and requesting at least one asset")
else:
offer_dict: Dict[Union[uint32, str], int] = {}
printable_dict: Dict[str, Tuple[str, int, int]] = {} # Dict[asset_name, Tuple[amount, unit, multiplier]]
for item in [*offers, *requests]:
wallet_id, amount = tuple(item.split(":")[0:2])
if int(wallet_id) == 1:
name: str = "XCH"
unit: int = units["chia"]
else:
name = await wallet_client.get_cat_name(wallet_id)
unit = units["cat"]
multiplier: int = -1 if item in offers else 1
printable_dict[name] = (amount, unit, multiplier)
if uint32(int(wallet_id)) in offer_dict:
print("Not creating offer: Cannot offer and request the same asset in a trade")
break
else:
offer_dict[uint32(int(wallet_id))] = int(Decimal(amount) * unit) * multiplier
else:
print("Creating Offer")
print("--------------")
print()
print("OFFERING:")
for name, info in printable_dict.items():
amount, unit, multiplier = info
if multiplier < 0:
print(f" - {amount} {name} ({int(Decimal(amount) * unit)} mojos)")
print("REQUESTING:")
for name, info in printable_dict.items():
amount, unit, multiplier = info
if multiplier > 0:
print(f" - {amount} {name} ({int(Decimal(amount) * unit)} mojos)")
confirmation = input("Confirm (y/n): ")
if confirmation not in ["y", "yes"]:
print("Not creating offer...")
else:
offer, trade_record = await wallet_client.create_offer_for_ids(offer_dict, fee=fee)
if offer is not None:
with open(pathlib.Path(filepath), "w") as file:
file.write(offer.to_bech32())
print(f"Created offer with ID {trade_record.trade_id}")
print(f"Use chia wallet get_offers --id {trade_record.trade_id} -f {fingerprint} to view status")
else:
print("Error creating offer")
def timestamp_to_time(timestamp):
return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
async def print_offer_summary(cat_name_resolver: CATNameResolver, sum_dict: Dict[str, int], has_fee: bool = False):
for asset_id, amount in sum_dict.items():
description: str = ""
unit: int = units["chia"]
wid: str = "1" if asset_id == "xch" else ""
mojo_amount: int = int(Decimal(amount))
name: str = "XCH"
if asset_id != "xch":
name = asset_id
if asset_id == "unknown":
name = "Unknown"
unit = units["mojo"]
if has_fee:
description = " [Typically represents change returned from the included fee]"
else:
unit = units["cat"]
result = await cat_name_resolver(bytes32.from_hexstr(asset_id))
if result is not None:
wid = str(result[0])
name = result[1]
output: str = f" - {name}"
mojo_str: str = f"{mojo_amount} {'mojo' if mojo_amount == 1 else 'mojos'}"
if len(wid) > 0:
output += f" (Wallet ID: {wid})"
if unit == units["mojo"]:
output += f": {mojo_str}"
else:
output += f": {mojo_amount / unit} ({mojo_str})"
if len(description) > 0:
output += f" {description}"
print(output)
async def print_trade_record(record, wallet_client: WalletRpcClient, summaries: bool = False) -> None:
print()
print(f"Record with id: {record.trade_id}")
print("---------------")
print(f"Created at: {timestamp_to_time(record.created_at_time)}")
print(f"Confirmed at: {record.confirmed_at_index}")
print(f"Accepted at: {timestamp_to_time(record.accepted_at_time) if record.accepted_at_time else 'N/A'}")
print(f"Status: {TradeStatus(record.status).name}")
if summaries:
print("Summary:")
offer = Offer.from_bytes(record.offer)
offered, requested, _ = offer.summary()
outbound_balances: Dict[str, int] = offer.get_pending_amounts()
fees: Decimal = Decimal(offer.bundle.fees())
cat_name_resolver = wallet_client.cat_asset_id_to_name
print(" OFFERED:")
await print_offer_summary(cat_name_resolver, offered)
print(" REQUESTED:")
await print_offer_summary(cat_name_resolver, requested)
print("Pending Outbound Balances:")
await print_offer_summary(cat_name_resolver, outbound_balances, has_fee=(fees > 0))
print(f"Included Fees: {fees / units['chia']}")
print("---------------")
async def get_offers(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
id: Optional[str] = args.get("id", None)
filepath: Optional[str] = args.get("filepath", None)
exclude_my_offers: bool = args.get("exclude_my_offers", False)
exclude_taken_offers: bool = args.get("exclude_taken_offers", False)
include_completed: bool = args.get("include_completed", False)
summaries: bool = args.get("summaries", False)
reverse: bool = args.get("reverse", False)
file_contents: bool = (filepath is not None) or summaries
records: List[TradeRecord] = []
if id is None:
batch_size: int = 10
start: int = 0
end: int = start + batch_size
# Traverse offers page by page
while True:
new_records: List[TradeRecord] = await wallet_client.get_all_offers(
start,
end,
reverse=reverse,
file_contents=file_contents,
exclude_my_offers=exclude_my_offers,
exclude_taken_offers=exclude_taken_offers,
include_completed=include_completed,
)
records.extend(new_records)
# If fewer records were returned than requested, we're done
if len(new_records) < batch_size:
break
start = end
end += batch_size
else:
records = [await wallet_client.get_offer(bytes32.from_hexstr(id), file_contents)]
if filepath is not None:
with open(pathlib.Path(filepath), "w") as file:
file.write(Offer.from_bytes(records[0].offer).to_bech32())
file.close()
for record in records:
await print_trade_record(record, wallet_client, summaries=summaries)
async def take_offer(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
if "." in args["file"]:
filepath = pathlib.Path(args["file"])
with open(filepath, "r") as file:
offer_hex: str = file.read()
file.close()
else:
offer_hex = args["file"]
examine_only: bool = args["examine_only"]
fee: int = int(Decimal(args["fee"]) * units["chia"])
try:
offer = Offer.from_bech32(offer_hex)
except ValueError:
print("Please enter a valid offer file or hex blob")
return
offered, requested, _ = offer.summary()
cat_name_resolver = wallet_client.cat_asset_id_to_name
print("Summary:")
print(" OFFERED:")
await print_offer_summary(cat_name_resolver, offered)
print(" REQUESTED:")
await print_offer_summary(cat_name_resolver, requested)
print(f"Included Fees: {Decimal(offer.bundle.fees()) / units['chia']}")
if not examine_only:
confirmation = input("Would you like to take this offer? (y/n): ")
if confirmation in ["y", "yes"]:
trade_record = await wallet_client.take_offer(offer, fee=fee)
print(f"Accepted offer with ID {trade_record.trade_id}")
print(f"Use chia wallet get_offers --id {trade_record.trade_id} -f {fingerprint} to view its status")
async def cancel_offer(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
id = bytes32.from_hexstr(args["id"])
secure: bool = not args["insecure"]
fee: int = int(Decimal(args["fee"]) * units["chia"])
trade_record = await wallet_client.get_offer(id, file_contents=True)
await print_trade_record(trade_record, wallet_client, summaries=True)
confirmation = input(f"Are you sure you wish to cancel offer with ID: {trade_record.trade_id}? (y/n): ")
if confirmation in ["y", "yes"]:
await wallet_client.cancel_offer(id, secure=secure, fee=fee)
print(f"Cancelled offer with ID {trade_record.trade_id}")
if secure:
print(f"Use chia wallet get_offers --id {trade_record.trade_id} -f {fingerprint} to view cancel status")
def wallet_coin_unit(typ: WalletType, address_prefix: str) -> Tuple[str, int]:
if typ == WalletType.CAT:
return "", units["cat"]
if typ in [WalletType.STANDARD_WALLET, WalletType.POOLING_WALLET, WalletType.MULTI_SIG, WalletType.RATE_LIMITED]:
return address_prefix, units["chia"]
return "", units["mojo"]
def print_balance(amount: int, scale: int, address_prefix: str) -> str:
ret = f"{amount/scale} {address_prefix} "
if scale > 1:
ret += f"({amount} mojo)"
return ret
async def print_balances(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_type: Optional[WalletType] = None
if "type" in args:
wallet_type = WalletType(args["type"])
summaries_response = await wallet_client.get_wallets(wallet_type)
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
address_prefix = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"]
is_synced: bool = await wallet_client.get_synced()
is_syncing: bool = await wallet_client.get_sync_status()
print(f"Wallet height: {await wallet_client.get_height_info()}")
if is_syncing:
print("Sync status: Syncing...")
elif is_synced:
print("Sync status: Synced")
else:
print("Sync status: Not synced")
if not is_syncing and is_synced:
if len(summaries_response) == 0:
type_hint = " " if wallet_type is None else f" from type {wallet_type.name} "
print(f"\nNo wallets{type_hint}available for fingerprint: {fingerprint}")
else:
print(f"Balances, fingerprint: {fingerprint}")
for summary in summaries_response:
indent: str = " "
# asset_id currently contains both the asset ID and TAIL program bytes concatenated together.
# A future RPC update may split them apart, but for now we'll show the first 32 bytes (64 chars)
asset_id = summary["data"][:64]
wallet_id = summary["id"]
balances = await wallet_client.get_wallet_balance(wallet_id)
typ = WalletType(int(summary["type"]))
address_prefix, scale = wallet_coin_unit(typ, address_prefix)
total_balance: str = print_balance(balances["confirmed_wallet_balance"], scale, address_prefix)
unconfirmed_wallet_balance: str = print_balance(
balances["unconfirmed_wallet_balance"], scale, address_prefix
)
spendable_balance: str = print_balance(balances["spendable_balance"], scale, address_prefix)
print()
print(f"{summary['name']}:")
print(f"{indent}{'-Total Balance:'.ljust(23)} {total_balance}")
print(f"{indent}{'-Pending Total Balance:'.ljust(23)} " f"{unconfirmed_wallet_balance}")
print(f"{indent}{'-Spendable:'.ljust(23)} {spendable_balance}")
print(f"{indent}{'-Type:'.ljust(23)} {typ.name}")
if len(asset_id) > 0:
print(f"{indent}{'-Asset ID:'.ljust(23)} {asset_id}")
print(f"{indent}{'-Wallet ID:'.ljust(23)} {wallet_id}")
print(" ")
trusted_peers: Dict = config["wallet"].get("trusted_peers", {})
await print_connections(wallet_client, trusted_peers)
async def get_wallet(wallet_client: WalletRpcClient, fingerprint: int = None) -> Optional[Tuple[WalletRpcClient, int]]:
if fingerprint is not None:
fingerprints = [fingerprint]
else:
fingerprints = await wallet_client.get_public_keys()
if len(fingerprints) == 0:
print("No keys loaded. Run 'chia keys generate' or import a key")
return None
if len(fingerprints) == 1:
fingerprint = fingerprints[0]
if fingerprint is not None:
log_in_response = await wallet_client.log_in(fingerprint)
else:
logged_in_fingerprint: Optional[int] = await wallet_client.get_logged_in_fingerprint()
spacing: str = " " if logged_in_fingerprint is not None else ""
current_sync_status: str = ""
if logged_in_fingerprint is not None:
if await wallet_client.get_synced():
current_sync_status = "Synced"
elif await wallet_client.get_sync_status():
current_sync_status = "Syncing"
else:
current_sync_status = "Not Synced"
print("Wallet keys:")
for i, fp in enumerate(fingerprints):
row: str = f"{i+1}) "
row += "* " if fp == logged_in_fingerprint else spacing
row += f"{fp}"
if fp == logged_in_fingerprint and len(current_sync_status) > 0:
row += f" ({current_sync_status})"
print(row)
val = None
prompt: str = (
f"Choose a wallet key [1-{len(fingerprints)}] ('q' to quit, or Enter to use {logged_in_fingerprint}): "
)
while val is None:
val = input(prompt)
if val == "q":
return None
elif val == "" and logged_in_fingerprint is not None:
fingerprint = logged_in_fingerprint
break
elif not val.isdigit():
val = None
else:
index = int(val) - 1
if index < 0 or index >= len(fingerprints):
print("Invalid value")
val = None
continue
else:
fingerprint = fingerprints[index]
assert fingerprint is not None
log_in_response = await wallet_client.log_in(fingerprint)
if log_in_response["success"] is False:
print(f"Login failed: {log_in_response}")
return None
return wallet_client, fingerprint
async def execute_with_wallet(
wallet_rpc_port: Optional[int], fingerprint: int, extra_params: Dict, function: Callable
) -> None:
try:
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
self_hostname = config["self_hostname"]
if wallet_rpc_port is None:
wallet_rpc_port = config["wallet"]["rpc_port"]
wallet_client = await WalletRpcClient.create(self_hostname, uint16(wallet_rpc_port), DEFAULT_ROOT_PATH, config)
wallet_client_f = await get_wallet(wallet_client, fingerprint=fingerprint)
if wallet_client_f is None:
wallet_client.close()
await wallet_client.await_closed()
return None
wallet_client, fingerprint = wallet_client_f
await function(extra_params, wallet_client, fingerprint)
except KeyboardInterrupt:
pass
except Exception as e:
if isinstance(e, aiohttp.ClientConnectorError):
print(
f"Connection error. Check if the wallet is running at {wallet_rpc_port}. "
"You can run the wallet via:\n\tchia start wallet"
)
else:
print(f"Exception from 'wallet' {e}")
wallet_client.close()
await wallet_client.await_closed()
async def create_did_wallet(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
amount = args["amount"]
fee = args["fee"]
name = args["name"]
try:
response = await wallet_client.create_new_did_wallet(amount, fee, name)
wallet_id = response["wallet_id"]
my_did = response["my_did"]
print(f"Successfully created a DID wallet with name {name} and id {wallet_id} on key {fingerprint}")
print(f"Successfully created a DID {my_did} in the newly created DID wallet")
except Exception as e:
print(f"Failed to create DID wallet: {e}")
async def did_set_wallet_name(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["wallet_id"]
name = args["name"]
try:
await wallet_client.did_set_wallet_name(wallet_id, name)
print(f"Successfully set a new name for DID wallet with id {wallet_id}: {name}")
except Exception as e:
print(f"Failed to set DID wallet name: {e}")
async def get_did(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
did_wallet_id: int = args["did_wallet_id"]
try:
response = await wallet_client.get_did_id(did_wallet_id)
my_did = response["my_did"]
coin_id = response["coin_id"]
print(f"{'DID:'.ljust(23)} {my_did}")
print(f"{'Coin ID:'.ljust(23)} {coin_id}")
except Exception as e:
print(f"Failed to get DID: {e}")
async def create_nft_wallet(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
try:
response = await wallet_client.create_new_nft_wallet(None)
wallet_id = response["wallet_id"]
print(f"Successfully created an NFT wallet with id {wallet_id} on key {fingerprint}")
except Exception as e:
print(f"Failed to create NFT wallet: {e}")
async def mint_nft(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["wallet_id"]
royalty_address = args["royalty_address"]
target_address = args["target_address"]
hash = args["hash"]
uris = args["uris"]
metadata_hash = args["metadata_hash"]
metadata_uris = args["metadata_uris"]
license_hash = args["license_hash"]
license_uris = args["license_uris"]
series_total = args["series_total"]
series_number = args["series_number"]
fee = args["fee"]
try:
response = await wallet_client.mint_nft(
wallet_id,
royalty_address,
target_address,
hash,
uris,
metadata_hash,
metadata_uris,
license_hash,
license_uris,
series_total,
series_number,
fee,
)
spend_bundle = response["spend_bundle"]
print(f"NFT minted Successfully with spend bundle: {spend_bundle}")
except Exception as e:
print(f"Failed to mint NFT: {e}")
async def add_uri_to_nft(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
try:
wallet_id = args["wallet_id"]
nft_coin_id = args["nft_coin_id"]
uri = args["uri"]
fee = args["fee"]
key = args.get("meta_uri", "u")
response = await wallet_client.add_uri_to_nft(wallet_id, nft_coin_id, key, uri, fee)
spend_bundle = response["spend_bundle"]
print(f"URI added successfully with spend bundle: {spend_bundle}")
except Exception as e:
print(f"Failed to add URI to NFT: {e}")
async def transfer_nft(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
try:
wallet_id = args["wallet_id"]
nft_coin_id = args["nft_coin_id"]
target_address = args["target_address"]
fee = args["fee"]
response = await wallet_client.transfer_nft(wallet_id, nft_coin_id, target_address, fee)
spend_bundle = response["spend_bundle"]
print(f"NFT transferred successfully with spend bundle: {spend_bundle}")
except Exception as e:
print(f"Failed to transfer NFT: {e}")
async def list_nfts(args: Dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args["wallet_id"]
try:
response = await wallet_client.list_nfts(wallet_id)
nft_list = response["nft_list"]
if len(nft_list) > 0:
from chia.wallet.nft_wallet.nft_info import NFTInfo
indent: str = " "
for n in nft_list:
nft = NFTInfo.from_json_dict(n)
print()
print(f"{'Launcher coin ID:'.ljust(26)} {nft.launcher_id}")
print(f"{'Launcher puzhash:'.ljust(26)} {nft.launcher_puzhash}")
print(f"{'Current NFT coin ID:'.ljust(26)} {nft.nft_coin_id}")
print(f"{'On-chain data/info:'.ljust(26)} {nft.chain_info}")
print(f"{'Owner DID:'.ljust(26)} {nft.owner_did}")
print(f"{'Owner pubkey:'.ljust(26)} {nft.owner_pubkey}")
print(f"{'Royalty percentage:'.ljust(26)} {nft.royalty_percentage}")
print(f"{'Royalty puzhash:'.ljust(26)} {nft.royalty_puzzle_hash}")
print(f"{'NFT content hash:'.ljust(26)} {nft.data_hash.hex()}")
print(f"{'Metadata hash:'.ljust(26)} {nft.metadata_hash.hex()}")
print(f"{'License hash:'.ljust(26)} {nft.license_hash.hex()}")
print(f"{'NFT series total:'.ljust(26)} {nft.series_total}")
print(f"{'Current NFT number in the series:'.ljust(26)} {nft.series_number}")
print(f"{'Metadata updater puzhash:'.ljust(26)} {nft.updater_puzhash}")
print(f"{'NFT minting block height:'.ljust(26)} {nft.mint_height}")
print(f"{'Inner puzzle supports DID:'.ljust(26)} {nft.supports_did}")
print(f"{'NFT is pending for a transaction:'.ljust(26)} {nft.pending_transaction}")
print()
print("URIs:")
for uri in nft.data_uris:
print(f"{indent}{uri}")
print()
print("Metadata URIs:")
for metadata_uri in nft.metadata_uris:
print(f"{indent}{metadata_uri}")
print()
print("License URIs:")
for license_uri in nft.license_uris:
print(f"{indent}{license_uri}")
else:
print(f"No NFTs found for wallet with id {wallet_id} on key {fingerprint}")
except Exception as e:
print(f"Failed to list NFTs for wallet with id {wallet_id} on key {fingerprint}: {e}")
|
import pickle
import traceback
from collections import Counter
from glob import glob
from pathlib import Path
from dpu_utils.utils import load_jsonl_gz
from .ts import code2identifiers, code2paths, code2paths4py, code2sexp
# JGD for alon_encoder
def paths2tokens(paths):
paths = [path.split(',') for path in paths]
terminals = list()
nonterminals = []
items = map(lambda x: x[0] + '|' + x[2], paths)
for item in items:
terminals.extend(item.split('|'))
items = map(lambda x: x[1], paths)
for item in items:
nonterminals.extend(item.split('|'))
return terminals, nonterminals
def collect_filenames(path):
pattern = path / "**/*_0.jsonl.gz"
# pattern = path / "**/*.jsonl.gz"
filenames = glob(str(pattern), recursive=True)
return filenames
def prepare_data(filenames, key='code'):
for filename in filenames:
for sample in load_jsonl_gz(filename):
value = sample[key]
yield value
def print_data(terminal_counter, nonterminal_counter):
print(f'{'@' * 9}terminal_counter\n{terminal_counter}')
print(f'{'@' * 9}nonterminal_counter\n{nonterminal_counter}')
# JGD for alon_encoder
def get_path(language, locally=False):
if locally:
return Path(f'/home/jian/data/{language}/final/jsonl/train')
# path = Path(f'C:\\Users\\jian\\Documents\\Corpus\\{language}\\final\\jsonl\\train')
else:
return Path(f'/home/dev/resources/data/{language}/final/jsonl/train')
# path = Path(f'/datadrive/CodeSearchNet/resources/data/{language}/final/jsonl/train')
# JGD for alon_encoder
def load_data(path):
contexts_file = path / f'contexts.csv'
# ast_contexts = list()
# with open(contexts_file, 'r') as file:
# context_lines = file.readlines()
# for context_line in context_lines:
# ast_paths = context_line.split()
# ast_contexts.append(ast_paths)
# print(f'contexts loaded from: {contexts_file}')
context_filename = str(contexts_file)
counters_file = path / f'counters.pkl'
with open(counters_file, 'rb') as file:
terminal_counter = pickle.load(file)
nonterminal_counter = pickle.load(file)
# print(f'counters loaded from: {counters_file}')
# return ast_contexts, terminal_counter, nonterminal_counter
return context_filename, terminal_counter, nonterminal_counter
def dump_data(terminal_counter, nonterminal_counter, path):
counters_file = path / f'counters.pkl'
with open(counters_file, 'wb') as file:
pickle.dump(terminal_counter, file)
pickle.dump(nonterminal_counter, file)
# print(f'counters saved to: {counters_file}')
def process_data(data, language='python', path=None):
success_num = 0
error_num = 0
terminal_counter = Counter()
nonterminal_counter = Counter()
for code in data:
try:
# identifiers = code2identifiers(code, language)
# print(identifiers)
# tree_paths = code2paths(code, language)
# print(tree_paths)
# JGD consider the top1M paths, just like in code2vec
tree_paths = code2paths(code, language)
# tree_paths = code2paths4py(code)
terminals, nonterminals = paths2tokens(tree_paths)
terminal_counter += Counter(terminals)
nonterminal_counter += Counter(nonterminals)
if path is None:
print('\n'.join(tree_paths))
else:
contexts_file = path / f'contexts.csv'
with open(contexts_file, 'a') as file:
file.write('\n'.join(tree_paths) + '\n')
# print(f'contexts saved to: {contexts_file}')
success_num += 1
print(f'success_num:{success_num}\t\terror_num:{error_num}', end='\r')
except (AttributeError, IndexError, SyntaxError, TypeError):
error_num += 1
traceback.print_exc()
return terminal_counter, nonterminal_counter
# return ast_contexts, None, None
def check_data(language='python', key='docstring_tokens'):
path = get_path(language, True)
print('A')
filenames = collect_filenames(path)
print('B')
print(filenames)
data = prepare_data(filenames, key)
print('C')
for datum in data:
print(datum)
def run4corpus(language='python', locally=False):
path = get_path(language, locally)
filenames = collect_filenames(path)
data = prepare_data(filenames)
terminal_counter, nonterminal_counter = process_data(data, language, path)
dump_data(terminal_counter, nonterminal_counter, path)
def run4file(language='python'):
path = Path()
filenames = ['python_test_0.jsonl.gz']
data = prepare_data(filenames)
terminal_counter, nonterminal_counter = process_data(data, language, path)
dump_data(terminal_counter, nonterminal_counter, path)
# print_data(terminal_counter, nonterminal_counter)
def run4demo():
go_code = """func (s *SkuM1Small) GetInnkeeperClient() (innkeeperclient.InnkeeperClient, error) {\n\tvar err error\n\tif s.Client == nil {\n\t\tif clnt, err := s.InitInnkeeperClient(); err == nil {\n\t\t\ts.Client = clnt\n\t\t} else {\n\t\t\tlo.G.Error(\"error parsing current cfenv: \", err.Error())\n\t\t}\n\t}\n\treturn s.Client, err\n}"""
java_code = """protected void notifyAttemptToReconnectIn(int seconds) {\n if (isReconnectionAllowed()) {\n for (ConnectionListener listener : connection.connectionListeners) {\n listener.reconnectingIn(seconds);\n }\n }\n }"""
javascript_code = """function (context, grunt) {\n this.context = context;\n this.grunt = grunt;\n\n // Merge task-specific and/or target-specific options with these defaults.\n this.options = context.options(defaultOptions);\n}"""
php_code = """public function init()\n {\n parent::init();\n if ($this->message === null) {\n $this->message = \\Reaction::t('rct', '{attribute} is invalid.');\n }\n }"""
python_code = """def get_url_args(url):\n \"\"\" Returns a dictionary from a URL params \"\"\"\n url_data = urllib.parse.urlparse(url)\n arg_dict = urllib.parse.parse_qs(url_data.query)\n return arg_dict"""
ruby_code = """def part(name)\n parts.select {|p| p.name.downcase == name.to_s.downcase }.first\n end"""
data = [go_code, java_code, javascript_code, php_code, python_code, ruby_code]
languages = ['go', 'java', 'javascript', 'php', 'python', 'ruby']
# process_data([go_code], 'go')
# process_data([java_code], 'java')
# process_data([javascript_code], 'javascript')
# process_data([php_code], 'php')
# process_data([python_code], 'python')
# process_data([ruby_code], 'ruby')
for code, language in zip(data, languages):
code2sexp(code, language)
# terminal_counter, nonterminal_counter = process_data([code], language)
# print_data(terminal_counter, nonterminal_counter)
| import pickle
import traceback
from collections import Counter
from glob import glob
from pathlib import Path
from dpu_utils.utils import load_jsonl_gz
from .ts import code2identifiers, code2paths, code2paths4py, code2sexp
# JGD for alon_encoder
def paths2tokens(paths):
paths = [path.split(',') for path in paths]
terminals = list()
nonterminals = []
items = map(lambda x: x[0] + '|' + x[2], paths)
for item in items:
terminals.extend(item.split('|'))
items = map(lambda x: x[1], paths)
for item in items:
nonterminals.extend(item.split('|'))
return terminals, nonterminals
def collect_filenames(path):
pattern = path / "**/*_0.jsonl.gz"
# pattern = path / "**/*.jsonl.gz"
filenames = glob(str(pattern), recursive=True)
return filenames
def prepare_data(filenames, key='code'):
for filename in filenames:
for sample in load_jsonl_gz(filename):
value = sample[key]
yield value
def print_data(terminal_counter, nonterminal_counter):
print(f'{"@" * 9}terminal_counter\n{terminal_counter}')
print(f'{"@" * 9}nonterminal_counter\n{nonterminal_counter}')
# JGD for alon_encoder
def get_path(language, locally=False):
if locally:
return Path(f'/home/jian/data/{language}/final/jsonl/train')
# path = Path(f'C:\\Users\\jian\\Documents\\Corpus\\{language}\\final\\jsonl\\train')
else:
return Path(f'/home/dev/resources/data/{language}/final/jsonl/train')
# path = Path(f'/datadrive/CodeSearchNet/resources/data/{language}/final/jsonl/train')
# JGD for alon_encoder
def load_data(path):
contexts_file = path / f'contexts.csv'
# ast_contexts = list()
# with open(contexts_file, 'r') as file:
# context_lines = file.readlines()
# for context_line in context_lines:
# ast_paths = context_line.split()
# ast_contexts.append(ast_paths)
# print(f'contexts loaded from: {contexts_file}')
context_filename = str(contexts_file)
counters_file = path / f'counters.pkl'
with open(counters_file, 'rb') as file:
terminal_counter = pickle.load(file)
nonterminal_counter = pickle.load(file)
# print(f'counters loaded from: {counters_file}')
# return ast_contexts, terminal_counter, nonterminal_counter
return context_filename, terminal_counter, nonterminal_counter
def dump_data(terminal_counter, nonterminal_counter, path):
counters_file = path / f'counters.pkl'
with open(counters_file, 'wb') as file:
pickle.dump(terminal_counter, file)
pickle.dump(nonterminal_counter, file)
# print(f'counters saved to: {counters_file}')
def process_data(data, language='python', path=None):
success_num = 0
error_num = 0
terminal_counter = Counter()
nonterminal_counter = Counter()
for code in data:
try:
# identifiers = code2identifiers(code, language)
# print(identifiers)
# tree_paths = code2paths(code, language)
# print(tree_paths)
# JGD consider the top1M paths, just like in code2vec
tree_paths = code2paths(code, language)
# tree_paths = code2paths4py(code)
terminals, nonterminals = paths2tokens(tree_paths)
terminal_counter += Counter(terminals)
nonterminal_counter += Counter(nonterminals)
if path is None:
print('\n'.join(tree_paths))
else:
contexts_file = path / f'contexts.csv'
with open(contexts_file, 'a') as file:
file.write('\n'.join(tree_paths) + '\n')
# print(f'contexts saved to: {contexts_file}')
success_num += 1
print(f'success_num:{success_num}\t\terror_num:{error_num}', end='\r')
except (AttributeError, IndexError, SyntaxError, TypeError):
error_num += 1
traceback.print_exc()
return terminal_counter, nonterminal_counter
# return ast_contexts, None, None
def check_data(language='python', key='docstring_tokens'):
path = get_path(language, True)
print('A')
filenames = collect_filenames(path)
print('B')
print(filenames)
data = prepare_data(filenames, key)
print('C')
for datum in data:
print(datum)
def run4corpus(language='python', locally=False):
path = get_path(language, locally)
filenames = collect_filenames(path)
data = prepare_data(filenames)
terminal_counter, nonterminal_counter = process_data(data, language, path)
dump_data(terminal_counter, nonterminal_counter, path)
def run4file(language='python'):
path = Path()
filenames = ['python_test_0.jsonl.gz']
data = prepare_data(filenames)
terminal_counter, nonterminal_counter = process_data(data, language, path)
dump_data(terminal_counter, nonterminal_counter, path)
# print_data(terminal_counter, nonterminal_counter)
def run4demo():
go_code = """func (s *SkuM1Small) GetInnkeeperClient() (innkeeperclient.InnkeeperClient, error) {\n\tvar err error\n\tif s.Client == nil {\n\t\tif clnt, err := s.InitInnkeeperClient(); err == nil {\n\t\t\ts.Client = clnt\n\t\t} else {\n\t\t\tlo.G.Error(\"error parsing current cfenv: \", err.Error())\n\t\t}\n\t}\n\treturn s.Client, err\n}"""
java_code = """protected void notifyAttemptToReconnectIn(int seconds) {\n if (isReconnectionAllowed()) {\n for (ConnectionListener listener : connection.connectionListeners) {\n listener.reconnectingIn(seconds);\n }\n }\n }"""
javascript_code = """function (context, grunt) {\n this.context = context;\n this.grunt = grunt;\n\n // Merge task-specific and/or target-specific options with these defaults.\n this.options = context.options(defaultOptions);\n}"""
php_code = """public function init()\n {\n parent::init();\n if ($this->message === null) {\n $this->message = \\Reaction::t('rct', '{attribute} is invalid.');\n }\n }"""
python_code = """def get_url_args(url):\n \"\"\" Returns a dictionary from a URL params \"\"\"\n url_data = urllib.parse.urlparse(url)\n arg_dict = urllib.parse.parse_qs(url_data.query)\n return arg_dict"""
ruby_code = """def part(name)\n parts.select {|p| p.name.downcase == name.to_s.downcase }.first\n end"""
data = [go_code, java_code, javascript_code, php_code, python_code, ruby_code]
languages = ['go', 'java', 'javascript', 'php', 'python', 'ruby']
# process_data([go_code], 'go')
# process_data([java_code], 'java')
# process_data([javascript_code], 'javascript')
# process_data([php_code], 'php')
# process_data([python_code], 'python')
# process_data([ruby_code], 'ruby')
for code, language in zip(data, languages):
code2sexp(code, language)
# terminal_counter, nonterminal_counter = process_data([code], language)
# print_data(terminal_counter, nonterminal_counter)
|
import math
import os
import re
from dataclasses import dataclass
from io import BytesIO
from typing import Dict, Callable, Tuple
from typing import List
from typing import Optional
from typing import Union
from urllib.parse import parse_qs, urlparse
import PIL
import requests
from PIL.Image import Image
from asyncpraw.models import Message
from asyncpraw.models import Submission
from bs4 import BeautifulSoup
import src.handler as handler_pkg
import src.model.result as result_pkg
from src.model.media_type import MediaType
from src.model.task_state import TaskConfigState
from src.model.task_state import TaskState
from src.util import exception, gif_utilities
from src.util.aux import Watermark
from src.util.aux import noop_image, fix_start_end_swap
from src.util.aux import watermark_image
from src.util.exception import TaskFailureException, OembedFailureException
from src.util.logger import root_logger, task_logger
@dataclass
class TaskConfig:
"""A task configuration which is not serializable.
Attributes:
message The reddit message object.
media_type The media type of the resource requested for cutting.
start The start time in milliseconds from where to cut the MediaType.
end The end time in milliseconds to stop the cut of the MediaType.
watermark An optional callable that watermarks the cut media.
state The state of this :class:~`TaskConfig`.
is_oembed A flag indicating if the media is embedded via the oEmbed format (https://oembed.com/).
is_video A flag indicating if the media is a video.
is_gif A flag indicating if the media is a gif.
is_crosspost A flag indicating if the media is crossposted.
media_url The url to the media.
duration The total duration of the media in seconds read from the `message`.
extension The file extension of the media.
"""
message: Message
media_type: MediaType
start: float
end: Optional[float]
watermark: Callable[[PIL.Image.Image], PIL.Image.Image]
def __init__(
self, message: Message, start: float, end: Optional[float], media_type: MediaType, watermark:
Optional[Watermark] = None
):
self.message = message
self.media_type = media_type
self.__is_video = self.media_type in [MediaType.MP4, MediaType.MOV, MediaType.WEBM]
self.__is_gif = self.media_type == MediaType.GIF
if hasattr(message.submission, 'crosspost_parent'):
self.__is_crosspost = message.submission.crosspost_parent is not None
else:
self.__is_crosspost = False
start_ms, end_ms = fix_start_end_swap(start=start, end=end)
start_ms = max(start_ms, 0) # put a realistic lower bound on end
if self.duration is not None:
# duration could be None here, will be computed in the specific handler
end_ms = min(end_ms or math.inf, self.duration * 1000) # put a realistic upper bound on end
self.start = start_ms
self.end = end_ms
self.watermark = noop_image if watermark is None else lambda img: watermark_image(img, watermark)
self._state = TaskConfigState.VALID
def __repr__(self) -> str:
return f'TaskConfig(message: {self.message}, media_type: {self.media_type}, start: {self.start}, ' \
f'end: {self.end}, watermark: {self.watermark}, state: {self.state}, is_oembed: {self.is_oembed}, ' \
f'is_video: {self.is_video}, is_gif: {self.is_gif}, is_crosspost: {self.is_crosspost}, ' \
f'duration: {self.duration}, extension: {self.extension}, media_url: {self.media_url})'
@property
def state(self) -> TaskConfigState:
return self._state
def is_state(self, state: Union[TaskConfigState, List[TaskConfigState]]) -> bool:
return self._state in state if state is List else self._state == state
@property
def is_oembed(self) -> bool:
# full oembed spec: https://oembed.com/#section2
# media is a dynamic attribute on submission
if not hasattr(self.message.submission, 'media'):
return False
return bool(self.message.submission.media.get('oembed', False))
@property
def is_video(self) -> bool:
return self.__is_video
@property
def is_gif(self) -> bool:
return self.__is_gif
@property
def is_crosspost(self) -> bool:
return self.__is_crosspost
@property
def media_url(self) -> str:
# todo do this in __init__ and store in a "_variable"
_submission: Submission = self.message.submission
if self.is_oembed:
return self.__get_oembed()[0]
elif self.is_gif:
if self.is_crosspost:
return '' # todo
else:
return _submission.url
elif self.is_video:
if self.is_crosspost:
reddit_video = _submission.crosspost_parent_list[0].get('secure_media').get('reddit_video')
else:
reddit_video = _submission.secure_media.get('reddit_video', {})
media_url = reddit_video.get('fallback_url', '')
if media_url == '':
self._state = TaskConfigState.INVALID
return media_url
else:
raise exception.TaskConfigFailureException('Cannot parse attribute media_url.')
@property
def duration(self) -> Optional[float]:
# todo do this in __init__ and store in a "_variable"
if self.is_gif:
# AFAIK there is no duration sent when we are dealing with a GIF
with requests.get(self.media_url, stream=True) as resp:
if resp.ok:
self._state = TaskConfigState.VALID
# read whole file via StreamReader into BytesIO
_stream = BytesIO(resp.raw.read())
_stream.seek(0)
return gif_utilities.get_gif_duration(image=PIL.Image.open(_stream))
else:
self._state = TaskConfigState.INVALID
return math.nan
elif self.is_video:
_submission: Submission = self.message.submission
if self.is_crosspost:
reddit_video = _submission.crosspost_parent_list[0].get('secure_media').get('reddit_video')
else:
reddit_video = _submission.secure_media.get('reddit_video', {})
return reddit_video.get('duration')
else:
# self._state = TaskState.INVALID # duration will be computed in the specific handler if None
return None
@property
def extension(self) -> Optional[str]:
# todo do this in __init__ and store in a "_variable"
ext: Optional[str]
_submission: Submission = self.message.submission
if self.is_oembed:
return self.__get_oembed()[-1]
elif self.is_gif:
if self.is_crosspost:
ext = None # todo how to handle crossposted gifs?
else:
ext = os.path.splitext(_submission.url)[-1][1:]
elif self.is_video:
if self.is_crosspost:
# todo make sure it always works with index 0 (should be the first post)
reddit_video = _submission.crosspost_parent_list[0].get('secure_media').get('reddit_video')
else:
reddit_video = _submission.secure_media.get('reddit_video', {})
ext = os.path.splitext(reddit_video.get('scrubber_media_url', [' ']))[-1][1:]
else:
self._state = TaskState.INVALID
ext = None
if ext == '' or ext is None:
ext = None
self._state = TaskConfigState.INVALID
return ext
def __get_oembed(self) -> Tuple[str, str, str]:
"""Returns a tuple with the source url, the media MIME-type and the media extension.
"""
oembed: Dict = self.message.submission.media.get('oembed', {})
html_string: str
try:
html_string = oembed['html']
except KeyError:
html_string = oembed['url']
if not isinstance(html_string, str):
task_logger.error('Failed to obtain the HTML of the oEmbed.')
soup = BeautifulSoup(html_string, features='html.parser')
try:
# todo proper error handling! this has only been validated with gfycat
src_url = parse_qs(urlparse(soup.iframe.get('src'))[4]).get('src')[0]
another_soup = BeautifulSoup(requests.get(src_url).content, features='html.parser')
source_tag = another_soup.video.findAll(name='source')[1]
ext: str = os.path.splitext(source_tag['src'])[-1][1:]
return source_tag['src'], source_tag['type'], ext
except Exception as ex:
task_logger.error(f'Encountered oEmbed provider {oembed.get('provider_name')}.\n{ex}')
raise OembedFailureException()
class TaskConfigFactory(TaskConfig):
state: TaskConfigState = TaskConfigState.VALID
@classmethod
def from_message(cls, message: Message) -> TaskConfig:
_config = {
'message': message,
'media_type': cls.__get_media_type(message),
**cls.__parse_start_and_end(message),
}
return TaskConfig(**_config)
@classmethod
def __is_crosspost(cls, message: Message) -> bool:
if hasattr(message.submission, 'crosspost_parent'):
return message.submission.crosspost_parent is not None
return False
@classmethod
def __is_video(cls, message: Message) -> bool:
if cls.__is_crosspost(message=message):
return message.submission.crosspost_parent_list[-1].get('is_video', False)
return message.submission.is_video
@classmethod
def __is_gif(cls, message: Message) -> bool:
if cls.__is_crosspost(message=message):
return False # todo
if message.submission.url:
return os.path.splitext(message.submission.url)[-1][1:] == 'gif'
return False
@classmethod
def __is_oembed(cls, message: Message):
# full oembed spec: https://oembed.com/#section2
# media is a dynamic attribute on submission
if not hasattr(message.submission, 'media'):
return False
return bool(message.submission.media.get('oembed', False))
@classmethod
def __parse_start_and_end(cls, message: Message) -> Dict[str, float]:
params = {}
pattern = re.compile(r'(s|start)=([\d]+) (e|end)=([\d]+)', re.IGNORECASE)
matches = pattern.search(message.body)
if matches is None:
root_logger.warning('Skipping message because no match was found.')
cls.state = TaskConfigState.INVALID
return {}
root_logger.debug(f'Found pattern matches: {matches.groups()}')
params['start'] = int(matches.group(2))
params['end'] = int(matches.group(4))
return params
@classmethod
def __get_media_type(cls, message: Message) -> Union[MediaType, None]:
if cls.__is_video(message=message):
# get video from original post (apparently we can only get it from there so we do the the backtrace)
if cls.__is_crosspost(message=message):
reddit_video = message.submission.crosspost_parent_list[0].get('secure_media').get('reddit_video')
else:
reddit_video = message.submission.secure_media.get('reddit_video', {})
ext: str = os.path.splitext(reddit_video.get('scrubber_media_url', [' ']))[-1][1:]
if ext == '':
cls.state = TaskConfigState.INVALID
return None
return MediaType[ext.upper()]
elif cls.__is_gif(message=message):
return MediaType.GIF
elif cls.__is_oembed(message=message):
oembed: Dict = message.submission.media.get('oembed', {})
html_string: str
try:
html_string = oembed['html']
except KeyError:
html_string = oembed['url']
if not isinstance(html_string, str):
task_logger.error('Failed to obtain the HTML of the oEmbed.')
soup = BeautifulSoup(html_string, features='html.parser')
try:
# todo proper error handling! this has only been validated with
src_url = parse_qs(urlparse(soup.iframe.get('src'))[4]).get('src')[0]
another_soup = BeautifulSoup(requests.get(src_url).content, features='html.parser')
source_tag = another_soup.video.findAll(name='source')[1]
ext: str = os.path.splitext(source_tag['src'])[-1][1:]
return MediaType[ext.upper()]
except Exception as ex:
task_logger.error(f'Encountered oEmbed provider {oembed.get('provider_name')}.\n{ex}')
else:
cls.state = TaskConfigState.INVALID
return None
class Task(object):
def __init__(self, config: TaskConfig):
self.__config: TaskConfig = config
self._task_state = TaskState.VALID
self._select_handler()
def __call__(self, *args, **kwargs):
return self.handle()
@property
def state(self):
return self._task_state
def is_state(self, state: Union[TaskState, List[TaskState]]) -> bool:
if state is List:
return self._task_state in state
return self._task_state == state
def _select_handler(self):
mt: MediaType = self.__config.media_type
if mt == MediaType.GIF:
self._task_handler = handler_pkg.gif.GifCutHandler()
elif mt in [MediaType.MP4, MediaType.MOV, MediaType.WEBM]:
self._task_handler = handler_pkg.video.VideoCutHandler()
else:
self._task_state = TaskState.DROP
# self._task_handler = TestCutHandler()
root_logger.warning(f'No handler for media type: {mt}')
def handle(self) -> result_pkg.Result:
_stream: Optional[BytesIO] = self._fetch_stream()
if self._task_state == TaskState.INVALID:
raise TaskFailureException('Failed to fetch stream from host!')
_result: result_pkg.Result = self._task_handler.cut(stream=_stream, config=self.__config)
self._task_state = TaskState.DONE
return _result
def _fetch_stream(self) -> Optional[BytesIO]:
_stream: BytesIO
media_url: str = self.__config.media_url
with requests.get(media_url, stream=True) as r:
if r.status_code == 200:
self._task_state = TaskState.VALID
_stream = BytesIO(r.raw.read())
else:
self._task_state = TaskState.INVALID
return None
return _stream
@property
def config(self):
return self.__config
| import math
import os
import re
from dataclasses import dataclass
from io import BytesIO
from typing import Dict, Callable, Tuple
from typing import List
from typing import Optional
from typing import Union
from urllib.parse import parse_qs, urlparse
import PIL
import requests
from PIL.Image import Image
from asyncpraw.models import Message
from asyncpraw.models import Submission
from bs4 import BeautifulSoup
import src.handler as handler_pkg
import src.model.result as result_pkg
from src.model.media_type import MediaType
from src.model.task_state import TaskConfigState
from src.model.task_state import TaskState
from src.util import exception, gif_utilities
from src.util.aux import Watermark
from src.util.aux import noop_image, fix_start_end_swap
from src.util.aux import watermark_image
from src.util.exception import TaskFailureException, OembedFailureException
from src.util.logger import root_logger, task_logger
@dataclass
class TaskConfig:
"""A task configuration which is not serializable.
Attributes:
message The reddit message object.
media_type The media type of the resource requested for cutting.
start The start time in milliseconds from where to cut the MediaType.
end The end time in milliseconds to stop the cut of the MediaType.
watermark An optional callable that watermarks the cut media.
state The state of this :class:~`TaskConfig`.
is_oembed A flag indicating if the media is embedded via the oEmbed format (https://oembed.com/).
is_video A flag indicating if the media is a video.
is_gif A flag indicating if the media is a gif.
is_crosspost A flag indicating if the media is crossposted.
media_url The url to the media.
duration The total duration of the media in seconds read from the `message`.
extension The file extension of the media.
"""
message: Message
media_type: MediaType
start: float
end: Optional[float]
watermark: Callable[[PIL.Image.Image], PIL.Image.Image]
def __init__(
self, message: Message, start: float, end: Optional[float], media_type: MediaType, watermark:
Optional[Watermark] = None
):
self.message = message
self.media_type = media_type
self.__is_video = self.media_type in [MediaType.MP4, MediaType.MOV, MediaType.WEBM]
self.__is_gif = self.media_type == MediaType.GIF
if hasattr(message.submission, 'crosspost_parent'):
self.__is_crosspost = message.submission.crosspost_parent is not None
else:
self.__is_crosspost = False
start_ms, end_ms = fix_start_end_swap(start=start, end=end)
start_ms = max(start_ms, 0) # put a realistic lower bound on end
if self.duration is not None:
# duration could be None here, will be computed in the specific handler
end_ms = min(end_ms or math.inf, self.duration * 1000) # put a realistic upper bound on end
self.start = start_ms
self.end = end_ms
self.watermark = noop_image if watermark is None else lambda img: watermark_image(img, watermark)
self._state = TaskConfigState.VALID
def __repr__(self) -> str:
return f'TaskConfig(message: {self.message}, media_type: {self.media_type}, start: {self.start}, ' \
f'end: {self.end}, watermark: {self.watermark}, state: {self.state}, is_oembed: {self.is_oembed}, ' \
f'is_video: {self.is_video}, is_gif: {self.is_gif}, is_crosspost: {self.is_crosspost}, ' \
f'duration: {self.duration}, extension: {self.extension}, media_url: {self.media_url})'
@property
def state(self) -> TaskConfigState:
return self._state
def is_state(self, state: Union[TaskConfigState, List[TaskConfigState]]) -> bool:
return self._state in state if state is List else self._state == state
@property
def is_oembed(self) -> bool:
# full oembed spec: https://oembed.com/#section2
# media is a dynamic attribute on submission
if not hasattr(self.message.submission, 'media'):
return False
return bool(self.message.submission.media.get('oembed', False))
@property
def is_video(self) -> bool:
return self.__is_video
@property
def is_gif(self) -> bool:
return self.__is_gif
@property
def is_crosspost(self) -> bool:
return self.__is_crosspost
@property
def media_url(self) -> str:
# todo do this in __init__ and store in a "_variable"
_submission: Submission = self.message.submission
if self.is_oembed:
return self.__get_oembed()[0]
elif self.is_gif:
if self.is_crosspost:
return '' # todo
else:
return _submission.url
elif self.is_video:
if self.is_crosspost:
reddit_video = _submission.crosspost_parent_list[0].get('secure_media').get('reddit_video')
else:
reddit_video = _submission.secure_media.get('reddit_video', {})
media_url = reddit_video.get('fallback_url', '')
if media_url == '':
self._state = TaskConfigState.INVALID
return media_url
else:
raise exception.TaskConfigFailureException('Cannot parse attribute media_url.')
@property
def duration(self) -> Optional[float]:
# todo do this in __init__ and store in a "_variable"
if self.is_gif:
# AFAIK there is no duration sent when we are dealing with a GIF
with requests.get(self.media_url, stream=True) as resp:
if resp.ok:
self._state = TaskConfigState.VALID
# read whole file via StreamReader into BytesIO
_stream = BytesIO(resp.raw.read())
_stream.seek(0)
return gif_utilities.get_gif_duration(image=PIL.Image.open(_stream))
else:
self._state = TaskConfigState.INVALID
return math.nan
elif self.is_video:
_submission: Submission = self.message.submission
if self.is_crosspost:
reddit_video = _submission.crosspost_parent_list[0].get('secure_media').get('reddit_video')
else:
reddit_video = _submission.secure_media.get('reddit_video', {})
return reddit_video.get('duration')
else:
# self._state = TaskState.INVALID # duration will be computed in the specific handler if None
return None
@property
def extension(self) -> Optional[str]:
# todo do this in __init__ and store in a "_variable"
ext: Optional[str]
_submission: Submission = self.message.submission
if self.is_oembed:
return self.__get_oembed()[-1]
elif self.is_gif:
if self.is_crosspost:
ext = None # todo how to handle crossposted gifs?
else:
ext = os.path.splitext(_submission.url)[-1][1:]
elif self.is_video:
if self.is_crosspost:
# todo make sure it always works with index 0 (should be the first post)
reddit_video = _submission.crosspost_parent_list[0].get('secure_media').get('reddit_video')
else:
reddit_video = _submission.secure_media.get('reddit_video', {})
ext = os.path.splitext(reddit_video.get('scrubber_media_url', [' ']))[-1][1:]
else:
self._state = TaskState.INVALID
ext = None
if ext == '' or ext is None:
ext = None
self._state = TaskConfigState.INVALID
return ext
def __get_oembed(self) -> Tuple[str, str, str]:
"""Returns a tuple with the source url, the media MIME-type and the media extension.
"""
oembed: Dict = self.message.submission.media.get('oembed', {})
html_string: str
try:
html_string = oembed['html']
except KeyError:
html_string = oembed['url']
if not isinstance(html_string, str):
task_logger.error('Failed to obtain the HTML of the oEmbed.')
soup = BeautifulSoup(html_string, features='html.parser')
try:
# todo proper error handling! this has only been validated with gfycat
src_url = parse_qs(urlparse(soup.iframe.get('src'))[4]).get('src')[0]
another_soup = BeautifulSoup(requests.get(src_url).content, features='html.parser')
source_tag = another_soup.video.findAll(name='source')[1]
ext: str = os.path.splitext(source_tag['src'])[-1][1:]
return source_tag['src'], source_tag['type'], ext
except Exception as ex:
task_logger.error(f'Encountered oEmbed provider {oembed.get("provider_name")}.\n{ex}')
raise OembedFailureException()
class TaskConfigFactory(TaskConfig):
state: TaskConfigState = TaskConfigState.VALID
@classmethod
def from_message(cls, message: Message) -> TaskConfig:
_config = {
'message': message,
'media_type': cls.__get_media_type(message),
**cls.__parse_start_and_end(message),
}
return TaskConfig(**_config)
@classmethod
def __is_crosspost(cls, message: Message) -> bool:
if hasattr(message.submission, 'crosspost_parent'):
return message.submission.crosspost_parent is not None
return False
@classmethod
def __is_video(cls, message: Message) -> bool:
if cls.__is_crosspost(message=message):
return message.submission.crosspost_parent_list[-1].get('is_video', False)
return message.submission.is_video
@classmethod
def __is_gif(cls, message: Message) -> bool:
if cls.__is_crosspost(message=message):
return False # todo
if message.submission.url:
return os.path.splitext(message.submission.url)[-1][1:] == 'gif'
return False
@classmethod
def __is_oembed(cls, message: Message):
# full oembed spec: https://oembed.com/#section2
# media is a dynamic attribute on submission
if not hasattr(message.submission, 'media'):
return False
return bool(message.submission.media.get('oembed', False))
@classmethod
def __parse_start_and_end(cls, message: Message) -> Dict[str, float]:
params = {}
pattern = re.compile(r'(s|start)=([\d]+) (e|end)=([\d]+)', re.IGNORECASE)
matches = pattern.search(message.body)
if matches is None:
root_logger.warning('Skipping message because no match was found.')
cls.state = TaskConfigState.INVALID
return {}
root_logger.debug(f'Found pattern matches: {matches.groups()}')
params['start'] = int(matches.group(2))
params['end'] = int(matches.group(4))
return params
@classmethod
def __get_media_type(cls, message: Message) -> Union[MediaType, None]:
if cls.__is_video(message=message):
# get video from original post (apparently we can only get it from there so we do the the backtrace)
if cls.__is_crosspost(message=message):
reddit_video = message.submission.crosspost_parent_list[0].get('secure_media').get('reddit_video')
else:
reddit_video = message.submission.secure_media.get('reddit_video', {})
ext: str = os.path.splitext(reddit_video.get('scrubber_media_url', [' ']))[-1][1:]
if ext == '':
cls.state = TaskConfigState.INVALID
return None
return MediaType[ext.upper()]
elif cls.__is_gif(message=message):
return MediaType.GIF
elif cls.__is_oembed(message=message):
oembed: Dict = message.submission.media.get('oembed', {})
html_string: str
try:
html_string = oembed['html']
except KeyError:
html_string = oembed['url']
if not isinstance(html_string, str):
task_logger.error('Failed to obtain the HTML of the oEmbed.')
soup = BeautifulSoup(html_string, features='html.parser')
try:
# todo proper error handling! this has only been validated with
src_url = parse_qs(urlparse(soup.iframe.get('src'))[4]).get('src')[0]
another_soup = BeautifulSoup(requests.get(src_url).content, features='html.parser')
source_tag = another_soup.video.findAll(name='source')[1]
ext: str = os.path.splitext(source_tag['src'])[-1][1:]
return MediaType[ext.upper()]
except Exception as ex:
task_logger.error(f'Encountered oEmbed provider {oembed.get("provider_name")}.\n{ex}')
else:
cls.state = TaskConfigState.INVALID
return None
class Task(object):
def __init__(self, config: TaskConfig):
self.__config: TaskConfig = config
self._task_state = TaskState.VALID
self._select_handler()
def __call__(self, *args, **kwargs):
return self.handle()
@property
def state(self):
return self._task_state
def is_state(self, state: Union[TaskState, List[TaskState]]) -> bool:
if state is List:
return self._task_state in state
return self._task_state == state
def _select_handler(self):
mt: MediaType = self.__config.media_type
if mt == MediaType.GIF:
self._task_handler = handler_pkg.gif.GifCutHandler()
elif mt in [MediaType.MP4, MediaType.MOV, MediaType.WEBM]:
self._task_handler = handler_pkg.video.VideoCutHandler()
else:
self._task_state = TaskState.DROP
# self._task_handler = TestCutHandler()
root_logger.warning(f'No handler for media type: {mt}')
def handle(self) -> result_pkg.Result:
_stream: Optional[BytesIO] = self._fetch_stream()
if self._task_state == TaskState.INVALID:
raise TaskFailureException('Failed to fetch stream from host!')
_result: result_pkg.Result = self._task_handler.cut(stream=_stream, config=self.__config)
self._task_state = TaskState.DONE
return _result
def _fetch_stream(self) -> Optional[BytesIO]:
_stream: BytesIO
media_url: str = self.__config.media_url
with requests.get(media_url, stream=True) as r:
if r.status_code == 200:
self._task_state = TaskState.VALID
_stream = BytesIO(r.raw.read())
else:
self._task_state = TaskState.INVALID
return None
return _stream
@property
def config(self):
return self.__config
|
import asyncio
import json
import logging
import traceback
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
import aiohttp
from joker.rpc.util import wrap_http_handler
from joker.server.outbound_message import NodeType
from joker.server.server import ssl_context_for_server
from joker.types.peer_info import PeerInfo
from joker.util.byte_types import hexstr_to_bytes
from joker.util.ints import uint16
from joker.util.json_util import dict_to_json_str
from joker.util.ws_message import create_payload, create_payload_dict, format_response, pong
log = logging.getLogger(__name__)
class RpcServer:
"""
Implementation of RPC server.
"""
def __init__(self, rpc_api: Any, service_name: str, stop_cb: Callable, root_path, net_config):
self.rpc_api = rpc_api
self.stop_cb: Callable = stop_cb
self.log = log
self.shut_down = False
self.websocket: Optional[aiohttp.ClientWebSocketResponse] = None
self.service_name = service_name
self.root_path = root_path
self.net_config = net_config
self.crt_path = root_path / net_config["daemon_ssl"]["private_crt"]
self.key_path = root_path / net_config["daemon_ssl"]["private_key"]
self.ca_cert_path = root_path / net_config["private_ssl_ca"]["crt"]
self.ca_key_path = root_path / net_config["private_ssl_ca"]["key"]
self.ssl_context = ssl_context_for_server(
self.ca_cert_path, self.ca_key_path, self.crt_path, self.key_path, log=self.log
)
async def stop(self):
self.shut_down = True
if self.websocket is not None:
await self.websocket.close()
async def _state_changed(self, *args):
if self.websocket is None:
return None
payloads: List[Dict] = await self.rpc_api._state_changed(*args)
change = args[0]
if change == "add_connection" or change == "close_connection" or change == "peer_changed_peak":
data = await self.get_connections({})
if data is not None:
payload = create_payload_dict(
"get_connections",
data,
self.service_name,
"wallet_ui",
)
payloads.append(payload)
for payload in payloads:
if "success" not in payload["data"]:
payload["data"]["success"] = True
if self.websocket is None:
return None
try:
await self.websocket.send_str(dict_to_json_str(payload))
except Exception:
tb = traceback.format_exc()
self.log.warning(f"Sending data failed. Exception {tb}.")
def state_changed(self, *args):
if self.websocket is None:
return None
asyncio.create_task(self._state_changed(*args))
def get_routes(self) -> Dict[str, Callable]:
return {
**self.rpc_api.get_routes(),
"/get_connections": self.get_connections,
"/open_connection": self.open_connection,
"/close_connection": self.close_connection,
"/stop_node": self.stop_node,
"/get_routes": self._get_routes,
}
async def _get_routes(self, request: Dict) -> Dict:
return {
"success": "true",
"routes": list(self.get_routes().keys()),
}
async def get_connections(self, request: Dict) -> Dict:
request_node_type: Optional[NodeType] = None
if "node_type" in request:
request_node_type = NodeType(request["node_type"])
if self.rpc_api.service.server is None:
raise ValueError("Global connections is not set")
if self.rpc_api.service.server._local_type is NodeType.FULL_NODE:
# TODO add peaks for peers
connections = self.rpc_api.service.server.get_connections(request_node_type)
con_info = []
if self.rpc_api.service.sync_store is not None:
peak_store = self.rpc_api.service.sync_store.peer_to_peak
else:
peak_store = None
for con in connections:
if peak_store is not None and con.peer_node_id in peak_store:
peak_hash, peak_height, peak_weight = peak_store[con.peer_node_id]
else:
peak_height = None
peak_hash = None
peak_weight = None
con_dict = {
"type": con.connection_type,
"local_port": con.local_port,
"peer_host": con.peer_host,
"peer_port": con.peer_port,
"peer_server_port": con.peer_server_port,
"node_id": con.peer_node_id,
"creation_time": con.creation_time,
"bytes_read": con.bytes_read,
"bytes_written": con.bytes_written,
"last_message_time": con.last_message_time,
"peak_height": peak_height,
"peak_weight": peak_weight,
"peak_hash": peak_hash,
}
con_info.append(con_dict)
else:
connections = self.rpc_api.service.server.get_connections(request_node_type)
con_info = [
{
"type": con.connection_type,
"local_port": con.local_port,
"peer_host": con.peer_host,
"peer_port": con.peer_port,
"peer_server_port": con.peer_server_port,
"node_id": con.peer_node_id,
"creation_time": con.creation_time,
"bytes_read": con.bytes_read,
"bytes_written": con.bytes_written,
"last_message_time": con.last_message_time,
}
for con in connections
]
return {"connections": con_info}
async def open_connection(self, request: Dict):
host = request["host"]
port = request["port"]
target_node: PeerInfo = PeerInfo(host, uint16(int(port)))
on_connect = None
if hasattr(self.rpc_api.service, "on_connect"):
on_connect = self.rpc_api.service.on_connect
if getattr(self.rpc_api.service, "server", None) is None or not (
await self.rpc_api.service.server.start_client(target_node, on_connect)
):
raise ValueError("Start client failed, or server is not set")
return {}
async def close_connection(self, request: Dict):
node_id = hexstr_to_bytes(request["node_id"])
if self.rpc_api.service.server is None:
raise aiohttp.web.HTTPInternalServerError()
connections_to_close = [c for c in self.rpc_api.service.server.get_connections() if c.peer_node_id == node_id]
if len(connections_to_close) == 0:
raise ValueError(f"Connection with node_id {node_id.hex()} does not exist")
for connection in connections_to_close:
await connection.close()
return {}
async def stop_node(self, request):
"""
Shuts down the node.
"""
if self.stop_cb is not None:
self.stop_cb()
return {}
async def ws_api(self, message):
"""
This function gets called when new message is received via websocket.
"""
command = message["command"]
if message["ack"]:
return None
data = None
if "data" in message:
data = message["data"]
if command == "ping":
return pong()
f = getattr(self, command, None)
if f is not None:
return await f(data)
f = getattr(self.rpc_api, command, None)
if f is not None:
return await f(data)
raise ValueError(f"unknown_command {command}")
async def safe_handle(self, websocket, payload):
message = None
try:
message = json.loads(payload)
self.log.debug(f"Rpc call <- {message["command"]}")
response = await self.ws_api(message)
# Only respond if we return something from api call
if response is not None:
log.debug(f"Rpc response -> {message["command"]}")
# Set success to true automatically (unless it's already set)
if "success" not in response:
response["success"] = True
await websocket.send_str(format_response(message, response))
except Exception as e:
tb = traceback.format_exc()
self.log.warning(f"Error while handling message: {tb}")
if message is not None:
error = e.args[0] if e.args else e
res = {"success": False, "error": f"{error}"}
await websocket.send_str(format_response(message, res))
async def connection(self, ws):
data = {"service": self.service_name}
payload = create_payload("register_service", data, self.service_name, "daemon")
await ws.send_str(payload)
while True:
msg = await ws.receive()
if msg.type == aiohttp.WSMsgType.TEXT:
message = msg.data.strip()
# self.log.info(f"received message: {message}")
await self.safe_handle(ws, message)
elif msg.type == aiohttp.WSMsgType.BINARY:
self.log.debug("Received binary data")
elif msg.type == aiohttp.WSMsgType.PING:
self.log.debug("Ping received")
await ws.pong()
elif msg.type == aiohttp.WSMsgType.PONG:
self.log.debug("Pong received")
else:
if msg.type == aiohttp.WSMsgType.CLOSE:
self.log.debug("Closing RPC websocket")
await ws.close()
elif msg.type == aiohttp.WSMsgType.ERROR:
self.log.error("Error during receive %s" % ws.exception())
elif msg.type == aiohttp.WSMsgType.CLOSED:
pass
break
await ws.close()
async def connect_to_daemon(self, self_hostname: str, daemon_port: uint16):
while True:
try:
if self.shut_down:
break
async with aiohttp.ClientSession() as session:
async with session.ws_connect(
f"wss://{self_hostname}:{daemon_port}",
autoclose=True,
autoping=True,
heartbeat=60,
ssl_context=self.ssl_context,
max_msg_size=100 * 1024 * 1024,
) as ws:
self.websocket = ws
await self.connection(ws)
self.websocket = None
except aiohttp.ClientConnectorError:
self.log.warning(f"Cannot connect to daemon at ws://{self_hostname}:{daemon_port}")
except Exception as e:
tb = traceback.format_exc()
self.log.warning(f"Exception: {tb} {type(e)}")
await asyncio.sleep(2)
async def start_rpc_server(
rpc_api: Any,
self_hostname: str,
daemon_port: uint16,
rpc_port: uint16,
stop_cb: Callable,
root_path: Path,
net_config,
connect_to_daemon=True,
):
"""
Starts an HTTP server with the following RPC methods, to be used by local clients to
query the node.
"""
app = aiohttp.web.Application()
rpc_server = RpcServer(rpc_api, rpc_api.service_name, stop_cb, root_path, net_config)
rpc_server.rpc_api.service._set_state_changed_callback(rpc_server.state_changed)
app.add_routes(
[aiohttp.web.post(route, wrap_http_handler(func)) for (route, func) in rpc_server.get_routes().items()]
)
if connect_to_daemon:
daemon_connection = asyncio.create_task(rpc_server.connect_to_daemon(self_hostname, daemon_port))
runner = aiohttp.web.AppRunner(app, access_log=None)
await runner.setup()
site = aiohttp.web.TCPSite(runner, self_hostname, int(rpc_port), ssl_context=rpc_server.ssl_context)
await site.start()
async def cleanup():
await rpc_server.stop()
await runner.cleanup()
if connect_to_daemon:
await daemon_connection
return cleanup
| import asyncio
import json
import logging
import traceback
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
import aiohttp
from joker.rpc.util import wrap_http_handler
from joker.server.outbound_message import NodeType
from joker.server.server import ssl_context_for_server
from joker.types.peer_info import PeerInfo
from joker.util.byte_types import hexstr_to_bytes
from joker.util.ints import uint16
from joker.util.json_util import dict_to_json_str
from joker.util.ws_message import create_payload, create_payload_dict, format_response, pong
log = logging.getLogger(__name__)
class RpcServer:
"""
Implementation of RPC server.
"""
def __init__(self, rpc_api: Any, service_name: str, stop_cb: Callable, root_path, net_config):
self.rpc_api = rpc_api
self.stop_cb: Callable = stop_cb
self.log = log
self.shut_down = False
self.websocket: Optional[aiohttp.ClientWebSocketResponse] = None
self.service_name = service_name
self.root_path = root_path
self.net_config = net_config
self.crt_path = root_path / net_config["daemon_ssl"]["private_crt"]
self.key_path = root_path / net_config["daemon_ssl"]["private_key"]
self.ca_cert_path = root_path / net_config["private_ssl_ca"]["crt"]
self.ca_key_path = root_path / net_config["private_ssl_ca"]["key"]
self.ssl_context = ssl_context_for_server(
self.ca_cert_path, self.ca_key_path, self.crt_path, self.key_path, log=self.log
)
async def stop(self):
self.shut_down = True
if self.websocket is not None:
await self.websocket.close()
async def _state_changed(self, *args):
if self.websocket is None:
return None
payloads: List[Dict] = await self.rpc_api._state_changed(*args)
change = args[0]
if change == "add_connection" or change == "close_connection" or change == "peer_changed_peak":
data = await self.get_connections({})
if data is not None:
payload = create_payload_dict(
"get_connections",
data,
self.service_name,
"wallet_ui",
)
payloads.append(payload)
for payload in payloads:
if "success" not in payload["data"]:
payload["data"]["success"] = True
if self.websocket is None:
return None
try:
await self.websocket.send_str(dict_to_json_str(payload))
except Exception:
tb = traceback.format_exc()
self.log.warning(f"Sending data failed. Exception {tb}.")
def state_changed(self, *args):
if self.websocket is None:
return None
asyncio.create_task(self._state_changed(*args))
def get_routes(self) -> Dict[str, Callable]:
return {
**self.rpc_api.get_routes(),
"/get_connections": self.get_connections,
"/open_connection": self.open_connection,
"/close_connection": self.close_connection,
"/stop_node": self.stop_node,
"/get_routes": self._get_routes,
}
async def _get_routes(self, request: Dict) -> Dict:
return {
"success": "true",
"routes": list(self.get_routes().keys()),
}
async def get_connections(self, request: Dict) -> Dict:
request_node_type: Optional[NodeType] = None
if "node_type" in request:
request_node_type = NodeType(request["node_type"])
if self.rpc_api.service.server is None:
raise ValueError("Global connections is not set")
if self.rpc_api.service.server._local_type is NodeType.FULL_NODE:
# TODO add peaks for peers
connections = self.rpc_api.service.server.get_connections(request_node_type)
con_info = []
if self.rpc_api.service.sync_store is not None:
peak_store = self.rpc_api.service.sync_store.peer_to_peak
else:
peak_store = None
for con in connections:
if peak_store is not None and con.peer_node_id in peak_store:
peak_hash, peak_height, peak_weight = peak_store[con.peer_node_id]
else:
peak_height = None
peak_hash = None
peak_weight = None
con_dict = {
"type": con.connection_type,
"local_port": con.local_port,
"peer_host": con.peer_host,
"peer_port": con.peer_port,
"peer_server_port": con.peer_server_port,
"node_id": con.peer_node_id,
"creation_time": con.creation_time,
"bytes_read": con.bytes_read,
"bytes_written": con.bytes_written,
"last_message_time": con.last_message_time,
"peak_height": peak_height,
"peak_weight": peak_weight,
"peak_hash": peak_hash,
}
con_info.append(con_dict)
else:
connections = self.rpc_api.service.server.get_connections(request_node_type)
con_info = [
{
"type": con.connection_type,
"local_port": con.local_port,
"peer_host": con.peer_host,
"peer_port": con.peer_port,
"peer_server_port": con.peer_server_port,
"node_id": con.peer_node_id,
"creation_time": con.creation_time,
"bytes_read": con.bytes_read,
"bytes_written": con.bytes_written,
"last_message_time": con.last_message_time,
}
for con in connections
]
return {"connections": con_info}
async def open_connection(self, request: Dict):
host = request["host"]
port = request["port"]
target_node: PeerInfo = PeerInfo(host, uint16(int(port)))
on_connect = None
if hasattr(self.rpc_api.service, "on_connect"):
on_connect = self.rpc_api.service.on_connect
if getattr(self.rpc_api.service, "server", None) is None or not (
await self.rpc_api.service.server.start_client(target_node, on_connect)
):
raise ValueError("Start client failed, or server is not set")
return {}
async def close_connection(self, request: Dict):
node_id = hexstr_to_bytes(request["node_id"])
if self.rpc_api.service.server is None:
raise aiohttp.web.HTTPInternalServerError()
connections_to_close = [c for c in self.rpc_api.service.server.get_connections() if c.peer_node_id == node_id]
if len(connections_to_close) == 0:
raise ValueError(f"Connection with node_id {node_id.hex()} does not exist")
for connection in connections_to_close:
await connection.close()
return {}
async def stop_node(self, request):
"""
Shuts down the node.
"""
if self.stop_cb is not None:
self.stop_cb()
return {}
async def ws_api(self, message):
"""
This function gets called when new message is received via websocket.
"""
command = message["command"]
if message["ack"]:
return None
data = None
if "data" in message:
data = message["data"]
if command == "ping":
return pong()
f = getattr(self, command, None)
if f is not None:
return await f(data)
f = getattr(self.rpc_api, command, None)
if f is not None:
return await f(data)
raise ValueError(f"unknown_command {command}")
async def safe_handle(self, websocket, payload):
message = None
try:
message = json.loads(payload)
self.log.debug(f"Rpc call <- {message['command']}")
response = await self.ws_api(message)
# Only respond if we return something from api call
if response is not None:
log.debug(f"Rpc response -> {message['command']}")
# Set success to true automatically (unless it's already set)
if "success" not in response:
response["success"] = True
await websocket.send_str(format_response(message, response))
except Exception as e:
tb = traceback.format_exc()
self.log.warning(f"Error while handling message: {tb}")
if message is not None:
error = e.args[0] if e.args else e
res = {"success": False, "error": f"{error}"}
await websocket.send_str(format_response(message, res))
async def connection(self, ws):
data = {"service": self.service_name}
payload = create_payload("register_service", data, self.service_name, "daemon")
await ws.send_str(payload)
while True:
msg = await ws.receive()
if msg.type == aiohttp.WSMsgType.TEXT:
message = msg.data.strip()
# self.log.info(f"received message: {message}")
await self.safe_handle(ws, message)
elif msg.type == aiohttp.WSMsgType.BINARY:
self.log.debug("Received binary data")
elif msg.type == aiohttp.WSMsgType.PING:
self.log.debug("Ping received")
await ws.pong()
elif msg.type == aiohttp.WSMsgType.PONG:
self.log.debug("Pong received")
else:
if msg.type == aiohttp.WSMsgType.CLOSE:
self.log.debug("Closing RPC websocket")
await ws.close()
elif msg.type == aiohttp.WSMsgType.ERROR:
self.log.error("Error during receive %s" % ws.exception())
elif msg.type == aiohttp.WSMsgType.CLOSED:
pass
break
await ws.close()
async def connect_to_daemon(self, self_hostname: str, daemon_port: uint16):
while True:
try:
if self.shut_down:
break
async with aiohttp.ClientSession() as session:
async with session.ws_connect(
f"wss://{self_hostname}:{daemon_port}",
autoclose=True,
autoping=True,
heartbeat=60,
ssl_context=self.ssl_context,
max_msg_size=100 * 1024 * 1024,
) as ws:
self.websocket = ws
await self.connection(ws)
self.websocket = None
except aiohttp.ClientConnectorError:
self.log.warning(f"Cannot connect to daemon at ws://{self_hostname}:{daemon_port}")
except Exception as e:
tb = traceback.format_exc()
self.log.warning(f"Exception: {tb} {type(e)}")
await asyncio.sleep(2)
async def start_rpc_server(
rpc_api: Any,
self_hostname: str,
daemon_port: uint16,
rpc_port: uint16,
stop_cb: Callable,
root_path: Path,
net_config,
connect_to_daemon=True,
):
"""
Starts an HTTP server with the following RPC methods, to be used by local clients to
query the node.
"""
app = aiohttp.web.Application()
rpc_server = RpcServer(rpc_api, rpc_api.service_name, stop_cb, root_path, net_config)
rpc_server.rpc_api.service._set_state_changed_callback(rpc_server.state_changed)
app.add_routes(
[aiohttp.web.post(route, wrap_http_handler(func)) for (route, func) in rpc_server.get_routes().items()]
)
if connect_to_daemon:
daemon_connection = asyncio.create_task(rpc_server.connect_to_daemon(self_hostname, daemon_port))
runner = aiohttp.web.AppRunner(app, access_log=None)
await runner.setup()
site = aiohttp.web.TCPSite(runner, self_hostname, int(rpc_port), ssl_context=rpc_server.ssl_context)
await site.start()
async def cleanup():
await rpc_server.stop()
await runner.cleanup()
if connect_to_daemon:
await daemon_connection
return cleanup
|
from decimal import Decimal
import time
import logging
import asyncio
import pandas as pd
from typing import List, Dict, Tuple
from hummingbot.core.utils.async_utils import safe_ensure_future
from hummingbot.core.clock import Clock
from hummingbot.core.data_type.limit_order import LimitOrder
from hummingbot.core.data_type.market_order import MarketOrder
from hummingbot.logger import HummingbotLogger
from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple
from hummingbot.strategy.strategy_py_base import StrategyPyBase
from hummingbot.connector.connector_base import ConnectorBase
from hummingbot.core.event.events import (
PositionAction,
PositionSide,
PositionMode
)
from hummingbot.connector.derivative.position import Position
from .arb_proposal import ArbProposalSide, ArbProposal
NaN = float("nan")
s_decimal_zero = Decimal(0)
spa_logger = None
class SpotPerpetualArbitrageStrategy(StrategyPyBase):
"""
This strategy arbitrages between a spot and a perpetual exchange connector.
For a given order amount, the strategy checks the divergence and convergence in prices that could occur
before and during funding payment on the perpetual exchange.
If presents, the strategy submits taker orders to both market.
"""
@classmethod
def logger(cls) -> HummingbotLogger:
global spa_logger
if spa_logger is None:
spa_logger = logging.getLogger(__name__)
return spa_logger
def __init__(self,
spot_market_info: MarketTradingPairTuple,
derivative_market_info: MarketTradingPairTuple,
order_amount: Decimal,
derivative_leverage: int,
min_divergence: Decimal,
min_convergence: Decimal,
spot_market_slippage_buffer: Decimal = Decimal("0"),
derivative_market_slippage_buffer: Decimal = Decimal("0"),
maximize_funding_rate: bool = True,
next_arbitrage_cycle_delay: float = 120,
status_report_interval: float = 10):
"""
:param spot_market_info: The first market
:param derivative_market_info: The second market
:param order_amount: The order amount
:param min_divergence: The minimum spread to start arbitrage (e.g. 0.0003 for 0.3%)
:param min_convergence: The minimum spread to close arbitrage (e.g. 0.0003 for 0.3%)
:param spot_market_slippage_buffer: The buffer for which to adjust order price for higher chance of
the order getting filled. This is quite important for AMM which transaction takes a long time where a slippage
is acceptable rather having the transaction get rejected. The submitted order price will be adjust higher
for buy order and lower for sell order.
:param derivative_market_slippage_buffer: The slipper buffer for market_2
:param maximize_funding_rate: whether to submit both arbitrage taker orders (buy and sell) simultaneously
If false, the bot will wait for first exchange order filled before submitting the other order.
"""
super().__init__()
self._spot_market_info = spot_market_info
self._derivative_market_info = derivative_market_info
self._min_divergence = min_divergence
self._min_convergence = min_convergence
self._order_amount = order_amount
self._derivative_leverage = derivative_leverage
self._spot_market_slippage_buffer = spot_market_slippage_buffer
self._derivative_market_slippage_buffer = derivative_market_slippage_buffer
self._maximize_funding_rate = maximize_funding_rate
self._next_arbitrage_cycle_delay = next_arbitrage_cycle_delay
self._next_arbitrage_cycle_time = 0
self._all_markets_ready = False
self._ev_loop = asyncio.get_event_loop()
self._last_timestamp = 0
self._status_report_interval = status_report_interval
self.add_markets([spot_market_info.market, derivative_market_info.market])
self._current_proposal = None
self._main_task = None
self._spot_done = True
self._deriv_done = True
self._spot_order_ids = []
self._deriv_order_ids = []
@property
def current_proposal(self) -> ArbProposal:
return self._current_proposal
@current_proposal.setter
def current_proposal(self, value):
self._current_proposal = value
@property
def min_divergence(self) -> Decimal:
return self._min_divergence
@property
def min_convergence(self) -> Decimal:
return self._min_convergence
@property
def order_amount(self) -> Decimal:
return self._order_amount
@order_amount.setter
def order_amount(self, value):
self._order_amount = value
@property
def market_info_to_active_orders(self) -> Dict[MarketTradingPairTuple, List[LimitOrder]]:
return self._sb_order_tracker.market_pair_to_active_orders
@property
def deriv_position(self) -> List[Position]:
return [s for s in self._derivative_market_info.market._account_positions.values() if
s.trading_pair == self._derivative_market_info.trading_pair]
def tick(self, timestamp: float):
"""
Clock tick entry point, is run every second (on normal tick setting).
:param timestamp: current tick timestamp
"""
if not self._all_markets_ready:
self._all_markets_ready = all([market.ready for market in self.active_markets])
if not self._all_markets_ready:
# self.logger().warning("Markets are not ready. Please wait...")
return
else:
self.logger().info("Markets are ready. Trading started.")
if len(self.deriv_position) > 0:
self.logger().info("Active position detected, bot assumes first arbitrage was done and would scan for second arbitrage.")
if self.ready_for_new_arb_trades():
if self._main_task is None or self._main_task.done():
self.current_proposal = ArbProposal(self._spot_market_info, self._derivative_market_info, self.order_amount, timestamp)
self._main_task = safe_ensure_future(self.main(timestamp))
async def main(self, timestamp):
"""
The main procedure for the arbitrage strategy. It first check if it's time for funding payment, decide if to compare with either
min_convergence or min_divergence, applies the slippage buffer, applies budget constraint, then finally execute the
arbitrage.
"""
execute_arb = False
funding_msg = ""
await self.current_proposal.proposed_spot_deriv_arb()
if len(self.deriv_position) > 0 and self.should_alternate_proposal_sides(self.current_proposal, self.deriv_position):
self.current_proposal.alternate_proposal_sides()
if self.current_proposal.is_funding_payment_time():
if len(self.deriv_position) > 0:
if self._maximize_funding_rate:
execute_arb = not self.would_receive_funding_payment(self.deriv_position)
if execute_arb:
funding_msg = "Time for funding payment, executing second arbitrage to prevent paying funding fee"
else:
funding_msg = "Waiting for funding payment."
else:
funding_msg = "Time for funding payment, executing second arbitrage " \
"immediately since we don't intend to maximize funding rate"
execute_arb = True
else:
funding_msg = "Funding payment time, not looking for arbitrage opportunity because prices should be converging now!"
else:
if len(self.deriv_position) > 0:
execute_arb = self.ready_for_execution(self.current_proposal, False)
else:
execute_arb = self.ready_for_execution(self.current_proposal, True)
if execute_arb:
self.logger().info(self.spread_msg())
self.apply_slippage_buffers(self.current_proposal)
self.apply_budget_constraint(self.current_proposal)
await self.execute_arb_proposals(self.current_proposal, funding_msg)
else:
if funding_msg:
self.timed_logger(timestamp, funding_msg)
elif self._next_arbitrage_cycle_time > time.time():
self.timed_logger(timestamp, "Cooling off...")
else:
self.timed_logger(timestamp, self.spread_msg())
def timed_logger(self, timestamp, msg):
"""
Displays log at specific intervals.
:param timestamp: current timestamp
:param msg: message to display at next interval
"""
if timestamp - self._last_timestamp > self._status_report_interval:
self.logger().info(msg)
self._last_timestamp = timestamp
def ready_for_execution(self, proposal: ArbProposal, first: bool):
"""
Check if the spread meets the required spread requirement for the right arbitrage.
:param proposal: current proposal object
:param first: True, if scanning for opportunity for first arbitrage, else, False
:return: True if ready, else, False
"""
spread = self.current_proposal.spread()
if first and spread >= self.min_divergence and self._next_arbitrage_cycle_time < time.time(): # we do not want to start new cycle untill cooloff is over
return True
elif not first and spread <= self.min_convergence and self._next_arbitrage_cycle_time < time.time(): # we also don't want second arbitrage to ever be retried within this period
return True
return False
def should_alternate_proposal_sides(self, proposal: ArbProposal, active_position: List[Position]):
"""
Checks if there's need to alternate the sides of a proposed arbitrage.
:param proposal: current proposal object
:param active_position: information about active position for the derivative connector
:return: True if sides need to be alternated, else, False
"""
deriv_proposal_side = PositionSide.LONG if proposal.derivative_side.is_buy else PositionSide.SHORT
position_side = PositionSide.LONG if active_position[0].amount > 0 else PositionSide.SHORT
if deriv_proposal_side == position_side:
return True
return False
def would_receive_funding_payment(self, active_position: List[Position]):
"""
Checks if an active position would receive funding payment.
:param active_position: information about active position for the derivative connector
:return: True if funding payment would be received, else, False
"""
funding_info = self._derivative_market_info.market.get_funding_info(self._derivative_market_info.trading_pair)
if (active_position[0].amount > 0 and funding_info["rate"] < 0) or \
(active_position[0].amount < 0 and funding_info["rate"] > 0):
return True
return False
def apply_slippage_buffers(self, arb_proposal: ArbProposal):
"""
Updates arb_proposals by adjusting order price for slipper buffer percentage.
E.g. if it is a buy order, for an order price of 100 and 1% slipper buffer, the new order price is 101,
for a sell order, the new order price is 99.
:param arb_proposal: the arbitrage proposal
"""
for arb_side in (arb_proposal.spot_side, arb_proposal.derivative_side):
market = arb_side.market_info.market
arb_side.amount = market.quantize_order_amount(arb_side.market_info.trading_pair, arb_side.amount)
s_buffer = self._spot_market_slippage_buffer if market == self._spot_market_info.market \
else self._derivative_market_slippage_buffer
if not arb_side.is_buy:
s_buffer *= Decimal("-1")
arb_side.order_price *= Decimal("1") + s_buffer
arb_side.order_price = market.quantize_order_price(arb_side.market_info.trading_pair,
arb_side.order_price)
def apply_budget_constraint(self, arb_proposal: ArbProposal):
"""
Updates arb_proposals by setting proposal amount to 0 if there is not enough balance to submit order with
required order amount.
:param arb_proposal: the arbitrage proposal
"""
spot_market = self._spot_market_info.market
deriv_market = self._derivative_market_info.market
spot_token = self._spot_market_info.quote_asset if arb_proposal.spot_side.is_buy else self._spot_market_info.base_asset
deriv_token = self._derivative_market_info.quote_asset
spot_token_balance = spot_market.get_available_balance(spot_token)
deriv_token_balance = deriv_market.get_available_balance(deriv_token)
required_spot_balance = arb_proposal.amount * arb_proposal.spot_side.order_price if arb_proposal.spot_side.is_buy else arb_proposal.amount
required_deriv_balance = (arb_proposal.amount * arb_proposal.derivative_side.order_price) / self._derivative_leverage
if spot_token_balance < required_spot_balance:
arb_proposal.amount = s_decimal_zero
self.logger().info(f"Can't arbitrage, {spot_market.display_name} "
f"{spot_token} balance "
f"({spot_token_balance}) is below required order amount ({required_spot_balance}).")
elif deriv_token_balance < required_deriv_balance:
arb_proposal.amount = s_decimal_zero
self.logger().info(f"Can't arbitrage, {deriv_market.display_name} "
f"{deriv_token} balance "
f"({deriv_token_balance}) is below required order amount ({required_deriv_balance}).")
async def execute_arb_proposals(self, arb_proposal: ArbProposal, is_funding_msg: str = ""):
"""
Execute both sides of the arbitrage trades concurrently.
:param arb_proposals: the arbitrage proposal
:param is_funding_msg: message pertaining to funding payment
"""
if arb_proposal.amount == s_decimal_zero:
return
self._spot_done = False
self._deriv_done = False
proposal = self.short_proposal_msg(False)
if is_funding_msg:
opportunity_msg = is_funding_msg
else:
first_arbitage = not bool(len(self.deriv_position))
opportunity_msg = "Spread wide enough to execute first arbitrage" if first_arbitage else \
"Spread low enough to execute second arbitrage"
if not first_arbitage:
self._next_arbitrage_cycle_time = time.time() + self._next_arbitrage_cycle_delay
self.logger().info(f"{opportunity_msg}!: \n"
f"{proposal[0]} \n"
f"{proposal[1]} \n")
safe_ensure_future(self.execute_spot_side(arb_proposal.spot_side))
safe_ensure_future(self.execute_derivative_side(arb_proposal.derivative_side))
async def execute_spot_side(self, arb_side: ArbProposalSide):
side = "BUY" if arb_side.is_buy else "SELL"
place_order_fn = self.buy_with_specific_market if arb_side.is_buy else self.sell_with_specific_market
self.log_with_clock(logging.INFO,
f"Placing {side} order for {arb_side.amount} {arb_side.market_info.base_asset} "
f"at {arb_side.market_info.market.display_name} at {arb_side.order_price} price")
order_id = place_order_fn(arb_side.market_info,
arb_side.amount,
arb_side.market_info.market.get_taker_order_type(),
arb_side.order_price,
)
self._spot_order_ids.append(order_id)
async def execute_derivative_side(self, arb_side: ArbProposalSide):
side = "BUY" if arb_side.is_buy else "SELL"
place_order_fn = self.buy_with_specific_market if arb_side.is_buy else self.sell_with_specific_market
position_action = PositionAction.OPEN if len(self.deriv_position) == 0 else PositionAction.CLOSE
self.log_with_clock(logging.INFO,
f"Placing {side} order for {arb_side.amount} {arb_side.market_info.base_asset} "
f"at {arb_side.market_info.market.display_name} at {arb_side.order_price} price to {position_action.name} position.")
order_id = place_order_fn(arb_side.market_info,
arb_side.amount,
arb_side.market_info.market.get_taker_order_type(),
arb_side.order_price,
position_action=position_action
)
self._deriv_order_ids.append(order_id)
def ready_for_new_arb_trades(self) -> bool:
"""
Returns True if there is no outstanding unfilled order.
"""
for market_info in [self._spot_market_info, self._derivative_market_info]:
if len(self.market_info_to_active_orders.get(market_info, [])) > 0:
return False
if not self._spot_done or not self._deriv_done:
return False
return True
def short_proposal_msg(self, indented: bool = True) -> List[str]:
"""
Composes a short proposal message.
:param indented: If the message should be indented (by 4 spaces)
:return A list of info on both sides of an arbitrage
"""
lines = []
proposal = self.current_proposal
lines.append(f"{" " if indented else ""}{proposal.spot_side}")
lines.append(f"{" " if indented else ""}{proposal.derivative_side}")
return lines
def spread_msg(self):
"""
Composes a short spread message.
:return Info about current spread of an arbitrage
"""
spread = self.current_proposal.spread()
first = not bool(len(self.deriv_position))
target_spread_str = "minimum divergence spread" if first else "minimum convergence spread"
target_spread = self.min_divergence if first else self.min_convergence
msg = f"Current spread: {spread:.2%}, {target_spread_str}: {target_spread:.2%}."
return msg
def active_positions_df(self) -> pd.DataFrame:
columns = ["Symbol", "Type", "Entry Price", "Amount", "Leverage", "Unrealized PnL"]
data = []
for idx in self.deriv_position:
unrealized_profit = ((self.current_proposal.derivative_side.order_price - idx.entry_price) * idx.amount)
data.append([
idx.trading_pair,
idx.position_side.name,
idx.entry_price,
idx.amount,
idx.leverage,
unrealized_profit
])
return pd.DataFrame(data=data, columns=columns)
async def format_status(self) -> str:
"""
Returns a status string formatted to display nicely on terminal. The strings composes of 4 parts: markets,
assets, spread and warnings(if any).
"""
columns = ["Exchange", "Market", "Sell Price", "Buy Price", "Mid Price"]
data = []
for market_info in [self._spot_market_info, self._derivative_market_info]:
market, trading_pair, base_asset, quote_asset = market_info
buy_price = await market.get_quote_price(trading_pair, True, self._order_amount)
sell_price = await market.get_quote_price(trading_pair, False, self._order_amount)
mid_price = (buy_price + sell_price) / 2
data.append([
market.display_name,
trading_pair,
float(sell_price),
float(buy_price),
float(mid_price)
])
markets_df = pd.DataFrame(data=data, columns=columns)
lines = []
lines.extend(["", " Markets:"] + [" " + line for line in markets_df.to_string(index=False).split("\n")])
# See if there're any active positions.
if len(self.deriv_position) > 0:
df = self.active_positions_df()
lines.extend(["", " Positions:"] + [" " + line for line in df.to_string(index=False).split("\n")])
else:
lines.extend(["", " No active positions."])
assets_df = self.wallet_balance_data_frame([self._spot_market_info, self._derivative_market_info])
lines.extend(["", " Assets:"] +
[" " + line for line in str(assets_df).split("\n")])
try:
lines.extend(["", " Spread details:"] + [" " + self.spread_msg()] +
self.short_proposal_msg())
except Exception:
pass
warning_lines = self.network_warning([self._spot_market_info])
warning_lines.extend(self.network_warning([self._derivative_market_info]))
warning_lines.extend(self.balance_warning([self._spot_market_info]))
warning_lines.extend(self.balance_warning([self._derivative_market_info]))
if len(warning_lines) > 0:
lines.extend(["", "*** WARNINGS ***"] + warning_lines)
return "\n".join(lines)
def did_complete_buy_order(self, order_completed_event):
self.update_status(order_completed_event)
def did_complete_sell_order(self, order_completed_event):
self.update_status(order_completed_event)
def did_fail_order(self, order_failed_event):
self.retry_order(order_failed_event)
def did_cancel_order(self, cancelled_event):
self.retry_order(cancelled_event)
def did_expire_order(self, expired_event):
self.retry_order(expired_event)
def did_complete_funding_payment(self, funding_payment_completed_event):
# Excute second arbitrage if necessary (even spread hasn't reached min convergence)
if len(self.deriv_position) > 0 and \
self._all_markets_ready and \
self.current_proposal and \
self.ready_for_new_arb_trades():
self.apply_slippage_buffers(self.current_proposal)
self.apply_budget_constraint(self.current_proposal)
funding_msg = "Executing second arbitrage after funding payment is received"
safe_ensure_future(self.execute_arb_proposals(self.current_proposal, funding_msg))
return
def update_status(self, event):
order_id = event.order_id
if order_id in self._spot_order_ids:
self._spot_done = True
self._spot_order_ids.remove(order_id)
elif order_id in self._deriv_order_ids:
self._deriv_done = True
self._deriv_order_ids.remove(order_id)
def retry_order(self, event):
order_id = event.order_id
# To-do: Should be updated to do counted retry rather than time base retry. i.e mark as done after retrying 3 times
if event.timestamp > (time.time() - 5): # retry if order failed less than 5 secs ago
if order_id in self._spot_order_ids:
self.logger().info("Retrying failed order on spot exchange.")
safe_ensure_future(self.execute_spot_side(self.current_proposal.spot_side))
self._spot_order_ids.remove(order_id)
elif order_id in self._deriv_order_ids:
self.logger().info("Retrying failed order on derivative exchange.")
safe_ensure_future(self.execute_derivative_side(self.current_proposal.derivative_side))
self._deriv_order_ids.remove(order_id)
else: # mark as done
self.update_status(event)
@property
def tracked_limit_orders(self) -> List[Tuple[ConnectorBase, LimitOrder]]:
return self._sb_order_tracker.tracked_limit_orders
@property
def tracked_market_orders(self) -> List[Tuple[ConnectorBase, MarketOrder]]:
return self._sb_order_tracker.tracked_market_orders
def apply_initial_settings(self, trading_pair, leverage):
deriv_market = self._derivative_market_info.market
deriv_market.set_leverage(trading_pair, leverage)
deriv_market.set_position_mode(PositionMode.ONEWAY)
def start(self, clock: Clock, timestamp: float):
self.apply_initial_settings(self._derivative_market_info.trading_pair, self._derivative_leverage)
def stop(self, clock: Clock):
if self._main_task is not None:
self._main_task.cancel()
self._main_task = None
| from decimal import Decimal
import time
import logging
import asyncio
import pandas as pd
from typing import List, Dict, Tuple
from hummingbot.core.utils.async_utils import safe_ensure_future
from hummingbot.core.clock import Clock
from hummingbot.core.data_type.limit_order import LimitOrder
from hummingbot.core.data_type.market_order import MarketOrder
from hummingbot.logger import HummingbotLogger
from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple
from hummingbot.strategy.strategy_py_base import StrategyPyBase
from hummingbot.connector.connector_base import ConnectorBase
from hummingbot.core.event.events import (
PositionAction,
PositionSide,
PositionMode
)
from hummingbot.connector.derivative.position import Position
from .arb_proposal import ArbProposalSide, ArbProposal
NaN = float("nan")
s_decimal_zero = Decimal(0)
spa_logger = None
class SpotPerpetualArbitrageStrategy(StrategyPyBase):
"""
This strategy arbitrages between a spot and a perpetual exchange connector.
For a given order amount, the strategy checks the divergence and convergence in prices that could occur
before and during funding payment on the perpetual exchange.
If presents, the strategy submits taker orders to both market.
"""
@classmethod
def logger(cls) -> HummingbotLogger:
global spa_logger
if spa_logger is None:
spa_logger = logging.getLogger(__name__)
return spa_logger
def __init__(self,
spot_market_info: MarketTradingPairTuple,
derivative_market_info: MarketTradingPairTuple,
order_amount: Decimal,
derivative_leverage: int,
min_divergence: Decimal,
min_convergence: Decimal,
spot_market_slippage_buffer: Decimal = Decimal("0"),
derivative_market_slippage_buffer: Decimal = Decimal("0"),
maximize_funding_rate: bool = True,
next_arbitrage_cycle_delay: float = 120,
status_report_interval: float = 10):
"""
:param spot_market_info: The first market
:param derivative_market_info: The second market
:param order_amount: The order amount
:param min_divergence: The minimum spread to start arbitrage (e.g. 0.0003 for 0.3%)
:param min_convergence: The minimum spread to close arbitrage (e.g. 0.0003 for 0.3%)
:param spot_market_slippage_buffer: The buffer for which to adjust order price for higher chance of
the order getting filled. This is quite important for AMM which transaction takes a long time where a slippage
is acceptable rather having the transaction get rejected. The submitted order price will be adjust higher
for buy order and lower for sell order.
:param derivative_market_slippage_buffer: The slipper buffer for market_2
:param maximize_funding_rate: whether to submit both arbitrage taker orders (buy and sell) simultaneously
If false, the bot will wait for first exchange order filled before submitting the other order.
"""
super().__init__()
self._spot_market_info = spot_market_info
self._derivative_market_info = derivative_market_info
self._min_divergence = min_divergence
self._min_convergence = min_convergence
self._order_amount = order_amount
self._derivative_leverage = derivative_leverage
self._spot_market_slippage_buffer = spot_market_slippage_buffer
self._derivative_market_slippage_buffer = derivative_market_slippage_buffer
self._maximize_funding_rate = maximize_funding_rate
self._next_arbitrage_cycle_delay = next_arbitrage_cycle_delay
self._next_arbitrage_cycle_time = 0
self._all_markets_ready = False
self._ev_loop = asyncio.get_event_loop()
self._last_timestamp = 0
self._status_report_interval = status_report_interval
self.add_markets([spot_market_info.market, derivative_market_info.market])
self._current_proposal = None
self._main_task = None
self._spot_done = True
self._deriv_done = True
self._spot_order_ids = []
self._deriv_order_ids = []
@property
def current_proposal(self) -> ArbProposal:
return self._current_proposal
@current_proposal.setter
def current_proposal(self, value):
self._current_proposal = value
@property
def min_divergence(self) -> Decimal:
return self._min_divergence
@property
def min_convergence(self) -> Decimal:
return self._min_convergence
@property
def order_amount(self) -> Decimal:
return self._order_amount
@order_amount.setter
def order_amount(self, value):
self._order_amount = value
@property
def market_info_to_active_orders(self) -> Dict[MarketTradingPairTuple, List[LimitOrder]]:
return self._sb_order_tracker.market_pair_to_active_orders
@property
def deriv_position(self) -> List[Position]:
return [s for s in self._derivative_market_info.market._account_positions.values() if
s.trading_pair == self._derivative_market_info.trading_pair]
def tick(self, timestamp: float):
"""
Clock tick entry point, is run every second (on normal tick setting).
:param timestamp: current tick timestamp
"""
if not self._all_markets_ready:
self._all_markets_ready = all([market.ready for market in self.active_markets])
if not self._all_markets_ready:
# self.logger().warning("Markets are not ready. Please wait...")
return
else:
self.logger().info("Markets are ready. Trading started.")
if len(self.deriv_position) > 0:
self.logger().info("Active position detected, bot assumes first arbitrage was done and would scan for second arbitrage.")
if self.ready_for_new_arb_trades():
if self._main_task is None or self._main_task.done():
self.current_proposal = ArbProposal(self._spot_market_info, self._derivative_market_info, self.order_amount, timestamp)
self._main_task = safe_ensure_future(self.main(timestamp))
async def main(self, timestamp):
"""
The main procedure for the arbitrage strategy. It first check if it's time for funding payment, decide if to compare with either
min_convergence or min_divergence, applies the slippage buffer, applies budget constraint, then finally execute the
arbitrage.
"""
execute_arb = False
funding_msg = ""
await self.current_proposal.proposed_spot_deriv_arb()
if len(self.deriv_position) > 0 and self.should_alternate_proposal_sides(self.current_proposal, self.deriv_position):
self.current_proposal.alternate_proposal_sides()
if self.current_proposal.is_funding_payment_time():
if len(self.deriv_position) > 0:
if self._maximize_funding_rate:
execute_arb = not self.would_receive_funding_payment(self.deriv_position)
if execute_arb:
funding_msg = "Time for funding payment, executing second arbitrage to prevent paying funding fee"
else:
funding_msg = "Waiting for funding payment."
else:
funding_msg = "Time for funding payment, executing second arbitrage " \
"immediately since we don't intend to maximize funding rate"
execute_arb = True
else:
funding_msg = "Funding payment time, not looking for arbitrage opportunity because prices should be converging now!"
else:
if len(self.deriv_position) > 0:
execute_arb = self.ready_for_execution(self.current_proposal, False)
else:
execute_arb = self.ready_for_execution(self.current_proposal, True)
if execute_arb:
self.logger().info(self.spread_msg())
self.apply_slippage_buffers(self.current_proposal)
self.apply_budget_constraint(self.current_proposal)
await self.execute_arb_proposals(self.current_proposal, funding_msg)
else:
if funding_msg:
self.timed_logger(timestamp, funding_msg)
elif self._next_arbitrage_cycle_time > time.time():
self.timed_logger(timestamp, "Cooling off...")
else:
self.timed_logger(timestamp, self.spread_msg())
def timed_logger(self, timestamp, msg):
"""
Displays log at specific intervals.
:param timestamp: current timestamp
:param msg: message to display at next interval
"""
if timestamp - self._last_timestamp > self._status_report_interval:
self.logger().info(msg)
self._last_timestamp = timestamp
def ready_for_execution(self, proposal: ArbProposal, first: bool):
"""
Check if the spread meets the required spread requirement for the right arbitrage.
:param proposal: current proposal object
:param first: True, if scanning for opportunity for first arbitrage, else, False
:return: True if ready, else, False
"""
spread = self.current_proposal.spread()
if first and spread >= self.min_divergence and self._next_arbitrage_cycle_time < time.time(): # we do not want to start new cycle untill cooloff is over
return True
elif not first and spread <= self.min_convergence and self._next_arbitrage_cycle_time < time.time(): # we also don't want second arbitrage to ever be retried within this period
return True
return False
def should_alternate_proposal_sides(self, proposal: ArbProposal, active_position: List[Position]):
"""
Checks if there's need to alternate the sides of a proposed arbitrage.
:param proposal: current proposal object
:param active_position: information about active position for the derivative connector
:return: True if sides need to be alternated, else, False
"""
deriv_proposal_side = PositionSide.LONG if proposal.derivative_side.is_buy else PositionSide.SHORT
position_side = PositionSide.LONG if active_position[0].amount > 0 else PositionSide.SHORT
if deriv_proposal_side == position_side:
return True
return False
def would_receive_funding_payment(self, active_position: List[Position]):
"""
Checks if an active position would receive funding payment.
:param active_position: information about active position for the derivative connector
:return: True if funding payment would be received, else, False
"""
funding_info = self._derivative_market_info.market.get_funding_info(self._derivative_market_info.trading_pair)
if (active_position[0].amount > 0 and funding_info["rate"] < 0) or \
(active_position[0].amount < 0 and funding_info["rate"] > 0):
return True
return False
def apply_slippage_buffers(self, arb_proposal: ArbProposal):
"""
Updates arb_proposals by adjusting order price for slipper buffer percentage.
E.g. if it is a buy order, for an order price of 100 and 1% slipper buffer, the new order price is 101,
for a sell order, the new order price is 99.
:param arb_proposal: the arbitrage proposal
"""
for arb_side in (arb_proposal.spot_side, arb_proposal.derivative_side):
market = arb_side.market_info.market
arb_side.amount = market.quantize_order_amount(arb_side.market_info.trading_pair, arb_side.amount)
s_buffer = self._spot_market_slippage_buffer if market == self._spot_market_info.market \
else self._derivative_market_slippage_buffer
if not arb_side.is_buy:
s_buffer *= Decimal("-1")
arb_side.order_price *= Decimal("1") + s_buffer
arb_side.order_price = market.quantize_order_price(arb_side.market_info.trading_pair,
arb_side.order_price)
def apply_budget_constraint(self, arb_proposal: ArbProposal):
"""
Updates arb_proposals by setting proposal amount to 0 if there is not enough balance to submit order with
required order amount.
:param arb_proposal: the arbitrage proposal
"""
spot_market = self._spot_market_info.market
deriv_market = self._derivative_market_info.market
spot_token = self._spot_market_info.quote_asset if arb_proposal.spot_side.is_buy else self._spot_market_info.base_asset
deriv_token = self._derivative_market_info.quote_asset
spot_token_balance = spot_market.get_available_balance(spot_token)
deriv_token_balance = deriv_market.get_available_balance(deriv_token)
required_spot_balance = arb_proposal.amount * arb_proposal.spot_side.order_price if arb_proposal.spot_side.is_buy else arb_proposal.amount
required_deriv_balance = (arb_proposal.amount * arb_proposal.derivative_side.order_price) / self._derivative_leverage
if spot_token_balance < required_spot_balance:
arb_proposal.amount = s_decimal_zero
self.logger().info(f"Can't arbitrage, {spot_market.display_name} "
f"{spot_token} balance "
f"({spot_token_balance}) is below required order amount ({required_spot_balance}).")
elif deriv_token_balance < required_deriv_balance:
arb_proposal.amount = s_decimal_zero
self.logger().info(f"Can't arbitrage, {deriv_market.display_name} "
f"{deriv_token} balance "
f"({deriv_token_balance}) is below required order amount ({required_deriv_balance}).")
async def execute_arb_proposals(self, arb_proposal: ArbProposal, is_funding_msg: str = ""):
"""
Execute both sides of the arbitrage trades concurrently.
:param arb_proposals: the arbitrage proposal
:param is_funding_msg: message pertaining to funding payment
"""
if arb_proposal.amount == s_decimal_zero:
return
self._spot_done = False
self._deriv_done = False
proposal = self.short_proposal_msg(False)
if is_funding_msg:
opportunity_msg = is_funding_msg
else:
first_arbitage = not bool(len(self.deriv_position))
opportunity_msg = "Spread wide enough to execute first arbitrage" if first_arbitage else \
"Spread low enough to execute second arbitrage"
if not first_arbitage:
self._next_arbitrage_cycle_time = time.time() + self._next_arbitrage_cycle_delay
self.logger().info(f"{opportunity_msg}!: \n"
f"{proposal[0]} \n"
f"{proposal[1]} \n")
safe_ensure_future(self.execute_spot_side(arb_proposal.spot_side))
safe_ensure_future(self.execute_derivative_side(arb_proposal.derivative_side))
async def execute_spot_side(self, arb_side: ArbProposalSide):
side = "BUY" if arb_side.is_buy else "SELL"
place_order_fn = self.buy_with_specific_market if arb_side.is_buy else self.sell_with_specific_market
self.log_with_clock(logging.INFO,
f"Placing {side} order for {arb_side.amount} {arb_side.market_info.base_asset} "
f"at {arb_side.market_info.market.display_name} at {arb_side.order_price} price")
order_id = place_order_fn(arb_side.market_info,
arb_side.amount,
arb_side.market_info.market.get_taker_order_type(),
arb_side.order_price,
)
self._spot_order_ids.append(order_id)
async def execute_derivative_side(self, arb_side: ArbProposalSide):
side = "BUY" if arb_side.is_buy else "SELL"
place_order_fn = self.buy_with_specific_market if arb_side.is_buy else self.sell_with_specific_market
position_action = PositionAction.OPEN if len(self.deriv_position) == 0 else PositionAction.CLOSE
self.log_with_clock(logging.INFO,
f"Placing {side} order for {arb_side.amount} {arb_side.market_info.base_asset} "
f"at {arb_side.market_info.market.display_name} at {arb_side.order_price} price to {position_action.name} position.")
order_id = place_order_fn(arb_side.market_info,
arb_side.amount,
arb_side.market_info.market.get_taker_order_type(),
arb_side.order_price,
position_action=position_action
)
self._deriv_order_ids.append(order_id)
def ready_for_new_arb_trades(self) -> bool:
"""
Returns True if there is no outstanding unfilled order.
"""
for market_info in [self._spot_market_info, self._derivative_market_info]:
if len(self.market_info_to_active_orders.get(market_info, [])) > 0:
return False
if not self._spot_done or not self._deriv_done:
return False
return True
def short_proposal_msg(self, indented: bool = True) -> List[str]:
"""
Composes a short proposal message.
:param indented: If the message should be indented (by 4 spaces)
:return A list of info on both sides of an arbitrage
"""
lines = []
proposal = self.current_proposal
lines.append(f"{' ' if indented else ''}{proposal.spot_side}")
lines.append(f"{' ' if indented else ''}{proposal.derivative_side}")
return lines
def spread_msg(self):
"""
Composes a short spread message.
:return Info about current spread of an arbitrage
"""
spread = self.current_proposal.spread()
first = not bool(len(self.deriv_position))
target_spread_str = "minimum divergence spread" if first else "minimum convergence spread"
target_spread = self.min_divergence if first else self.min_convergence
msg = f"Current spread: {spread:.2%}, {target_spread_str}: {target_spread:.2%}."
return msg
def active_positions_df(self) -> pd.DataFrame:
columns = ["Symbol", "Type", "Entry Price", "Amount", "Leverage", "Unrealized PnL"]
data = []
for idx in self.deriv_position:
unrealized_profit = ((self.current_proposal.derivative_side.order_price - idx.entry_price) * idx.amount)
data.append([
idx.trading_pair,
idx.position_side.name,
idx.entry_price,
idx.amount,
idx.leverage,
unrealized_profit
])
return pd.DataFrame(data=data, columns=columns)
async def format_status(self) -> str:
"""
Returns a status string formatted to display nicely on terminal. The strings composes of 4 parts: markets,
assets, spread and warnings(if any).
"""
columns = ["Exchange", "Market", "Sell Price", "Buy Price", "Mid Price"]
data = []
for market_info in [self._spot_market_info, self._derivative_market_info]:
market, trading_pair, base_asset, quote_asset = market_info
buy_price = await market.get_quote_price(trading_pair, True, self._order_amount)
sell_price = await market.get_quote_price(trading_pair, False, self._order_amount)
mid_price = (buy_price + sell_price) / 2
data.append([
market.display_name,
trading_pair,
float(sell_price),
float(buy_price),
float(mid_price)
])
markets_df = pd.DataFrame(data=data, columns=columns)
lines = []
lines.extend(["", " Markets:"] + [" " + line for line in markets_df.to_string(index=False).split("\n")])
# See if there're any active positions.
if len(self.deriv_position) > 0:
df = self.active_positions_df()
lines.extend(["", " Positions:"] + [" " + line for line in df.to_string(index=False).split("\n")])
else:
lines.extend(["", " No active positions."])
assets_df = self.wallet_balance_data_frame([self._spot_market_info, self._derivative_market_info])
lines.extend(["", " Assets:"] +
[" " + line for line in str(assets_df).split("\n")])
try:
lines.extend(["", " Spread details:"] + [" " + self.spread_msg()] +
self.short_proposal_msg())
except Exception:
pass
warning_lines = self.network_warning([self._spot_market_info])
warning_lines.extend(self.network_warning([self._derivative_market_info]))
warning_lines.extend(self.balance_warning([self._spot_market_info]))
warning_lines.extend(self.balance_warning([self._derivative_market_info]))
if len(warning_lines) > 0:
lines.extend(["", "*** WARNINGS ***"] + warning_lines)
return "\n".join(lines)
def did_complete_buy_order(self, order_completed_event):
self.update_status(order_completed_event)
def did_complete_sell_order(self, order_completed_event):
self.update_status(order_completed_event)
def did_fail_order(self, order_failed_event):
self.retry_order(order_failed_event)
def did_cancel_order(self, cancelled_event):
self.retry_order(cancelled_event)
def did_expire_order(self, expired_event):
self.retry_order(expired_event)
def did_complete_funding_payment(self, funding_payment_completed_event):
# Excute second arbitrage if necessary (even spread hasn't reached min convergence)
if len(self.deriv_position) > 0 and \
self._all_markets_ready and \
self.current_proposal and \
self.ready_for_new_arb_trades():
self.apply_slippage_buffers(self.current_proposal)
self.apply_budget_constraint(self.current_proposal)
funding_msg = "Executing second arbitrage after funding payment is received"
safe_ensure_future(self.execute_arb_proposals(self.current_proposal, funding_msg))
return
def update_status(self, event):
order_id = event.order_id
if order_id in self._spot_order_ids:
self._spot_done = True
self._spot_order_ids.remove(order_id)
elif order_id in self._deriv_order_ids:
self._deriv_done = True
self._deriv_order_ids.remove(order_id)
def retry_order(self, event):
order_id = event.order_id
# To-do: Should be updated to do counted retry rather than time base retry. i.e mark as done after retrying 3 times
if event.timestamp > (time.time() - 5): # retry if order failed less than 5 secs ago
if order_id in self._spot_order_ids:
self.logger().info("Retrying failed order on spot exchange.")
safe_ensure_future(self.execute_spot_side(self.current_proposal.spot_side))
self._spot_order_ids.remove(order_id)
elif order_id in self._deriv_order_ids:
self.logger().info("Retrying failed order on derivative exchange.")
safe_ensure_future(self.execute_derivative_side(self.current_proposal.derivative_side))
self._deriv_order_ids.remove(order_id)
else: # mark as done
self.update_status(event)
@property
def tracked_limit_orders(self) -> List[Tuple[ConnectorBase, LimitOrder]]:
return self._sb_order_tracker.tracked_limit_orders
@property
def tracked_market_orders(self) -> List[Tuple[ConnectorBase, MarketOrder]]:
return self._sb_order_tracker.tracked_market_orders
def apply_initial_settings(self, trading_pair, leverage):
deriv_market = self._derivative_market_info.market
deriv_market.set_leverage(trading_pair, leverage)
deriv_market.set_position_mode(PositionMode.ONEWAY)
def start(self, clock: Clock, timestamp: float):
self.apply_initial_settings(self._derivative_market_info.trading_pair, self._derivative_leverage)
def stop(self, clock: Clock):
if self._main_task is not None:
self._main_task.cancel()
self._main_task = None
|
"""Module for trying to find card info and write them to card_info"""
import json
import pandas as pd
import numpy as np
from collections import defaultdict
PATHBASE = "../card_info/specifics/"
def get_card_quality(df):
df["DrawQualityNew"] = (2*pd.to_numeric(df["Cards"], errors='coerce')).fillna(0).astype(np.int64)
with open(PATHBASE + "DrawQuality.txt", "r") as f:
data = json.load(f)
data = defaultdict(lambda: 0, data)
old_data = df[["Name", "DrawQualityNew"]].to_dict()
old_data = {old_data["Name"][i]: old_data["DrawQuality"][i] for i in range(len(old_data["Name"]))}
new_data = {name: max(data[name], old_data[name]) for name in sorted(old_data.keys())}
# new_data = {name: data[name] -1 if 1 < data[name] < 4 else data[name] for name in data.keys()}
with open(f"../card_info/specifics/DrawQuality.txt", "w") as f:
json.dump(new_data, f)
def get_village_quality(df):
df["VillageQualityTest"] = 0
# All regular Villages get the value of 5
df.loc[(pd.to_numeric(df["Actions / Villagers"], errors="coerce") == 2) \
& (pd.to_numeric(df["Cards"], errors="coerce") == 1), "VillageQualityTest"] = 5
# All villages with no + card get the value 3
df.loc[(pd.to_numeric(df["Actions / Villagers"], errors="coerce") == 2) \
& (pd.to_numeric(df["Cards"], errors="coerce").fillna(0) == 0), "VillageQualityTest"] = 3
# All villages with more cards get the value 6
df.loc[(pd.to_numeric(df["Actions / Villagers"], errors="coerce") == 2) \
& (pd.to_numeric(df["Cards"], errors="coerce").fillna(0) > 1), "VillageQualityTest"] = 6
my_villages = df[["Name", "VillageQualityTest"]].to_dict()
my_villages = {my_villages["Name"][i]: my_villages["VillageQualityTest"][i] for i in range(len(my_villages["Name"]))}
# Throne rooms get a value of 4,
other_villages = {"Throne Room": 4, "Diplomat": 4, "Tribute": 2, "Nobles": 3, "Fishing Village": 4, "Tactician": 1, "Golem": 3, "King's Court": 6, "Hamlet": 4, "Trusty Steed": 7, "Crossroads": 5, "Squire": 3, "Ironmonger": 6, "Procession": 4, "Herald": 5, "Coin of the Realm": 4, "Royal Carriage": 4, "Lost Arts": 6, "Disciple": 4, "Teacher": 5, "Champion": 10, "Sacrifice": 3, "Villa": 3, "Bustling Village": 6, "Crown": 4, "Ghost Town": 5, "Conclave": 3, "Zombie Apprentice": 3, "Lackeys": 4, "Acting Troupe": 4, "Silk Merchant": 1, "Recruiter": 8, "Scepter": 3, "Exploration": 3, "Academy": 10, "Piazza": 3, "Barracks": 5, "Innovation": 4, "Citadel": 5, "Snowy Village": 5, "Village Green": 6, "Mastermind": 6, "Paddock": 3, "Toil": 2, "March": 1, "Sauna": 2, "Captain": 6, "Prince": 4}
other_villages = defaultdict(lambda: 0, other_villages)
new_data = {name: max(other_villages[name], my_villages[name]) for name in sorted(my_villages.keys())}
print(df[df["Name"] == "Lost City"][["Name", "Actions / Villagers", "Cards", "VillageQualityTest"]])
for i, card in df[(df["VillageQuality"] == 0) & (df["Actions / Villagers"].notna()) & (pd.to_numeric(df["Actions / Villagers"], errors="coerce") != 1)].iterrows():
print(f'"{card['Name']}": ', end=", ")
with open(PATHBASE + "VillageQuality.txt", "w") as f:
json.dump(new_data, f)
def get_trashing_quality(df):
df["TrashingQualityTest"] = 0
df.fillna('', inplace=True)
df.loc[(~df["Trash / Return"].str.lower().apply(lambda x: x in ["self", "self?"])) & (df["Trash / Return"].str.len() != 0), "TrashingQualityTest"] = 10 # The self-trashers are only returned, so we don't want them in here
for i in range(5):
df.loc[(df["Trash / Return"].str.contains(str(i))), "TrashingQualityTest"] = i*2
df.loc[(df["Exile"].str.contains(str(i))), "TrashingQualityTest"] = i*2
my_trashers = df[["Name", "TrashingQualityTest"]].to_dict()
my_trashers = {my_trashers["Name"][i]: my_trashers["TrashingQualityTest"][i] for i in range(len(my_trashers["Name"]))}
other_trashers = {"Mint": 5, "Forge": 6, "Count": 5, "Donate": 10, "Monastery": 6, "Sauna": 2, "Banish": 5}
other_trashers = defaultdict(lambda: 0, other_trashers)
new_data = {name: max(other_trashers[name], my_trashers[name]) for name in sorted(my_trashers.keys())}
# print(set(df["Trash / Return"]))
# print(", ".join(['"' + row[1]["Name"] + '": ' + str(row[1]["TrashingQualityTest"]) for row in df[df["TrashingQualityTest"] == 10][["Name", "Trash / Return", "TrashingQualityTest"]].iterrows()]))
# print(df[df["Trash / Return"].str.contains("1\?")]["Name"])
# print("\n".join([f'"{name}": ' for name in df[df["TrashingQualityTest"] > 5]["Name"]]))
with open(PATHBASE + "TrashingQuality.txt", "w") as f:
json.dump(new_data, f)
def main():
fpath = "../card_info/good_card_data.csv"
df = df = pd.read_csv(fpath, sep=";", header=0)
get_trashing_quality(df)
if __name__ == '__main__':
main() | """Module for trying to find card info and write them to card_info"""
import json
import pandas as pd
import numpy as np
from collections import defaultdict
PATHBASE = "../card_info/specifics/"
def get_card_quality(df):
df["DrawQualityNew"] = (2*pd.to_numeric(df["Cards"], errors='coerce')).fillna(0).astype(np.int64)
with open(PATHBASE + "DrawQuality.txt", "r") as f:
data = json.load(f)
data = defaultdict(lambda: 0, data)
old_data = df[["Name", "DrawQualityNew"]].to_dict()
old_data = {old_data["Name"][i]: old_data["DrawQuality"][i] for i in range(len(old_data["Name"]))}
new_data = {name: max(data[name], old_data[name]) for name in sorted(old_data.keys())}
# new_data = {name: data[name] -1 if 1 < data[name] < 4 else data[name] for name in data.keys()}
with open(f"../card_info/specifics/DrawQuality.txt", "w") as f:
json.dump(new_data, f)
def get_village_quality(df):
df["VillageQualityTest"] = 0
# All regular Villages get the value of 5
df.loc[(pd.to_numeric(df["Actions / Villagers"], errors="coerce") == 2) \
& (pd.to_numeric(df["Cards"], errors="coerce") == 1), "VillageQualityTest"] = 5
# All villages with no + card get the value 3
df.loc[(pd.to_numeric(df["Actions / Villagers"], errors="coerce") == 2) \
& (pd.to_numeric(df["Cards"], errors="coerce").fillna(0) == 0), "VillageQualityTest"] = 3
# All villages with more cards get the value 6
df.loc[(pd.to_numeric(df["Actions / Villagers"], errors="coerce") == 2) \
& (pd.to_numeric(df["Cards"], errors="coerce").fillna(0) > 1), "VillageQualityTest"] = 6
my_villages = df[["Name", "VillageQualityTest"]].to_dict()
my_villages = {my_villages["Name"][i]: my_villages["VillageQualityTest"][i] for i in range(len(my_villages["Name"]))}
# Throne rooms get a value of 4,
other_villages = {"Throne Room": 4, "Diplomat": 4, "Tribute": 2, "Nobles": 3, "Fishing Village": 4, "Tactician": 1, "Golem": 3, "King's Court": 6, "Hamlet": 4, "Trusty Steed": 7, "Crossroads": 5, "Squire": 3, "Ironmonger": 6, "Procession": 4, "Herald": 5, "Coin of the Realm": 4, "Royal Carriage": 4, "Lost Arts": 6, "Disciple": 4, "Teacher": 5, "Champion": 10, "Sacrifice": 3, "Villa": 3, "Bustling Village": 6, "Crown": 4, "Ghost Town": 5, "Conclave": 3, "Zombie Apprentice": 3, "Lackeys": 4, "Acting Troupe": 4, "Silk Merchant": 1, "Recruiter": 8, "Scepter": 3, "Exploration": 3, "Academy": 10, "Piazza": 3, "Barracks": 5, "Innovation": 4, "Citadel": 5, "Snowy Village": 5, "Village Green": 6, "Mastermind": 6, "Paddock": 3, "Toil": 2, "March": 1, "Sauna": 2, "Captain": 6, "Prince": 4}
other_villages = defaultdict(lambda: 0, other_villages)
new_data = {name: max(other_villages[name], my_villages[name]) for name in sorted(my_villages.keys())}
print(df[df["Name"] == "Lost City"][["Name", "Actions / Villagers", "Cards", "VillageQualityTest"]])
for i, card in df[(df["VillageQuality"] == 0) & (df["Actions / Villagers"].notna()) & (pd.to_numeric(df["Actions / Villagers"], errors="coerce") != 1)].iterrows():
print(f'"{card["Name"]}": ', end=", ")
with open(PATHBASE + "VillageQuality.txt", "w") as f:
json.dump(new_data, f)
def get_trashing_quality(df):
df["TrashingQualityTest"] = 0
df.fillna('', inplace=True)
df.loc[(~df["Trash / Return"].str.lower().apply(lambda x: x in ["self", "self?"])) & (df["Trash / Return"].str.len() != 0), "TrashingQualityTest"] = 10 # The self-trashers are only returned, so we don't want them in here
for i in range(5):
df.loc[(df["Trash / Return"].str.contains(str(i))), "TrashingQualityTest"] = i*2
df.loc[(df["Exile"].str.contains(str(i))), "TrashingQualityTest"] = i*2
my_trashers = df[["Name", "TrashingQualityTest"]].to_dict()
my_trashers = {my_trashers["Name"][i]: my_trashers["TrashingQualityTest"][i] for i in range(len(my_trashers["Name"]))}
other_trashers = {"Mint": 5, "Forge": 6, "Count": 5, "Donate": 10, "Monastery": 6, "Sauna": 2, "Banish": 5}
other_trashers = defaultdict(lambda: 0, other_trashers)
new_data = {name: max(other_trashers[name], my_trashers[name]) for name in sorted(my_trashers.keys())}
# print(set(df["Trash / Return"]))
# print(", ".join(['"' + row[1]["Name"] + '": ' + str(row[1]["TrashingQualityTest"]) for row in df[df["TrashingQualityTest"] == 10][["Name", "Trash / Return", "TrashingQualityTest"]].iterrows()]))
# print(df[df["Trash / Return"].str.contains("1\?")]["Name"])
# print("\n".join([f'"{name}": ' for name in df[df["TrashingQualityTest"] > 5]["Name"]]))
with open(PATHBASE + "TrashingQuality.txt", "w") as f:
json.dump(new_data, f)
def main():
fpath = "../card_info/good_card_data.csv"
df = df = pd.read_csv(fpath, sep=";", header=0)
get_trashing_quality(df)
if __name__ == '__main__':
main() |
# *******************************************************************************
# Copyright (C) 2021 INAF
#
# This software is distributed under the terms of the BSD-3-Clause license
#
# Authors:
# Ambra Di Piano <ambra.dipiano@inaf.it>
# *******************************************************************************
import numpy as np
import os
import sys
import argparse
from os.path import isdir, join, isfile, expandvars
from RTAscience.lib.RTACtoolsAnalysis import RTACtoolsAnalysis
from RTAscience.lib.RTAGammapyAnalysis import *
from RTAscience.lib.RTAUtils import *
from RTAscience.cfg.Config import Config
from RTAscience.lib.RTAVisualise import plotSkymap
from RTAscience.aph.utils import *
parser = argparse.ArgumentParser(description='ADD SCRIPT DESCRIPTION HERE')
parser.add_argument('-f', '--cfgfile', type=str, required=True, help="Path to the yaml configuration file")
parser.add_argument('--merge', type=str, default='true', help='Merge in single phlist (true) or use observation library (false)')
parser.add_argument('--remove', type=str, default='true', help='Keep only outputs')
parser.add_argument('--print', type=str, default='false', help='Print out results')
args = parser.parse_args()
cfg = Config(args.cfgfile)
# GRB ---!
if cfg.get('runid') == 'all':
runids = [f.replace('.fits', '') for f in os.listdir(cfg.get('catalog')) if isfile(join(cfg.get('catalog'), f))]
elif type(cfg.get('runid')) == str:
runids = [cfg.get('runid')]
else:
runids = cfg.get('runid')
runids = sorted(runids)
# CALDB ---!
if type(cfg.get('caldb')) == str:
caldbs = [cfg.get('caldb')]
else:
caldbs = cfg.get('caldb')
caldbs = sorted(caldbs)
# IRF ---!
if type(cfg.get('irf')) == str:
irfs = [cfg.get('irf')]
else:
irfs = cfg.get('irf')
irfs = sorted(irfs)
# general ---!
start_count = cfg.get('start_count')
trials = cfg.get('trials')
if cfg.get('offset') == 'str':
offset = cfg.get('offset').upper()
else:
offset = cfg.get('offset')
# paths ---!
datapath = cfg.get('data')
if not isdir(datapath): # main data folder
raise ValueError('Please specify a valid path')
if not isdir(join(datapath, 'obs')): # obs parent folder
raise ValueError(f'Missing obs parent folder in {datapath}')
if not isdir(f"{datapath}/outputs"):
os.mkdir(f"{datapath}/outputs")
if not isdir(f"{datapath}/rta_products"):
os.mkdir(f"{datapath}/rta_products")
if not isdir(f"{datapath}/skymaps"):
os.mkdir(f"{datapath}/skymaps")
# ------------------------------------------------------ loop runid --- !!!
for runid in runids:
print(f"{"-"*50} #\nProcessing runid: {runid}")
if not isdir(f"{datapath}/outputs/{runid}"):
os.mkdir(f"{datapath}/outputs/{runid}")
if not isdir(f"{datapath}/rta_products/{runid}"):
os.mkdir(f"{datapath}/rta_products/{runid}")
png = f"{datapath}/skymaps/{runid}"
if not isdir(png):
os.mkdir(png)
# grb path ---!
grbpath = join(datapath, 'obs', runid)
if not isdir(grbpath):
raise FileExistsError(f"Directory {runid} not found in {datapath}/obs")
rtapath = f'{datapath}/rta_products/{runid}'
# true coords ---!
target = get_pointing(f"{os.path.expandvars(cfg.get("catalog"))}/{runid}.fits")
# get alert pointing
if type(cfg.get('offset')) == str and cfg.get('offset').lower() == 'gw':
mergerpath = os.path.expandvars(cfg.get('merger'))
mergermap = get_mergermap(runid, mergerpath)
if mergermap == None:
raise ValueError(f'Merger map of runid {runid} not found. ')
pointing = get_alert_pointing_gw(mergermap)
else:
if runid == 'crab':
pointing = [83.6331, 22.0145]
else:
pointing = list(get_pointing(f"{os.path.expandvars(cfg.get("catalog"))}/{runid}.fits"))
if pointing[1] < 0:
pointing[0] += 0.0
pointing[1] += -cfg.get('offset')
else:
pointing[0] += 0.0
pointing[1] += cfg.get('offset')
# ------------------------------------------------------ loop caldb ---!!!
for caldb in caldbs:
if args.print.lower() == 'true':
print(f'Calibration database: {caldb}')
# ------------------------------------------------------ loop irf ---!!!
for irf in irfs:
girf = load_cta_irfs(f"{expandvars("$CTOOLS")}/share/caldb/data/cta/{caldb}/bcf/{irf}/irf_file.fits")
if args.print.lower() == 'true':
print(f'Instrument response function: {irf}')
erange = check_energy_thresholds(erange=[cfg.get('emin'), cfg.get('emax')], irf=irf)
# outputs
logname = f"{datapath}/outputs/{runid}/{cfg.get("tool")}{cfg.get("type")}-{caldb}-{irf}-seed{start_count+1:06d}-{start_count+trials:06d}.txt"
if isfile(logname):
os.remove(logname)
# ------------------------------------------------------ loop trials ---!!!
for i in range(trials):
count = start_count + i + 1
if args.print.lower() == 'true':
print(f'Seed = {count:06d}')
name = f'ebl{count:06d}'
if args.merge.lower() == 'true':
phlist = join(grbpath, name+'.fits')
sky = phlist.replace('.fits', '_sky.fits').replace('/obs/', '/rta_products/')
else:
phlist = join(grbpath, f'{name}.xml')
sky = phlist.replace('.xml', '_sky.fits').replace('/obs/', '/rta_products/')
candidates = sky.replace('_sky.fits', '_sources.xml')
fit = candidates.replace('sources', 'fit')
if args.print.lower() == 'true':
print(f'Input observation: {phlist}')
if not isfile(phlist):
print(f'Missing observation {phlist}. \nSkip runid {runid}.')
break
# --------------------------------------------------- loop exposure times ---!!!
for exp in cfg.get('exposure'):
if cfg.get('cumulative'):
times = increase_exposure(start=exp, stop=cfg.get('tobs'), function='linear')
elif cfg.get('lightcurve'):
times = lightcurve_base_binning(start=cfg.get('delay'), stop=cfg.get('tobs'), exposure=exp)
else:
times = exp
if args.print.lower() == 'true':
print(f"Time selections = {times} s")
# ---------------------------------------------------------- loop binning ---!!!
for t in times:
if t == len(times) and cfg.get('lightcurve'):
break
# selection ---!
selphlist = phlist.replace(f'{name}', f'texp{exp}s_{name}')
grb = RTACtoolsAnalysis()
grb.caldb = caldb
grb.irf = irf
grb.roi = cfg.get('roi')
grb.e = erange
if cfg.get('lightcurve'):
grb.t = [t, t + exp]
else:
grb.t = [cfg.get('delay'), cfg.get('delay')+t]
if args.print.lower() == 'true':
print(f"Selection t = {grb.t} s")
texp = grb.t[1] - grb.t[0]
if args.print.lower() == 'true':
print(f"Exposure = {texp} s")
grb.input = phlist
grb.output = selphlist
if args.merge.lower() == 'true':
grb.run_selection()
else:
prefix = join(grbpath, f'texp{exp}s_')
grb.run_selection(prefix=prefix)
# load the event list
events = EventList.read(selphlist, hdu='EVENTS')
gti = GTI.read(selphlist, hdu='GTI')
pointing = events.pointing_radec
observation = Observation.create(pointing=pointing, obs_id=f'{count:02d}', tstart=gti.table['START'] * u.s, tstop=gti.table['STOP'] * u.s, irfs=girf, reference_time=gti.time_ref)
observation._events = events
observations = Observations()
observations.append(observation)
observation.fixed_pointing_info
# initialise gammapy configuration ---!
config = gammapy_config(cfg=cfg, target=target, obs=selphlist, blind=cfg.get('blind'))
# reduce dataset ---!
grb2 = Analysis(config)
grb2.observations = observations
grb2.get_datasets()
# significance
stats = grb2.datasets.info_table()
sqrt_ts = np.nan
oncounts = stats['counts'][0]
offcounts = stats['counts_off'][0]
excess = stats['excess'][0]
alpha = stats['alpha'][0]
sigma = stats['sqrt_ts'][0]
if args.print.lower() == 'true':
print(f"on = {oncounts}; off={offcounts}; excess={excess}; alpha={alpha}; sigma={sigma}")
if sigma < 5:
if args.print.lower() == 'true':
print("Sigma < 5 => break")
break
data = grb2.datasets.stack_reduce(name="stacked")
model = set_model(default=True, target=target, source='GRB', index=cfg.get('index'))
data.models = model[0]
# fit ---!
fit = Fit([data])
result = fit.run()
# flux ---!
phflux = model[1].integral_error(cfg.get('emin')*u.TeV, cfg.get('emax')*u.TeV)
flux = phflux.value[0]
flux_err = phflux.value[1]
# save spectral ---!
k0 = model[1].amplitude.value
gamma = model[1].index.value
e0 = model[1].reference.value
# save target coords ---!
ra = target[0]
dec = target[1]
if args.print.lower() == 'true':
print(f"flux={flux} +/- {flux_err}")
print(f"Spectral k0={k0}; gamma={gamma}; e0={e0}")
if sigma < 5 or grb.t[1] > (cfg.get('tobs')+cfg.get('delay')):
break
# save data ---!
row = f"{runid} {count} {grb.t[0]} {grb.t[1]} {exp} {sqrt_ts} {flux} {flux_err} {ra} {dec} {k0} {gamma} {e0} {oncounts} {offcounts} {alpha} {excess} {sigma} {offset} {cfg.get("delay")} {cfg.get("scalefluxfactor")} {caldb} {irf} gammapy1d\n"
if args.print.lower() == 'true':
print(f"Results: {row}")
if not isfile(logname):
hdr = 'runid seed start stop texp sqrt_ts flux flux_err ra dec prefactor index scale on off alpha excess sigma offset delay scaleflux caldb irf pipe\n'
log = open(logname, 'w+')
log.write(hdr)
log.write(row)
log.close()
else:
log = open(logname, 'a')
log.write(row)
log.close()
del grb
if args.remove.lower() == 'true':
# remove files ---!
os.system(f"rm {datapath}/obs/{runid}/texp*{name}*")
print('...done.\n') | # *******************************************************************************
# Copyright (C) 2021 INAF
#
# This software is distributed under the terms of the BSD-3-Clause license
#
# Authors:
# Ambra Di Piano <ambra.dipiano@inaf.it>
# *******************************************************************************
import numpy as np
import os
import sys
import argparse
from os.path import isdir, join, isfile, expandvars
from RTAscience.lib.RTACtoolsAnalysis import RTACtoolsAnalysis
from RTAscience.lib.RTAGammapyAnalysis import *
from RTAscience.lib.RTAUtils import *
from RTAscience.cfg.Config import Config
from RTAscience.lib.RTAVisualise import plotSkymap
from RTAscience.aph.utils import *
parser = argparse.ArgumentParser(description='ADD SCRIPT DESCRIPTION HERE')
parser.add_argument('-f', '--cfgfile', type=str, required=True, help="Path to the yaml configuration file")
parser.add_argument('--merge', type=str, default='true', help='Merge in single phlist (true) or use observation library (false)')
parser.add_argument('--remove', type=str, default='true', help='Keep only outputs')
parser.add_argument('--print', type=str, default='false', help='Print out results')
args = parser.parse_args()
cfg = Config(args.cfgfile)
# GRB ---!
if cfg.get('runid') == 'all':
runids = [f.replace('.fits', '') for f in os.listdir(cfg.get('catalog')) if isfile(join(cfg.get('catalog'), f))]
elif type(cfg.get('runid')) == str:
runids = [cfg.get('runid')]
else:
runids = cfg.get('runid')
runids = sorted(runids)
# CALDB ---!
if type(cfg.get('caldb')) == str:
caldbs = [cfg.get('caldb')]
else:
caldbs = cfg.get('caldb')
caldbs = sorted(caldbs)
# IRF ---!
if type(cfg.get('irf')) == str:
irfs = [cfg.get('irf')]
else:
irfs = cfg.get('irf')
irfs = sorted(irfs)
# general ---!
start_count = cfg.get('start_count')
trials = cfg.get('trials')
if cfg.get('offset') == 'str':
offset = cfg.get('offset').upper()
else:
offset = cfg.get('offset')
# paths ---!
datapath = cfg.get('data')
if not isdir(datapath): # main data folder
raise ValueError('Please specify a valid path')
if not isdir(join(datapath, 'obs')): # obs parent folder
raise ValueError(f'Missing obs parent folder in {datapath}')
if not isdir(f"{datapath}/outputs"):
os.mkdir(f"{datapath}/outputs")
if not isdir(f"{datapath}/rta_products"):
os.mkdir(f"{datapath}/rta_products")
if not isdir(f"{datapath}/skymaps"):
os.mkdir(f"{datapath}/skymaps")
# ------------------------------------------------------ loop runid --- !!!
for runid in runids:
print(f"{'-'*50} #\nProcessing runid: {runid}")
if not isdir(f"{datapath}/outputs/{runid}"):
os.mkdir(f"{datapath}/outputs/{runid}")
if not isdir(f"{datapath}/rta_products/{runid}"):
os.mkdir(f"{datapath}/rta_products/{runid}")
png = f"{datapath}/skymaps/{runid}"
if not isdir(png):
os.mkdir(png)
# grb path ---!
grbpath = join(datapath, 'obs', runid)
if not isdir(grbpath):
raise FileExistsError(f"Directory {runid} not found in {datapath}/obs")
rtapath = f'{datapath}/rta_products/{runid}'
# true coords ---!
target = get_pointing(f"{os.path.expandvars(cfg.get('catalog'))}/{runid}.fits")
# get alert pointing
if type(cfg.get('offset')) == str and cfg.get('offset').lower() == 'gw':
mergerpath = os.path.expandvars(cfg.get('merger'))
mergermap = get_mergermap(runid, mergerpath)
if mergermap == None:
raise ValueError(f'Merger map of runid {runid} not found. ')
pointing = get_alert_pointing_gw(mergermap)
else:
if runid == 'crab':
pointing = [83.6331, 22.0145]
else:
pointing = list(get_pointing(f"{os.path.expandvars(cfg.get('catalog'))}/{runid}.fits"))
if pointing[1] < 0:
pointing[0] += 0.0
pointing[1] += -cfg.get('offset')
else:
pointing[0] += 0.0
pointing[1] += cfg.get('offset')
# ------------------------------------------------------ loop caldb ---!!!
for caldb in caldbs:
if args.print.lower() == 'true':
print(f'Calibration database: {caldb}')
# ------------------------------------------------------ loop irf ---!!!
for irf in irfs:
girf = load_cta_irfs(f"{expandvars('$CTOOLS')}/share/caldb/data/cta/{caldb}/bcf/{irf}/irf_file.fits")
if args.print.lower() == 'true':
print(f'Instrument response function: {irf}')
erange = check_energy_thresholds(erange=[cfg.get('emin'), cfg.get('emax')], irf=irf)
# outputs
logname = f"{datapath}/outputs/{runid}/{cfg.get('tool')}{cfg.get('type')}-{caldb}-{irf}-seed{start_count+1:06d}-{start_count+trials:06d}.txt"
if isfile(logname):
os.remove(logname)
# ------------------------------------------------------ loop trials ---!!!
for i in range(trials):
count = start_count + i + 1
if args.print.lower() == 'true':
print(f'Seed = {count:06d}')
name = f'ebl{count:06d}'
if args.merge.lower() == 'true':
phlist = join(grbpath, name+'.fits')
sky = phlist.replace('.fits', '_sky.fits').replace('/obs/', '/rta_products/')
else:
phlist = join(grbpath, f'{name}.xml')
sky = phlist.replace('.xml', '_sky.fits').replace('/obs/', '/rta_products/')
candidates = sky.replace('_sky.fits', '_sources.xml')
fit = candidates.replace('sources', 'fit')
if args.print.lower() == 'true':
print(f'Input observation: {phlist}')
if not isfile(phlist):
print(f'Missing observation {phlist}. \nSkip runid {runid}.')
break
# --------------------------------------------------- loop exposure times ---!!!
for exp in cfg.get('exposure'):
if cfg.get('cumulative'):
times = increase_exposure(start=exp, stop=cfg.get('tobs'), function='linear')
elif cfg.get('lightcurve'):
times = lightcurve_base_binning(start=cfg.get('delay'), stop=cfg.get('tobs'), exposure=exp)
else:
times = exp
if args.print.lower() == 'true':
print(f"Time selections = {times} s")
# ---------------------------------------------------------- loop binning ---!!!
for t in times:
if t == len(times) and cfg.get('lightcurve'):
break
# selection ---!
selphlist = phlist.replace(f'{name}', f'texp{exp}s_{name}')
grb = RTACtoolsAnalysis()
grb.caldb = caldb
grb.irf = irf
grb.roi = cfg.get('roi')
grb.e = erange
if cfg.get('lightcurve'):
grb.t = [t, t + exp]
else:
grb.t = [cfg.get('delay'), cfg.get('delay')+t]
if args.print.lower() == 'true':
print(f"Selection t = {grb.t} s")
texp = grb.t[1] - grb.t[0]
if args.print.lower() == 'true':
print(f"Exposure = {texp} s")
grb.input = phlist
grb.output = selphlist
if args.merge.lower() == 'true':
grb.run_selection()
else:
prefix = join(grbpath, f'texp{exp}s_')
grb.run_selection(prefix=prefix)
# load the event list
events = EventList.read(selphlist, hdu='EVENTS')
gti = GTI.read(selphlist, hdu='GTI')
pointing = events.pointing_radec
observation = Observation.create(pointing=pointing, obs_id=f'{count:02d}', tstart=gti.table['START'] * u.s, tstop=gti.table['STOP'] * u.s, irfs=girf, reference_time=gti.time_ref)
observation._events = events
observations = Observations()
observations.append(observation)
observation.fixed_pointing_info
# initialise gammapy configuration ---!
config = gammapy_config(cfg=cfg, target=target, obs=selphlist, blind=cfg.get('blind'))
# reduce dataset ---!
grb2 = Analysis(config)
grb2.observations = observations
grb2.get_datasets()
# significance
stats = grb2.datasets.info_table()
sqrt_ts = np.nan
oncounts = stats['counts'][0]
offcounts = stats['counts_off'][0]
excess = stats['excess'][0]
alpha = stats['alpha'][0]
sigma = stats['sqrt_ts'][0]
if args.print.lower() == 'true':
print(f"on = {oncounts}; off={offcounts}; excess={excess}; alpha={alpha}; sigma={sigma}")
if sigma < 5:
if args.print.lower() == 'true':
print("Sigma < 5 => break")
break
data = grb2.datasets.stack_reduce(name="stacked")
model = set_model(default=True, target=target, source='GRB', index=cfg.get('index'))
data.models = model[0]
# fit ---!
fit = Fit([data])
result = fit.run()
# flux ---!
phflux = model[1].integral_error(cfg.get('emin')*u.TeV, cfg.get('emax')*u.TeV)
flux = phflux.value[0]
flux_err = phflux.value[1]
# save spectral ---!
k0 = model[1].amplitude.value
gamma = model[1].index.value
e0 = model[1].reference.value
# save target coords ---!
ra = target[0]
dec = target[1]
if args.print.lower() == 'true':
print(f"flux={flux} +/- {flux_err}")
print(f"Spectral k0={k0}; gamma={gamma}; e0={e0}")
if sigma < 5 or grb.t[1] > (cfg.get('tobs')+cfg.get('delay')):
break
# save data ---!
row = f"{runid} {count} {grb.t[0]} {grb.t[1]} {exp} {sqrt_ts} {flux} {flux_err} {ra} {dec} {k0} {gamma} {e0} {oncounts} {offcounts} {alpha} {excess} {sigma} {offset} {cfg.get('delay')} {cfg.get('scalefluxfactor')} {caldb} {irf} gammapy1d\n"
if args.print.lower() == 'true':
print(f"Results: {row}")
if not isfile(logname):
hdr = 'runid seed start stop texp sqrt_ts flux flux_err ra dec prefactor index scale on off alpha excess sigma offset delay scaleflux caldb irf pipe\n'
log = open(logname, 'w+')
log.write(hdr)
log.write(row)
log.close()
else:
log = open(logname, 'a')
log.write(row)
log.close()
del grb
if args.remove.lower() == 'true':
# remove files ---!
os.system(f"rm {datapath}/obs/{runid}/texp*{name}*")
print('...done.\n') |
import logging
import math
from time import process_time
from datetime import date
from numpy.core.numeric import Infinity, NaN
import pandas as pd
from bsbetl.alltable_calcs import Calculation
from bsbetl.alltable_calcs.at_params import at_calc_params
from bsbetl.calc_helpers import first_trading_row_index, last_days_filter, last_trading_row_index, single_day_condition
from bsbetl import ov_helpers
class M_ParticularSumOfMV(Calculation.Calculation):
def __init__(self):
super().__init__('ParticularSumOfMV')
self.description = 'Particular Sum of Minute Volume'
self.dependents = ['volume','AvMV']
self.at_computeds = ['PSMV','CV1','RCV1','MVm','AvMVdec']
self.ov_computeds = ['PSMV','CV1','CV1.D-1','CV1.D-2','CV1.D-3','CV1.D-4','CV1.D-5','RCV1','RCV1.D-1','RCV1.D-2','RCV1.D-3','RCV1.D-4','RCV1.D-5','AvMVdec']
# def decline_PSMV(self, row, **kwargs):
# ''' gets called for every row by an apply function'''
# df = kwargs['df']
# psmv_colnum = kwargs['psmv_colnum']
# volume_colnum = kwargs['volume_colnum']
# df_index_list=kwargs['df_index_list']
# try:
# row_ordinal = df_index_list.index(row.name)
# prior_ordinal = row_ordinal-1
# if prior_ordinal >= 0:
# # Step 1: Decline the PSMVCV1 M by 0.97:
# # PSMVCV1 M = 0.97 * PSMVCV1 M-1
# df.iat[row_ordinal,psmv_colnum] = 0.97*df.iat[prior_ordinal,volume_colnum]
# # Step 2: Add the vol of the next minute (MVM after):
# # PSMVCV1 M = PSMVCV1 M-1 + MVM after
# df.iat[row_ordinal,psmv_colnum] = df.iat[prior_ordinal,psmv_colnum] + row['MVm']
# except ValueError as exc:
# logging.warn(f"{exc}\n row name='{row.name}'")
# return row
def calculate(self, df: pd.DataFrame, share_num: str, dates_in_df: list, top_up: bool, stage: int):
''' Module CV1 2: Calc the Particular Sum of MV, PSMVCV1 M:
Module CV1 3: Calc the Cluster Vol of the day D, CV1D :
'''
assert stage == 1, f'{self.name} calculation should only run at stage 1'
# 'AvMV' assumed already computed in M_DailyHighPrice.py
cv1=0
cv1_stack=[]
rcv1=0
rcv1_stack=[]
bot_idx=None
MVm_colnum = df.columns.get_loc('MVm')
PSMV_colnum = df.columns.get_loc('PSMV')
#VOL_colnum = df.columns.get_loc('volume')
#df_index_list=df.index.tolist()
# 2a1) Decline every MV which is not zero by AvMVD:
# MVM before - AvMVD = MVM after
df['MVm'] = df['volume']-df['AvMV']
# zero the negative ones
df['MVm'][df['MVm'] < 0]=0
# compute PSMV NOTE takes 40 seconds per share !!!
# df.apply(lambda row: self.decline_PSMV(row,df=df, psmv_colnum=PSMV_colnum, volume_colnum=VOL_colnum, df_index_list=df_index_list), axis=1)
# Step 1: Decline the PSMVCV1 M by 0.97:
# PSMVCV1 M = 0.97 * PSMVCV1 M-1
df['PSMV'] = 0.97*df['PSMV'].shift(1,fill_value=df.iat[0,PSMV_colnum])
# Step 2: Add the vol of the next minute (MVM after):
# PSMVCV1 M = PSMVCV1 M-1 + MVM after
df['PSMV'] = df['PSMV'].shift(1,fill_value=df.iat[0,PSMV_colnum]) + df['MVm'].shift(-1,fill_value=0)
for cur_dt in dates_in_df:
# should be unecessary since its already been stripped of weekdays
if cur_dt.weekday() >= 5:
continue
single_day = single_day_condition(df, cur_dt)
# work one day at a time
day_DF = df[single_day]
# at this point every MVm and PSMV has been computed (above)
# Module CV1 3: Calc the Cluster Vol of the day D, CV1D :
# CV1 = PSMVWb1 biggest / AvMV
# Now again calc an Average Minute Vol, AvMVdec on day D (AvMVdec D):
AvMVdecD = day_DF['MVm'].mean()
# this value needs to be in every row
df['AvMVdec'][single_day] = AvMVdecD
psmv_biggest = day_DF['PSMV'].max(axis=0)
psmv_last = day_DF.iloc[-1,PSMV_colnum]
# end of day assignments of CV1 and RCV1
# CV1 = PSMVWb1 biggest / AvMV
cv1 = psmv_biggest/AvMVdecD
# convoluted way to safely obtain sensible prior_cv1
try:
prior_cv1=cv1 # init
if len(cv1_stack)>0:
# prior_cv1=cv1_stack.pop()
# cv1_stack.append(prior_cv1)
prior_cv1=cv1_stack[-1]
except IndexError as exc:
logging.error(f'M_ParticularSumOfMV exception {exc}')
cv1_stack.append(cv1) # save this cv1 for recall below
rcv1=0
if prior_cv1 != 0:
rcv1 = cv1/prior_cv1
rcv1_stack.append(rcv1) # save this rcv1 for recall below
bot_idx = last_trading_row_index(df, cur_dt, stage)
if len(bot_idx) > 0:
# this ought to be the 17:35 slot
#print(f"assigning cv1 {cv1} and rcv1 {rcv1} to row {bot_idx}")
df.loc[bot_idx,'CV1'] = cv1
df.loc[bot_idx,'RCV1'] = rcv1
#df.loc[bot_idx,'AvMVdec'] = AvMVdecD
else:
logging.debug(f"M_PSMV: Share {share_num}: couldn"t locate 17:35 band for date {cur_dt.strftime("%Y-%m-%d")}")
# NOTE check if the very last day of the data was not the 17:35 slot
if isinstance(bot_idx,pd.DatetimeIndex) and len(bot_idx)==0:
# put the last computed values into the last
# row, even though its not a 17:35 slot
df.loc[df.index[-1],'CV1'] = cv1
df.loc[df.index[-1],'RCV1'] = rcv1
#df.loc[df.index[-1],'AvMVdec'] = rcv1
# now for the overview... use last assigned values
ov_helpers.global_ov_update(share_num, 'PSMV', psmv_last)
ov_helpers.global_ov_update(share_num, 'CV1', cv1)
ov_helpers.global_ov_update(share_num, 'RCV1', rcv1)
# now assign CV1.D-1 thru D-5
try:
_ = cv1_stack.pop() # discard last one since its already stored as 'CV1'
CV1s = ['CV1.D-1','CV1.D-2','CV1.D-3','CV1.D-4','CV1.D-5',]
for entry in CV1s:
cv1=cv1_stack.pop()
ov_helpers.global_ov_update(share_num, entry, cv1)
_ = rcv1_stack.pop() # discard " " " "
# assign RCV1.D-1 ..etc
RCV1s = ['RCV1.D-1','RCV1.D-2','RCV1.D-3','RCV1.D-4','RCV1.D-5',]
smallest_rcv1 = math.inf
for entry in RCV1s:
rcv1=rcv1_stack.pop()
ov_helpers.global_ov_update(share_num, entry, rcv1)
# also grab the smallest rcv1 while assigning
if rcv1 < smallest_rcv1:
smallest_rcv1 = rcv1
except IndexError as exc:
logging.error(f'M_ParticularSumOfMV exception {exc}')
#assign smallest
ov_helpers.global_ov_update(share_num, 'RCV1small', smallest_rcv1)
logging.info(f'{self.name} done.')
| import logging
import math
from time import process_time
from datetime import date
from numpy.core.numeric import Infinity, NaN
import pandas as pd
from bsbetl.alltable_calcs import Calculation
from bsbetl.alltable_calcs.at_params import at_calc_params
from bsbetl.calc_helpers import first_trading_row_index, last_days_filter, last_trading_row_index, single_day_condition
from bsbetl import ov_helpers
class M_ParticularSumOfMV(Calculation.Calculation):
def __init__(self):
super().__init__('ParticularSumOfMV')
self.description = 'Particular Sum of Minute Volume'
self.dependents = ['volume','AvMV']
self.at_computeds = ['PSMV','CV1','RCV1','MVm','AvMVdec']
self.ov_computeds = ['PSMV','CV1','CV1.D-1','CV1.D-2','CV1.D-3','CV1.D-4','CV1.D-5','RCV1','RCV1.D-1','RCV1.D-2','RCV1.D-3','RCV1.D-4','RCV1.D-5','AvMVdec']
# def decline_PSMV(self, row, **kwargs):
# ''' gets called for every row by an apply function'''
# df = kwargs['df']
# psmv_colnum = kwargs['psmv_colnum']
# volume_colnum = kwargs['volume_colnum']
# df_index_list=kwargs['df_index_list']
# try:
# row_ordinal = df_index_list.index(row.name)
# prior_ordinal = row_ordinal-1
# if prior_ordinal >= 0:
# # Step 1: Decline the PSMVCV1 M by 0.97:
# # PSMVCV1 M = 0.97 * PSMVCV1 M-1
# df.iat[row_ordinal,psmv_colnum] = 0.97*df.iat[prior_ordinal,volume_colnum]
# # Step 2: Add the vol of the next minute (MVM after):
# # PSMVCV1 M = PSMVCV1 M-1 + MVM after
# df.iat[row_ordinal,psmv_colnum] = df.iat[prior_ordinal,psmv_colnum] + row['MVm']
# except ValueError as exc:
# logging.warn(f"{exc}\n row name='{row.name}'")
# return row
def calculate(self, df: pd.DataFrame, share_num: str, dates_in_df: list, top_up: bool, stage: int):
''' Module CV1 2: Calc the Particular Sum of MV, PSMVCV1 M:
Module CV1 3: Calc the Cluster Vol of the day D, CV1D :
'''
assert stage == 1, f'{self.name} calculation should only run at stage 1'
# 'AvMV' assumed already computed in M_DailyHighPrice.py
cv1=0
cv1_stack=[]
rcv1=0
rcv1_stack=[]
bot_idx=None
MVm_colnum = df.columns.get_loc('MVm')
PSMV_colnum = df.columns.get_loc('PSMV')
#VOL_colnum = df.columns.get_loc('volume')
#df_index_list=df.index.tolist()
# 2a1) Decline every MV which is not zero by AvMVD:
# MVM before - AvMVD = MVM after
df['MVm'] = df['volume']-df['AvMV']
# zero the negative ones
df['MVm'][df['MVm'] < 0]=0
# compute PSMV NOTE takes 40 seconds per share !!!
# df.apply(lambda row: self.decline_PSMV(row,df=df, psmv_colnum=PSMV_colnum, volume_colnum=VOL_colnum, df_index_list=df_index_list), axis=1)
# Step 1: Decline the PSMVCV1 M by 0.97:
# PSMVCV1 M = 0.97 * PSMVCV1 M-1
df['PSMV'] = 0.97*df['PSMV'].shift(1,fill_value=df.iat[0,PSMV_colnum])
# Step 2: Add the vol of the next minute (MVM after):
# PSMVCV1 M = PSMVCV1 M-1 + MVM after
df['PSMV'] = df['PSMV'].shift(1,fill_value=df.iat[0,PSMV_colnum]) + df['MVm'].shift(-1,fill_value=0)
for cur_dt in dates_in_df:
# should be unecessary since its already been stripped of weekdays
if cur_dt.weekday() >= 5:
continue
single_day = single_day_condition(df, cur_dt)
# work one day at a time
day_DF = df[single_day]
# at this point every MVm and PSMV has been computed (above)
# Module CV1 3: Calc the Cluster Vol of the day D, CV1D :
# CV1 = PSMVWb1 biggest / AvMV
# Now again calc an Average Minute Vol, AvMVdec on day D (AvMVdec D):
AvMVdecD = day_DF['MVm'].mean()
# this value needs to be in every row
df['AvMVdec'][single_day] = AvMVdecD
psmv_biggest = day_DF['PSMV'].max(axis=0)
psmv_last = day_DF.iloc[-1,PSMV_colnum]
# end of day assignments of CV1 and RCV1
# CV1 = PSMVWb1 biggest / AvMV
cv1 = psmv_biggest/AvMVdecD
# convoluted way to safely obtain sensible prior_cv1
try:
prior_cv1=cv1 # init
if len(cv1_stack)>0:
# prior_cv1=cv1_stack.pop()
# cv1_stack.append(prior_cv1)
prior_cv1=cv1_stack[-1]
except IndexError as exc:
logging.error(f'M_ParticularSumOfMV exception {exc}')
cv1_stack.append(cv1) # save this cv1 for recall below
rcv1=0
if prior_cv1 != 0:
rcv1 = cv1/prior_cv1
rcv1_stack.append(rcv1) # save this rcv1 for recall below
bot_idx = last_trading_row_index(df, cur_dt, stage)
if len(bot_idx) > 0:
# this ought to be the 17:35 slot
#print(f"assigning cv1 {cv1} and rcv1 {rcv1} to row {bot_idx}")
df.loc[bot_idx,'CV1'] = cv1
df.loc[bot_idx,'RCV1'] = rcv1
#df.loc[bot_idx,'AvMVdec'] = AvMVdecD
else:
logging.debug(f"M_PSMV: Share {share_num}: couldn't locate 17:35 band for date {cur_dt.strftime('%Y-%m-%d')}")
# NOTE check if the very last day of the data was not the 17:35 slot
if isinstance(bot_idx,pd.DatetimeIndex) and len(bot_idx)==0:
# put the last computed values into the last
# row, even though its not a 17:35 slot
df.loc[df.index[-1],'CV1'] = cv1
df.loc[df.index[-1],'RCV1'] = rcv1
#df.loc[df.index[-1],'AvMVdec'] = rcv1
# now for the overview... use last assigned values
ov_helpers.global_ov_update(share_num, 'PSMV', psmv_last)
ov_helpers.global_ov_update(share_num, 'CV1', cv1)
ov_helpers.global_ov_update(share_num, 'RCV1', rcv1)
# now assign CV1.D-1 thru D-5
try:
_ = cv1_stack.pop() # discard last one since its already stored as 'CV1'
CV1s = ['CV1.D-1','CV1.D-2','CV1.D-3','CV1.D-4','CV1.D-5',]
for entry in CV1s:
cv1=cv1_stack.pop()
ov_helpers.global_ov_update(share_num, entry, cv1)
_ = rcv1_stack.pop() # discard " " " "
# assign RCV1.D-1 ..etc
RCV1s = ['RCV1.D-1','RCV1.D-2','RCV1.D-3','RCV1.D-4','RCV1.D-5',]
smallest_rcv1 = math.inf
for entry in RCV1s:
rcv1=rcv1_stack.pop()
ov_helpers.global_ov_update(share_num, entry, rcv1)
# also grab the smallest rcv1 while assigning
if rcv1 < smallest_rcv1:
smallest_rcv1 = rcv1
except IndexError as exc:
logging.error(f'M_ParticularSumOfMV exception {exc}')
#assign smallest
ov_helpers.global_ov_update(share_num, 'RCV1small', smallest_rcv1)
logging.info(f'{self.name} done.')
|
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import functools
import logging
import os
import re
from dataclasses import dataclass
from enum import Enum
from pants.backend.jvm.subsystems.dependency_context import DependencyContext # noqa
from pants.backend.jvm.subsystems.rsc import Rsc
from pants.backend.jvm.subsystems.shader import Shader
from pants.backend.jvm.targets.jvm_target import JvmTarget
from pants.backend.jvm.tasks.classpath_entry import ClasspathEntry
from pants.backend.jvm.tasks.jvm_compile.compile_context import CompileContext
from pants.backend.jvm.tasks.jvm_compile.execution_graph import Job
from pants.backend.jvm.tasks.jvm_compile.zinc.zinc_compile import ZincCompile
from pants.base.build_environment import get_buildroot
from pants.base.exceptions import TaskError
from pants.base.workunit import WorkUnitLabel
from pants.build_graph.mirrored_target_option_mixin import MirroredTargetOptionMixin
from pants.engine.fs import (
EMPTY_DIRECTORY_DIGEST,
Digest,
DirectoryToMaterialize,
PathGlobs,
PathGlobsAndRoot,
)
from pants.engine.isolated_process import ExecuteProcessRequest, FallibleExecuteProcessResult
from pants.java.jar.jar_dependency import JarDependency
from pants.reporting.reporting_utils import items_to_report_element
from pants.task.scm_publish_mixin import Semver
from pants.util.collections import assert_single_element
from pants.util.contextutil import Timer
from pants.util.dirutil import fast_relpath, fast_relpath_optional, safe_mkdir
from pants.util.enums import match
from pants.util.memo import memoized_method, memoized_property
from pants.util.strutil import safe_shlex_join
#
# This is a subclass of zinc compile that uses both Rsc and Zinc to do
# compilation.
# It uses Rsc and the associated tools to outline scala targets. It then
# passes those outlines to zinc to produce the final compile artifacts.
#
#
logger = logging.getLogger(__name__)
def fast_relpath_collection(collection):
buildroot = get_buildroot()
return [fast_relpath_optional(c, buildroot) or c for c in collection]
def stdout_contents(wu):
if isinstance(wu, FallibleExecuteProcessResult):
return wu.stdout.rstrip()
with open(wu.output_paths()["stdout"]) as f:
return f.read().rstrip()
def _create_desandboxify_fn(possible_path_patterns):
# Takes a collection of possible canonical prefixes, and returns a function that
# if it finds a matching prefix, strips the path prior to the prefix and returns it
# if it doesn't it returns the original path
# TODO remove this after https://github.com/scalameta/scalameta/issues/1791 is released
regexes = [re.compile(f"/({p})") for p in possible_path_patterns]
def desandboxify(path):
if not path:
return path
for r in regexes:
match = r.search(path)
if match:
logger.debug(f"path-cleanup: matched {match} with {r.pattern} against {path}")
return match.group(1)
logger.debug(f"path-cleanup: no match for {path}")
return path
return desandboxify
class CompositeProductAdder:
def __init__(self, *products):
self.products = products
def add_for_target(self, *args, **kwargs):
for product in self.products:
product.add_for_target(*args, **kwargs)
class RscCompileContext(CompileContext):
def __init__(
self,
target,
analysis_file,
classes_dir,
rsc_jar_file,
jar_file,
log_dir,
args_file,
post_compile_merge_dir,
sources,
workflow,
):
super().__init__(
target,
analysis_file,
classes_dir,
jar_file,
log_dir,
args_file,
post_compile_merge_dir,
sources,
)
self.workflow = workflow
self.rsc_jar_file = rsc_jar_file
def ensure_output_dirs_exist(self):
safe_mkdir(os.path.dirname(self.rsc_jar_file.path))
class RscCompile(ZincCompile, MirroredTargetOptionMixin):
"""Compile Scala and Java code to classfiles using Rsc."""
_name = "mixed"
compiler_name = "rsc"
@classmethod
def subsystem_dependencies(cls):
return super().subsystem_dependencies() + (Rsc,)
@memoized_property
def mirrored_target_option_actions(self):
return {
"workflow": self._identify_workflow_tags,
}
@classmethod
def implementation_version(cls):
return super().implementation_version() + [("RscCompile", 174)]
class JvmCompileWorkflowType(Enum):
"""Target classifications used to correctly schedule Zinc and Rsc jobs.
There are some limitations we have to work around before we can compile everything through Rsc
and followed by Zinc.
- rsc is not able to outline all scala code just yet (this is also being addressed through
automated rewrites).
- javac is unable to consume rsc's jars just yet.
- rsc is not able to outline all java code just yet (this is likely to *not* require rewrites,
just some more work on rsc).
As we work on improving our Rsc integration, we'll need to create more workflows to more closely
map the supported features of Rsc. This enum class allows us to do that.
- zinc-only: compiles targets just with Zinc and uses the Zinc products of their dependencies.
- zinc-java: the same as zinc-only for now, for targets with any java sources (which rsc can't
syet outline).
- rsc-and-zinc: compiles targets with Rsc to create "header" jars, and runs Zinc against the
Rsc products of their dependencies. The Rsc compile uses the Rsc products of Rsc compatible
targets and the Zinc products of zinc-only targets.
- outline-and-zinc: compiles targets with scalac's outlining to create "header" jars,
in place of Rsc. While this is slower, it conforms to Scala without rewriting code.
"""
zinc_only = "zinc-only"
zinc_java = "zinc-java"
rsc_and_zinc = "rsc-and-zinc"
outline_and_zinc = "outline-and-zinc"
@memoized_property
def _compiler_tags(self):
return {
f"{self.get_options().force_compiler_tag_prefix}:{workflow.value}": workflow
for workflow in self.JvmCompileWorkflowType
}
@classmethod
def register_options(cls, register):
super().register_options(register)
register(
"--force-compiler-tag-prefix",
default="use-compiler",
metavar="<tag>",
help="Always compile targets marked with this tag with rsc, unless the workflow is "
"specified on the cli.",
)
register(
"--workflow",
type=cls.JvmCompileWorkflowType,
choices=list(cls.JvmCompileWorkflowType),
default=cls.JvmCompileWorkflowType.zinc_only,
metavar="<workflow>",
help="The default workflow to use to compile JVM targets. This is overridden on a per-target basis with the force-compiler-tag-prefix tag.",
fingerprint=True,
)
register(
"--scala-workflow-override",
type=cls.JvmCompileWorkflowType,
choices=list(cls.JvmCompileWorkflowType),
default=None,
metavar="<workflow_override>",
help='Experimental option. The workflow to use to compile Scala targets, overriding the "workflow" option as well as any force-compiler-tag-prefix tags applied to targets. An example use case is to quickly turn off outlining workflows in case of errors.',
fingerprint=True,
)
register(
"--extra-rsc-args",
type=list,
default=[],
help="Extra arguments to pass to the rsc invocation.",
)
register(
"--zinc-outline",
type=bool,
default=False,
help="Outline via Zinc when workflow is outline-and-zinc instead of a standalone scalac tool. This allows outlining to happen in the same nailgun instance as zinc compiles.",
fingerprint=True,
)
cls.register_jvm_tool(
register,
"rsc",
classpath=[
JarDependency(org="com.twitter", name="rsc_2.12", rev="0.0.0-768-7357aa0a",),
],
custom_rules=[Shader.exclude_package("rsc", recursive=True),],
)
scalac_outliner_version = "2.12.10"
cls.register_jvm_tool(
register,
"scalac-outliner",
classpath=[
JarDependency(
org="org.scala-lang", name="scala-compiler", rev=scalac_outliner_version,
),
],
custom_rules=[
Shader.exclude_package("scala", recursive=True),
Shader.exclude_package("xsbt", recursive=True),
Shader.exclude_package("xsbti", recursive=True),
# Unfortunately, is loaded reflectively by the compiler.
Shader.exclude_package("org.apache.logging.log4j", recursive=True),
],
)
@classmethod
def product_types(cls):
return super(RscCompile, cls).product_types() + ["rsc_mixed_compile_classpath"]
@memoized_property
def _rsc(self):
return Rsc.global_instance()
@memoized_property
def _rsc_classpath(self):
return self.tool_classpath("rsc")
@memoized_property
def _scalac_classpath(self):
return self.tool_classpath("scalac-outliner")
@memoized_property
def _scala_library_version(self):
return self._zinc.scala_library.coordinate.rev
# TODO: allow @memoized_method to convert lists into tuples so they can be hashed!
@memoized_property
def _nailgunnable_combined_classpath(self):
"""Register all of the component tools of the rsc compile task as a "combined" jvm tool.
This allows us to invoke their combined classpath in a single nailgun instance (see #7089
and #7092). We still invoke their classpaths separately when not using nailgun, however.
"""
cp = []
cp.extend(self._rsc_classpath)
# Add zinc's classpath so that it can be invoked from the same nailgun instance.
cp.extend(super().get_zinc_compiler_classpath())
return cp
# Overrides the normal zinc compiler classpath, which only contains zinc.
def get_zinc_compiler_classpath(self):
return match(
self.execution_strategy,
{
# NB: We must use the verbose version of super() here, possibly because of the lambda.
self.ExecutionStrategy.hermetic: lambda: super(
RscCompile, self
).get_zinc_compiler_classpath(),
self.ExecutionStrategy.subprocess: lambda: super(
RscCompile, self
).get_zinc_compiler_classpath(),
self.ExecutionStrategy.nailgun: lambda: self._nailgunnable_combined_classpath,
},
)()
def register_extra_products_from_contexts(self, targets, compile_contexts):
super().register_extra_products_from_contexts(targets, compile_contexts)
def confify(entries):
return [(conf, e) for e in entries for conf in self._confs]
# Ensure that the jar/rsc jar is on the rsc_mixed_compile_classpath.
for target in targets:
merged_cc = compile_contexts[target]
zinc_cc = merged_cc.zinc_cc
rsc_cc = merged_cc.rsc_cc
# Make sure m.jar is digested if it exists when the target is validated.
if rsc_cc.rsc_jar_file.directory_digest is None and os.path.exists(
rsc_cc.rsc_jar_file.path
):
relpath = fast_relpath(rsc_cc.rsc_jar_file.path, get_buildroot())
(classes_dir_snapshot,) = self.context._scheduler.capture_snapshots(
[
PathGlobsAndRoot(
PathGlobs([relpath]), get_buildroot(), Digest.load(relpath),
),
]
)
rsc_cc.rsc_jar_file.hydrate_missing_directory_digest(
classes_dir_snapshot.directory_digest
)
if rsc_cc.workflow is not None:
cp_entries = match(
rsc_cc.workflow,
{
self.JvmCompileWorkflowType.zinc_only: lambda: confify(
[self._classpath_for_context(zinc_cc)]
),
self.JvmCompileWorkflowType.zinc_java: lambda: confify(
[self._classpath_for_context(zinc_cc)]
),
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: confify(
[rsc_cc.rsc_jar_file]
),
self.JvmCompileWorkflowType.outline_and_zinc: lambda: confify(
[rsc_cc.rsc_jar_file]
),
},
)()
self.context.products.get_data("rsc_mixed_compile_classpath").add_for_target(
target, cp_entries
)
def create_empty_extra_products(self):
super().create_empty_extra_products()
compile_classpath = self.context.products.get_data("compile_classpath")
runtime_classpath = self.context.products.get_data("runtime_classpath")
classpath_product = self.context.products.get_data("rsc_mixed_compile_classpath")
if not classpath_product:
classpath_product = self.context.products.get_data(
"rsc_mixed_compile_classpath", compile_classpath.copy
)
else:
classpath_product.update(compile_classpath)
classpath_product.update(runtime_classpath)
def select(self, target):
if not isinstance(target, JvmTarget):
return False
return self._classify_target_compile_workflow(target) is not None
@memoized_method
def _identify_workflow_tags(self, target):
try:
all_tags = [self._compiler_tags.get(tag) for tag in target.tags]
filtered_tags = filter(None, all_tags)
return assert_single_element(list(filtered_tags))
except StopIteration:
return None
except ValueError as e:
raise ValueError(
"Multiple compile workflow tags specified for target {}: {}".format(target, e)
)
@memoized_method
def _classify_target_compile_workflow(self, target):
"""Return the compile workflow to use for this target."""
# scala_library() targets may have a `.java_sources` property.
java_sources = getattr(target, "java_sources", [])
if java_sources or target.has_sources(".java"):
# If there are any java sources to compile, treat it as a java library since rsc can't outline
# java yet.
return self.JvmCompileWorkflowType.zinc_java
if target.has_sources(".scala"):
workflow_override = self.get_options().scala_workflow_override
if workflow_override is not None:
return self.JvmCompileWorkflowType(workflow_override)
return self.get_scalar_mirrored_target_option("workflow", target)
return None
def _key_for_target_as_dep(self, target, workflow):
# used for jobs that are either rsc jobs or zinc jobs run against rsc
return match(
workflow,
{
self.JvmCompileWorkflowType.zinc_only: lambda: self._zinc_key_for_target(
target, workflow
),
self.JvmCompileWorkflowType.zinc_java: lambda: self._zinc_key_for_target(
target, workflow
),
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: self._rsc_key_for_target(target),
self.JvmCompileWorkflowType.outline_and_zinc: lambda: self._outline_key_for_target(
target
),
},
)()
def _rsc_key_for_target(self, target):
return f"rsc({target.address.spec})"
def _outline_key_for_target(self, target):
return f"outline({target.address.spec})"
def _zinc_key_for_target(self, target, workflow):
return match(
workflow,
{
self.JvmCompileWorkflowType.zinc_only: lambda: f"zinc[zinc-only]({target.address.spec})",
self.JvmCompileWorkflowType.zinc_java: lambda: f"zinc[zinc-java]({target.address.spec})",
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: f"zinc[rsc-and-zinc]({target.address.spec})",
self.JvmCompileWorkflowType.outline_and_zinc: lambda: f"zinc[outline-and-zinc]({target.address.spec})",
},
)()
def _write_to_cache_key_for_target(self, target):
return f"write_to_cache({target.address.spec})"
def create_compile_jobs(
self,
compile_target,
compile_contexts,
invalid_dependencies,
ivts,
counter,
runtime_classpath_product,
):
def work_for_vts_rsc(vts, ctx):
target = ctx.target
(tgt,) = vts.targets
rsc_cc = compile_contexts[target].rsc_cc
use_youtline = rsc_cc.workflow == self.JvmCompileWorkflowType.outline_and_zinc
outliner = "scalac-outliner" if use_youtline else "rsc"
if use_youtline and Semver.parse(self._scala_library_version) < Semver.parse("2.12.9"):
raise RuntimeError(
f"To use scalac's built-in outlining, scala version must be at least 2.12.9, but got {self._scala_library_version}"
)
# If we didn't hit the cache in the cache job, run rsc.
if not vts.valid:
counter_val = str(counter()).rjust(counter.format_length(), " ")
counter_str = f"[{counter_val}/{counter.size}] "
action_str = "Outlining " if use_youtline else "Rsc-ing "
self.context.log.info(
counter_str,
action_str,
items_to_report_element(ctx.sources, f"{self.name()} source"),
" in ",
items_to_report_element([t.address.reference() for t in vts.targets], "target"),
" (",
ctx.target.address.spec,
").",
)
# This does the following
# - Collect the rsc classpath elements, including zinc compiles of rsc incompatible targets
# and rsc compiles of rsc compatible targets.
# - Run Rsc on the current target with those as dependencies.
dependencies_for_target = list(
DependencyContext.global_instance().dependencies_respecting_strict_deps(target)
)
classpath_paths = []
classpath_directory_digests = []
classpath_product = self.context.products.get_data("rsc_mixed_compile_classpath")
classpath_entries = classpath_product.get_classpath_entries_for_targets(
dependencies_for_target
)
hermetic = self.execution_strategy == self.ExecutionStrategy.hermetic
for _conf, classpath_entry in classpath_entries:
classpath_paths.append(fast_relpath(classpath_entry.path, get_buildroot()))
if hermetic and not classpath_entry.directory_digest:
raise AssertionError(
"ClasspathEntry {} didn't have a Digest, so won't be present for hermetic "
"execution of {}".format(classpath_entry, outliner)
)
classpath_directory_digests.append(classpath_entry.directory_digest)
ctx.ensure_output_dirs_exist()
with Timer() as timer:
# Outline Scala sources into SemanticDB / scalac compatible header jars.
# ---------------------------------------------
rsc_jar_file_relative_path = fast_relpath(
ctx.rsc_jar_file.path, get_buildroot()
)
sources_snapshot = ctx.target.sources_snapshot(
scheduler=self.context._scheduler
)
distribution = self._get_jvm_distribution()
def hermetic_digest_classpath():
jdk_libs_rel, jdk_libs_digest = self._jdk_libs_paths_and_digest(
distribution
)
merged_sources_and_jdk_digest = self.context._scheduler.merge_directories(
(jdk_libs_digest, sources_snapshot.directory_digest)
+ tuple(classpath_directory_digests)
)
classpath_rel_jdk = classpath_paths + jdk_libs_rel
return (merged_sources_and_jdk_digest, classpath_rel_jdk)
def nonhermetic_digest_classpath():
classpath_abs_jdk = classpath_paths + self._jdk_libs_abs(distribution)
return ((EMPTY_DIRECTORY_DIGEST), classpath_abs_jdk)
(input_digest, classpath_entry_paths) = match(
self.execution_strategy,
{
self.ExecutionStrategy.hermetic: hermetic_digest_classpath,
self.ExecutionStrategy.subprocess: nonhermetic_digest_classpath,
self.ExecutionStrategy.nailgun: nonhermetic_digest_classpath,
},
)()
youtline_args = []
if use_youtline:
youtline_args = [
"-Youtline",
"-Ystop-after:pickler",
"-Ypickle-write",
rsc_jar_file_relative_path,
]
target_sources = ctx.sources
# TODO: m.jar digests aren't found, so hermetic will fail.
if use_youtline and not hermetic and self.get_options().zinc_outline:
self._zinc_outline(ctx, classpath_paths, target_sources, youtline_args)
else:
args = (
[
"-cp",
os.pathsep.join(classpath_entry_paths),
"-d",
rsc_jar_file_relative_path,
]
+ self.get_options().extra_rsc_args
+ youtline_args
+ target_sources
)
self.write_argsfile(ctx, args)
self._runtool(distribution, input_digest, ctx, use_youtline)
self._record_target_stats(
tgt,
len(classpath_entry_paths),
len(target_sources),
timer.elapsed,
False,
outliner,
)
# Update the products with the latest classes.
self.register_extra_products_from_contexts([ctx.target], compile_contexts)
### Create Jobs for ExecutionGraph
cache_doublecheck_jobs = []
rsc_jobs = []
zinc_jobs = []
# Invalidated targets are a subset of relevant targets: get the context for this one.
compile_target = ivts.target
merged_compile_context = compile_contexts[compile_target]
rsc_compile_context = merged_compile_context.rsc_cc
zinc_compile_context = merged_compile_context.zinc_cc
workflow = rsc_compile_context.workflow
cache_doublecheck_key = self.exec_graph_double_check_cache_key_for_target(compile_target)
def all_zinc_rsc_invalid_dep_keys(invalid_deps):
"""Get the rsc key for an rsc-and-zinc target, or the zinc key for a zinc-only
target."""
for tgt in invalid_deps:
# None can occur for e.g. JarLibrary deps, which we don't need to compile as they are
# populated in the resolve goal.
tgt_rsc_cc = compile_contexts[tgt].rsc_cc
if tgt_rsc_cc.workflow is not None:
# Rely on the results of zinc compiles for zinc-compatible targets
yield self._key_for_target_as_dep(tgt, tgt_rsc_cc.workflow)
def make_cache_doublecheck_job(dep_keys):
# As in JvmCompile.create_compile_jobs, we create a cache-double-check job that all "real" work
# depends on. It depends on completion of the same dependencies as the rsc job in order to run
# as late as possible, while still running before rsc or zinc.
return Job(
key=cache_doublecheck_key,
fn=functools.partial(self._double_check_cache_for_vts, ivts, zinc_compile_context),
dependencies=list(dep_keys),
options_scope=self.options_scope,
)
def make_outline_job(target, dep_targets):
if workflow == self.JvmCompileWorkflowType.outline_and_zinc:
target_key = self._outline_key_for_target(target)
else:
target_key = self._rsc_key_for_target(target)
return Job(
key=target_key,
fn=functools.partial(
# NB: This will output to the 'rsc_mixed_compile_classpath' product via
# self.register_extra_products_from_contexts()!
work_for_vts_rsc,
ivts,
rsc_compile_context,
),
# The rsc jobs depend on other rsc jobs, and on zinc jobs for targets that are not
# processed by rsc.
dependencies=[cache_doublecheck_key]
+ list(all_zinc_rsc_invalid_dep_keys(dep_targets)),
size=self._size_estimator(rsc_compile_context.sources),
options_scope=self.options_scope,
target=target,
)
def only_zinc_invalid_dep_keys(invalid_deps):
for tgt in invalid_deps:
rsc_cc_tgt = compile_contexts[tgt].rsc_cc
if rsc_cc_tgt.workflow is not None:
yield self._zinc_key_for_target(tgt, rsc_cc_tgt.workflow)
def make_zinc_job(target, input_product_key, output_products, dep_keys):
return Job(
key=self._zinc_key_for_target(target, rsc_compile_context.workflow),
fn=functools.partial(
self._default_work_for_vts,
ivts,
zinc_compile_context,
input_product_key,
counter,
compile_contexts,
CompositeProductAdder(*output_products),
),
dependencies=[cache_doublecheck_key] + list(dep_keys),
size=self._size_estimator(zinc_compile_context.sources),
options_scope=self.options_scope,
target=target,
)
# Replica of JvmCompile's _record_target_stats logic
def record(k, v):
self.context.run_tracker.report_target_info(
self.options_scope, compile_target, ["compile", k], v
)
record("workflow", workflow.value)
record("execution_strategy", self.execution_strategy.value)
# Create the cache doublecheck job.
match(
workflow,
{
self.JvmCompileWorkflowType.zinc_only: lambda: cache_doublecheck_jobs.append(
make_cache_doublecheck_job(
list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies))
)
),
self.JvmCompileWorkflowType.zinc_java: lambda: cache_doublecheck_jobs.append(
make_cache_doublecheck_job(
list(only_zinc_invalid_dep_keys(invalid_dependencies))
)
),
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: cache_doublecheck_jobs.append(
make_cache_doublecheck_job(
list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies))
)
),
self.JvmCompileWorkflowType.outline_and_zinc: lambda: cache_doublecheck_jobs.append(
make_cache_doublecheck_job(
list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies))
)
),
},
)()
# Create the rsc job.
# Currently, rsc only supports outlining scala.
match(
workflow,
{
self.JvmCompileWorkflowType.zinc_only: lambda: None,
self.JvmCompileWorkflowType.zinc_java: lambda: None,
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: rsc_jobs.append(
make_outline_job(compile_target, invalid_dependencies)
),
self.JvmCompileWorkflowType.outline_and_zinc: lambda: rsc_jobs.append(
make_outline_job(compile_target, invalid_dependencies)
),
},
)()
# Create the zinc compile jobs.
# - Scala zinc compile jobs depend on the results of running rsc on the scala target.
# - Java zinc compile jobs depend on the zinc compiles of their dependencies, because we can't
# generate jars that make javac happy at this point.
match(
workflow,
{
# NB: zinc-only zinc jobs run zinc and depend on rsc and/or zinc compile outputs.
self.JvmCompileWorkflowType.zinc_only: lambda: zinc_jobs.append(
make_zinc_job(
compile_target,
input_product_key="rsc_mixed_compile_classpath",
output_products=[
runtime_classpath_product,
self.context.products.get_data("rsc_mixed_compile_classpath"),
],
dep_keys=list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies)),
)
),
# NB: javac can't read rsc output yet, so we need it to depend strictly on zinc
# compilations of dependencies.
self.JvmCompileWorkflowType.zinc_java: lambda: zinc_jobs.append(
make_zinc_job(
compile_target,
input_product_key="runtime_classpath",
output_products=[
runtime_classpath_product,
self.context.products.get_data("rsc_mixed_compile_classpath"),
],
dep_keys=list(only_zinc_invalid_dep_keys(invalid_dependencies)),
)
),
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: zinc_jobs.append(
# NB: rsc-and-zinc jobs run zinc and depend on both rsc and zinc compile outputs.
make_zinc_job(
compile_target,
input_product_key="rsc_mixed_compile_classpath",
# NB: We want to ensure the 'runtime_classpath' product *only* contains the outputs of
# zinc compiles, and that the 'rsc_mixed_compile_classpath' entries for rsc-compatible targets
# *only* contain the output of an rsc compile for that target.
output_products=[runtime_classpath_product,],
dep_keys=list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies)),
)
),
# Should be the same as 'rsc-and-zinc' case
self.JvmCompileWorkflowType.outline_and_zinc: lambda: zinc_jobs.append(
make_zinc_job(
compile_target,
input_product_key="rsc_mixed_compile_classpath",
output_products=[runtime_classpath_product,],
dep_keys=list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies)),
)
),
},
)()
compile_jobs = rsc_jobs + zinc_jobs
# Create a job that depends on all real work having completed that will eagerly write to the
# cache by calling `vt.update()`.
write_to_cache_job = Job(
key=self._write_to_cache_key_for_target(compile_target),
fn=ivts.update,
dependencies=[job.key for job in compile_jobs],
run_asap=True,
on_failure=ivts.force_invalidate,
options_scope=self.options_scope,
target=compile_target,
)
all_jobs = cache_doublecheck_jobs + rsc_jobs + zinc_jobs + [write_to_cache_job]
return (all_jobs, len(compile_jobs))
@dataclass(frozen=True)
class RscZincMergedCompileContexts:
rsc_cc: RscCompileContext
zinc_cc: CompileContext
def select_runtime_context(self, merged_compile_context):
return merged_compile_context.zinc_cc
def create_compile_context(self, target, target_workdir):
# workdir layout:
# rsc/
# - outline/ -- semanticdbs for the current target as created by rsc
# - m.jar -- reified scala signature jar, also used for scalac -Youtline
# zinc/
# - classes/ -- class files
# - z.analysis -- zinc analysis for the target
# - z.jar -- final jar for the target
# - zinc_args -- file containing the used zinc args
sources = self._compute_sources_for_target(target)
rsc_dir = os.path.join(target_workdir, "rsc")
zinc_dir = os.path.join(target_workdir, "zinc")
return self.RscZincMergedCompileContexts(
rsc_cc=RscCompileContext(
target=target,
# The analysis_file and classes_dir are not supposed to be useful
# It's a hacky way of preserving most of the logic in zinc_compile.py
# While allowing it to use RscCompileContexts for outlining.
analysis_file=os.path.join(rsc_dir, "z.analysis.outline"),
classes_dir=ClasspathEntry(os.path.join(rsc_dir, "zinc_classes"), None),
jar_file=None,
args_file=os.path.join(rsc_dir, "rsc_args"),
rsc_jar_file=ClasspathEntry(os.path.join(rsc_dir, "m.jar")),
log_dir=os.path.join(rsc_dir, "logs"),
post_compile_merge_dir=os.path.join(rsc_dir, "post_compile_merge_dir"),
sources=sources,
workflow=self._classify_target_compile_workflow(target),
),
zinc_cc=CompileContext(
target=target,
analysis_file=os.path.join(zinc_dir, "z.analysis"),
classes_dir=ClasspathEntry(os.path.join(zinc_dir, "classes"), None),
jar_file=ClasspathEntry(os.path.join(zinc_dir, "z.jar"), None),
log_dir=os.path.join(zinc_dir, "logs"),
args_file=os.path.join(zinc_dir, "zinc_args"),
post_compile_merge_dir=os.path.join(zinc_dir, "post_compile_merge_dir"),
sources=sources,
),
)
def _runtool_hermetic(self, main, tool_name, distribution, input_digest, ctx):
use_youtline = tool_name == "scalac-outliner"
tool_classpath_abs = self._scalac_classpath if use_youtline else self._rsc_classpath
tool_classpath = fast_relpath_collection(tool_classpath_abs)
rsc_jvm_options = Rsc.global_instance().get_options().jvm_options
if not use_youtline and self._rsc.use_native_image:
if rsc_jvm_options:
raise ValueError(
"`{}` got non-empty jvm_options when running with a graal native-image, but this is "
"unsupported. jvm_options received: {}".format(
self.options_scope, safe_shlex_join(rsc_jvm_options)
)
)
native_image_path, native_image_snapshot = self._rsc.native_image(self.context)
additional_snapshots = [native_image_snapshot]
initial_args = [native_image_path]
else:
additional_snapshots = []
initial_args = (
[distribution.java,]
+ rsc_jvm_options
+ ["-cp", os.pathsep.join(tool_classpath), main,]
)
(argfile_snapshot,) = self.context._scheduler.capture_snapshots(
[
PathGlobsAndRoot(
PathGlobs([fast_relpath(ctx.args_file, get_buildroot())]), get_buildroot(),
),
]
)
cmd = initial_args + [f"@{argfile_snapshot.files[0]}"]
pathglobs = list(tool_classpath)
if pathglobs:
root = PathGlobsAndRoot(PathGlobs(tuple(pathglobs)), get_buildroot())
# dont capture snapshot, if pathglobs is empty
path_globs_input_digest = self.context._scheduler.capture_snapshots((root,))[
0
].directory_digest
epr_input_files = self.context._scheduler.merge_directories(
((path_globs_input_digest,) if path_globs_input_digest else ())
+ ((input_digest,) if input_digest else ())
+ tuple(s.directory_digest for s in additional_snapshots)
+ (argfile_snapshot.directory_digest,)
)
epr = ExecuteProcessRequest(
argv=tuple(cmd),
input_files=epr_input_files,
output_files=(fast_relpath(ctx.rsc_jar_file.path, get_buildroot()),),
output_directories=tuple(),
timeout_seconds=15 * 60,
description=f"run {tool_name} for {ctx.target}",
# TODO: These should always be unicodes
# Since this is always hermetic, we need to use `underlying.home` because
# ExecuteProcessRequest requires an existing, local jdk location.
jdk_home=distribution.underlying_home,
is_nailgunnable=True,
)
res = self.context.execute_process_synchronously_without_raising(
epr, self.name(), [WorkUnitLabel.COMPILER]
)
if res.exit_code != 0:
raise TaskError(res.stderr, exit_code=res.exit_code)
# TODO: parse the output of -Xprint:timings for rsc and write it to self._record_target_stats()!
res.output_directory_digest.dump(ctx.rsc_jar_file.path)
self.context._scheduler.materialize_directory(
DirectoryToMaterialize(res.output_directory_digest),
)
ctx.rsc_jar_file.hydrate_missing_directory_digest(res.output_directory_digest)
return res
# The classpath is parameterized so that we can have a single nailgun instance serving all of our
# execution requests.
def _runtool_nonhermetic(self, parent_workunit, classpath, main, tool_name, distribution, ctx):
# Scalac -Youtline cannot coexist with zinc jar in the same nailgun in a mulitithreaded run
# Forcing scalac -Youtline to run as a separate process circumvents this problem
use_youtline = tool_name == "scalac-outliner"
result = self.runjava(
classpath=classpath,
main=main,
jvm_options=self.get_options().jvm_options,
args=[f"@{ctx.args_file}"],
workunit_name=tool_name,
workunit_labels=[WorkUnitLabel.COMPILER],
dist=distribution,
force_subprocess=use_youtline,
)
if result != 0:
raise TaskError(f"Running {tool_name} failed")
runjava_workunit = None
for c in parent_workunit.children:
if c.name is tool_name:
runjava_workunit = c
break
# TODO: figure out and document when would this happen.
if runjava_workunit is None:
raise Exception("couldnt find work unit for underlying execution")
return runjava_workunit
# Mostly a copy-paste from ZincCompile.compile with many options removed
def _zinc_outline(self, ctx, relative_classpath, target_sources, youtline_args):
zinc_youtline_args = [f"-S{arg}" for arg in youtline_args]
zinc_file_manager = DependencyContext.global_instance().defaulted_property(
ctx.target, "zinc_file_manager"
)
def relative_to_exec_root(path):
return fast_relpath(path, get_buildroot())
analysis_cache = relative_to_exec_root(ctx.analysis_file)
classes_dir = relative_to_exec_root(ctx.classes_dir.path)
scalac_classpath_entries = self.scalac_classpath_entries()
scala_path = [
relative_to_exec_root(classpath_entry.path)
for classpath_entry in scalac_classpath_entries
]
zinc_args = []
zinc_args.extend(
[
"-log-level",
self.get_options().level,
"-analysis-cache",
analysis_cache,
"-classpath",
os.pathsep.join(relative_classpath),
]
)
compiler_bridge_classpath_entry = self._zinc.compile_compiler_bridge(self.context)
zinc_args.extend(
["-compiled-bridge-jar", relative_to_exec_root(compiler_bridge_classpath_entry.path)]
)
zinc_args.extend(["-scala-path", ":".join(scala_path)])
zinc_args.extend(zinc_youtline_args)
if not zinc_file_manager:
zinc_args.append("-no-zinc-file-manager")
jvm_options = []
if self.javac_classpath():
jvm_options.extend([f"-Xbootclasspath/p:{":".join(self.javac_classpath())}"])
jvm_options.extend(self._jvm_options)
zinc_args.extend(ctx.sources)
self.log_zinc_file(ctx.analysis_file)
self.write_argsfile(ctx, zinc_args)
return self.execution_strategy.match(
{
self.ExecutionStrategy.hermetic: lambda: None,
self.ExecutionStrategy.subprocess: lambda: self._compile_nonhermetic(
jvm_options, ctx, classes_dir
),
self.ExecutionStrategy.nailgun: lambda: self._compile_nonhermetic(
jvm_options, ctx, classes_dir
),
}
)()
def _runtool(self, distribution, input_digest, ctx, use_youtline):
if use_youtline:
main = "scala.tools.nsc.Main"
tool_name = "scalac-outliner"
tool_classpath = self._scalac_classpath
# In fact, nailgun should not be used for -Youtline
# in case of self.ExecutionStrategy.nailgun,
# we will force the scalac -Youtline invokation to run via subprocess
nailgun_classpath = self._scalac_classpath
else:
main = "rsc.cli.Main"
tool_name = "rsc"
tool_classpath = self._rsc_classpath
nailgun_classpath = self._nailgunnable_combined_classpath
with self.context.new_workunit(tool_name) as wu:
return match(
self.execution_strategy,
{
self.ExecutionStrategy.hermetic: lambda: self._runtool_hermetic(
main, tool_name, distribution, input_digest, ctx
),
self.ExecutionStrategy.subprocess: lambda: self._runtool_nonhermetic(
wu, tool_classpath, main, tool_name, distribution, ctx
),
self.ExecutionStrategy.nailgun: lambda: self._runtool_nonhermetic(
wu, nailgun_classpath, main, tool_name, distribution, ctx
),
},
)()
_JDK_LIB_NAMES = ["rt.jar", "dt.jar", "jce.jar", "tools.jar"]
@memoized_method
def _jdk_libs_paths_and_digest(self, hermetic_dist):
jdk_libs_rel, jdk_libs_globs = hermetic_dist.find_libs_path_globs(self._JDK_LIB_NAMES)
jdk_libs_digest = self.context._scheduler.merge_directories(
[
snap.directory_digest
for snap in (self.context._scheduler.capture_snapshots(jdk_libs_globs))
]
)
return (jdk_libs_rel, jdk_libs_digest)
@memoized_method
def _jdk_libs_abs(self, nonhermetic_dist):
return nonhermetic_dist.find_libs(self._JDK_LIB_NAMES)
def _double_check_cache_for_vts(self, vts, zinc_compile_context):
# Double check the cache before beginning compilation
if self.check_cache(vts):
self.context.log.debug(f"Snapshotting results for {vts.target.address.spec}")
classpath_entry = self._classpath_for_context(zinc_compile_context)
relpath = fast_relpath(classpath_entry.path, get_buildroot())
(classes_dir_snapshot,) = self.context._scheduler.capture_snapshots(
[PathGlobsAndRoot(PathGlobs([relpath]), get_buildroot(), Digest.load(relpath),),]
)
classpath_entry.hydrate_missing_directory_digest(classes_dir_snapshot.directory_digest)
# Re-validate the vts!
vts.update()
| # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import functools
import logging
import os
import re
from dataclasses import dataclass
from enum import Enum
from pants.backend.jvm.subsystems.dependency_context import DependencyContext # noqa
from pants.backend.jvm.subsystems.rsc import Rsc
from pants.backend.jvm.subsystems.shader import Shader
from pants.backend.jvm.targets.jvm_target import JvmTarget
from pants.backend.jvm.tasks.classpath_entry import ClasspathEntry
from pants.backend.jvm.tasks.jvm_compile.compile_context import CompileContext
from pants.backend.jvm.tasks.jvm_compile.execution_graph import Job
from pants.backend.jvm.tasks.jvm_compile.zinc.zinc_compile import ZincCompile
from pants.base.build_environment import get_buildroot
from pants.base.exceptions import TaskError
from pants.base.workunit import WorkUnitLabel
from pants.build_graph.mirrored_target_option_mixin import MirroredTargetOptionMixin
from pants.engine.fs import (
EMPTY_DIRECTORY_DIGEST,
Digest,
DirectoryToMaterialize,
PathGlobs,
PathGlobsAndRoot,
)
from pants.engine.isolated_process import ExecuteProcessRequest, FallibleExecuteProcessResult
from pants.java.jar.jar_dependency import JarDependency
from pants.reporting.reporting_utils import items_to_report_element
from pants.task.scm_publish_mixin import Semver
from pants.util.collections import assert_single_element
from pants.util.contextutil import Timer
from pants.util.dirutil import fast_relpath, fast_relpath_optional, safe_mkdir
from pants.util.enums import match
from pants.util.memo import memoized_method, memoized_property
from pants.util.strutil import safe_shlex_join
#
# This is a subclass of zinc compile that uses both Rsc and Zinc to do
# compilation.
# It uses Rsc and the associated tools to outline scala targets. It then
# passes those outlines to zinc to produce the final compile artifacts.
#
#
logger = logging.getLogger(__name__)
def fast_relpath_collection(collection):
buildroot = get_buildroot()
return [fast_relpath_optional(c, buildroot) or c for c in collection]
def stdout_contents(wu):
if isinstance(wu, FallibleExecuteProcessResult):
return wu.stdout.rstrip()
with open(wu.output_paths()["stdout"]) as f:
return f.read().rstrip()
def _create_desandboxify_fn(possible_path_patterns):
# Takes a collection of possible canonical prefixes, and returns a function that
# if it finds a matching prefix, strips the path prior to the prefix and returns it
# if it doesn't it returns the original path
# TODO remove this after https://github.com/scalameta/scalameta/issues/1791 is released
regexes = [re.compile(f"/({p})") for p in possible_path_patterns]
def desandboxify(path):
if not path:
return path
for r in regexes:
match = r.search(path)
if match:
logger.debug(f"path-cleanup: matched {match} with {r.pattern} against {path}")
return match.group(1)
logger.debug(f"path-cleanup: no match for {path}")
return path
return desandboxify
class CompositeProductAdder:
def __init__(self, *products):
self.products = products
def add_for_target(self, *args, **kwargs):
for product in self.products:
product.add_for_target(*args, **kwargs)
class RscCompileContext(CompileContext):
def __init__(
self,
target,
analysis_file,
classes_dir,
rsc_jar_file,
jar_file,
log_dir,
args_file,
post_compile_merge_dir,
sources,
workflow,
):
super().__init__(
target,
analysis_file,
classes_dir,
jar_file,
log_dir,
args_file,
post_compile_merge_dir,
sources,
)
self.workflow = workflow
self.rsc_jar_file = rsc_jar_file
def ensure_output_dirs_exist(self):
safe_mkdir(os.path.dirname(self.rsc_jar_file.path))
class RscCompile(ZincCompile, MirroredTargetOptionMixin):
"""Compile Scala and Java code to classfiles using Rsc."""
_name = "mixed"
compiler_name = "rsc"
@classmethod
def subsystem_dependencies(cls):
return super().subsystem_dependencies() + (Rsc,)
@memoized_property
def mirrored_target_option_actions(self):
return {
"workflow": self._identify_workflow_tags,
}
@classmethod
def implementation_version(cls):
return super().implementation_version() + [("RscCompile", 174)]
class JvmCompileWorkflowType(Enum):
"""Target classifications used to correctly schedule Zinc and Rsc jobs.
There are some limitations we have to work around before we can compile everything through Rsc
and followed by Zinc.
- rsc is not able to outline all scala code just yet (this is also being addressed through
automated rewrites).
- javac is unable to consume rsc's jars just yet.
- rsc is not able to outline all java code just yet (this is likely to *not* require rewrites,
just some more work on rsc).
As we work on improving our Rsc integration, we'll need to create more workflows to more closely
map the supported features of Rsc. This enum class allows us to do that.
- zinc-only: compiles targets just with Zinc and uses the Zinc products of their dependencies.
- zinc-java: the same as zinc-only for now, for targets with any java sources (which rsc can't
syet outline).
- rsc-and-zinc: compiles targets with Rsc to create "header" jars, and runs Zinc against the
Rsc products of their dependencies. The Rsc compile uses the Rsc products of Rsc compatible
targets and the Zinc products of zinc-only targets.
- outline-and-zinc: compiles targets with scalac's outlining to create "header" jars,
in place of Rsc. While this is slower, it conforms to Scala without rewriting code.
"""
zinc_only = "zinc-only"
zinc_java = "zinc-java"
rsc_and_zinc = "rsc-and-zinc"
outline_and_zinc = "outline-and-zinc"
@memoized_property
def _compiler_tags(self):
return {
f"{self.get_options().force_compiler_tag_prefix}:{workflow.value}": workflow
for workflow in self.JvmCompileWorkflowType
}
@classmethod
def register_options(cls, register):
super().register_options(register)
register(
"--force-compiler-tag-prefix",
default="use-compiler",
metavar="<tag>",
help="Always compile targets marked with this tag with rsc, unless the workflow is "
"specified on the cli.",
)
register(
"--workflow",
type=cls.JvmCompileWorkflowType,
choices=list(cls.JvmCompileWorkflowType),
default=cls.JvmCompileWorkflowType.zinc_only,
metavar="<workflow>",
help="The default workflow to use to compile JVM targets. This is overridden on a per-target basis with the force-compiler-tag-prefix tag.",
fingerprint=True,
)
register(
"--scala-workflow-override",
type=cls.JvmCompileWorkflowType,
choices=list(cls.JvmCompileWorkflowType),
default=None,
metavar="<workflow_override>",
help='Experimental option. The workflow to use to compile Scala targets, overriding the "workflow" option as well as any force-compiler-tag-prefix tags applied to targets. An example use case is to quickly turn off outlining workflows in case of errors.',
fingerprint=True,
)
register(
"--extra-rsc-args",
type=list,
default=[],
help="Extra arguments to pass to the rsc invocation.",
)
register(
"--zinc-outline",
type=bool,
default=False,
help="Outline via Zinc when workflow is outline-and-zinc instead of a standalone scalac tool. This allows outlining to happen in the same nailgun instance as zinc compiles.",
fingerprint=True,
)
cls.register_jvm_tool(
register,
"rsc",
classpath=[
JarDependency(org="com.twitter", name="rsc_2.12", rev="0.0.0-768-7357aa0a",),
],
custom_rules=[Shader.exclude_package("rsc", recursive=True),],
)
scalac_outliner_version = "2.12.10"
cls.register_jvm_tool(
register,
"scalac-outliner",
classpath=[
JarDependency(
org="org.scala-lang", name="scala-compiler", rev=scalac_outliner_version,
),
],
custom_rules=[
Shader.exclude_package("scala", recursive=True),
Shader.exclude_package("xsbt", recursive=True),
Shader.exclude_package("xsbti", recursive=True),
# Unfortunately, is loaded reflectively by the compiler.
Shader.exclude_package("org.apache.logging.log4j", recursive=True),
],
)
@classmethod
def product_types(cls):
return super(RscCompile, cls).product_types() + ["rsc_mixed_compile_classpath"]
@memoized_property
def _rsc(self):
return Rsc.global_instance()
@memoized_property
def _rsc_classpath(self):
return self.tool_classpath("rsc")
@memoized_property
def _scalac_classpath(self):
return self.tool_classpath("scalac-outliner")
@memoized_property
def _scala_library_version(self):
return self._zinc.scala_library.coordinate.rev
# TODO: allow @memoized_method to convert lists into tuples so they can be hashed!
@memoized_property
def _nailgunnable_combined_classpath(self):
"""Register all of the component tools of the rsc compile task as a "combined" jvm tool.
This allows us to invoke their combined classpath in a single nailgun instance (see #7089
and #7092). We still invoke their classpaths separately when not using nailgun, however.
"""
cp = []
cp.extend(self._rsc_classpath)
# Add zinc's classpath so that it can be invoked from the same nailgun instance.
cp.extend(super().get_zinc_compiler_classpath())
return cp
# Overrides the normal zinc compiler classpath, which only contains zinc.
def get_zinc_compiler_classpath(self):
return match(
self.execution_strategy,
{
# NB: We must use the verbose version of super() here, possibly because of the lambda.
self.ExecutionStrategy.hermetic: lambda: super(
RscCompile, self
).get_zinc_compiler_classpath(),
self.ExecutionStrategy.subprocess: lambda: super(
RscCompile, self
).get_zinc_compiler_classpath(),
self.ExecutionStrategy.nailgun: lambda: self._nailgunnable_combined_classpath,
},
)()
def register_extra_products_from_contexts(self, targets, compile_contexts):
super().register_extra_products_from_contexts(targets, compile_contexts)
def confify(entries):
return [(conf, e) for e in entries for conf in self._confs]
# Ensure that the jar/rsc jar is on the rsc_mixed_compile_classpath.
for target in targets:
merged_cc = compile_contexts[target]
zinc_cc = merged_cc.zinc_cc
rsc_cc = merged_cc.rsc_cc
# Make sure m.jar is digested if it exists when the target is validated.
if rsc_cc.rsc_jar_file.directory_digest is None and os.path.exists(
rsc_cc.rsc_jar_file.path
):
relpath = fast_relpath(rsc_cc.rsc_jar_file.path, get_buildroot())
(classes_dir_snapshot,) = self.context._scheduler.capture_snapshots(
[
PathGlobsAndRoot(
PathGlobs([relpath]), get_buildroot(), Digest.load(relpath),
),
]
)
rsc_cc.rsc_jar_file.hydrate_missing_directory_digest(
classes_dir_snapshot.directory_digest
)
if rsc_cc.workflow is not None:
cp_entries = match(
rsc_cc.workflow,
{
self.JvmCompileWorkflowType.zinc_only: lambda: confify(
[self._classpath_for_context(zinc_cc)]
),
self.JvmCompileWorkflowType.zinc_java: lambda: confify(
[self._classpath_for_context(zinc_cc)]
),
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: confify(
[rsc_cc.rsc_jar_file]
),
self.JvmCompileWorkflowType.outline_and_zinc: lambda: confify(
[rsc_cc.rsc_jar_file]
),
},
)()
self.context.products.get_data("rsc_mixed_compile_classpath").add_for_target(
target, cp_entries
)
def create_empty_extra_products(self):
super().create_empty_extra_products()
compile_classpath = self.context.products.get_data("compile_classpath")
runtime_classpath = self.context.products.get_data("runtime_classpath")
classpath_product = self.context.products.get_data("rsc_mixed_compile_classpath")
if not classpath_product:
classpath_product = self.context.products.get_data(
"rsc_mixed_compile_classpath", compile_classpath.copy
)
else:
classpath_product.update(compile_classpath)
classpath_product.update(runtime_classpath)
def select(self, target):
if not isinstance(target, JvmTarget):
return False
return self._classify_target_compile_workflow(target) is not None
@memoized_method
def _identify_workflow_tags(self, target):
try:
all_tags = [self._compiler_tags.get(tag) for tag in target.tags]
filtered_tags = filter(None, all_tags)
return assert_single_element(list(filtered_tags))
except StopIteration:
return None
except ValueError as e:
raise ValueError(
"Multiple compile workflow tags specified for target {}: {}".format(target, e)
)
@memoized_method
def _classify_target_compile_workflow(self, target):
"""Return the compile workflow to use for this target."""
# scala_library() targets may have a `.java_sources` property.
java_sources = getattr(target, "java_sources", [])
if java_sources or target.has_sources(".java"):
# If there are any java sources to compile, treat it as a java library since rsc can't outline
# java yet.
return self.JvmCompileWorkflowType.zinc_java
if target.has_sources(".scala"):
workflow_override = self.get_options().scala_workflow_override
if workflow_override is not None:
return self.JvmCompileWorkflowType(workflow_override)
return self.get_scalar_mirrored_target_option("workflow", target)
return None
def _key_for_target_as_dep(self, target, workflow):
# used for jobs that are either rsc jobs or zinc jobs run against rsc
return match(
workflow,
{
self.JvmCompileWorkflowType.zinc_only: lambda: self._zinc_key_for_target(
target, workflow
),
self.JvmCompileWorkflowType.zinc_java: lambda: self._zinc_key_for_target(
target, workflow
),
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: self._rsc_key_for_target(target),
self.JvmCompileWorkflowType.outline_and_zinc: lambda: self._outline_key_for_target(
target
),
},
)()
def _rsc_key_for_target(self, target):
return f"rsc({target.address.spec})"
def _outline_key_for_target(self, target):
return f"outline({target.address.spec})"
def _zinc_key_for_target(self, target, workflow):
return match(
workflow,
{
self.JvmCompileWorkflowType.zinc_only: lambda: f"zinc[zinc-only]({target.address.spec})",
self.JvmCompileWorkflowType.zinc_java: lambda: f"zinc[zinc-java]({target.address.spec})",
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: f"zinc[rsc-and-zinc]({target.address.spec})",
self.JvmCompileWorkflowType.outline_and_zinc: lambda: f"zinc[outline-and-zinc]({target.address.spec})",
},
)()
def _write_to_cache_key_for_target(self, target):
return f"write_to_cache({target.address.spec})"
def create_compile_jobs(
self,
compile_target,
compile_contexts,
invalid_dependencies,
ivts,
counter,
runtime_classpath_product,
):
def work_for_vts_rsc(vts, ctx):
target = ctx.target
(tgt,) = vts.targets
rsc_cc = compile_contexts[target].rsc_cc
use_youtline = rsc_cc.workflow == self.JvmCompileWorkflowType.outline_and_zinc
outliner = "scalac-outliner" if use_youtline else "rsc"
if use_youtline and Semver.parse(self._scala_library_version) < Semver.parse("2.12.9"):
raise RuntimeError(
f"To use scalac's built-in outlining, scala version must be at least 2.12.9, but got {self._scala_library_version}"
)
# If we didn't hit the cache in the cache job, run rsc.
if not vts.valid:
counter_val = str(counter()).rjust(counter.format_length(), " ")
counter_str = f"[{counter_val}/{counter.size}] "
action_str = "Outlining " if use_youtline else "Rsc-ing "
self.context.log.info(
counter_str,
action_str,
items_to_report_element(ctx.sources, f"{self.name()} source"),
" in ",
items_to_report_element([t.address.reference() for t in vts.targets], "target"),
" (",
ctx.target.address.spec,
").",
)
# This does the following
# - Collect the rsc classpath elements, including zinc compiles of rsc incompatible targets
# and rsc compiles of rsc compatible targets.
# - Run Rsc on the current target with those as dependencies.
dependencies_for_target = list(
DependencyContext.global_instance().dependencies_respecting_strict_deps(target)
)
classpath_paths = []
classpath_directory_digests = []
classpath_product = self.context.products.get_data("rsc_mixed_compile_classpath")
classpath_entries = classpath_product.get_classpath_entries_for_targets(
dependencies_for_target
)
hermetic = self.execution_strategy == self.ExecutionStrategy.hermetic
for _conf, classpath_entry in classpath_entries:
classpath_paths.append(fast_relpath(classpath_entry.path, get_buildroot()))
if hermetic and not classpath_entry.directory_digest:
raise AssertionError(
"ClasspathEntry {} didn't have a Digest, so won't be present for hermetic "
"execution of {}".format(classpath_entry, outliner)
)
classpath_directory_digests.append(classpath_entry.directory_digest)
ctx.ensure_output_dirs_exist()
with Timer() as timer:
# Outline Scala sources into SemanticDB / scalac compatible header jars.
# ---------------------------------------------
rsc_jar_file_relative_path = fast_relpath(
ctx.rsc_jar_file.path, get_buildroot()
)
sources_snapshot = ctx.target.sources_snapshot(
scheduler=self.context._scheduler
)
distribution = self._get_jvm_distribution()
def hermetic_digest_classpath():
jdk_libs_rel, jdk_libs_digest = self._jdk_libs_paths_and_digest(
distribution
)
merged_sources_and_jdk_digest = self.context._scheduler.merge_directories(
(jdk_libs_digest, sources_snapshot.directory_digest)
+ tuple(classpath_directory_digests)
)
classpath_rel_jdk = classpath_paths + jdk_libs_rel
return (merged_sources_and_jdk_digest, classpath_rel_jdk)
def nonhermetic_digest_classpath():
classpath_abs_jdk = classpath_paths + self._jdk_libs_abs(distribution)
return ((EMPTY_DIRECTORY_DIGEST), classpath_abs_jdk)
(input_digest, classpath_entry_paths) = match(
self.execution_strategy,
{
self.ExecutionStrategy.hermetic: hermetic_digest_classpath,
self.ExecutionStrategy.subprocess: nonhermetic_digest_classpath,
self.ExecutionStrategy.nailgun: nonhermetic_digest_classpath,
},
)()
youtline_args = []
if use_youtline:
youtline_args = [
"-Youtline",
"-Ystop-after:pickler",
"-Ypickle-write",
rsc_jar_file_relative_path,
]
target_sources = ctx.sources
# TODO: m.jar digests aren't found, so hermetic will fail.
if use_youtline and not hermetic and self.get_options().zinc_outline:
self._zinc_outline(ctx, classpath_paths, target_sources, youtline_args)
else:
args = (
[
"-cp",
os.pathsep.join(classpath_entry_paths),
"-d",
rsc_jar_file_relative_path,
]
+ self.get_options().extra_rsc_args
+ youtline_args
+ target_sources
)
self.write_argsfile(ctx, args)
self._runtool(distribution, input_digest, ctx, use_youtline)
self._record_target_stats(
tgt,
len(classpath_entry_paths),
len(target_sources),
timer.elapsed,
False,
outliner,
)
# Update the products with the latest classes.
self.register_extra_products_from_contexts([ctx.target], compile_contexts)
### Create Jobs for ExecutionGraph
cache_doublecheck_jobs = []
rsc_jobs = []
zinc_jobs = []
# Invalidated targets are a subset of relevant targets: get the context for this one.
compile_target = ivts.target
merged_compile_context = compile_contexts[compile_target]
rsc_compile_context = merged_compile_context.rsc_cc
zinc_compile_context = merged_compile_context.zinc_cc
workflow = rsc_compile_context.workflow
cache_doublecheck_key = self.exec_graph_double_check_cache_key_for_target(compile_target)
def all_zinc_rsc_invalid_dep_keys(invalid_deps):
"""Get the rsc key for an rsc-and-zinc target, or the zinc key for a zinc-only
target."""
for tgt in invalid_deps:
# None can occur for e.g. JarLibrary deps, which we don't need to compile as they are
# populated in the resolve goal.
tgt_rsc_cc = compile_contexts[tgt].rsc_cc
if tgt_rsc_cc.workflow is not None:
# Rely on the results of zinc compiles for zinc-compatible targets
yield self._key_for_target_as_dep(tgt, tgt_rsc_cc.workflow)
def make_cache_doublecheck_job(dep_keys):
# As in JvmCompile.create_compile_jobs, we create a cache-double-check job that all "real" work
# depends on. It depends on completion of the same dependencies as the rsc job in order to run
# as late as possible, while still running before rsc or zinc.
return Job(
key=cache_doublecheck_key,
fn=functools.partial(self._double_check_cache_for_vts, ivts, zinc_compile_context),
dependencies=list(dep_keys),
options_scope=self.options_scope,
)
def make_outline_job(target, dep_targets):
if workflow == self.JvmCompileWorkflowType.outline_and_zinc:
target_key = self._outline_key_for_target(target)
else:
target_key = self._rsc_key_for_target(target)
return Job(
key=target_key,
fn=functools.partial(
# NB: This will output to the 'rsc_mixed_compile_classpath' product via
# self.register_extra_products_from_contexts()!
work_for_vts_rsc,
ivts,
rsc_compile_context,
),
# The rsc jobs depend on other rsc jobs, and on zinc jobs for targets that are not
# processed by rsc.
dependencies=[cache_doublecheck_key]
+ list(all_zinc_rsc_invalid_dep_keys(dep_targets)),
size=self._size_estimator(rsc_compile_context.sources),
options_scope=self.options_scope,
target=target,
)
def only_zinc_invalid_dep_keys(invalid_deps):
for tgt in invalid_deps:
rsc_cc_tgt = compile_contexts[tgt].rsc_cc
if rsc_cc_tgt.workflow is not None:
yield self._zinc_key_for_target(tgt, rsc_cc_tgt.workflow)
def make_zinc_job(target, input_product_key, output_products, dep_keys):
return Job(
key=self._zinc_key_for_target(target, rsc_compile_context.workflow),
fn=functools.partial(
self._default_work_for_vts,
ivts,
zinc_compile_context,
input_product_key,
counter,
compile_contexts,
CompositeProductAdder(*output_products),
),
dependencies=[cache_doublecheck_key] + list(dep_keys),
size=self._size_estimator(zinc_compile_context.sources),
options_scope=self.options_scope,
target=target,
)
# Replica of JvmCompile's _record_target_stats logic
def record(k, v):
self.context.run_tracker.report_target_info(
self.options_scope, compile_target, ["compile", k], v
)
record("workflow", workflow.value)
record("execution_strategy", self.execution_strategy.value)
# Create the cache doublecheck job.
match(
workflow,
{
self.JvmCompileWorkflowType.zinc_only: lambda: cache_doublecheck_jobs.append(
make_cache_doublecheck_job(
list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies))
)
),
self.JvmCompileWorkflowType.zinc_java: lambda: cache_doublecheck_jobs.append(
make_cache_doublecheck_job(
list(only_zinc_invalid_dep_keys(invalid_dependencies))
)
),
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: cache_doublecheck_jobs.append(
make_cache_doublecheck_job(
list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies))
)
),
self.JvmCompileWorkflowType.outline_and_zinc: lambda: cache_doublecheck_jobs.append(
make_cache_doublecheck_job(
list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies))
)
),
},
)()
# Create the rsc job.
# Currently, rsc only supports outlining scala.
match(
workflow,
{
self.JvmCompileWorkflowType.zinc_only: lambda: None,
self.JvmCompileWorkflowType.zinc_java: lambda: None,
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: rsc_jobs.append(
make_outline_job(compile_target, invalid_dependencies)
),
self.JvmCompileWorkflowType.outline_and_zinc: lambda: rsc_jobs.append(
make_outline_job(compile_target, invalid_dependencies)
),
},
)()
# Create the zinc compile jobs.
# - Scala zinc compile jobs depend on the results of running rsc on the scala target.
# - Java zinc compile jobs depend on the zinc compiles of their dependencies, because we can't
# generate jars that make javac happy at this point.
match(
workflow,
{
# NB: zinc-only zinc jobs run zinc and depend on rsc and/or zinc compile outputs.
self.JvmCompileWorkflowType.zinc_only: lambda: zinc_jobs.append(
make_zinc_job(
compile_target,
input_product_key="rsc_mixed_compile_classpath",
output_products=[
runtime_classpath_product,
self.context.products.get_data("rsc_mixed_compile_classpath"),
],
dep_keys=list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies)),
)
),
# NB: javac can't read rsc output yet, so we need it to depend strictly on zinc
# compilations of dependencies.
self.JvmCompileWorkflowType.zinc_java: lambda: zinc_jobs.append(
make_zinc_job(
compile_target,
input_product_key="runtime_classpath",
output_products=[
runtime_classpath_product,
self.context.products.get_data("rsc_mixed_compile_classpath"),
],
dep_keys=list(only_zinc_invalid_dep_keys(invalid_dependencies)),
)
),
self.JvmCompileWorkflowType.rsc_and_zinc: lambda: zinc_jobs.append(
# NB: rsc-and-zinc jobs run zinc and depend on both rsc and zinc compile outputs.
make_zinc_job(
compile_target,
input_product_key="rsc_mixed_compile_classpath",
# NB: We want to ensure the 'runtime_classpath' product *only* contains the outputs of
# zinc compiles, and that the 'rsc_mixed_compile_classpath' entries for rsc-compatible targets
# *only* contain the output of an rsc compile for that target.
output_products=[runtime_classpath_product,],
dep_keys=list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies)),
)
),
# Should be the same as 'rsc-and-zinc' case
self.JvmCompileWorkflowType.outline_and_zinc: lambda: zinc_jobs.append(
make_zinc_job(
compile_target,
input_product_key="rsc_mixed_compile_classpath",
output_products=[runtime_classpath_product,],
dep_keys=list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies)),
)
),
},
)()
compile_jobs = rsc_jobs + zinc_jobs
# Create a job that depends on all real work having completed that will eagerly write to the
# cache by calling `vt.update()`.
write_to_cache_job = Job(
key=self._write_to_cache_key_for_target(compile_target),
fn=ivts.update,
dependencies=[job.key for job in compile_jobs],
run_asap=True,
on_failure=ivts.force_invalidate,
options_scope=self.options_scope,
target=compile_target,
)
all_jobs = cache_doublecheck_jobs + rsc_jobs + zinc_jobs + [write_to_cache_job]
return (all_jobs, len(compile_jobs))
@dataclass(frozen=True)
class RscZincMergedCompileContexts:
rsc_cc: RscCompileContext
zinc_cc: CompileContext
def select_runtime_context(self, merged_compile_context):
return merged_compile_context.zinc_cc
def create_compile_context(self, target, target_workdir):
# workdir layout:
# rsc/
# - outline/ -- semanticdbs for the current target as created by rsc
# - m.jar -- reified scala signature jar, also used for scalac -Youtline
# zinc/
# - classes/ -- class files
# - z.analysis -- zinc analysis for the target
# - z.jar -- final jar for the target
# - zinc_args -- file containing the used zinc args
sources = self._compute_sources_for_target(target)
rsc_dir = os.path.join(target_workdir, "rsc")
zinc_dir = os.path.join(target_workdir, "zinc")
return self.RscZincMergedCompileContexts(
rsc_cc=RscCompileContext(
target=target,
# The analysis_file and classes_dir are not supposed to be useful
# It's a hacky way of preserving most of the logic in zinc_compile.py
# While allowing it to use RscCompileContexts for outlining.
analysis_file=os.path.join(rsc_dir, "z.analysis.outline"),
classes_dir=ClasspathEntry(os.path.join(rsc_dir, "zinc_classes"), None),
jar_file=None,
args_file=os.path.join(rsc_dir, "rsc_args"),
rsc_jar_file=ClasspathEntry(os.path.join(rsc_dir, "m.jar")),
log_dir=os.path.join(rsc_dir, "logs"),
post_compile_merge_dir=os.path.join(rsc_dir, "post_compile_merge_dir"),
sources=sources,
workflow=self._classify_target_compile_workflow(target),
),
zinc_cc=CompileContext(
target=target,
analysis_file=os.path.join(zinc_dir, "z.analysis"),
classes_dir=ClasspathEntry(os.path.join(zinc_dir, "classes"), None),
jar_file=ClasspathEntry(os.path.join(zinc_dir, "z.jar"), None),
log_dir=os.path.join(zinc_dir, "logs"),
args_file=os.path.join(zinc_dir, "zinc_args"),
post_compile_merge_dir=os.path.join(zinc_dir, "post_compile_merge_dir"),
sources=sources,
),
)
def _runtool_hermetic(self, main, tool_name, distribution, input_digest, ctx):
use_youtline = tool_name == "scalac-outliner"
tool_classpath_abs = self._scalac_classpath if use_youtline else self._rsc_classpath
tool_classpath = fast_relpath_collection(tool_classpath_abs)
rsc_jvm_options = Rsc.global_instance().get_options().jvm_options
if not use_youtline and self._rsc.use_native_image:
if rsc_jvm_options:
raise ValueError(
"`{}` got non-empty jvm_options when running with a graal native-image, but this is "
"unsupported. jvm_options received: {}".format(
self.options_scope, safe_shlex_join(rsc_jvm_options)
)
)
native_image_path, native_image_snapshot = self._rsc.native_image(self.context)
additional_snapshots = [native_image_snapshot]
initial_args = [native_image_path]
else:
additional_snapshots = []
initial_args = (
[distribution.java,]
+ rsc_jvm_options
+ ["-cp", os.pathsep.join(tool_classpath), main,]
)
(argfile_snapshot,) = self.context._scheduler.capture_snapshots(
[
PathGlobsAndRoot(
PathGlobs([fast_relpath(ctx.args_file, get_buildroot())]), get_buildroot(),
),
]
)
cmd = initial_args + [f"@{argfile_snapshot.files[0]}"]
pathglobs = list(tool_classpath)
if pathglobs:
root = PathGlobsAndRoot(PathGlobs(tuple(pathglobs)), get_buildroot())
# dont capture snapshot, if pathglobs is empty
path_globs_input_digest = self.context._scheduler.capture_snapshots((root,))[
0
].directory_digest
epr_input_files = self.context._scheduler.merge_directories(
((path_globs_input_digest,) if path_globs_input_digest else ())
+ ((input_digest,) if input_digest else ())
+ tuple(s.directory_digest for s in additional_snapshots)
+ (argfile_snapshot.directory_digest,)
)
epr = ExecuteProcessRequest(
argv=tuple(cmd),
input_files=epr_input_files,
output_files=(fast_relpath(ctx.rsc_jar_file.path, get_buildroot()),),
output_directories=tuple(),
timeout_seconds=15 * 60,
description=f"run {tool_name} for {ctx.target}",
# TODO: These should always be unicodes
# Since this is always hermetic, we need to use `underlying.home` because
# ExecuteProcessRequest requires an existing, local jdk location.
jdk_home=distribution.underlying_home,
is_nailgunnable=True,
)
res = self.context.execute_process_synchronously_without_raising(
epr, self.name(), [WorkUnitLabel.COMPILER]
)
if res.exit_code != 0:
raise TaskError(res.stderr, exit_code=res.exit_code)
# TODO: parse the output of -Xprint:timings for rsc and write it to self._record_target_stats()!
res.output_directory_digest.dump(ctx.rsc_jar_file.path)
self.context._scheduler.materialize_directory(
DirectoryToMaterialize(res.output_directory_digest),
)
ctx.rsc_jar_file.hydrate_missing_directory_digest(res.output_directory_digest)
return res
# The classpath is parameterized so that we can have a single nailgun instance serving all of our
# execution requests.
def _runtool_nonhermetic(self, parent_workunit, classpath, main, tool_name, distribution, ctx):
# Scalac -Youtline cannot coexist with zinc jar in the same nailgun in a mulitithreaded run
# Forcing scalac -Youtline to run as a separate process circumvents this problem
use_youtline = tool_name == "scalac-outliner"
result = self.runjava(
classpath=classpath,
main=main,
jvm_options=self.get_options().jvm_options,
args=[f"@{ctx.args_file}"],
workunit_name=tool_name,
workunit_labels=[WorkUnitLabel.COMPILER],
dist=distribution,
force_subprocess=use_youtline,
)
if result != 0:
raise TaskError(f"Running {tool_name} failed")
runjava_workunit = None
for c in parent_workunit.children:
if c.name is tool_name:
runjava_workunit = c
break
# TODO: figure out and document when would this happen.
if runjava_workunit is None:
raise Exception("couldnt find work unit for underlying execution")
return runjava_workunit
# Mostly a copy-paste from ZincCompile.compile with many options removed
def _zinc_outline(self, ctx, relative_classpath, target_sources, youtline_args):
zinc_youtline_args = [f"-S{arg}" for arg in youtline_args]
zinc_file_manager = DependencyContext.global_instance().defaulted_property(
ctx.target, "zinc_file_manager"
)
def relative_to_exec_root(path):
return fast_relpath(path, get_buildroot())
analysis_cache = relative_to_exec_root(ctx.analysis_file)
classes_dir = relative_to_exec_root(ctx.classes_dir.path)
scalac_classpath_entries = self.scalac_classpath_entries()
scala_path = [
relative_to_exec_root(classpath_entry.path)
for classpath_entry in scalac_classpath_entries
]
zinc_args = []
zinc_args.extend(
[
"-log-level",
self.get_options().level,
"-analysis-cache",
analysis_cache,
"-classpath",
os.pathsep.join(relative_classpath),
]
)
compiler_bridge_classpath_entry = self._zinc.compile_compiler_bridge(self.context)
zinc_args.extend(
["-compiled-bridge-jar", relative_to_exec_root(compiler_bridge_classpath_entry.path)]
)
zinc_args.extend(["-scala-path", ":".join(scala_path)])
zinc_args.extend(zinc_youtline_args)
if not zinc_file_manager:
zinc_args.append("-no-zinc-file-manager")
jvm_options = []
if self.javac_classpath():
jvm_options.extend([f"-Xbootclasspath/p:{':'.join(self.javac_classpath())}"])
jvm_options.extend(self._jvm_options)
zinc_args.extend(ctx.sources)
self.log_zinc_file(ctx.analysis_file)
self.write_argsfile(ctx, zinc_args)
return self.execution_strategy.match(
{
self.ExecutionStrategy.hermetic: lambda: None,
self.ExecutionStrategy.subprocess: lambda: self._compile_nonhermetic(
jvm_options, ctx, classes_dir
),
self.ExecutionStrategy.nailgun: lambda: self._compile_nonhermetic(
jvm_options, ctx, classes_dir
),
}
)()
def _runtool(self, distribution, input_digest, ctx, use_youtline):
if use_youtline:
main = "scala.tools.nsc.Main"
tool_name = "scalac-outliner"
tool_classpath = self._scalac_classpath
# In fact, nailgun should not be used for -Youtline
# in case of self.ExecutionStrategy.nailgun,
# we will force the scalac -Youtline invokation to run via subprocess
nailgun_classpath = self._scalac_classpath
else:
main = "rsc.cli.Main"
tool_name = "rsc"
tool_classpath = self._rsc_classpath
nailgun_classpath = self._nailgunnable_combined_classpath
with self.context.new_workunit(tool_name) as wu:
return match(
self.execution_strategy,
{
self.ExecutionStrategy.hermetic: lambda: self._runtool_hermetic(
main, tool_name, distribution, input_digest, ctx
),
self.ExecutionStrategy.subprocess: lambda: self._runtool_nonhermetic(
wu, tool_classpath, main, tool_name, distribution, ctx
),
self.ExecutionStrategy.nailgun: lambda: self._runtool_nonhermetic(
wu, nailgun_classpath, main, tool_name, distribution, ctx
),
},
)()
_JDK_LIB_NAMES = ["rt.jar", "dt.jar", "jce.jar", "tools.jar"]
@memoized_method
def _jdk_libs_paths_and_digest(self, hermetic_dist):
jdk_libs_rel, jdk_libs_globs = hermetic_dist.find_libs_path_globs(self._JDK_LIB_NAMES)
jdk_libs_digest = self.context._scheduler.merge_directories(
[
snap.directory_digest
for snap in (self.context._scheduler.capture_snapshots(jdk_libs_globs))
]
)
return (jdk_libs_rel, jdk_libs_digest)
@memoized_method
def _jdk_libs_abs(self, nonhermetic_dist):
return nonhermetic_dist.find_libs(self._JDK_LIB_NAMES)
def _double_check_cache_for_vts(self, vts, zinc_compile_context):
# Double check the cache before beginning compilation
if self.check_cache(vts):
self.context.log.debug(f"Snapshotting results for {vts.target.address.spec}")
classpath_entry = self._classpath_for_context(zinc_compile_context)
relpath = fast_relpath(classpath_entry.path, get_buildroot())
(classes_dir_snapshot,) = self.context._scheduler.capture_snapshots(
[PathGlobsAndRoot(PathGlobs([relpath]), get_buildroot(), Digest.load(relpath),),]
)
classpath_entry.hydrate_missing_directory_digest(classes_dir_snapshot.directory_digest)
# Re-validate the vts!
vts.update()
|
#!/usr/bin/env python3.9
# -*- coding: utf-8 -*-
# ██████╗██╗██████╗ ██████╗██╗ ███████╗███████╗
# ██╔════╝██║██╔══██╗██╔════╝██║ ██╔════╝██╔════╝
# ██║ ██║██████╔╝██║ ██║ █████╗ ███████╗
# ██║ ██║██╔══██╗██║ ██║ ██╔══╝ ╚════██║
# ╚██████╗██║██║ ██║╚██████╗███████╗███████╗███████║
# ╚═════╝╚═╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚══════╝╚══════╝
import asyncio
import io
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path
import aiohttp
import aiomysql
import cmyui
import datadog
import geoip2.database
import orjson
from cmyui.logging import Ansi, log
import bg_loops
import utils.misc
from constants.privileges import Privileges
from objects.achievement import Achievement
from objects.collections import Channels, Clans, MapPools, Matches, Players
from objects.player import Player
from utils.updater import Updater
__all__ = ()
# we print utf-8 content quite often
if isinstance(sys.stdout, io.TextIOWrapper):
sys.stdout.reconfigure(encoding='utf-8')
# set cwd to /circles
os.chdir(os.path.dirname(os.path.realpath(__file__)))
try:
from objects import glob
except ModuleNotFoundError as exc:
if exc.name == 'config':
# config file doesn't exist; create it from the default.
import shutil
shutil.copy('ext/config.sample.py', 'config.py')
log('A config file has been generated, '
'please configure it to your needs.', Ansi.LRED)
raise SystemExit(1)
else:
raise
utils.misc.install_excepthook()
# current version of circles
# NOTE: this is used internally for the updater, it may be
# worth reading through it's code before playing with it.
glob.version = cmyui.Version(3, 5, 4)
OPPAI_PATH = Path.cwd() / 'oppai-ng'
GEOLOC_DB_FILE = Path.cwd() / 'ext/GeoLite2-City.mmdb'
DEBUG_HOOKS_PATH = Path.cwd() / '_testing/runtime.py'
DATA_PATH = Path.cwd() / '.data'
ACHIEVEMENTS_ASSETS_PATH = DATA_PATH / 'assets/medals/client'
async def setup_collections(db_cursor: aiomysql.DictCursor) -> None:
"""Setup & cache many global collections."""
# dynamic (active) sets, only in ram
glob.players = Players()
glob.matches = Matches()
# static (inactive) sets, in ram & sql
glob.channels = await Channels.prepare(db_cursor)
glob.clans = await Clans.prepare(db_cursor)
glob.pools = await MapPools.prepare(db_cursor)
# create bot & add it to online players
glob.bot = Player(
id=1,
name=await utils.misc.fetch_bot_name(db_cursor),
login_time=float(0x7fffffff), # (never auto-dc)
priv=Privileges.Normal,
bot_client=True
)
glob.players.append(glob.bot)
# global achievements (sorted by vn gamemodes)
glob.achievements = []
await db_cursor.execute('SELECT * FROM achievements')
async for row in db_cursor:
# NOTE: achievement conditions are stored as stringified python
# expressions in the database to allow for extensive customizability.
condition = eval(f'lambda score, mode_vn: {row.pop('cond')}')
achievement = Achievement(**row, cond=condition)
glob.achievements.append(achievement)
# static api keys
await db_cursor.execute(
'SELECT id, api_key FROM users '
'WHERE api_key IS NOT NULL'
)
glob.api_keys = {
row['api_key']: row['id']
async for row in db_cursor
}
async def before_serving() -> None:
"""Called before the server begins serving connections."""
glob.loop = asyncio.get_running_loop()
if glob.has_internet:
# retrieve a client session to use for http connections.
glob.http = aiohttp.ClientSession(
json_serialize=orjson.dumps) # type: ignore
else:
glob.http = None
# retrieve a pool of connections to use for mysql interaction.
glob.db = cmyui.AsyncSQLPool()
await glob.db.connect(glob.config.mysql)
# run the sql & submodule updater (uses http & db).
# TODO: updating cmyui_pkg should run before it's imported.
updater = Updater(glob.version)
await updater.run()
await updater.log_startup()
# open a connection to our local geoloc database,
# if the database file is present.
if GEOLOC_DB_FILE.exists():
glob.geoloc_db = geoip2.database.Reader(GEOLOC_DB_FILE)
else:
glob.geoloc_db = None
# support for https://datadoghq.com
if all(glob.config.datadog.values()):
datadog.initialize(**glob.config.datadog)
glob.datadog = datadog.ThreadStats()
glob.datadog.start(flush_in_thread=True,
flush_interval=15)
# wipe any previous stats from the page.
glob.datadog.gauge('circles.online_players', 0)
else:
glob.datadog = None
new_coros = []
# cache many global collections/objects from sql,
# such as channels, mappools, clans, bot, etc.
async with glob.db.pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as db_cursor:
await setup_collections(db_cursor)
# create a task for each donor expiring in 30d.
new_coros.extend(await bg_loops.donor_expiry(db_cursor))
# setup a loop to kick inactive ghosted players.
new_coros.append(bg_loops.disconnect_ghosts())
'''
# if the surveillance webhook has a value, run
# automatic (still very primitive) detections on
# replays deemed by the server's configurable values.
if glob.config.webhooks['surveillance']:
new_coros.append(bg_loops.replay_detections())
'''
# reroll the bot's random status every `interval` sec.
new_coros.append(bg_loops.reroll_bot_status(interval=300))
for coro in new_coros:
glob.app.add_pending_task(coro)
async def after_serving() -> None:
"""Called after the server stops serving connections."""
if hasattr(glob, 'http') and glob.http is not None:
await glob.http.close()
if hasattr(glob, 'db') and glob.db.pool is not None:
await glob.db.close()
if hasattr(glob, 'geoloc_db') and glob.geoloc_db is not None:
glob.geoloc_db.close()
if hasattr(glob, 'datadog') and glob.datadog is not None:
glob.datadog.stop()
glob.datadog.flush()
def ensure_supported_platform() -> int:
"""Ensure we're running on an appropriate platform for circles."""
if sys.platform != 'linux':
log('circles currently only supports linux', Ansi.LRED)
if sys.platform == 'win32':
log("you could also try wsl(2), i'd recommend ubuntu 18.04 "
"(i use it to test circles)", Ansi.LBLUE)
return 1
if sys.version_info < (3, 9):
log('circles uses many modern python features, '
'and the minimum python version is 3.9.', Ansi.LRED)
return 1
return 0
def ensure_local_services_are_running() -> int:
"""Ensure all required services (mysql) are running."""
# NOTE: if you have any problems with this, please contact me
# @cmyui#0425/cmyuiosu@gmail.com. i'm interested in knowing
# how people are using the software so that i can keep it
# in mind while developing new features & refactoring.
if glob.config.mysql['host'] in ('localhost', '127.0.0.1', None):
# sql server running locally, make sure it's running
for service in ('mysqld', 'mariadb'):
if os.path.exists(f'/var/run/{service}/{service}.pid'):
break
else:
# not found, try pgrep
pgrep_exit_code = os.system('pgrep mysqld')
if pgrep_exit_code != 0:
log('Please start your mysqld server.', Ansi.LRED)
return 1
return 0
def ensure_directory_structure() -> int:
"""Ensure the .data directory and git submodules are ready."""
# create /.data and its subdirectories.
DATA_PATH.mkdir(exist_ok=True)
for sub_dir in ('avatars', 'logs', 'osu', 'osr', 'ss'):
subdir = DATA_PATH / sub_dir
subdir.mkdir(exist_ok=True)
if not ACHIEVEMENTS_ASSETS_PATH.exists():
if not glob.has_internet:
# TODO: make it safe to run without achievements
return 1
ACHIEVEMENTS_ASSETS_PATH.mkdir(parents=True)
utils.misc.download_achievement_images(ACHIEVEMENTS_ASSETS_PATH)
return 0
def ensure_dependencies_and_requirements() -> int:
"""Make sure all of circles's dependencies are ready."""
if not OPPAI_PATH.exists():
log('No oppai-ng submodule found, attempting to clone.', Ansi.LMAGENTA)
p = subprocess.Popen(args=['git', 'submodule', 'init'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
if exit_code := p.wait():
log('Failed to initialize git submodules.', Ansi.LRED)
return exit_code
p = subprocess.Popen(args=['git', 'submodule', 'update'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
if exit_code := p.wait():
log('Failed to update git submodules.', Ansi.LRED)
return exit_code
if not (OPPAI_PATH / 'liboppai.so').exists():
log('No oppai-ng library found, attempting to build.', Ansi.LMAGENTA)
p = subprocess.Popen(args=['./libbuild'], cwd='oppai-ng',
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
if exit_code := p.wait():
log('Failed to build oppai-ng automatically.', Ansi.LRED)
return exit_code
return 0
def __install_debugging_hooks() -> None:
"""Change internals to help with debugging & active development."""
if DEBUG_HOOKS_PATH.exists():
from _testing import runtime # type: ignore
runtime.setup()
def display_startup_dialog() -> None:
"""Print any general information or warnings to the console."""
if glob.config.advanced:
log('running in advanced mode', Ansi.LRED)
# running on root grants the software potentally dangerous and
# unnecessary power over the operating system and is not advised.
if os.geteuid() == 0:
log('It is not recommended to run circles as root, '
'especially in production..', Ansi.LYELLOW)
if glob.config.advanced:
log('The risk is even greater with features '
'such as config.advanced enabled.', Ansi.LRED)
if not glob.has_internet:
log('Running in offline mode, some features '
'will not be available.', Ansi.LRED)
def main() -> int:
for safety_check in (
ensure_supported_platform, # linux only at the moment
ensure_local_services_are_running, # mysql (if local)
ensure_directory_structure, # .data/ & achievements/ dir structure
ensure_dependencies_and_requirements # submodules & oppai-ng built
):
if (exit_code := safety_check()) != 0:
return exit_code
'''Server is safe to start up'''
glob.boot_time = datetime.now()
# install any debugging hooks from
# _testing/runtime.py, if present
__install_debugging_hooks()
# check our internet connection status
glob.has_internet = utils.misc.check_connection(timeout=1.5)
# show info & any contextual warnings.
display_startup_dialog()
# create the server object; this will handle http connections
# for us via the transport (tcp/ip) socket interface, and will
# handle housekeeping (setup, cleanup) for us automatically.
glob.app = cmyui.Server(
name=f'circles v{glob.version}',
gzip=4, debug=glob.config.debug
)
# add the domains and their respective endpoints to our server object
from domains.ava import domain as ava_domain # a.ppy.sh
from domains.cho import domain as cho_domain # c[e4-6]?.ppy.sh
from domains.map import domain as map_domain # b.ppy.sh
from domains.osu import domain as osu_domain # osu.ppy.sh
glob.app.add_domains({cho_domain, osu_domain,
ava_domain, map_domain})
# attach housekeeping tasks (setup, cleanup)
glob.app.before_serving = before_serving
glob.app.after_serving = after_serving
# run the server (this is a blocking call)
glob.app.run(addr=glob.config.server_addr,
handle_restart=True) # (using SIGUSR1)
return 0
if __name__ == '__main__':
raise SystemExit(main())
elif __name__ == 'main':
# check specifically for asgi servers since many related projects
# (such as circles-web) use them, so people may assume we do as well.
if utils.misc.running_via_asgi_webserver(sys.argv[0]):
raise RuntimeError(
"circles does not use an ASGI framework, and uses it's own custom "
"web framework implementation; please run it directly (./main.py)."
)
else:
raise RuntimeError('circles should only be run directly (./main.py).')
| #!/usr/bin/env python3.9
# -*- coding: utf-8 -*-
# ██████╗██╗██████╗ ██████╗██╗ ███████╗███████╗
# ██╔════╝██║██╔══██╗██╔════╝██║ ██╔════╝██╔════╝
# ██║ ██║██████╔╝██║ ██║ █████╗ ███████╗
# ██║ ██║██╔══██╗██║ ██║ ██╔══╝ ╚════██║
# ╚██████╗██║██║ ██║╚██████╗███████╗███████╗███████║
# ╚═════╝╚═╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚══════╝╚══════╝
import asyncio
import io
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path
import aiohttp
import aiomysql
import cmyui
import datadog
import geoip2.database
import orjson
from cmyui.logging import Ansi, log
import bg_loops
import utils.misc
from constants.privileges import Privileges
from objects.achievement import Achievement
from objects.collections import Channels, Clans, MapPools, Matches, Players
from objects.player import Player
from utils.updater import Updater
__all__ = ()
# we print utf-8 content quite often
if isinstance(sys.stdout, io.TextIOWrapper):
sys.stdout.reconfigure(encoding='utf-8')
# set cwd to /circles
os.chdir(os.path.dirname(os.path.realpath(__file__)))
try:
from objects import glob
except ModuleNotFoundError as exc:
if exc.name == 'config':
# config file doesn't exist; create it from the default.
import shutil
shutil.copy('ext/config.sample.py', 'config.py')
log('A config file has been generated, '
'please configure it to your needs.', Ansi.LRED)
raise SystemExit(1)
else:
raise
utils.misc.install_excepthook()
# current version of circles
# NOTE: this is used internally for the updater, it may be
# worth reading through it's code before playing with it.
glob.version = cmyui.Version(3, 5, 4)
OPPAI_PATH = Path.cwd() / 'oppai-ng'
GEOLOC_DB_FILE = Path.cwd() / 'ext/GeoLite2-City.mmdb'
DEBUG_HOOKS_PATH = Path.cwd() / '_testing/runtime.py'
DATA_PATH = Path.cwd() / '.data'
ACHIEVEMENTS_ASSETS_PATH = DATA_PATH / 'assets/medals/client'
async def setup_collections(db_cursor: aiomysql.DictCursor) -> None:
"""Setup & cache many global collections."""
# dynamic (active) sets, only in ram
glob.players = Players()
glob.matches = Matches()
# static (inactive) sets, in ram & sql
glob.channels = await Channels.prepare(db_cursor)
glob.clans = await Clans.prepare(db_cursor)
glob.pools = await MapPools.prepare(db_cursor)
# create bot & add it to online players
glob.bot = Player(
id=1,
name=await utils.misc.fetch_bot_name(db_cursor),
login_time=float(0x7fffffff), # (never auto-dc)
priv=Privileges.Normal,
bot_client=True
)
glob.players.append(glob.bot)
# global achievements (sorted by vn gamemodes)
glob.achievements = []
await db_cursor.execute('SELECT * FROM achievements')
async for row in db_cursor:
# NOTE: achievement conditions are stored as stringified python
# expressions in the database to allow for extensive customizability.
condition = eval(f'lambda score, mode_vn: {row.pop("cond")}')
achievement = Achievement(**row, cond=condition)
glob.achievements.append(achievement)
# static api keys
await db_cursor.execute(
'SELECT id, api_key FROM users '
'WHERE api_key IS NOT NULL'
)
glob.api_keys = {
row['api_key']: row['id']
async for row in db_cursor
}
async def before_serving() -> None:
"""Called before the server begins serving connections."""
glob.loop = asyncio.get_running_loop()
if glob.has_internet:
# retrieve a client session to use for http connections.
glob.http = aiohttp.ClientSession(
json_serialize=orjson.dumps) # type: ignore
else:
glob.http = None
# retrieve a pool of connections to use for mysql interaction.
glob.db = cmyui.AsyncSQLPool()
await glob.db.connect(glob.config.mysql)
# run the sql & submodule updater (uses http & db).
# TODO: updating cmyui_pkg should run before it's imported.
updater = Updater(glob.version)
await updater.run()
await updater.log_startup()
# open a connection to our local geoloc database,
# if the database file is present.
if GEOLOC_DB_FILE.exists():
glob.geoloc_db = geoip2.database.Reader(GEOLOC_DB_FILE)
else:
glob.geoloc_db = None
# support for https://datadoghq.com
if all(glob.config.datadog.values()):
datadog.initialize(**glob.config.datadog)
glob.datadog = datadog.ThreadStats()
glob.datadog.start(flush_in_thread=True,
flush_interval=15)
# wipe any previous stats from the page.
glob.datadog.gauge('circles.online_players', 0)
else:
glob.datadog = None
new_coros = []
# cache many global collections/objects from sql,
# such as channels, mappools, clans, bot, etc.
async with glob.db.pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as db_cursor:
await setup_collections(db_cursor)
# create a task for each donor expiring in 30d.
new_coros.extend(await bg_loops.donor_expiry(db_cursor))
# setup a loop to kick inactive ghosted players.
new_coros.append(bg_loops.disconnect_ghosts())
'''
# if the surveillance webhook has a value, run
# automatic (still very primitive) detections on
# replays deemed by the server's configurable values.
if glob.config.webhooks['surveillance']:
new_coros.append(bg_loops.replay_detections())
'''
# reroll the bot's random status every `interval` sec.
new_coros.append(bg_loops.reroll_bot_status(interval=300))
for coro in new_coros:
glob.app.add_pending_task(coro)
async def after_serving() -> None:
"""Called after the server stops serving connections."""
if hasattr(glob, 'http') and glob.http is not None:
await glob.http.close()
if hasattr(glob, 'db') and glob.db.pool is not None:
await glob.db.close()
if hasattr(glob, 'geoloc_db') and glob.geoloc_db is not None:
glob.geoloc_db.close()
if hasattr(glob, 'datadog') and glob.datadog is not None:
glob.datadog.stop()
glob.datadog.flush()
def ensure_supported_platform() -> int:
"""Ensure we're running on an appropriate platform for circles."""
if sys.platform != 'linux':
log('circles currently only supports linux', Ansi.LRED)
if sys.platform == 'win32':
log("you could also try wsl(2), i'd recommend ubuntu 18.04 "
"(i use it to test circles)", Ansi.LBLUE)
return 1
if sys.version_info < (3, 9):
log('circles uses many modern python features, '
'and the minimum python version is 3.9.', Ansi.LRED)
return 1
return 0
def ensure_local_services_are_running() -> int:
"""Ensure all required services (mysql) are running."""
# NOTE: if you have any problems with this, please contact me
# @cmyui#0425/cmyuiosu@gmail.com. i'm interested in knowing
# how people are using the software so that i can keep it
# in mind while developing new features & refactoring.
if glob.config.mysql['host'] in ('localhost', '127.0.0.1', None):
# sql server running locally, make sure it's running
for service in ('mysqld', 'mariadb'):
if os.path.exists(f'/var/run/{service}/{service}.pid'):
break
else:
# not found, try pgrep
pgrep_exit_code = os.system('pgrep mysqld')
if pgrep_exit_code != 0:
log('Please start your mysqld server.', Ansi.LRED)
return 1
return 0
def ensure_directory_structure() -> int:
"""Ensure the .data directory and git submodules are ready."""
# create /.data and its subdirectories.
DATA_PATH.mkdir(exist_ok=True)
for sub_dir in ('avatars', 'logs', 'osu', 'osr', 'ss'):
subdir = DATA_PATH / sub_dir
subdir.mkdir(exist_ok=True)
if not ACHIEVEMENTS_ASSETS_PATH.exists():
if not glob.has_internet:
# TODO: make it safe to run without achievements
return 1
ACHIEVEMENTS_ASSETS_PATH.mkdir(parents=True)
utils.misc.download_achievement_images(ACHIEVEMENTS_ASSETS_PATH)
return 0
def ensure_dependencies_and_requirements() -> int:
"""Make sure all of circles's dependencies are ready."""
if not OPPAI_PATH.exists():
log('No oppai-ng submodule found, attempting to clone.', Ansi.LMAGENTA)
p = subprocess.Popen(args=['git', 'submodule', 'init'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
if exit_code := p.wait():
log('Failed to initialize git submodules.', Ansi.LRED)
return exit_code
p = subprocess.Popen(args=['git', 'submodule', 'update'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
if exit_code := p.wait():
log('Failed to update git submodules.', Ansi.LRED)
return exit_code
if not (OPPAI_PATH / 'liboppai.so').exists():
log('No oppai-ng library found, attempting to build.', Ansi.LMAGENTA)
p = subprocess.Popen(args=['./libbuild'], cwd='oppai-ng',
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
if exit_code := p.wait():
log('Failed to build oppai-ng automatically.', Ansi.LRED)
return exit_code
return 0
def __install_debugging_hooks() -> None:
"""Change internals to help with debugging & active development."""
if DEBUG_HOOKS_PATH.exists():
from _testing import runtime # type: ignore
runtime.setup()
def display_startup_dialog() -> None:
"""Print any general information or warnings to the console."""
if glob.config.advanced:
log('running in advanced mode', Ansi.LRED)
# running on root grants the software potentally dangerous and
# unnecessary power over the operating system and is not advised.
if os.geteuid() == 0:
log('It is not recommended to run circles as root, '
'especially in production..', Ansi.LYELLOW)
if glob.config.advanced:
log('The risk is even greater with features '
'such as config.advanced enabled.', Ansi.LRED)
if not glob.has_internet:
log('Running in offline mode, some features '
'will not be available.', Ansi.LRED)
def main() -> int:
for safety_check in (
ensure_supported_platform, # linux only at the moment
ensure_local_services_are_running, # mysql (if local)
ensure_directory_structure, # .data/ & achievements/ dir structure
ensure_dependencies_and_requirements # submodules & oppai-ng built
):
if (exit_code := safety_check()) != 0:
return exit_code
'''Server is safe to start up'''
glob.boot_time = datetime.now()
# install any debugging hooks from
# _testing/runtime.py, if present
__install_debugging_hooks()
# check our internet connection status
glob.has_internet = utils.misc.check_connection(timeout=1.5)
# show info & any contextual warnings.
display_startup_dialog()
# create the server object; this will handle http connections
# for us via the transport (tcp/ip) socket interface, and will
# handle housekeeping (setup, cleanup) for us automatically.
glob.app = cmyui.Server(
name=f'circles v{glob.version}',
gzip=4, debug=glob.config.debug
)
# add the domains and their respective endpoints to our server object
from domains.ava import domain as ava_domain # a.ppy.sh
from domains.cho import domain as cho_domain # c[e4-6]?.ppy.sh
from domains.map import domain as map_domain # b.ppy.sh
from domains.osu import domain as osu_domain # osu.ppy.sh
glob.app.add_domains({cho_domain, osu_domain,
ava_domain, map_domain})
# attach housekeeping tasks (setup, cleanup)
glob.app.before_serving = before_serving
glob.app.after_serving = after_serving
# run the server (this is a blocking call)
glob.app.run(addr=glob.config.server_addr,
handle_restart=True) # (using SIGUSR1)
return 0
if __name__ == '__main__':
raise SystemExit(main())
elif __name__ == 'main':
# check specifically for asgi servers since many related projects
# (such as circles-web) use them, so people may assume we do as well.
if utils.misc.running_via_asgi_webserver(sys.argv[0]):
raise RuntimeError(
"circles does not use an ASGI framework, and uses it's own custom "
"web framework implementation; please run it directly (./main.py)."
)
else:
raise RuntimeError('circles should only be run directly (./main.py).')
|
# -*- coding: utf8 -*-
# Copyright (c) 2019 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import dataclasses
import logging
import re
import typing as t
import docspec
from pydoc_markdown.interfaces import Processor, Resolver
logger = logging.getLogger(__name__)
@dataclasses.dataclass
class _ParamLine:
"""
Helper data class for holding details of Sphinx arguments.
"""
name: str
docs: str
type: t.Optional[str] = None
def generate_sections_markdown(lines, sections):
for key, section in sections.items():
if lines and lines[-1]:
lines.append('')
lines.extend(['**{}**:'.format(key), '']) # add an extra line because of markdown syntax
lines.extend(section)
@dataclasses.dataclass
class SphinxProcessor(Processor):
"""
This processor parses ReST/Sphinx-style function documentation and converts it into
Markdown syntax.
Example:
```
:param arg1: This is the first argument.
:raise ValueError: If *arg1* is a bad value.
:return: An `int` that represents an interesting value.
```
Renders as:
:param arg1: This is the first argument.
:raise ValueError: If *arg1* is a bad value.
:return: An `int` that represents an interesting value.
@doc:fmt:sphinx
"""
_KEYWORDS = {
'Arguments': [
'arg',
'argument',
'param',
'parameter',
'type',
],
'Returns': [
'return',
'returns',
'rtype',
],
'Raises': [
'raises',
'raise',
]
}
def check_docstring_format(self, docstring: str) -> bool:
return any(f':{k}' in docstring for _, value in self._KEYWORDS.items() for k in value)
def process(self, modules: t.List[docspec.Module], resolver: t.Optional[Resolver]) -> None:
docspec.visit(modules, self._process)
def _process(self, node):
if not node.docstring:
return
lines = []
in_codeblock = False
keyword = None
components: t.Dict[str, t.List[str]] = {}
parameters: t.List[_ParamLine] = []
return_: t.Optional[_ParamLine] = None
for line in node.docstring.split('\n'):
keyword = None
if line.strip().startswith("```"):
in_codeblock = not in_codeblock
line_codeblock = line.startswith(' ')
if not in_codeblock and not line_codeblock:
line = line.strip()
match = re.match(rf'\s*:({'|'.join(self._KEYWORDS['Arguments'])})\s+(\w+)\s*:(.*)?$', line)
if match:
keyword = 'Arguments'
components.setdefault(keyword, [])
param = match.group(2)
text = match.group(3)
text = text.strip()
param_data = next((p for p in parameters if p.name == param), None)
if match.group(1) == 'type':
if param_data is None:
param_data = _ParamLine(param, '', text)
parameters.append(param_data)
else:
param_data.type = text
else:
if param_data is None:
param_data = _ParamLine(param, text, None)
parameters.append(param_data)
else:
param_data.docs = text
continue
match = re.match(rf'\s*:({'|'.join(self._KEYWORDS['Returns'])})\s*:(.*)?$', line)
if match:
keyword = 'Returns'
components.setdefault('Returns', [])
text = match.group(2)
text = text.strip()
if match.group(1) == 'rtype':
if return_ is None:
return_ = _ParamLine('return', '', text)
else:
return_.type = text
else:
if return_ is None:
return_ = _ParamLine('return', text, None)
else:
return_.docs = text
continue
match = re.match(f'\\s*:(?:{'|'.join(self._KEYWORDS['Raises'])})\\s+(\\w+)\\s*:(.*)?$', line)
if match:
keyword = 'Raises'
exception = match.group(1)
text = match.group(2)
text = text.strip()
component = components.setdefault(keyword, [])
component.append('- `{}`: {}'.format(exception, text))
continue
if keyword is not None:
components[keyword].append(line)
else:
lines.append(line)
# Convert the parameters into actual markdown format.
component = components['Arguments'] if parameters else []
for param in parameters:
if param.type:
component.append('- `{}` (`{}`): {}'.format(param.name, param.type, param.docs))
else:
component.append('- `{}`: {}'.format(param.name, param.docs))
# Convert the return data into markdown format.
if return_:
return_fmt = f'`{return_.type}`: {return_.docs}' if return_.type else return_.docs
components['Returns'] = [return_fmt]
generate_sections_markdown(lines, components)
node.docstring = '\n'.join(lines)
| # -*- coding: utf8 -*-
# Copyright (c) 2019 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import dataclasses
import logging
import re
import typing as t
import docspec
from pydoc_markdown.interfaces import Processor, Resolver
logger = logging.getLogger(__name__)
@dataclasses.dataclass
class _ParamLine:
"""
Helper data class for holding details of Sphinx arguments.
"""
name: str
docs: str
type: t.Optional[str] = None
def generate_sections_markdown(lines, sections):
for key, section in sections.items():
if lines and lines[-1]:
lines.append('')
lines.extend(['**{}**:'.format(key), '']) # add an extra line because of markdown syntax
lines.extend(section)
@dataclasses.dataclass
class SphinxProcessor(Processor):
"""
This processor parses ReST/Sphinx-style function documentation and converts it into
Markdown syntax.
Example:
```
:param arg1: This is the first argument.
:raise ValueError: If *arg1* is a bad value.
:return: An `int` that represents an interesting value.
```
Renders as:
:param arg1: This is the first argument.
:raise ValueError: If *arg1* is a bad value.
:return: An `int` that represents an interesting value.
@doc:fmt:sphinx
"""
_KEYWORDS = {
'Arguments': [
'arg',
'argument',
'param',
'parameter',
'type',
],
'Returns': [
'return',
'returns',
'rtype',
],
'Raises': [
'raises',
'raise',
]
}
def check_docstring_format(self, docstring: str) -> bool:
return any(f':{k}' in docstring for _, value in self._KEYWORDS.items() for k in value)
def process(self, modules: t.List[docspec.Module], resolver: t.Optional[Resolver]) -> None:
docspec.visit(modules, self._process)
def _process(self, node):
if not node.docstring:
return
lines = []
in_codeblock = False
keyword = None
components: t.Dict[str, t.List[str]] = {}
parameters: t.List[_ParamLine] = []
return_: t.Optional[_ParamLine] = None
for line in node.docstring.split('\n'):
keyword = None
if line.strip().startswith("```"):
in_codeblock = not in_codeblock
line_codeblock = line.startswith(' ')
if not in_codeblock and not line_codeblock:
line = line.strip()
match = re.match(rf'\s*:({"|".join(self._KEYWORDS["Arguments"])})\s+(\w+)\s*:(.*)?$', line)
if match:
keyword = 'Arguments'
components.setdefault(keyword, [])
param = match.group(2)
text = match.group(3)
text = text.strip()
param_data = next((p for p in parameters if p.name == param), None)
if match.group(1) == 'type':
if param_data is None:
param_data = _ParamLine(param, '', text)
parameters.append(param_data)
else:
param_data.type = text
else:
if param_data is None:
param_data = _ParamLine(param, text, None)
parameters.append(param_data)
else:
param_data.docs = text
continue
match = re.match(rf'\s*:({"|".join(self._KEYWORDS["Returns"])})\s*:(.*)?$', line)
if match:
keyword = 'Returns'
components.setdefault('Returns', [])
text = match.group(2)
text = text.strip()
if match.group(1) == 'rtype':
if return_ is None:
return_ = _ParamLine('return', '', text)
else:
return_.type = text
else:
if return_ is None:
return_ = _ParamLine('return', text, None)
else:
return_.docs = text
continue
match = re.match(f'\\s*:(?:{"|".join(self._KEYWORDS["Raises"])})\\s+(\\w+)\\s*:(.*)?$', line)
if match:
keyword = 'Raises'
exception = match.group(1)
text = match.group(2)
text = text.strip()
component = components.setdefault(keyword, [])
component.append('- `{}`: {}'.format(exception, text))
continue
if keyword is not None:
components[keyword].append(line)
else:
lines.append(line)
# Convert the parameters into actual markdown format.
component = components['Arguments'] if parameters else []
for param in parameters:
if param.type:
component.append('- `{}` (`{}`): {}'.format(param.name, param.type, param.docs))
else:
component.append('- `{}`: {}'.format(param.name, param.docs))
# Convert the return data into markdown format.
if return_:
return_fmt = f'`{return_.type}`: {return_.docs}' if return_.type else return_.docs
components['Returns'] = [return_fmt]
generate_sections_markdown(lines, components)
node.docstring = '\n'.join(lines)
|
from typing import Dict, List, Optional, Tuple
import aiosqlite
from thyme.consensus.block_record import BlockRecord
from thyme.types.blockchain_format.sized_bytes import bytes32
from thyme.types.blockchain_format.sub_epoch_summary import SubEpochSummary
from thyme.types.header_block import HeaderBlock
from thyme.util.db_wrapper import DBWrapper
from thyme.util.ints import uint32, uint64
from thyme.util.lru_cache import LRUCache
from thyme.wallet.block_record import HeaderBlockRecord
class WalletBlockStore:
"""
This object handles HeaderBlocks and Blocks stored in DB used by wallet.
"""
db: aiosqlite.Connection
db_wrapper: DBWrapper
block_cache: LRUCache
@classmethod
async def create(cls, db_wrapper: DBWrapper):
self = cls()
self.db_wrapper = db_wrapper
self.db = db_wrapper.db
await self.db.execute("pragma journal_mode=wal")
await self.db.execute("pragma synchronous=2")
await self.db.execute(
"CREATE TABLE IF NOT EXISTS header_blocks(header_hash text PRIMARY KEY, height int,"
" timestamp int, block blob)"
)
await self.db.execute("CREATE INDEX IF NOT EXISTS header_hash on header_blocks(header_hash)")
await self.db.execute("CREATE INDEX IF NOT EXISTS timestamp on header_blocks(timestamp)")
await self.db.execute("CREATE INDEX IF NOT EXISTS height on header_blocks(height)")
# Block records
await self.db.execute(
"CREATE TABLE IF NOT EXISTS block_records(header_hash "
"text PRIMARY KEY, prev_hash text, height bigint, weight bigint, total_iters text,"
"block blob, sub_epoch_summary blob, is_peak tinyint)"
)
# Height index so we can look up in order of height for sync purposes
await self.db.execute("CREATE INDEX IF NOT EXISTS height on block_records(height)")
await self.db.execute("CREATE INDEX IF NOT EXISTS hh on block_records(header_hash)")
await self.db.execute("CREATE INDEX IF NOT EXISTS peak on block_records(is_peak)")
await self.db.commit()
self.block_cache = LRUCache(1000)
return self
async def _clear_database(self):
cursor_2 = await self.db.execute("DELETE FROM header_blocks")
await cursor_2.close()
await self.db.commit()
async def add_block_record(self, header_block_record: HeaderBlockRecord, block_record: BlockRecord):
"""
Adds a block record to the database. This block record is assumed to be connected
to the chain, but it may or may not be in the LCA path.
"""
cached = self.block_cache.get(header_block_record.header_hash)
if cached is not None:
# Since write to db can fail, we remove from cache here to avoid potential inconsistency
# Adding to cache only from reading
self.block_cache.put(header_block_record.header_hash, None)
if header_block_record.header.foliage_transaction_block is not None:
timestamp = header_block_record.header.foliage_transaction_block.timestamp
else:
timestamp = uint64(0)
cursor = await self.db.execute(
"INSERT OR REPLACE INTO header_blocks VALUES(?, ?, ?, ?)",
(
header_block_record.header_hash.hex(),
header_block_record.height,
timestamp,
bytes(header_block_record),
),
)
await cursor.close()
cursor_2 = await self.db.execute(
"INSERT OR REPLACE INTO block_records VALUES(?, ?, ?, ?, ?, ?, ?,?)",
(
header_block_record.header.header_hash.hex(),
header_block_record.header.prev_header_hash.hex(),
header_block_record.header.height,
header_block_record.header.weight.to_bytes(128 // 8, "big", signed=False).hex(),
header_block_record.header.total_iters.to_bytes(128 // 8, "big", signed=False).hex(),
bytes(block_record),
None
if block_record.sub_epoch_summary_included is None
else bytes(block_record.sub_epoch_summary_included),
False,
),
)
await cursor_2.close()
async def get_header_block_at(self, heights: List[uint32]) -> List[HeaderBlock]:
if len(heights) == 0:
return []
heights_db = tuple(heights)
formatted_str = f'SELECT block from header_blocks WHERE height in ({'?,' * (len(heights_db) - 1)}?)'
cursor = await self.db.execute(formatted_str, heights_db)
rows = await cursor.fetchall()
await cursor.close()
return [HeaderBlock.from_bytes(row[0]) for row in rows]
async def get_header_block_record(self, header_hash: bytes32) -> Optional[HeaderBlockRecord]:
"""Gets a block record from the database, if present"""
cached = self.block_cache.get(header_hash)
if cached is not None:
return cached
cursor = await self.db.execute("SELECT block from header_blocks WHERE header_hash=?", (header_hash.hex(),))
row = await cursor.fetchone()
await cursor.close()
if row is not None:
hbr: HeaderBlockRecord = HeaderBlockRecord.from_bytes(row[0])
self.block_cache.put(hbr.header_hash, hbr)
return hbr
else:
return None
async def get_block_record(self, header_hash: bytes32) -> Optional[BlockRecord]:
cursor = await self.db.execute(
"SELECT block from block_records WHERE header_hash=?",
(header_hash.hex(),),
)
row = await cursor.fetchone()
await cursor.close()
if row is not None:
return BlockRecord.from_bytes(row[0])
return None
async def get_block_records(
self,
) -> Tuple[Dict[bytes32, BlockRecord], Optional[bytes32]]:
"""
Returns a dictionary with all blocks, as well as the header hash of the peak,
if present.
"""
cursor = await self.db.execute("SELECT header_hash, block, is_peak from block_records")
rows = await cursor.fetchall()
await cursor.close()
ret: Dict[bytes32, BlockRecord] = {}
peak: Optional[bytes32] = None
for row in rows:
header_hash_bytes, block_record_bytes, is_peak = row
header_hash = bytes.fromhex(header_hash_bytes)
ret[header_hash] = BlockRecord.from_bytes(block_record_bytes)
if is_peak:
assert peak is None # Sanity check, only one peak
peak = header_hash
return ret, peak
async def set_peak(self, header_hash: bytes32) -> None:
cursor_1 = await self.db.execute("UPDATE block_records SET is_peak=0 WHERE is_peak=1")
await cursor_1.close()
cursor_2 = await self.db.execute(
"UPDATE block_records SET is_peak=1 WHERE header_hash=?",
(header_hash.hex(),),
)
await cursor_2.close()
async def get_block_records_close_to_peak(
self, blocks_n: int
) -> Tuple[Dict[bytes32, BlockRecord], Optional[bytes32]]:
"""
Returns a dictionary with all blocks, as well as the header hash of the peak,
if present.
"""
res = await self.db.execute("SELECT header_hash, height from block_records WHERE is_peak = 1")
row = await res.fetchone()
await res.close()
if row is None:
return {}, None
header_hash_bytes, peak_height = row
peak: bytes32 = bytes32(bytes.fromhex(header_hash_bytes))
formatted_str = f"SELECT header_hash, block from block_records WHERE height >= {peak_height - blocks_n}"
cursor = await self.db.execute(formatted_str)
rows = await cursor.fetchall()
await cursor.close()
ret: Dict[bytes32, BlockRecord] = {}
for row in rows:
header_hash_bytes, block_record_bytes = row
header_hash = bytes.fromhex(header_hash_bytes)
ret[header_hash] = BlockRecord.from_bytes(block_record_bytes)
return ret, peak
async def get_header_blocks_in_range(
self,
start: int,
stop: int,
) -> Dict[bytes32, HeaderBlock]:
formatted_str = f"SELECT header_hash, block from header_blocks WHERE height >= {start} and height <= {stop}"
cursor = await self.db.execute(formatted_str)
rows = await cursor.fetchall()
await cursor.close()
ret: Dict[bytes32, HeaderBlock] = {}
for row in rows:
header_hash_bytes, block_record_bytes = row
header_hash = bytes.fromhex(header_hash_bytes)
ret[header_hash] = HeaderBlock.from_bytes(block_record_bytes)
return ret
async def get_block_records_in_range(
self,
start: int,
stop: int,
) -> Dict[bytes32, BlockRecord]:
"""
Returns a dictionary with all blocks, as well as the header hash of the peak,
if present.
"""
formatted_str = f"SELECT header_hash, block from block_records WHERE height >= {start} and height <= {stop}"
cursor = await self.db.execute(formatted_str)
rows = await cursor.fetchall()
await cursor.close()
ret: Dict[bytes32, BlockRecord] = {}
for row in rows:
header_hash_bytes, block_record_bytes = row
header_hash = bytes.fromhex(header_hash_bytes)
ret[header_hash] = BlockRecord.from_bytes(block_record_bytes)
return ret
async def get_peak_heights_dicts(self) -> Tuple[Dict[uint32, bytes32], Dict[uint32, SubEpochSummary]]:
"""
Returns a dictionary with all blocks, as well as the header hash of the peak,
if present.
"""
res = await self.db.execute("SELECT header_hash from block_records WHERE is_peak = 1")
row = await res.fetchone()
await res.close()
if row is None:
return {}, {}
peak: bytes32 = bytes.fromhex(row[0])
cursor = await self.db.execute("SELECT header_hash,prev_hash,height,sub_epoch_summary from block_records")
rows = await cursor.fetchall()
await cursor.close()
hash_to_prev_hash: Dict[bytes32, bytes32] = {}
hash_to_height: Dict[bytes32, uint32] = {}
hash_to_summary: Dict[bytes32, SubEpochSummary] = {}
for row in rows:
hash_to_prev_hash[bytes.fromhex(row[0])] = bytes.fromhex(row[1])
hash_to_height[bytes.fromhex(row[0])] = row[2]
if row[3] is not None:
hash_to_summary[bytes.fromhex(row[0])] = SubEpochSummary.from_bytes(row[3])
height_to_hash: Dict[uint32, bytes32] = {}
sub_epoch_summaries: Dict[uint32, SubEpochSummary] = {}
curr_header_hash = peak
curr_height = hash_to_height[curr_header_hash]
while True:
height_to_hash[curr_height] = curr_header_hash
if curr_header_hash in hash_to_summary:
sub_epoch_summaries[curr_height] = hash_to_summary[curr_header_hash]
if curr_height == 0:
break
curr_header_hash = hash_to_prev_hash[curr_header_hash]
curr_height = hash_to_height[curr_header_hash]
return height_to_hash, sub_epoch_summaries
| from typing import Dict, List, Optional, Tuple
import aiosqlite
from thyme.consensus.block_record import BlockRecord
from thyme.types.blockchain_format.sized_bytes import bytes32
from thyme.types.blockchain_format.sub_epoch_summary import SubEpochSummary
from thyme.types.header_block import HeaderBlock
from thyme.util.db_wrapper import DBWrapper
from thyme.util.ints import uint32, uint64
from thyme.util.lru_cache import LRUCache
from thyme.wallet.block_record import HeaderBlockRecord
class WalletBlockStore:
"""
This object handles HeaderBlocks and Blocks stored in DB used by wallet.
"""
db: aiosqlite.Connection
db_wrapper: DBWrapper
block_cache: LRUCache
@classmethod
async def create(cls, db_wrapper: DBWrapper):
self = cls()
self.db_wrapper = db_wrapper
self.db = db_wrapper.db
await self.db.execute("pragma journal_mode=wal")
await self.db.execute("pragma synchronous=2")
await self.db.execute(
"CREATE TABLE IF NOT EXISTS header_blocks(header_hash text PRIMARY KEY, height int,"
" timestamp int, block blob)"
)
await self.db.execute("CREATE INDEX IF NOT EXISTS header_hash on header_blocks(header_hash)")
await self.db.execute("CREATE INDEX IF NOT EXISTS timestamp on header_blocks(timestamp)")
await self.db.execute("CREATE INDEX IF NOT EXISTS height on header_blocks(height)")
# Block records
await self.db.execute(
"CREATE TABLE IF NOT EXISTS block_records(header_hash "
"text PRIMARY KEY, prev_hash text, height bigint, weight bigint, total_iters text,"
"block blob, sub_epoch_summary blob, is_peak tinyint)"
)
# Height index so we can look up in order of height for sync purposes
await self.db.execute("CREATE INDEX IF NOT EXISTS height on block_records(height)")
await self.db.execute("CREATE INDEX IF NOT EXISTS hh on block_records(header_hash)")
await self.db.execute("CREATE INDEX IF NOT EXISTS peak on block_records(is_peak)")
await self.db.commit()
self.block_cache = LRUCache(1000)
return self
async def _clear_database(self):
cursor_2 = await self.db.execute("DELETE FROM header_blocks")
await cursor_2.close()
await self.db.commit()
async def add_block_record(self, header_block_record: HeaderBlockRecord, block_record: BlockRecord):
"""
Adds a block record to the database. This block record is assumed to be connected
to the chain, but it may or may not be in the LCA path.
"""
cached = self.block_cache.get(header_block_record.header_hash)
if cached is not None:
# Since write to db can fail, we remove from cache here to avoid potential inconsistency
# Adding to cache only from reading
self.block_cache.put(header_block_record.header_hash, None)
if header_block_record.header.foliage_transaction_block is not None:
timestamp = header_block_record.header.foliage_transaction_block.timestamp
else:
timestamp = uint64(0)
cursor = await self.db.execute(
"INSERT OR REPLACE INTO header_blocks VALUES(?, ?, ?, ?)",
(
header_block_record.header_hash.hex(),
header_block_record.height,
timestamp,
bytes(header_block_record),
),
)
await cursor.close()
cursor_2 = await self.db.execute(
"INSERT OR REPLACE INTO block_records VALUES(?, ?, ?, ?, ?, ?, ?,?)",
(
header_block_record.header.header_hash.hex(),
header_block_record.header.prev_header_hash.hex(),
header_block_record.header.height,
header_block_record.header.weight.to_bytes(128 // 8, "big", signed=False).hex(),
header_block_record.header.total_iters.to_bytes(128 // 8, "big", signed=False).hex(),
bytes(block_record),
None
if block_record.sub_epoch_summary_included is None
else bytes(block_record.sub_epoch_summary_included),
False,
),
)
await cursor_2.close()
async def get_header_block_at(self, heights: List[uint32]) -> List[HeaderBlock]:
if len(heights) == 0:
return []
heights_db = tuple(heights)
formatted_str = f'SELECT block from header_blocks WHERE height in ({"?," * (len(heights_db) - 1)}?)'
cursor = await self.db.execute(formatted_str, heights_db)
rows = await cursor.fetchall()
await cursor.close()
return [HeaderBlock.from_bytes(row[0]) for row in rows]
async def get_header_block_record(self, header_hash: bytes32) -> Optional[HeaderBlockRecord]:
"""Gets a block record from the database, if present"""
cached = self.block_cache.get(header_hash)
if cached is not None:
return cached
cursor = await self.db.execute("SELECT block from header_blocks WHERE header_hash=?", (header_hash.hex(),))
row = await cursor.fetchone()
await cursor.close()
if row is not None:
hbr: HeaderBlockRecord = HeaderBlockRecord.from_bytes(row[0])
self.block_cache.put(hbr.header_hash, hbr)
return hbr
else:
return None
async def get_block_record(self, header_hash: bytes32) -> Optional[BlockRecord]:
cursor = await self.db.execute(
"SELECT block from block_records WHERE header_hash=?",
(header_hash.hex(),),
)
row = await cursor.fetchone()
await cursor.close()
if row is not None:
return BlockRecord.from_bytes(row[0])
return None
async def get_block_records(
self,
) -> Tuple[Dict[bytes32, BlockRecord], Optional[bytes32]]:
"""
Returns a dictionary with all blocks, as well as the header hash of the peak,
if present.
"""
cursor = await self.db.execute("SELECT header_hash, block, is_peak from block_records")
rows = await cursor.fetchall()
await cursor.close()
ret: Dict[bytes32, BlockRecord] = {}
peak: Optional[bytes32] = None
for row in rows:
header_hash_bytes, block_record_bytes, is_peak = row
header_hash = bytes.fromhex(header_hash_bytes)
ret[header_hash] = BlockRecord.from_bytes(block_record_bytes)
if is_peak:
assert peak is None # Sanity check, only one peak
peak = header_hash
return ret, peak
async def set_peak(self, header_hash: bytes32) -> None:
cursor_1 = await self.db.execute("UPDATE block_records SET is_peak=0 WHERE is_peak=1")
await cursor_1.close()
cursor_2 = await self.db.execute(
"UPDATE block_records SET is_peak=1 WHERE header_hash=?",
(header_hash.hex(),),
)
await cursor_2.close()
async def get_block_records_close_to_peak(
self, blocks_n: int
) -> Tuple[Dict[bytes32, BlockRecord], Optional[bytes32]]:
"""
Returns a dictionary with all blocks, as well as the header hash of the peak,
if present.
"""
res = await self.db.execute("SELECT header_hash, height from block_records WHERE is_peak = 1")
row = await res.fetchone()
await res.close()
if row is None:
return {}, None
header_hash_bytes, peak_height = row
peak: bytes32 = bytes32(bytes.fromhex(header_hash_bytes))
formatted_str = f"SELECT header_hash, block from block_records WHERE height >= {peak_height - blocks_n}"
cursor = await self.db.execute(formatted_str)
rows = await cursor.fetchall()
await cursor.close()
ret: Dict[bytes32, BlockRecord] = {}
for row in rows:
header_hash_bytes, block_record_bytes = row
header_hash = bytes.fromhex(header_hash_bytes)
ret[header_hash] = BlockRecord.from_bytes(block_record_bytes)
return ret, peak
async def get_header_blocks_in_range(
self,
start: int,
stop: int,
) -> Dict[bytes32, HeaderBlock]:
formatted_str = f"SELECT header_hash, block from header_blocks WHERE height >= {start} and height <= {stop}"
cursor = await self.db.execute(formatted_str)
rows = await cursor.fetchall()
await cursor.close()
ret: Dict[bytes32, HeaderBlock] = {}
for row in rows:
header_hash_bytes, block_record_bytes = row
header_hash = bytes.fromhex(header_hash_bytes)
ret[header_hash] = HeaderBlock.from_bytes(block_record_bytes)
return ret
async def get_block_records_in_range(
self,
start: int,
stop: int,
) -> Dict[bytes32, BlockRecord]:
"""
Returns a dictionary with all blocks, as well as the header hash of the peak,
if present.
"""
formatted_str = f"SELECT header_hash, block from block_records WHERE height >= {start} and height <= {stop}"
cursor = await self.db.execute(formatted_str)
rows = await cursor.fetchall()
await cursor.close()
ret: Dict[bytes32, BlockRecord] = {}
for row in rows:
header_hash_bytes, block_record_bytes = row
header_hash = bytes.fromhex(header_hash_bytes)
ret[header_hash] = BlockRecord.from_bytes(block_record_bytes)
return ret
async def get_peak_heights_dicts(self) -> Tuple[Dict[uint32, bytes32], Dict[uint32, SubEpochSummary]]:
"""
Returns a dictionary with all blocks, as well as the header hash of the peak,
if present.
"""
res = await self.db.execute("SELECT header_hash from block_records WHERE is_peak = 1")
row = await res.fetchone()
await res.close()
if row is None:
return {}, {}
peak: bytes32 = bytes.fromhex(row[0])
cursor = await self.db.execute("SELECT header_hash,prev_hash,height,sub_epoch_summary from block_records")
rows = await cursor.fetchall()
await cursor.close()
hash_to_prev_hash: Dict[bytes32, bytes32] = {}
hash_to_height: Dict[bytes32, uint32] = {}
hash_to_summary: Dict[bytes32, SubEpochSummary] = {}
for row in rows:
hash_to_prev_hash[bytes.fromhex(row[0])] = bytes.fromhex(row[1])
hash_to_height[bytes.fromhex(row[0])] = row[2]
if row[3] is not None:
hash_to_summary[bytes.fromhex(row[0])] = SubEpochSummary.from_bytes(row[3])
height_to_hash: Dict[uint32, bytes32] = {}
sub_epoch_summaries: Dict[uint32, SubEpochSummary] = {}
curr_header_hash = peak
curr_height = hash_to_height[curr_header_hash]
while True:
height_to_hash[curr_height] = curr_header_hash
if curr_header_hash in hash_to_summary:
sub_epoch_summaries[curr_height] = hash_to_summary[curr_header_hash]
if curr_height == 0:
break
curr_header_hash = hash_to_prev_hash[curr_header_hash]
curr_height = hash_to_height[curr_header_hash]
return height_to_hash, sub_epoch_summaries
|
import os
# use if needed to pass args to external modules
import sys
# used for directory handling
import glob
import time
import threading
#gogo MOD telegram needs import request
import requests
# needed for the binance API / websockets / Exception handling
from binance.client import Client
from binance.exceptions import BinanceAPIException
from requests.exceptions import ReadTimeout, ConnectionError
# used to store trades and sell assets
import json
from helpers.parameters import (
parse_args, load_config
)
# Load creds modules
from helpers.handle_creds import (
load_correct_creds, test_api_key,
load_telegram_creds
)
from bot.settings import *
from bot.grab import *
def trailing_buy(volatile_coins):
global trail_buy_historical
global trail_buy_coins
buy_volatile_coins = {}
trail_buy_last_price = get_price(False)
for coin in volatile_coins:
trail_buy_coins[coin] = volatile_coins[coin]
for coin in trail_buy_coins:
if float(trail_buy_historical[coin]['price']) > float(trail_buy_last_price[coin]['price']):
trail_buy_coins[coin] = trail_buy_coins[coin] + (-1.0 *(float(trail_buy_historical[coin]['price']) - float(trail_buy_last_price[coin]['price'])) / float(trail_buy_historical[coin]['price']) * 100)
print(f"COIN: {coin} has DROPPED from {trail_buy_historical[coin]["price"]} to {trail_buy_last_price[coin]["price"]}")
print(f"COIN: {coin} has DROPPED for {-1.0 *(float(trail_buy_historical[coin]["price"]) - float(trail_buy_last_price[coin]["price"])) / float(trail_buy_historical[coin]["price"]) * 100}%")
if float(trail_buy_historical[coin]['price']) < float(trail_buy_last_price[coin]['price']):
print(f"COIN: {coin} has GONE UP!!!! from {trail_buy_historical[coin]["price"]} to {trail_buy_last_price[coin]["price"]}")
print(f"COIN: {coin} has GONE UP!!!! for {-1.0 *(float(trail_buy_historical[coin]["price"]) - float(trail_buy_last_price[coin]["price"])) / float(trail_buy_historical[coin]["price"]) * 100}%")
if float(-1.0 *(float(trail_buy_historical[coin]['price']) - float(trail_buy_last_price[coin]['price'])) / float(trail_buy_historical[coin]['price']) * 100) > settings_struct['TRAILING_BUY_THRESHOLD']:
buy_volatile_coins[coin] = trail_buy_coins[coin]
if buy_volatile_coins:
for coin in buy_volatile_coins:
del trail_buy_coins[coin]
trail_buy_historical = trail_buy_last_price
print(f"TRAIL_BUY_COINS: {trail_buy_coins}")
print(f"BUY_VOLATILE_COINS: {buy_volatile_coins}")
return buy_volatile_coins
def trade_calculations(type, priceChange):
if type == 'holding':
if trading_struct['max_holding_price'] < priceChange :
trading_struct['max_holding_price'] = priceChange
if trading_struct['min_holding_price'] > priceChange :
trading_struct['min_holding_price'] = priceChange
session_struct['unrealised_percent'] = session_struct['unrealised_percent'] + priceChange
if type == 'sell':
if priceChange > 0:
session_struct['win_trade_count'] = session_struct['win_trade_count'] + 1
session_struct['last_trade_won'] = True
trading_struct['consecutive_loss'] = 0
trading_struct['won_trade_percent'] = priceChange
trading_struct['sum_won_trades'] = trading_struct['sum_won_trades'] + trading_struct['won_trade_percent']
else:
session_struct['loss_trade_count'] = session_struct['loss_trade_count'] + 1
session_struct['last_trade_won'] = False
if session_struct['last_trade_won'] == False:
trading_struct['consecutive_loss'] += 1
trading_struct['lost_trade_percent'] = priceChange
trading_struct['sum_lost_trades'] = trading_struct['sum_lost_trades'] + trading_struct['lost_trade_percent']
settings_struct['STOP_LOSS'] = (settings_struct['STOP_LOSS'] + session_struct['profit_to_trade_ratio']) / 2
trading_struct['sum_max_holding_price'] = trading_struct['sum_max_holding_price'] + trading_struct['max_holding_price']
trading_struct['max_holding_price'] = 0
trading_struct['sum_min_holding_price'] = trading_struct['sum_min_holding_price'] + trading_struct['min_holding_price']
trading_struct['min_holding_price'] = 0
session_struct['closed_trades_percent'] = session_struct['closed_trades_percent'] + priceChange
session_struct['reload_tickers_list'] = True
session_struct['unrealised_percent'] = 0
def convert_volume():
'''Converts the volume given in QUANTITY from USDT to the each coin's volume'''
#added feature to buy only if percent and signal triggers uses PERCENT_SIGNAL_BUY true or false from config
if PERCENT_SIGNAL_BUY == True:
volatile_coins, number_of_coins, last_price = wait_for_price('percent_mix_signal')
else:
volatile_coins, number_of_coins, last_price = wait_for_price('percent_and_signal')
buy_volatile_coins = {}
lot_size = {}
volume = {}
buy_volatile_coins = trailing_buy(volatile_coins)
for coin in buy_volatile_coins:
# Find the correct step size for each coin
# max accuracy for BTC for example is 6 decimal points
# while XRP is only 1
try:
step_size = session_struct['symbol_info'][coin]
lot_size[coin] = step_size.index('1') - 1
except KeyError:
# not retrieved at startup, try again
try:
coin_info = client.get_symbol_info(coin)
step_size = coin_info['filters'][2]['stepSize']
lot_size[coin] = step_size.index('1') - 1
except:
pass
lot_size[coin] = max(lot_size[coin], 0)
# calculate the volume in coin from QUANTITY in USDT (default)
volume[coin] = float(QUANTITY / float(last_price[coin]['price']))
# define the volume with the correct step size
if coin not in lot_size:
volume[coin] = float('{:.1f}'.format(volume[coin]))
else:
# if lot size has 0 decimal points, make the volume an integer
if lot_size[coin] == 0:
volume[coin] = int(volume[coin])
else:
volume[coin] = float('{:.{}f}'.format(volume[coin], lot_size[coin]))
return volume, last_price
def test_order_id():
import random
"""returns a fake order id by hashing the current time"""
test_order_id_number = random.randint(100000000,999999999)
return test_order_id_number
def buy():
'''Place Buy market orders for each volatile coin found'''
global UNIQUE_BUYS
volume, last_price = convert_volume()
orders = {}
for coin in volume:
BUYABLE = True
if UNIQUE_BUYS and (coin in coins_bought):
BUYABLE = False
# only buy if the there are no active trades on the coin
if BUYABLE:
print(f"{txcolors.BUY}Preparing to buy {volume[coin]} {coin}{txcolors.DEFAULT}")
REPORT = str(f"Buy : {volume[coin]} {coin} - {last_price[coin]["price"]}")
if TEST_MODE:
orders[coin] = [{
'symbol': coin,
'orderId': test_order_id(),
'time': datetime.now().timestamp()
}]
# Log trades
report_struct['report'] = REPORT
report_struct['log'] = True
continue
# try to create a real order if the test orders did not raise an exception
try:
order_details = client.create_order(
symbol = coin,
side = 'BUY',
type = 'MARKET',
quantity = volume[coin]
)
# error handling here in case position cannot be placed
except Exception as e:
print(e)
# run the else block if the position has been placed and return order info
else:
orders[coin] = client.get_all_orders(symbol=coin, limit=1)
# binance sometimes returns an empty list, the code will wait here until binance returns the order
while orders[coin] == []:
print('Binance is being slow in returning the order, calling the API again...')
orders[coin] = client.get_all_orders(symbol=coin, limit=1)
time.sleep(1)
else:
# Log, announce, and report trade
print('Order returned, saving order to file')
if not TEST_MODE:
orders[coin] = extract_order_data(order_details)
REPORT = str(f"BUY: bought {orders[coin]["volume"]} {coin} - average price: {orders[coin]["avgPrice"]} {PAIR_WITH}")
report_struct['report'] = REPORT
report_struct['log'] = True
else:
print(f'Signal detected, but there is already an active trade on {coin}')
return orders, last_price, volume
def sell_coins():
'''sell coins that have reached the STOP LOSS or TAKE PROFIT threshold'''
global session_struct, settings_struct, trading_struct
global hsp_head
global FULL_LOG
last_price = get_price(False) # don't populate rolling window
#last_price = get_price(add_to_historical=True) # don't populate rolling window
coins_sold = {}
holding_timeout_sell_trigger = False
for coin in list(coins_bought):
BUY_PRICE = float(coins_bought[coin]['bought_at'])
# coinTakeProfit is the price at which to 'take profit' based on config % markup
coinTakeProfit = BUY_PRICE + ((BUY_PRICE * coins_bought[coin]['take_profit']) / 100)
# coinStopLoss is the price at which to 'stop losses' based on config % markdown
coinStopLoss = BUY_PRICE + ((BUY_PRICE * coins_bought[coin]['stop_loss']) / 100)
# coinHoldingTimeLimit is the time limit for holding onto a coin
coinHoldingTimeLimit = float(coins_bought[coin]['timestamp']) + settings_struct['HOLDING_TIME_LIMIT']
lastPrice = float(last_price[coin]['price'])
LAST_PRICE = "{:.8f}".format(lastPrice)
sellFee = (coins_bought[coin]['volume'] * lastPrice) * (TRADING_FEE/100)
buyPrice = float(coins_bought[coin]['bought_at'])
BUY_PRICE = "{:.8f}". format(buyPrice)
buyFee = (coins_bought[coin]['volume'] * buyPrice) * (TRADING_FEE/100)
# Note: priceChange and priceChangeWithFee are percentages!
priceChange = float((lastPrice - buyPrice) / buyPrice * 100)
# priceChange = (0.00006648 - 0.00006733) / 0.00006733 * 100
# volume = 150
# buyPrice: 0.00006733
# lastPrice: 0.00006648
# buyFee = (150 * 0.00006733) * (0.075/100)
# buyFee = 0.000007574625
# sellFee = (150 * 0.00006648) * (0.075/100)
# sellFee = 0.000007479
# check that the price is above the take profit and readjust coinStopLoss and coinTakeProfit accordingly if trialing stop loss used
if lastPrice > coinTakeProfit and USE_TRAILING_STOP_LOSS:
# increasing coinTakeProfit by TRAILING_TAKE_PROFIT (essentially next time to readjust coinStopLoss)
coins_bought[coin]['take_profit'] = priceChange + settings_struct['TRAILING_TAKE_PROFIT']
coins_bought[coin]['stop_loss'] = coins_bought[coin]['take_profit'] - settings_struct['TRAILING_STOP_LOSS']
if DEBUG: print(f"{coin} TP reached, adjusting TP {coins_bought[coin]["take_profit"]:.{decimals()}f} and SL {coins_bought[coin]["stop_loss"]:.{decimals()}f} accordingly to lock-in profit")
continue
if not TEST_MODE:
current_time = float(round(time.time() * 1000))
# print(f'TL:{coinHoldingTimeLimit}, time: {current_time} HOLDING_TIME_LIMIT: {HOLDING_TIME_LIMIT}, TimeLeft: {(coinHoldingTimeLimit - current_time)/1000/60} ')
if TEST_MODE:
current_time = float(round(time.time()))
# print(f'TL:{coinHoldingTimeLimit}, time: {current_time} HOLDING_TIME_LIMIT: {HOLDING_TIME_LIMIT}, TimeLeft: {(coinHoldingTimeLimit - current_time)/60} ')
trade_calculations('holding', priceChange)
if coinHoldingTimeLimit < current_time and priceChange > settings_struct['HOLDING_PRICE_THRESHOLD']:
holding_timeout_sell_trigger = True
# check that the price is below the stop loss or above take profit (if trailing stop loss not used) and sell if this is the case
if session_struct['sell_all_coins'] == True or lastPrice < coinStopLoss or lastPrice > coinTakeProfit and not USE_TRAILING_STOP_LOSS or holding_timeout_sell_trigger == True:
print(f"{txcolors.SELL_PROFIT if priceChange >= 0. else txcolors.SELL_LOSS}TP or SL reached, selling {coins_bought[coin]["volume"]} {coin}. Bought at: {BUY_PRICE} (Price now: {LAST_PRICE}) - {priceChange:.2f}% - Est: {(QUANTITY * priceChange) / 100:.{decimals()}f} {PAIR_WITH}{txcolors.DEFAULT}")
# try to create a real order
try:
if not TEST_MODE:
order_details = client.create_order(
symbol = coin,
side = 'SELL',
type = 'MARKET',
quantity = coins_bought[coin]['volume']
)
# error handling here in case position cannot be placed
except Exception as e:
print(e)
# run the else block if coin has been sold and create a dict for each coin sold
else:
if not TEST_MODE:
coins_sold[coin] = extract_order_data(order_details)
lastPrice = coins_sold[coin]['avgPrice']
sellFee = coins_sold[coin]['tradeFee']
coins_sold[coin]['orderid'] = coins_bought[coin]['orderid']
priceChange = float((lastPrice - buyPrice) / buyPrice * 100)
else:
coins_sold[coin] = coins_bought[coin]
# prevent system from buying this coin for the next TIME_DIFFERENCE minutes
volatility_cooloff[coin] = datetime.now()
# Log trade
trade_profit = (lastPrice - buyPrice) * coins_sold[coin]['volume']
trade_calculations('sell', priceChange)
#gogo MOD to trigger trade lost or won and to count lost or won trades
if session_struct['sell_all_coins'] == True: REPORT = f"PAUSE_SELL - SELL: {coins_sold[coin]["volume"]} {coin} - Bought at {buyPrice:.{decimals()}f}, sold at {lastPrice:.{decimals()}f} - Profit: {trade_profit:.{decimals()}f} {PAIR_WITH} ({priceChange:.2f}%)"
if lastPrice < coinStopLoss: REPORT = f"STOP_LOSS - SELL: {coins_sold[coin]["volume"]} {coin} - Bought at {buyPrice:.{decimals()}f}, sold at {lastPrice:.{decimals()}f} - Profit: {trade_profit:.{decimals()}f} {PAIR_WITH} ({priceChange:.2f}%)"
if lastPrice > coinTakeProfit: REPORT = f"TAKE_PROFIT - SELL: {coins_sold[coin]["volume"]} {coin} - Bought at {buyPrice:.{decimals()}f}, sold at {lastPrice:.{decimals()}f} - Profit: {trade_profit:.{decimals()}f} {PAIR_WITH} ({priceChange:.2f}%)"
if holding_timeout_sell_trigger: REPORT = f"HOLDING_TIMEOUT - SELL: {coins_sold[coin]["volume"]} {coin} - Bought at {buyPrice:.{decimals()}f}, sold at {lastPrice:.{decimals()}f} - Profit: {trade_profit:.{decimals()}f} {PAIR_WITH} ({priceChange:.2f}%)"
session_struct['session_profit'] = session_struct['session_profit'] + trade_profit
holding_timeout_sell_trigger = False
report_struct['report'] = REPORT
report_struct['message'] = True
report_struct['log'] = True
continue
if len(coins_bought) > 0:
print(f"TP:{coinTakeProfit:.{decimals()}f}:{coins_bought[coin]["take_profit"]:.2f} or SL:{coinStopLoss:.{decimals()}f}:{coins_bought[coin]["stop_loss"]:.2f} not yet reached, not selling {coin} for now >> Bought at: {BUY_PRICE} - Now: {LAST_PRICE} : {txcolors.SELL_PROFIT if priceChange >= 0. else txcolors.SELL_LOSS}{priceChange:.2f}% Est: {(QUANTITY*(priceChange-(buyFee+sellFee)))/100:.{decimals()}f} {PAIR_WITH} - CIP: {settings_struct["CHANGE_IN_PRICE_MIN"]:.2f}/{settings_struct["CHANGE_IN_PRICE_MAX"]:.2f} - TAKE_PROFIT: {settings_struct["TAKE_PROFIT"]:.2f}{txcolors.DEFAULT}")
return coins_sold
def extract_order_data(order_details):
global TRADING_FEE, STOP_LOSS, TAKE_PROFIT
transactionInfo = {}
# adding order fill extractions here
#
# just to explain what I am doing here:
# Market orders are not always filled at one price, we need to find the averages of all 'parts' (fills) of this order.
#
# reset other variables to 0 before use
FILLS_TOTAL = 0
FILLS_QTY = 0
FILLS_FEE = 0
BNB_WARNING = 0
# loop through each 'fill':
for fills in order_details['fills']:
FILL_PRICE = float(fills['price'])
FILL_QTY = float(fills['qty'])
FILLS_FEE += float(fills['commission'])
# check if the fee was in BNB. If not, log a nice warning:
if (fills['commissionAsset'] != 'BNB') and (TRADING_FEE == 0.75) and (BNB_WARNING == 0):
print(f"WARNING: BNB not used for trading fee, please ")
BNB_WARNING += 1
# quantity of fills * price
FILLS_TOTAL += (FILL_PRICE * FILL_QTY)
# add to running total of fills quantity
FILLS_QTY += FILL_QTY
# increase fills array index by 1
# calculate average fill price:
FILL_AVG = (FILLS_TOTAL / FILLS_QTY)
tradeFeeApprox = (float(FILLS_QTY) * float(FILL_AVG)) * (TRADING_FEE/100)
# create object with received data from Binance
transactionInfo = {
'symbol': order_details['symbol'],
'orderId': order_details['orderId'],
'timestamp': order_details['transactTime'],
'avgPrice': float(FILL_AVG),
'volume': float(FILLS_QTY),
'tradeFeeBNB': float(FILLS_FEE),
'tradeFee': tradeFeeApprox,
}
return transactionInfo
def update_portfolio(orders, last_price, volume):
global session_struct
'''add every coin bought to our portfolio for tracking/selling later'''
if DEBUG: print(orders)
for coin in orders:
if not TEST_MODE:
coins_bought[coin] = {
'symbol': orders[coin]['symbol'],
'orderid': orders[coin]['orderId'],
'timestamp': orders[coin]['timestamp'],
'bought_at': orders[coin]['avgPrice'],
'volume': orders[coin]['volume'],
'buyFeeBNB': orders[coin]['tradeFeeBNB'],
'buyFee': orders[coin]['tradeFee'],
'stop_loss': -settings_struct['STOP_LOSS'],
'take_profit': settings_struct['TAKE_PROFIT'],
}
else:
coins_bought[coin] = {
'symbol': orders[coin][0]['symbol'],
'orderid': orders[coin][0]['orderId'],
'timestamp': orders[coin][0]['time'],
'bought_at': last_price[coin]['price'],
'volume': volume[coin],
'stop_loss': -settings_struct['STOP_LOSS'],
'take_profit': settings_struct['TAKE_PROFIT'],
}
# save the coins in a json file in the same directory
with open(coins_bought_file_path, 'w') as file:
json.dump(coins_bought, file, indent=4)
if TEST_MODE: print(f'Order for {orders[coin][0]['symbol']} with ID {orders[coin][0]['orderId']} placed and saved to file.')
if not TEST_MODE: print(f'Order for {orders[coin]['symbol']} with ID {orders[coin]['orderId']} placed and saved to file.')
session_struct['trade_slots'] = len(coins_bought)
def remove_from_portfolio(coins_sold):
global session_struct
'''Remove coins sold due to SL or TP from portfolio'''
for coin,data in coins_sold.items():
symbol = coin
order_id = data['orderid']
# code below created by getsec <3
for bought_coin, bought_coin_data in coins_bought.items():
if bought_coin_data['orderid'] == order_id:
print(f"Sold {bought_coin}, removed order ID {order_id} from history.")
coins_bought.pop(bought_coin)
with open(coins_bought_file_path, 'w') as file:
json.dump(coins_bought, file, indent=4)
break
session_struct['trade_slots'] = len(coins_bought)
session_struct['reload_tickers_list'] = True
def trade_crypto():
global CONNECTION_ERROR_COUNT, READ_TIMEOUT_COUNT
try:
orders, last_price, volume = buy()
update_portfolio(orders, last_price, volume)
coins_sold = sell_coins()
remove_from_portfolio(coins_sold)
except ReadTimeout as rt:
READ_TIMEOUT_COUNT += 1
print(f'We got a timeout error from from binance. Going to re-loop. Current Count: {READ_TIMEOUT_COUNT}')
except ConnectionError as ce:
CONNECTION_ERROR_COUNT +=1
print(f'{txcolors.WARNING}We got a timeout error from from binance. Going to re-loop. Current Count: {CONNECTION_ERROR_COUNT}\n{ce}{txcolors.DEFAULT}')
| import os
# use if needed to pass args to external modules
import sys
# used for directory handling
import glob
import time
import threading
#gogo MOD telegram needs import request
import requests
# needed for the binance API / websockets / Exception handling
from binance.client import Client
from binance.exceptions import BinanceAPIException
from requests.exceptions import ReadTimeout, ConnectionError
# used to store trades and sell assets
import json
from helpers.parameters import (
parse_args, load_config
)
# Load creds modules
from helpers.handle_creds import (
load_correct_creds, test_api_key,
load_telegram_creds
)
from bot.settings import *
from bot.grab import *
def trailing_buy(volatile_coins):
global trail_buy_historical
global trail_buy_coins
buy_volatile_coins = {}
trail_buy_last_price = get_price(False)
for coin in volatile_coins:
trail_buy_coins[coin] = volatile_coins[coin]
for coin in trail_buy_coins:
if float(trail_buy_historical[coin]['price']) > float(trail_buy_last_price[coin]['price']):
trail_buy_coins[coin] = trail_buy_coins[coin] + (-1.0 *(float(trail_buy_historical[coin]['price']) - float(trail_buy_last_price[coin]['price'])) / float(trail_buy_historical[coin]['price']) * 100)
print(f"COIN: {coin} has DROPPED from {trail_buy_historical[coin]['price']} to {trail_buy_last_price[coin]['price']}")
print(f"COIN: {coin} has DROPPED for {-1.0 *(float(trail_buy_historical[coin]['price']) - float(trail_buy_last_price[coin]['price'])) / float(trail_buy_historical[coin]['price']) * 100}%")
if float(trail_buy_historical[coin]['price']) < float(trail_buy_last_price[coin]['price']):
print(f"COIN: {coin} has GONE UP!!!! from {trail_buy_historical[coin]['price']} to {trail_buy_last_price[coin]['price']}")
print(f"COIN: {coin} has GONE UP!!!! for {-1.0 *(float(trail_buy_historical[coin]['price']) - float(trail_buy_last_price[coin]['price'])) / float(trail_buy_historical[coin]['price']) * 100}%")
if float(-1.0 *(float(trail_buy_historical[coin]['price']) - float(trail_buy_last_price[coin]['price'])) / float(trail_buy_historical[coin]['price']) * 100) > settings_struct['TRAILING_BUY_THRESHOLD']:
buy_volatile_coins[coin] = trail_buy_coins[coin]
if buy_volatile_coins:
for coin in buy_volatile_coins:
del trail_buy_coins[coin]
trail_buy_historical = trail_buy_last_price
print(f"TRAIL_BUY_COINS: {trail_buy_coins}")
print(f"BUY_VOLATILE_COINS: {buy_volatile_coins}")
return buy_volatile_coins
def trade_calculations(type, priceChange):
if type == 'holding':
if trading_struct['max_holding_price'] < priceChange :
trading_struct['max_holding_price'] = priceChange
if trading_struct['min_holding_price'] > priceChange :
trading_struct['min_holding_price'] = priceChange
session_struct['unrealised_percent'] = session_struct['unrealised_percent'] + priceChange
if type == 'sell':
if priceChange > 0:
session_struct['win_trade_count'] = session_struct['win_trade_count'] + 1
session_struct['last_trade_won'] = True
trading_struct['consecutive_loss'] = 0
trading_struct['won_trade_percent'] = priceChange
trading_struct['sum_won_trades'] = trading_struct['sum_won_trades'] + trading_struct['won_trade_percent']
else:
session_struct['loss_trade_count'] = session_struct['loss_trade_count'] + 1
session_struct['last_trade_won'] = False
if session_struct['last_trade_won'] == False:
trading_struct['consecutive_loss'] += 1
trading_struct['lost_trade_percent'] = priceChange
trading_struct['sum_lost_trades'] = trading_struct['sum_lost_trades'] + trading_struct['lost_trade_percent']
settings_struct['STOP_LOSS'] = (settings_struct['STOP_LOSS'] + session_struct['profit_to_trade_ratio']) / 2
trading_struct['sum_max_holding_price'] = trading_struct['sum_max_holding_price'] + trading_struct['max_holding_price']
trading_struct['max_holding_price'] = 0
trading_struct['sum_min_holding_price'] = trading_struct['sum_min_holding_price'] + trading_struct['min_holding_price']
trading_struct['min_holding_price'] = 0
session_struct['closed_trades_percent'] = session_struct['closed_trades_percent'] + priceChange
session_struct['reload_tickers_list'] = True
session_struct['unrealised_percent'] = 0
def convert_volume():
'''Converts the volume given in QUANTITY from USDT to the each coin's volume'''
#added feature to buy only if percent and signal triggers uses PERCENT_SIGNAL_BUY true or false from config
if PERCENT_SIGNAL_BUY == True:
volatile_coins, number_of_coins, last_price = wait_for_price('percent_mix_signal')
else:
volatile_coins, number_of_coins, last_price = wait_for_price('percent_and_signal')
buy_volatile_coins = {}
lot_size = {}
volume = {}
buy_volatile_coins = trailing_buy(volatile_coins)
for coin in buy_volatile_coins:
# Find the correct step size for each coin
# max accuracy for BTC for example is 6 decimal points
# while XRP is only 1
try:
step_size = session_struct['symbol_info'][coin]
lot_size[coin] = step_size.index('1') - 1
except KeyError:
# not retrieved at startup, try again
try:
coin_info = client.get_symbol_info(coin)
step_size = coin_info['filters'][2]['stepSize']
lot_size[coin] = step_size.index('1') - 1
except:
pass
lot_size[coin] = max(lot_size[coin], 0)
# calculate the volume in coin from QUANTITY in USDT (default)
volume[coin] = float(QUANTITY / float(last_price[coin]['price']))
# define the volume with the correct step size
if coin not in lot_size:
volume[coin] = float('{:.1f}'.format(volume[coin]))
else:
# if lot size has 0 decimal points, make the volume an integer
if lot_size[coin] == 0:
volume[coin] = int(volume[coin])
else:
volume[coin] = float('{:.{}f}'.format(volume[coin], lot_size[coin]))
return volume, last_price
def test_order_id():
import random
"""returns a fake order id by hashing the current time"""
test_order_id_number = random.randint(100000000,999999999)
return test_order_id_number
def buy():
'''Place Buy market orders for each volatile coin found'''
global UNIQUE_BUYS
volume, last_price = convert_volume()
orders = {}
for coin in volume:
BUYABLE = True
if UNIQUE_BUYS and (coin in coins_bought):
BUYABLE = False
# only buy if the there are no active trades on the coin
if BUYABLE:
print(f"{txcolors.BUY}Preparing to buy {volume[coin]} {coin}{txcolors.DEFAULT}")
REPORT = str(f"Buy : {volume[coin]} {coin} - {last_price[coin]['price']}")
if TEST_MODE:
orders[coin] = [{
'symbol': coin,
'orderId': test_order_id(),
'time': datetime.now().timestamp()
}]
# Log trades
report_struct['report'] = REPORT
report_struct['log'] = True
continue
# try to create a real order if the test orders did not raise an exception
try:
order_details = client.create_order(
symbol = coin,
side = 'BUY',
type = 'MARKET',
quantity = volume[coin]
)
# error handling here in case position cannot be placed
except Exception as e:
print(e)
# run the else block if the position has been placed and return order info
else:
orders[coin] = client.get_all_orders(symbol=coin, limit=1)
# binance sometimes returns an empty list, the code will wait here until binance returns the order
while orders[coin] == []:
print('Binance is being slow in returning the order, calling the API again...')
orders[coin] = client.get_all_orders(symbol=coin, limit=1)
time.sleep(1)
else:
# Log, announce, and report trade
print('Order returned, saving order to file')
if not TEST_MODE:
orders[coin] = extract_order_data(order_details)
REPORT = str(f"BUY: bought {orders[coin]['volume']} {coin} - average price: {orders[coin]['avgPrice']} {PAIR_WITH}")
report_struct['report'] = REPORT
report_struct['log'] = True
else:
print(f'Signal detected, but there is already an active trade on {coin}')
return orders, last_price, volume
def sell_coins():
'''sell coins that have reached the STOP LOSS or TAKE PROFIT threshold'''
global session_struct, settings_struct, trading_struct
global hsp_head
global FULL_LOG
last_price = get_price(False) # don't populate rolling window
#last_price = get_price(add_to_historical=True) # don't populate rolling window
coins_sold = {}
holding_timeout_sell_trigger = False
for coin in list(coins_bought):
BUY_PRICE = float(coins_bought[coin]['bought_at'])
# coinTakeProfit is the price at which to 'take profit' based on config % markup
coinTakeProfit = BUY_PRICE + ((BUY_PRICE * coins_bought[coin]['take_profit']) / 100)
# coinStopLoss is the price at which to 'stop losses' based on config % markdown
coinStopLoss = BUY_PRICE + ((BUY_PRICE * coins_bought[coin]['stop_loss']) / 100)
# coinHoldingTimeLimit is the time limit for holding onto a coin
coinHoldingTimeLimit = float(coins_bought[coin]['timestamp']) + settings_struct['HOLDING_TIME_LIMIT']
lastPrice = float(last_price[coin]['price'])
LAST_PRICE = "{:.8f}".format(lastPrice)
sellFee = (coins_bought[coin]['volume'] * lastPrice) * (TRADING_FEE/100)
buyPrice = float(coins_bought[coin]['bought_at'])
BUY_PRICE = "{:.8f}". format(buyPrice)
buyFee = (coins_bought[coin]['volume'] * buyPrice) * (TRADING_FEE/100)
# Note: priceChange and priceChangeWithFee are percentages!
priceChange = float((lastPrice - buyPrice) / buyPrice * 100)
# priceChange = (0.00006648 - 0.00006733) / 0.00006733 * 100
# volume = 150
# buyPrice: 0.00006733
# lastPrice: 0.00006648
# buyFee = (150 * 0.00006733) * (0.075/100)
# buyFee = 0.000007574625
# sellFee = (150 * 0.00006648) * (0.075/100)
# sellFee = 0.000007479
# check that the price is above the take profit and readjust coinStopLoss and coinTakeProfit accordingly if trialing stop loss used
if lastPrice > coinTakeProfit and USE_TRAILING_STOP_LOSS:
# increasing coinTakeProfit by TRAILING_TAKE_PROFIT (essentially next time to readjust coinStopLoss)
coins_bought[coin]['take_profit'] = priceChange + settings_struct['TRAILING_TAKE_PROFIT']
coins_bought[coin]['stop_loss'] = coins_bought[coin]['take_profit'] - settings_struct['TRAILING_STOP_LOSS']
if DEBUG: print(f"{coin} TP reached, adjusting TP {coins_bought[coin]['take_profit']:.{decimals()}f} and SL {coins_bought[coin]['stop_loss']:.{decimals()}f} accordingly to lock-in profit")
continue
if not TEST_MODE:
current_time = float(round(time.time() * 1000))
# print(f'TL:{coinHoldingTimeLimit}, time: {current_time} HOLDING_TIME_LIMIT: {HOLDING_TIME_LIMIT}, TimeLeft: {(coinHoldingTimeLimit - current_time)/1000/60} ')
if TEST_MODE:
current_time = float(round(time.time()))
# print(f'TL:{coinHoldingTimeLimit}, time: {current_time} HOLDING_TIME_LIMIT: {HOLDING_TIME_LIMIT}, TimeLeft: {(coinHoldingTimeLimit - current_time)/60} ')
trade_calculations('holding', priceChange)
if coinHoldingTimeLimit < current_time and priceChange > settings_struct['HOLDING_PRICE_THRESHOLD']:
holding_timeout_sell_trigger = True
# check that the price is below the stop loss or above take profit (if trailing stop loss not used) and sell if this is the case
if session_struct['sell_all_coins'] == True or lastPrice < coinStopLoss or lastPrice > coinTakeProfit and not USE_TRAILING_STOP_LOSS or holding_timeout_sell_trigger == True:
print(f"{txcolors.SELL_PROFIT if priceChange >= 0. else txcolors.SELL_LOSS}TP or SL reached, selling {coins_bought[coin]['volume']} {coin}. Bought at: {BUY_PRICE} (Price now: {LAST_PRICE}) - {priceChange:.2f}% - Est: {(QUANTITY * priceChange) / 100:.{decimals()}f} {PAIR_WITH}{txcolors.DEFAULT}")
# try to create a real order
try:
if not TEST_MODE:
order_details = client.create_order(
symbol = coin,
side = 'SELL',
type = 'MARKET',
quantity = coins_bought[coin]['volume']
)
# error handling here in case position cannot be placed
except Exception as e:
print(e)
# run the else block if coin has been sold and create a dict for each coin sold
else:
if not TEST_MODE:
coins_sold[coin] = extract_order_data(order_details)
lastPrice = coins_sold[coin]['avgPrice']
sellFee = coins_sold[coin]['tradeFee']
coins_sold[coin]['orderid'] = coins_bought[coin]['orderid']
priceChange = float((lastPrice - buyPrice) / buyPrice * 100)
else:
coins_sold[coin] = coins_bought[coin]
# prevent system from buying this coin for the next TIME_DIFFERENCE minutes
volatility_cooloff[coin] = datetime.now()
# Log trade
trade_profit = (lastPrice - buyPrice) * coins_sold[coin]['volume']
trade_calculations('sell', priceChange)
#gogo MOD to trigger trade lost or won and to count lost or won trades
if session_struct['sell_all_coins'] == True: REPORT = f"PAUSE_SELL - SELL: {coins_sold[coin]['volume']} {coin} - Bought at {buyPrice:.{decimals()}f}, sold at {lastPrice:.{decimals()}f} - Profit: {trade_profit:.{decimals()}f} {PAIR_WITH} ({priceChange:.2f}%)"
if lastPrice < coinStopLoss: REPORT = f"STOP_LOSS - SELL: {coins_sold[coin]['volume']} {coin} - Bought at {buyPrice:.{decimals()}f}, sold at {lastPrice:.{decimals()}f} - Profit: {trade_profit:.{decimals()}f} {PAIR_WITH} ({priceChange:.2f}%)"
if lastPrice > coinTakeProfit: REPORT = f"TAKE_PROFIT - SELL: {coins_sold[coin]['volume']} {coin} - Bought at {buyPrice:.{decimals()}f}, sold at {lastPrice:.{decimals()}f} - Profit: {trade_profit:.{decimals()}f} {PAIR_WITH} ({priceChange:.2f}%)"
if holding_timeout_sell_trigger: REPORT = f"HOLDING_TIMEOUT - SELL: {coins_sold[coin]['volume']} {coin} - Bought at {buyPrice:.{decimals()}f}, sold at {lastPrice:.{decimals()}f} - Profit: {trade_profit:.{decimals()}f} {PAIR_WITH} ({priceChange:.2f}%)"
session_struct['session_profit'] = session_struct['session_profit'] + trade_profit
holding_timeout_sell_trigger = False
report_struct['report'] = REPORT
report_struct['message'] = True
report_struct['log'] = True
continue
if len(coins_bought) > 0:
print(f"TP:{coinTakeProfit:.{decimals()}f}:{coins_bought[coin]['take_profit']:.2f} or SL:{coinStopLoss:.{decimals()}f}:{coins_bought[coin]['stop_loss']:.2f} not yet reached, not selling {coin} for now >> Bought at: {BUY_PRICE} - Now: {LAST_PRICE} : {txcolors.SELL_PROFIT if priceChange >= 0. else txcolors.SELL_LOSS}{priceChange:.2f}% Est: {(QUANTITY*(priceChange-(buyFee+sellFee)))/100:.{decimals()}f} {PAIR_WITH} - CIP: {settings_struct['CHANGE_IN_PRICE_MIN']:.2f}/{settings_struct['CHANGE_IN_PRICE_MAX']:.2f} - TAKE_PROFIT: {settings_struct['TAKE_PROFIT']:.2f}{txcolors.DEFAULT}")
return coins_sold
def extract_order_data(order_details):
global TRADING_FEE, STOP_LOSS, TAKE_PROFIT
transactionInfo = {}
# adding order fill extractions here
#
# just to explain what I am doing here:
# Market orders are not always filled at one price, we need to find the averages of all 'parts' (fills) of this order.
#
# reset other variables to 0 before use
FILLS_TOTAL = 0
FILLS_QTY = 0
FILLS_FEE = 0
BNB_WARNING = 0
# loop through each 'fill':
for fills in order_details['fills']:
FILL_PRICE = float(fills['price'])
FILL_QTY = float(fills['qty'])
FILLS_FEE += float(fills['commission'])
# check if the fee was in BNB. If not, log a nice warning:
if (fills['commissionAsset'] != 'BNB') and (TRADING_FEE == 0.75) and (BNB_WARNING == 0):
print(f"WARNING: BNB not used for trading fee, please ")
BNB_WARNING += 1
# quantity of fills * price
FILLS_TOTAL += (FILL_PRICE * FILL_QTY)
# add to running total of fills quantity
FILLS_QTY += FILL_QTY
# increase fills array index by 1
# calculate average fill price:
FILL_AVG = (FILLS_TOTAL / FILLS_QTY)
tradeFeeApprox = (float(FILLS_QTY) * float(FILL_AVG)) * (TRADING_FEE/100)
# create object with received data from Binance
transactionInfo = {
'symbol': order_details['symbol'],
'orderId': order_details['orderId'],
'timestamp': order_details['transactTime'],
'avgPrice': float(FILL_AVG),
'volume': float(FILLS_QTY),
'tradeFeeBNB': float(FILLS_FEE),
'tradeFee': tradeFeeApprox,
}
return transactionInfo
def update_portfolio(orders, last_price, volume):
global session_struct
'''add every coin bought to our portfolio for tracking/selling later'''
if DEBUG: print(orders)
for coin in orders:
if not TEST_MODE:
coins_bought[coin] = {
'symbol': orders[coin]['symbol'],
'orderid': orders[coin]['orderId'],
'timestamp': orders[coin]['timestamp'],
'bought_at': orders[coin]['avgPrice'],
'volume': orders[coin]['volume'],
'buyFeeBNB': orders[coin]['tradeFeeBNB'],
'buyFee': orders[coin]['tradeFee'],
'stop_loss': -settings_struct['STOP_LOSS'],
'take_profit': settings_struct['TAKE_PROFIT'],
}
else:
coins_bought[coin] = {
'symbol': orders[coin][0]['symbol'],
'orderid': orders[coin][0]['orderId'],
'timestamp': orders[coin][0]['time'],
'bought_at': last_price[coin]['price'],
'volume': volume[coin],
'stop_loss': -settings_struct['STOP_LOSS'],
'take_profit': settings_struct['TAKE_PROFIT'],
}
# save the coins in a json file in the same directory
with open(coins_bought_file_path, 'w') as file:
json.dump(coins_bought, file, indent=4)
if TEST_MODE: print(f'Order for {orders[coin][0]["symbol"]} with ID {orders[coin][0]["orderId"]} placed and saved to file.')
if not TEST_MODE: print(f'Order for {orders[coin]["symbol"]} with ID {orders[coin]["orderId"]} placed and saved to file.')
session_struct['trade_slots'] = len(coins_bought)
def remove_from_portfolio(coins_sold):
global session_struct
'''Remove coins sold due to SL or TP from portfolio'''
for coin,data in coins_sold.items():
symbol = coin
order_id = data['orderid']
# code below created by getsec <3
for bought_coin, bought_coin_data in coins_bought.items():
if bought_coin_data['orderid'] == order_id:
print(f"Sold {bought_coin}, removed order ID {order_id} from history.")
coins_bought.pop(bought_coin)
with open(coins_bought_file_path, 'w') as file:
json.dump(coins_bought, file, indent=4)
break
session_struct['trade_slots'] = len(coins_bought)
session_struct['reload_tickers_list'] = True
def trade_crypto():
global CONNECTION_ERROR_COUNT, READ_TIMEOUT_COUNT
try:
orders, last_price, volume = buy()
update_portfolio(orders, last_price, volume)
coins_sold = sell_coins()
remove_from_portfolio(coins_sold)
except ReadTimeout as rt:
READ_TIMEOUT_COUNT += 1
print(f'We got a timeout error from from binance. Going to re-loop. Current Count: {READ_TIMEOUT_COUNT}')
except ConnectionError as ce:
CONNECTION_ERROR_COUNT +=1
print(f'{txcolors.WARNING}We got a timeout error from from binance. Going to re-loop. Current Count: {CONNECTION_ERROR_COUNT}\n{ce}{txcolors.DEFAULT}')
|
import unittest
from unittest import mock
import discord
from bot.cogs.sync.syncers import RoleSyncer, _Diff, _Role
from tests import helpers
def fake_role(**kwargs):
"""Fixture to return a dictionary representing a role with default values set."""
kwargs.setdefault("id", 9)
kwargs.setdefault("name", "fake role")
kwargs.setdefault("colour", 7)
kwargs.setdefault("permissions", 0)
kwargs.setdefault("position", 55)
return kwargs
class RoleSyncerDiffTests(unittest.IsolatedAsyncioTestCase):
"""Tests for determining differences between roles in the DB and roles in the Guild cache."""
def setUp(self):
self.bot = helpers.MockBot()
self.syncer = RoleSyncer(self.bot)
@staticmethod
def get_guild(*roles):
"""Fixture to return a guild object with the given roles."""
guild = helpers.MockGuild()
guild.roles = []
for role in roles:
mock_role = helpers.MockRole(**role)
mock_role.colour = discord.Colour(role["colour"])
mock_role.permissions = discord.Permissions(role["permissions"])
guild.roles.append(mock_role)
return guild
async def test_empty_diff_for_identical_roles(self):
"""No differences should be found if the roles in the guild and DB are identical."""
self.bot.api_client.get.return_value = [fake_role()]
guild = self.get_guild(fake_role())
actual_diff = await self.syncer._get_diff(guild)
expected_diff = (set(), set(), set())
self.assertEqual(actual_diff, expected_diff)
async def test_diff_for_updated_roles(self):
"""Only updated roles should be added to the 'updated' set of the diff."""
updated_role = fake_role(id=41, name="new")
self.bot.api_client.get.return_value = [fake_role(id=41, name="old"), fake_role()]
guild = self.get_guild(updated_role, fake_role())
actual_diff = await self.syncer._get_diff(guild)
expected_diff = (set(), {_Role(**updated_role)}, set())
self.assertEqual(actual_diff, expected_diff)
async def test_diff_for_new_roles(self):
"""Only new roles should be added to the 'created' set of the diff."""
new_role = fake_role(id=41, name="new")
self.bot.api_client.get.return_value = [fake_role()]
guild = self.get_guild(fake_role(), new_role)
actual_diff = await self.syncer._get_diff(guild)
expected_diff = ({_Role(**new_role)}, set(), set())
self.assertEqual(actual_diff, expected_diff)
async def test_diff_for_deleted_roles(self):
"""Only deleted roles should be added to the 'deleted' set of the diff."""
deleted_role = fake_role(id=61, name="deleted")
self.bot.api_client.get.return_value = [fake_role(), deleted_role]
guild = self.get_guild(fake_role())
actual_diff = await self.syncer._get_diff(guild)
expected_diff = (set(), set(), {_Role(**deleted_role)})
self.assertEqual(actual_diff, expected_diff)
async def test_diff_for_new_updated_and_deleted_roles(self):
"""When roles are added, updated, and removed, all of them are returned properly."""
new = fake_role(id=41, name="new")
updated = fake_role(id=71, name="updated")
deleted = fake_role(id=61, name="deleted")
self.bot.api_client.get.return_value = [
fake_role(),
fake_role(id=71, name="updated name"),
deleted,
]
guild = self.get_guild(fake_role(), new, updated)
actual_diff = await self.syncer._get_diff(guild)
expected_diff = ({_Role(**new)}, {_Role(**updated)}, {_Role(**deleted)})
self.assertEqual(actual_diff, expected_diff)
class RoleSyncerSyncTests(unittest.IsolatedAsyncioTestCase):
"""Tests for the API requests that sync roles."""
def setUp(self):
self.bot = helpers.MockBot()
self.syncer = RoleSyncer(self.bot)
async def test_sync_created_roles(self):
"""Only POST requests should be made with the correct payload."""
roles = [fake_role(id=111), fake_role(id=222)]
role_tuples = {_Role(**role) for role in roles}
diff = _Diff(role_tuples, set(), set())
await self.syncer._sync(diff)
calls = [mock.call("bot/roles", json=role) for role in roles]
self.bot.api_client.post.assert_has_calls(calls, any_order=True)
self.assertEqual(self.bot.api_client.post.call_count, len(roles))
self.bot.api_client.put.assert_not_called()
self.bot.api_client.delete.assert_not_called()
async def test_sync_updated_roles(self):
"""Only PUT requests should be made with the correct payload."""
roles = [fake_role(id=111), fake_role(id=222)]
role_tuples = {_Role(**role) for role in roles}
diff = _Diff(set(), role_tuples, set())
await self.syncer._sync(diff)
calls = [mock.call(f"bot/roles/{role["id"]}", json=role) for role in roles]
self.bot.api_client.put.assert_has_calls(calls, any_order=True)
self.assertEqual(self.bot.api_client.put.call_count, len(roles))
self.bot.api_client.post.assert_not_called()
self.bot.api_client.delete.assert_not_called()
async def test_sync_deleted_roles(self):
"""Only DELETE requests should be made with the correct payload."""
roles = [fake_role(id=111), fake_role(id=222)]
role_tuples = {_Role(**role) for role in roles}
diff = _Diff(set(), set(), role_tuples)
await self.syncer._sync(diff)
calls = [mock.call(f"bot/roles/{role["id"]}") for role in roles]
self.bot.api_client.delete.assert_has_calls(calls, any_order=True)
self.assertEqual(self.bot.api_client.delete.call_count, len(roles))
self.bot.api_client.post.assert_not_called()
self.bot.api_client.put.assert_not_called()
| import unittest
from unittest import mock
import discord
from bot.cogs.sync.syncers import RoleSyncer, _Diff, _Role
from tests import helpers
def fake_role(**kwargs):
"""Fixture to return a dictionary representing a role with default values set."""
kwargs.setdefault("id", 9)
kwargs.setdefault("name", "fake role")
kwargs.setdefault("colour", 7)
kwargs.setdefault("permissions", 0)
kwargs.setdefault("position", 55)
return kwargs
class RoleSyncerDiffTests(unittest.IsolatedAsyncioTestCase):
"""Tests for determining differences between roles in the DB and roles in the Guild cache."""
def setUp(self):
self.bot = helpers.MockBot()
self.syncer = RoleSyncer(self.bot)
@staticmethod
def get_guild(*roles):
"""Fixture to return a guild object with the given roles."""
guild = helpers.MockGuild()
guild.roles = []
for role in roles:
mock_role = helpers.MockRole(**role)
mock_role.colour = discord.Colour(role["colour"])
mock_role.permissions = discord.Permissions(role["permissions"])
guild.roles.append(mock_role)
return guild
async def test_empty_diff_for_identical_roles(self):
"""No differences should be found if the roles in the guild and DB are identical."""
self.bot.api_client.get.return_value = [fake_role()]
guild = self.get_guild(fake_role())
actual_diff = await self.syncer._get_diff(guild)
expected_diff = (set(), set(), set())
self.assertEqual(actual_diff, expected_diff)
async def test_diff_for_updated_roles(self):
"""Only updated roles should be added to the 'updated' set of the diff."""
updated_role = fake_role(id=41, name="new")
self.bot.api_client.get.return_value = [fake_role(id=41, name="old"), fake_role()]
guild = self.get_guild(updated_role, fake_role())
actual_diff = await self.syncer._get_diff(guild)
expected_diff = (set(), {_Role(**updated_role)}, set())
self.assertEqual(actual_diff, expected_diff)
async def test_diff_for_new_roles(self):
"""Only new roles should be added to the 'created' set of the diff."""
new_role = fake_role(id=41, name="new")
self.bot.api_client.get.return_value = [fake_role()]
guild = self.get_guild(fake_role(), new_role)
actual_diff = await self.syncer._get_diff(guild)
expected_diff = ({_Role(**new_role)}, set(), set())
self.assertEqual(actual_diff, expected_diff)
async def test_diff_for_deleted_roles(self):
"""Only deleted roles should be added to the 'deleted' set of the diff."""
deleted_role = fake_role(id=61, name="deleted")
self.bot.api_client.get.return_value = [fake_role(), deleted_role]
guild = self.get_guild(fake_role())
actual_diff = await self.syncer._get_diff(guild)
expected_diff = (set(), set(), {_Role(**deleted_role)})
self.assertEqual(actual_diff, expected_diff)
async def test_diff_for_new_updated_and_deleted_roles(self):
"""When roles are added, updated, and removed, all of them are returned properly."""
new = fake_role(id=41, name="new")
updated = fake_role(id=71, name="updated")
deleted = fake_role(id=61, name="deleted")
self.bot.api_client.get.return_value = [
fake_role(),
fake_role(id=71, name="updated name"),
deleted,
]
guild = self.get_guild(fake_role(), new, updated)
actual_diff = await self.syncer._get_diff(guild)
expected_diff = ({_Role(**new)}, {_Role(**updated)}, {_Role(**deleted)})
self.assertEqual(actual_diff, expected_diff)
class RoleSyncerSyncTests(unittest.IsolatedAsyncioTestCase):
"""Tests for the API requests that sync roles."""
def setUp(self):
self.bot = helpers.MockBot()
self.syncer = RoleSyncer(self.bot)
async def test_sync_created_roles(self):
"""Only POST requests should be made with the correct payload."""
roles = [fake_role(id=111), fake_role(id=222)]
role_tuples = {_Role(**role) for role in roles}
diff = _Diff(role_tuples, set(), set())
await self.syncer._sync(diff)
calls = [mock.call("bot/roles", json=role) for role in roles]
self.bot.api_client.post.assert_has_calls(calls, any_order=True)
self.assertEqual(self.bot.api_client.post.call_count, len(roles))
self.bot.api_client.put.assert_not_called()
self.bot.api_client.delete.assert_not_called()
async def test_sync_updated_roles(self):
"""Only PUT requests should be made with the correct payload."""
roles = [fake_role(id=111), fake_role(id=222)]
role_tuples = {_Role(**role) for role in roles}
diff = _Diff(set(), role_tuples, set())
await self.syncer._sync(diff)
calls = [mock.call(f"bot/roles/{role['id']}", json=role) for role in roles]
self.bot.api_client.put.assert_has_calls(calls, any_order=True)
self.assertEqual(self.bot.api_client.put.call_count, len(roles))
self.bot.api_client.post.assert_not_called()
self.bot.api_client.delete.assert_not_called()
async def test_sync_deleted_roles(self):
"""Only DELETE requests should be made with the correct payload."""
roles = [fake_role(id=111), fake_role(id=222)]
role_tuples = {_Role(**role) for role in roles}
diff = _Diff(set(), set(), role_tuples)
await self.syncer._sync(diff)
calls = [mock.call(f"bot/roles/{role['id']}") for role in roles]
self.bot.api_client.delete.assert_has_calls(calls, any_order=True)
self.assertEqual(self.bot.api_client.delete.call_count, len(roles))
self.bot.api_client.post.assert_not_called()
self.bot.api_client.put.assert_not_called()
|
# as due to their complexity multi-gpu tests could impact other tests, and to aid debug we have those in a separate module.
import logging
import os
import sys
from pathlib import Path
import pytest
import torch
from transformers.testing_utils import TestCasePlus, require_torch_multigpu
from .utils import load_json
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
CUDA_AVAILABLE = torch.cuda.is_available()
CHEAP_ARGS = {
"max_tokens_per_batch": None,
"supervise_forward": True,
"normalize_hidden": True,
"label_smoothing": 0.2,
"eval_max_gen_length": None,
"eval_beams": 1,
"val_metric": "loss",
"save_top_k": 1,
"adafactor": True,
"early_stopping_patience": 2,
"logger_name": "default",
"length_penalty": 0.5,
"cache_dir": "",
"task": "summarization",
"num_workers": 2,
"alpha_hid": 0,
"freeze_embeds": True,
"enc_only": False,
"tgt_suffix": "",
"resume_from_checkpoint": None,
"sortish_sampler": True,
"student_decoder_layers": 1,
"val_check_interval": 1.0,
"output_dir": "",
"fp16": False, # TODO(SS): set this to CUDA_AVAILABLE if ci installs apex or start using native amp
"no_teacher": False,
"fp16_opt_level": "O1",
"gpus": 1 if CUDA_AVAILABLE else 0,
"n_tpu_cores": 0,
"max_grad_norm": 1.0,
"do_train": True,
"do_predict": True,
"accumulate_grad_batches": 1,
"server_ip": "",
"server_port": "",
"seed": 42,
"model_name_or_path": "sshleifer/bart-tiny-random",
"config_name": "",
"tokenizer_name": "facebook/bart-large",
"do_lower_case": False,
"learning_rate": 0.3,
"lr_scheduler": "linear",
"weight_decay": 0.0,
"adam_epsilon": 1e-08,
"warmup_steps": 0,
"max_epochs": 1,
"train_batch_size": 2,
"eval_batch_size": 2,
"max_source_length": 12,
"max_target_length": 12,
"val_max_target_length": 12,
"test_max_target_length": 12,
"fast_dev_run": False,
"no_cache": False,
"n_train": -1,
"n_val": -1,
"n_test": -1,
"student_encoder_layers": 1,
"freeze_encoder": False,
"auto_scale_batch_size": False,
}
def _dump_articles(path: Path, articles: list):
content = "\n".join(articles)
Path(path).open("w").writelines(content)
ARTICLES = [" Sam ate lunch today.", "Sams lunch ingredients."]
SUMMARIES = ["A very interesting story about what I ate for lunch.", "Avocado, celery, turkey, coffee"]
T5_TINY = "patrickvonplaten/t5-tiny-random"
BART_TINY = "sshleifer/bart-tiny-random"
MBART_TINY = "sshleifer/tiny-mbart"
MARIAN_TINY = "sshleifer/tiny-marian-en-de"
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks
def make_test_data_dir(tmp_dir):
for split in ["train", "val", "test"]:
_dump_articles(os.path.join(tmp_dir, f"{split}.source"), ARTICLES)
_dump_articles(os.path.join(tmp_dir, f"{split}.target"), SUMMARIES)
return tmp_dir
# XXX: a candidate for testing_utils (python>=3.6)
# https://stackoverflow.com/a/59041913/9201239
import asyncio # noqa
class RunOutput:
def __init__(self, returncode, stdout, stderr):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
async def _read_stream(stream, callback):
while True:
line = await stream.readline()
if line:
callback(line)
else:
break
async def _stream_subprocess(cmd, env=None, stdin=None, timeout=None, quiet=False, echo=False) -> RunOutput:
if echo:
print(cmd)
p = await asyncio.create_subprocess_exec(
cmd[0],
*cmd[1:],
stdin=stdin,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=env,
)
out = []
err = []
def tee(line, sink, pipe, label=""):
line = line.decode("utf-8").rstrip()
sink.append(line)
if not quiet:
print(label, line, file=pipe)
await asyncio.wait(
[
_read_stream(p.stdout, lambda l: tee(l, out, sys.stdout)),
_read_stream(p.stderr, lambda l: tee(l, err, sys.stderr, label="stderr:")),
],
timeout=timeout,
)
# XXX: warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
#
# If it starts hanging, will need to switch s/wait/communicate/ - so perhaps for debug we will enable
# `wait` as it's easier to see in real time, but for normal runs use `communicate`
return RunOutput(await p.wait(), out, err)
def execute_async_std(cmd, env=None, stdin=None, timeout=None, quiet=False, echo=False) -> RunOutput:
loop = asyncio.get_event_loop()
result = loop.run_until_complete(
_stream_subprocess(cmd, env=env, stdin=stdin, timeout=timeout, quiet=quiet, echo=echo)
)
return result
class TestSummarizationDistillerMultiGPU(TestCasePlus):
@classmethod
def setUpClass(cls):
logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks
return cls
@require_torch_multigpu
def test_multigpu(self):
updates = dict(
no_teacher=True,
freeze_encoder=True,
gpus=2,
overwrite_output_dir=True,
sortish_sampler=True,
)
self._test_distiller_cli_fork(updates, check_contents=False)
def _test_distiller_cli_fork(self, updates, check_contents=True):
default_updates = dict(
label_smoothing=0.0,
early_stopping_patience=-1,
train_batch_size=1,
eval_batch_size=2,
max_epochs=2,
alpha_mlm=0.2,
alpha_ce=0.8,
do_predict=True,
model_name_or_path="sshleifer/tinier_bart",
teacher=CHEAP_ARGS["model_name_or_path"],
val_check_interval=0.5,
)
default_updates.update(updates)
args_d: dict = CHEAP_ARGS.copy()
tmp_dir = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())
output_dir = self.get_auto_remove_tmp_dir()
args_d.update(data_dir=tmp_dir, output_dir=output_dir, **default_updates)
def convert(k, v):
if k in ["tgt_suffix", "server_ip", "server_port", "out", "n_tpu_cores"]:
return ""
if v is False or v is None:
return ""
if v is True: # or len(str(v))==0:
return f"--{k}"
return f"--{k}={v}"
cli_args = [x for x in (convert(k, v) for k, v in args_d.items()) if len(x)]
cmd = [sys.executable, "./examples/seq2seq/distillation.py"] + cli_args
print("\nRunning: ", " ".join(cmd))
path = Path(__file__).resolve()
examples_path = path.parents[1]
src_path = f"{path.parents[2]}/src"
env = os.environ.copy()
env["PYTHONPATH"] = f"{examples_path}:{src_path}:{env.get("PYTHONPATH", "")}"
result = execute_async_std(cmd, env=env, stdin=None, timeout=180, quiet=False, echo=False)
assert result.stdout, "produced no output"
if result.returncode > 0:
pytest.fail(f"failed with returncode {result.returncode}")
contents = os.listdir(output_dir)
contents = {os.path.basename(p) for p in contents}
ckpt_files = [p for p in contents if p.endswith("ckpt")]
assert len(ckpt_files) > 0
self.assertIn("test_generations.txt", contents)
self.assertIn("test_results.txt", contents)
# get the following from the module, (we don't have access to `model` here)
metrics_save_path = os.path.join(output_dir, "metrics.json")
val_metric = "rouge2"
metrics = load_json(metrics_save_path)
# {'test': [{'test_avg_loss': 10.63731575012207, 'test_avg_rouge1': 0.0, 'test_avg_rouge2': 0.0, 'test_avg_rougeL': 0.0, 'test_avg_gen_time': 0.1822289228439331, 'test_avg_gen_len': 142.0, 'step_count': 1}]}
print(metrics)
last_step_stats = metrics["val"][-1]
self.assertGreaterEqual(last_step_stats["val_avg_gen_time"], 0.01)
self.assertGreaterEqual(1.0, last_step_stats["val_avg_gen_time"])
self.assertIsInstance(last_step_stats[f"val_avg_{val_metric}"], float)
self.assertEqual(len(metrics["test"]), 1)
desired_n_evals = int(args_d["max_epochs"] * (1 / args_d["val_check_interval"]) / 2 + 1)
self.assertEqual(len(metrics["val"]), desired_n_evals)
| # as due to their complexity multi-gpu tests could impact other tests, and to aid debug we have those in a separate module.
import logging
import os
import sys
from pathlib import Path
import pytest
import torch
from transformers.testing_utils import TestCasePlus, require_torch_multigpu
from .utils import load_json
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
CUDA_AVAILABLE = torch.cuda.is_available()
CHEAP_ARGS = {
"max_tokens_per_batch": None,
"supervise_forward": True,
"normalize_hidden": True,
"label_smoothing": 0.2,
"eval_max_gen_length": None,
"eval_beams": 1,
"val_metric": "loss",
"save_top_k": 1,
"adafactor": True,
"early_stopping_patience": 2,
"logger_name": "default",
"length_penalty": 0.5,
"cache_dir": "",
"task": "summarization",
"num_workers": 2,
"alpha_hid": 0,
"freeze_embeds": True,
"enc_only": False,
"tgt_suffix": "",
"resume_from_checkpoint": None,
"sortish_sampler": True,
"student_decoder_layers": 1,
"val_check_interval": 1.0,
"output_dir": "",
"fp16": False, # TODO(SS): set this to CUDA_AVAILABLE if ci installs apex or start using native amp
"no_teacher": False,
"fp16_opt_level": "O1",
"gpus": 1 if CUDA_AVAILABLE else 0,
"n_tpu_cores": 0,
"max_grad_norm": 1.0,
"do_train": True,
"do_predict": True,
"accumulate_grad_batches": 1,
"server_ip": "",
"server_port": "",
"seed": 42,
"model_name_or_path": "sshleifer/bart-tiny-random",
"config_name": "",
"tokenizer_name": "facebook/bart-large",
"do_lower_case": False,
"learning_rate": 0.3,
"lr_scheduler": "linear",
"weight_decay": 0.0,
"adam_epsilon": 1e-08,
"warmup_steps": 0,
"max_epochs": 1,
"train_batch_size": 2,
"eval_batch_size": 2,
"max_source_length": 12,
"max_target_length": 12,
"val_max_target_length": 12,
"test_max_target_length": 12,
"fast_dev_run": False,
"no_cache": False,
"n_train": -1,
"n_val": -1,
"n_test": -1,
"student_encoder_layers": 1,
"freeze_encoder": False,
"auto_scale_batch_size": False,
}
def _dump_articles(path: Path, articles: list):
content = "\n".join(articles)
Path(path).open("w").writelines(content)
ARTICLES = [" Sam ate lunch today.", "Sams lunch ingredients."]
SUMMARIES = ["A very interesting story about what I ate for lunch.", "Avocado, celery, turkey, coffee"]
T5_TINY = "patrickvonplaten/t5-tiny-random"
BART_TINY = "sshleifer/bart-tiny-random"
MBART_TINY = "sshleifer/tiny-mbart"
MARIAN_TINY = "sshleifer/tiny-marian-en-de"
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks
def make_test_data_dir(tmp_dir):
for split in ["train", "val", "test"]:
_dump_articles(os.path.join(tmp_dir, f"{split}.source"), ARTICLES)
_dump_articles(os.path.join(tmp_dir, f"{split}.target"), SUMMARIES)
return tmp_dir
# XXX: a candidate for testing_utils (python>=3.6)
# https://stackoverflow.com/a/59041913/9201239
import asyncio # noqa
class RunOutput:
def __init__(self, returncode, stdout, stderr):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
async def _read_stream(stream, callback):
while True:
line = await stream.readline()
if line:
callback(line)
else:
break
async def _stream_subprocess(cmd, env=None, stdin=None, timeout=None, quiet=False, echo=False) -> RunOutput:
if echo:
print(cmd)
p = await asyncio.create_subprocess_exec(
cmd[0],
*cmd[1:],
stdin=stdin,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=env,
)
out = []
err = []
def tee(line, sink, pipe, label=""):
line = line.decode("utf-8").rstrip()
sink.append(line)
if not quiet:
print(label, line, file=pipe)
await asyncio.wait(
[
_read_stream(p.stdout, lambda l: tee(l, out, sys.stdout)),
_read_stream(p.stderr, lambda l: tee(l, err, sys.stderr, label="stderr:")),
],
timeout=timeout,
)
# XXX: warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
#
# If it starts hanging, will need to switch s/wait/communicate/ - so perhaps for debug we will enable
# `wait` as it's easier to see in real time, but for normal runs use `communicate`
return RunOutput(await p.wait(), out, err)
def execute_async_std(cmd, env=None, stdin=None, timeout=None, quiet=False, echo=False) -> RunOutput:
loop = asyncio.get_event_loop()
result = loop.run_until_complete(
_stream_subprocess(cmd, env=env, stdin=stdin, timeout=timeout, quiet=quiet, echo=echo)
)
return result
class TestSummarizationDistillerMultiGPU(TestCasePlus):
@classmethod
def setUpClass(cls):
logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks
return cls
@require_torch_multigpu
def test_multigpu(self):
updates = dict(
no_teacher=True,
freeze_encoder=True,
gpus=2,
overwrite_output_dir=True,
sortish_sampler=True,
)
self._test_distiller_cli_fork(updates, check_contents=False)
def _test_distiller_cli_fork(self, updates, check_contents=True):
default_updates = dict(
label_smoothing=0.0,
early_stopping_patience=-1,
train_batch_size=1,
eval_batch_size=2,
max_epochs=2,
alpha_mlm=0.2,
alpha_ce=0.8,
do_predict=True,
model_name_or_path="sshleifer/tinier_bart",
teacher=CHEAP_ARGS["model_name_or_path"],
val_check_interval=0.5,
)
default_updates.update(updates)
args_d: dict = CHEAP_ARGS.copy()
tmp_dir = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())
output_dir = self.get_auto_remove_tmp_dir()
args_d.update(data_dir=tmp_dir, output_dir=output_dir, **default_updates)
def convert(k, v):
if k in ["tgt_suffix", "server_ip", "server_port", "out", "n_tpu_cores"]:
return ""
if v is False or v is None:
return ""
if v is True: # or len(str(v))==0:
return f"--{k}"
return f"--{k}={v}"
cli_args = [x for x in (convert(k, v) for k, v in args_d.items()) if len(x)]
cmd = [sys.executable, "./examples/seq2seq/distillation.py"] + cli_args
print("\nRunning: ", " ".join(cmd))
path = Path(__file__).resolve()
examples_path = path.parents[1]
src_path = f"{path.parents[2]}/src"
env = os.environ.copy()
env["PYTHONPATH"] = f"{examples_path}:{src_path}:{env.get('PYTHONPATH', '')}"
result = execute_async_std(cmd, env=env, stdin=None, timeout=180, quiet=False, echo=False)
assert result.stdout, "produced no output"
if result.returncode > 0:
pytest.fail(f"failed with returncode {result.returncode}")
contents = os.listdir(output_dir)
contents = {os.path.basename(p) for p in contents}
ckpt_files = [p for p in contents if p.endswith("ckpt")]
assert len(ckpt_files) > 0
self.assertIn("test_generations.txt", contents)
self.assertIn("test_results.txt", contents)
# get the following from the module, (we don't have access to `model` here)
metrics_save_path = os.path.join(output_dir, "metrics.json")
val_metric = "rouge2"
metrics = load_json(metrics_save_path)
# {'test': [{'test_avg_loss': 10.63731575012207, 'test_avg_rouge1': 0.0, 'test_avg_rouge2': 0.0, 'test_avg_rougeL': 0.0, 'test_avg_gen_time': 0.1822289228439331, 'test_avg_gen_len': 142.0, 'step_count': 1}]}
print(metrics)
last_step_stats = metrics["val"][-1]
self.assertGreaterEqual(last_step_stats["val_avg_gen_time"], 0.01)
self.assertGreaterEqual(1.0, last_step_stats["val_avg_gen_time"])
self.assertIsInstance(last_step_stats[f"val_avg_{val_metric}"], float)
self.assertEqual(len(metrics["test"]), 1)
desired_n_evals = int(args_d["max_epochs"] * (1 / args_d["val_check_interval"]) / 2 + 1)
self.assertEqual(len(metrics["val"]), desired_n_evals)
|
"""
Arquivo de definição da entidade matches do banco de dados.
"""
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from App.database_models.users import Users
from api_utils.json_helper import build_json_response
Base = declarative_base()
class Matches(Base):
"""
Definição da entidade matches do banco de dados.
"""
__tablename__ = 'matches'
id = Column(Integer, primary_key=True)
time = Column(Integer, nullable=False)
total_beer = Column(Integer)
total_poison = Column(Integer)
score = Column(Integer)
user_id = Column(Integer, ForeignKey(Users.id))
def __repr__(self):
return build_json_response(time=self.time,
total_beer=self.total_beer,
total_poison=self.total_poison,
score=self.score,
user_id=self.user_id)
def __str__(self):
return f"""{{ "time": {self.time}, "total_beer": {self.total_beer},
"total_poison": {self.total_poison}, "score": {self.score},
"user_id": {self.user_id} }}"""
| """
Arquivo de definição da entidade matches do banco de dados.
"""
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from App.database_models.users import Users
from api_utils.json_helper import build_json_response
Base = declarative_base()
class Matches(Base):
"""
Definição da entidade matches do banco de dados.
"""
__tablename__ = 'matches'
id = Column(Integer, primary_key=True)
time = Column(Integer, nullable=False)
total_beer = Column(Integer)
total_poison = Column(Integer)
score = Column(Integer)
user_id = Column(Integer, ForeignKey(Users.id))
def __repr__(self):
return build_json_response(time=self.time,
total_beer=self.total_beer,
total_poison=self.total_poison,
score=self.score,
user_id=self.user_id)
def __str__(self):
return f"""{{ "time": {self.time}, "total_beer": {self.total_beer},
"total_poison": {self.total_poison}, "score": {self.score},
"user_id": {self.user_id} }}"""
|
import base64
import json
import re
import requests
from bs4 import BeautifulSoup
from requests import request
URL_API = '/v2/api'
URL_LOGIN = f'{URL_API}/auth/login'
URL_DASHBOARD = f'{URL_API}/student/dashboard/dashboard'
URL_CALENDAR = f'{URL_API}/calendar/student'
URL_GRADES = f'{URL_API}/student/all_subjects'
URL_PROFILE = f'{URL_API}/profile/get'
URL_MESSAGES = f'{URL_API}/message/getMyMessages'
URL_ABSENCES = f'{URL_API}/student/dashboard/absences'
URL_NOTIFICATIONS = f'{URL_API}/notification/unread'
URL_COURSECONTENT = f'{URL_API}/courseContent/getCourse'
URL_LOG = f'{URL_API}/lesson/student'
URL_RECIPIENTS = f'{URL_API}/message/getRecipients'
URL_UPDATE_ENTRY = f'{URL_API}/submission/updateEntry'
URL_UPLOAD = f'{URL_API}/file/upload'
URL_DELETE_ENTRY = f'{URL_API}/submission/deleteEntry'
URL_CHECK = f'{URL_API}/student/dashboard/toggle_reminder'
URL_LESSON_DETAIL = f'{URL_API}/lesson/get'
URL_GRADE_DETAIL = f'{URL_API}/student/subject_detail'
URL_GET_COURSE = f'{URL_API}/courseContent/getCourse'
URL_CHANGE_LANG = f'{URL_API}/profile/updateLanguage'
URL_NOTIFICATIONS_SETTINGS = f'{URL_API}/profile/updateNotificationSettings'
URL_CHANGE_PASSWORD = f'{URL_API}/auth/setNewPassword'
URL_CHANGE_EMIL = f'{URL_API}/profile/updateProfile'
URL_RECIPIENT_DETAILS = f'{URL_API}/message/getRecipientsDetails'
URL_SEND_MESSAGE = f'{URL_API}/message/sendMessage'
URL_SAVE_REMINDER = f'{URL_API}/student/dashboard/save_reminder'
URL_DELETE_REMIDER = f'{URL_API}/student/dashboard/delete_reminder'
URL_EXTEND_SESSION = f'{URL_API}/auth/extendSession'
URL_GET_GRADE = f'{URL_API}/student/entry/getGrade'
URL_GET_TYPES = f'{URL_API}/grade/getTypes'
URL_CHANGE_SEMESTER = '/v2/?semesterWechsel='
URL_CERTIFICATE = '/v2/student/certificate'
URL_HOMEWORK_OVERVIEW = '/v2/vorstand/homework&klasse'
class user():
def __init__(self, username_: str, password_: str, domain_: str):
self.cache_dump = {}
self.protocol = 'https://'
self.domain = domain_
self.username = username_
self.password = password_
self.cookies = None
def reqst(self, url, method='POST', data=None, json=None, cache=None, get_cache=None, **kwargs):
if get_cache is not None and (temp := self.cache_dump.get(get_cache, False)):
result = temp
print(self.cache_dump)
else:
result = request(method, self.protocol + self.domain + url, json=json, data=data, cookies=self.cookies,
allow_redirects=True, **kwargs)
if result.text.count('window.location = "https://rgtfo-me.digitalesregister.it/v2/login";'):
self.request_cookies()
return self.reqst(url, method=method, data=data, json=json, cache=cache, get_cache=get_cache, **kwargs)
try:
result.json()
except ValueError:
pass
else:
if isinstance(result.json(), dict):
if error := result.json().get('error', False):
raise Exception(f"{error}: {result.json().get("error", False)}")
if cache is not None:
self.cache_dump[cache] = result
return result
def request_cookies(self):
class LoginError(Exception):
pass
login_payload = dict(username=self.username, password=self.password)
login = requests.get(self.protocol + self.domain + URL_LOGIN, json=login_payload, allow_redirects=True)
if 'error' in (data := login.json()).keys() and data['error'] is not None:
raise LoginError(f"{data["error"]}: {data["message"]}")
self.cookies = login.cookies
def request_dashboard(self, viewFuture=True, **kwargs):
return self.reqst(URL_DASHBOARD, json={"viewFuture": viewFuture}, **kwargs)
def request_notifications(self, **kwargs):
return self.reqst(URL_NOTIFICATIONS, **kwargs)
def request_profile(self, **kwargs):
return self.reqst(URL_PROFILE, **kwargs)
def request_grades(self, **kwargs):
return self.reqst(URL_GRADES, **kwargs)
def request_absences(self, **kwargs):
return self.reqst(URL_ABSENCES, **kwargs)
def request_log(self, **kwargs):
return self.reqst(URL_LOG, **kwargs)
def request_week_calendar(self, date, **kwargs):
return self.reqst(URL_CALENDAR, json={"startDate": date}, **kwargs)
def request_messages(self, **kwargs):
return self.reqst(URL_MESSAGES, **kwargs)
def request_recipients(self, filter, **kwargs):
return self.reqst(URL_RECIPIENTS, json={"filter": filter}, **kwargs)
def request_recipients_details(self, recipients, **kwargs):
return self.reqst(URL_RECIPIENT_DETAILS, json={"recipientGroups": recipients}, **kwargs)
def request_entry_deletion(self, submission_item_id, category_id, **kwargs):
return self.reqst(URL_DELETE_ENTRY, json={"submissionItemId": submission_item_id, "categoryId": category_id}, **kwargs)
def request_entry_check(self, id, value, **kwargs):
return self.reqst(URL_CHECK, json={"id": id, "type": "gradeGroup", "value": value}, **kwargs)
def request_hour_details(self, date, hour, to_hour, class_id, **kwargs):
return self.reqst(URL_LESSON_DETAIL, json={"date": date, "hour": str(hour), "toHour": to_hour, "classId": class_id},
**kwargs)
def request_subject_detail(self, subject_id, student_id, **kwargs):
return self.reqst(URL_GRADE_DETAIL, json={"subjectId": subject_id, "studentId": student_id}, **kwargs)
def request_course(self, class_id, subject_id, **kwargs):
return self.reqst(URL_GET_COURSE, json={"classId": class_id, "subjectId": subject_id}, **kwargs)
def request_language_switch(self, lang, **kwargs):
return self.reqst(URL_CHANGE_LANG, json={"language": lang}, **kwargs)
def request_email_notifications_change(self, bool, **kwargs):
return self.reqst(URL_NOTIFICATIONS_SETTINGS, json={"notificationsEnabled": bool}, **kwargs)
def request_grade(self, gradeId, **kwargs):
return self.reqst(URL_GET_GRADE, json={"gradeId": gradeId}, **kwargs)
def request_types(self, classId, subjectId, **kwargs):
return self.reqst(URL_GET_TYPES, payload={"classId": classId, "subjectId": subjectId}, **kwargs)
def request_password_change(self, username, old_password, new_password, **kwargs):
return self.reqst(URL_CHANGE_PASSWORD,
json={"username": username, "oldPassword": old_password, "newPassword": new_password}, **kwargs)
def request_email_change(self, new_email, password, **kwargs):
return self.reqst(URL_CHANGE_EMIL, json={"email": new_email, "password": password}, **kwargs)
def request_reminder_save(self, date, text, **kwargs):
return self.reqst(URL_SAVE_REMINDER, json={"date": date, "text": text}, **kwargs)
def request_reminder_deletion(self, id, **kwargs):
return self.reqst(URL_DELETE_REMIDER, json={"id": id}, **kwargs)
def request_semester_change(self, sem, **kwargs):
return self.reqst("https://rgtfo-me.digitalesregister.it/v2/", params=('semesterWechsel', str(sem)), **kwargs)
def request_base_html(self, **kwargs):
return self.reqst("/v2/", **kwargs)
def parse_certificate(self, ):
arr = BeautifulSoup(self.request_base_html(cache='html', get_cache='html'), 'html.parser').find_all("td", {
"class": "padding-cell"})
dic = {}
for i in range(0, len(arr), 2):
dic[arr[i].text] = arr[i + 1].text
return dic
def parse_teachers(self, ):
return json.loads(
re.search("(?<=teachers = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_teachers_object(self, ):
return json.loads(
re.search("(?<=teachersObject = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_lesson_types(self, ):
return json.loads(
re.search("(?<=lessontypes = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_rooms(self, ):
return json.loads(
re.search("(?<=rooms = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_subjects(self, ):
return json.loads(
re.search("(?<=subjects = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_classes(self, ):
return json.loads(
re.search("(?<=classes = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_grade_types(self, ):
return json.loads(
re.search("(?<=gradeTypes = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_observation_types(self, ):
return json.loads(
re.search("(?<=observationTypes = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_calendar_time_grid_objects_without_gaps(self, ):
return json.loads(re.search("(?<=calendarTimeGridObjectsWithoutGaps = )(.*)(?=;)",
self.request_base_html(cache='html', get_cache='html').text).group())
def parse_student_absence_time_grid_objects(self, ):
return json.loads(re.search("(?<=studentAbsenceTimeGridObjects = )(.*)(?=;)",
self.request_base_html(cache='html', get_cache='html').text).group())
def parse_new_lesson_time_grid_array(self, ):
return json.loads(re.search("(?<=newLessonTimeGridArray = )(.*)(?=;)",
self.request_base_html(cache='html', get_cache='html').text).group())
# message sending has been removed
# def send_message(sendable):
# return self.reqst(URL_SEND_MESSAGE, payload=sendable))
# TODO: homework overview
# TODO: file uploader
# TODO: entry updater
| import base64
import json
import re
import requests
from bs4 import BeautifulSoup
from requests import request
URL_API = '/v2/api'
URL_LOGIN = f'{URL_API}/auth/login'
URL_DASHBOARD = f'{URL_API}/student/dashboard/dashboard'
URL_CALENDAR = f'{URL_API}/calendar/student'
URL_GRADES = f'{URL_API}/student/all_subjects'
URL_PROFILE = f'{URL_API}/profile/get'
URL_MESSAGES = f'{URL_API}/message/getMyMessages'
URL_ABSENCES = f'{URL_API}/student/dashboard/absences'
URL_NOTIFICATIONS = f'{URL_API}/notification/unread'
URL_COURSECONTENT = f'{URL_API}/courseContent/getCourse'
URL_LOG = f'{URL_API}/lesson/student'
URL_RECIPIENTS = f'{URL_API}/message/getRecipients'
URL_UPDATE_ENTRY = f'{URL_API}/submission/updateEntry'
URL_UPLOAD = f'{URL_API}/file/upload'
URL_DELETE_ENTRY = f'{URL_API}/submission/deleteEntry'
URL_CHECK = f'{URL_API}/student/dashboard/toggle_reminder'
URL_LESSON_DETAIL = f'{URL_API}/lesson/get'
URL_GRADE_DETAIL = f'{URL_API}/student/subject_detail'
URL_GET_COURSE = f'{URL_API}/courseContent/getCourse'
URL_CHANGE_LANG = f'{URL_API}/profile/updateLanguage'
URL_NOTIFICATIONS_SETTINGS = f'{URL_API}/profile/updateNotificationSettings'
URL_CHANGE_PASSWORD = f'{URL_API}/auth/setNewPassword'
URL_CHANGE_EMIL = f'{URL_API}/profile/updateProfile'
URL_RECIPIENT_DETAILS = f'{URL_API}/message/getRecipientsDetails'
URL_SEND_MESSAGE = f'{URL_API}/message/sendMessage'
URL_SAVE_REMINDER = f'{URL_API}/student/dashboard/save_reminder'
URL_DELETE_REMIDER = f'{URL_API}/student/dashboard/delete_reminder'
URL_EXTEND_SESSION = f'{URL_API}/auth/extendSession'
URL_GET_GRADE = f'{URL_API}/student/entry/getGrade'
URL_GET_TYPES = f'{URL_API}/grade/getTypes'
URL_CHANGE_SEMESTER = '/v2/?semesterWechsel='
URL_CERTIFICATE = '/v2/student/certificate'
URL_HOMEWORK_OVERVIEW = '/v2/vorstand/homework&klasse'
class user():
def __init__(self, username_: str, password_: str, domain_: str):
self.cache_dump = {}
self.protocol = 'https://'
self.domain = domain_
self.username = username_
self.password = password_
self.cookies = None
def reqst(self, url, method='POST', data=None, json=None, cache=None, get_cache=None, **kwargs):
if get_cache is not None and (temp := self.cache_dump.get(get_cache, False)):
result = temp
print(self.cache_dump)
else:
result = request(method, self.protocol + self.domain + url, json=json, data=data, cookies=self.cookies,
allow_redirects=True, **kwargs)
if result.text.count('window.location = "https://rgtfo-me.digitalesregister.it/v2/login";'):
self.request_cookies()
return self.reqst(url, method=method, data=data, json=json, cache=cache, get_cache=get_cache, **kwargs)
try:
result.json()
except ValueError:
pass
else:
if isinstance(result.json(), dict):
if error := result.json().get('error', False):
raise Exception(f"{error}: {result.json().get('error', False)}")
if cache is not None:
self.cache_dump[cache] = result
return result
def request_cookies(self):
class LoginError(Exception):
pass
login_payload = dict(username=self.username, password=self.password)
login = requests.get(self.protocol + self.domain + URL_LOGIN, json=login_payload, allow_redirects=True)
if 'error' in (data := login.json()).keys() and data['error'] is not None:
raise LoginError(f"{data['error']}: {data['message']}")
self.cookies = login.cookies
def request_dashboard(self, viewFuture=True, **kwargs):
return self.reqst(URL_DASHBOARD, json={"viewFuture": viewFuture}, **kwargs)
def request_notifications(self, **kwargs):
return self.reqst(URL_NOTIFICATIONS, **kwargs)
def request_profile(self, **kwargs):
return self.reqst(URL_PROFILE, **kwargs)
def request_grades(self, **kwargs):
return self.reqst(URL_GRADES, **kwargs)
def request_absences(self, **kwargs):
return self.reqst(URL_ABSENCES, **kwargs)
def request_log(self, **kwargs):
return self.reqst(URL_LOG, **kwargs)
def request_week_calendar(self, date, **kwargs):
return self.reqst(URL_CALENDAR, json={"startDate": date}, **kwargs)
def request_messages(self, **kwargs):
return self.reqst(URL_MESSAGES, **kwargs)
def request_recipients(self, filter, **kwargs):
return self.reqst(URL_RECIPIENTS, json={"filter": filter}, **kwargs)
def request_recipients_details(self, recipients, **kwargs):
return self.reqst(URL_RECIPIENT_DETAILS, json={"recipientGroups": recipients}, **kwargs)
def request_entry_deletion(self, submission_item_id, category_id, **kwargs):
return self.reqst(URL_DELETE_ENTRY, json={"submissionItemId": submission_item_id, "categoryId": category_id}, **kwargs)
def request_entry_check(self, id, value, **kwargs):
return self.reqst(URL_CHECK, json={"id": id, "type": "gradeGroup", "value": value}, **kwargs)
def request_hour_details(self, date, hour, to_hour, class_id, **kwargs):
return self.reqst(URL_LESSON_DETAIL, json={"date": date, "hour": str(hour), "toHour": to_hour, "classId": class_id},
**kwargs)
def request_subject_detail(self, subject_id, student_id, **kwargs):
return self.reqst(URL_GRADE_DETAIL, json={"subjectId": subject_id, "studentId": student_id}, **kwargs)
def request_course(self, class_id, subject_id, **kwargs):
return self.reqst(URL_GET_COURSE, json={"classId": class_id, "subjectId": subject_id}, **kwargs)
def request_language_switch(self, lang, **kwargs):
return self.reqst(URL_CHANGE_LANG, json={"language": lang}, **kwargs)
def request_email_notifications_change(self, bool, **kwargs):
return self.reqst(URL_NOTIFICATIONS_SETTINGS, json={"notificationsEnabled": bool}, **kwargs)
def request_grade(self, gradeId, **kwargs):
return self.reqst(URL_GET_GRADE, json={"gradeId": gradeId}, **kwargs)
def request_types(self, classId, subjectId, **kwargs):
return self.reqst(URL_GET_TYPES, payload={"classId": classId, "subjectId": subjectId}, **kwargs)
def request_password_change(self, username, old_password, new_password, **kwargs):
return self.reqst(URL_CHANGE_PASSWORD,
json={"username": username, "oldPassword": old_password, "newPassword": new_password}, **kwargs)
def request_email_change(self, new_email, password, **kwargs):
return self.reqst(URL_CHANGE_EMIL, json={"email": new_email, "password": password}, **kwargs)
def request_reminder_save(self, date, text, **kwargs):
return self.reqst(URL_SAVE_REMINDER, json={"date": date, "text": text}, **kwargs)
def request_reminder_deletion(self, id, **kwargs):
return self.reqst(URL_DELETE_REMIDER, json={"id": id}, **kwargs)
def request_semester_change(self, sem, **kwargs):
return self.reqst("https://rgtfo-me.digitalesregister.it/v2/", params=('semesterWechsel', str(sem)), **kwargs)
def request_base_html(self, **kwargs):
return self.reqst("/v2/", **kwargs)
def parse_certificate(self, ):
arr = BeautifulSoup(self.request_base_html(cache='html', get_cache='html'), 'html.parser').find_all("td", {
"class": "padding-cell"})
dic = {}
for i in range(0, len(arr), 2):
dic[arr[i].text] = arr[i + 1].text
return dic
def parse_teachers(self, ):
return json.loads(
re.search("(?<=teachers = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_teachers_object(self, ):
return json.loads(
re.search("(?<=teachersObject = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_lesson_types(self, ):
return json.loads(
re.search("(?<=lessontypes = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_rooms(self, ):
return json.loads(
re.search("(?<=rooms = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_subjects(self, ):
return json.loads(
re.search("(?<=subjects = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_classes(self, ):
return json.loads(
re.search("(?<=classes = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_grade_types(self, ):
return json.loads(
re.search("(?<=gradeTypes = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_observation_types(self, ):
return json.loads(
re.search("(?<=observationTypes = )(.*)(?=;)", self.request_base_html(cache='html', get_cache='html').text).group())
def parse_calendar_time_grid_objects_without_gaps(self, ):
return json.loads(re.search("(?<=calendarTimeGridObjectsWithoutGaps = )(.*)(?=;)",
self.request_base_html(cache='html', get_cache='html').text).group())
def parse_student_absence_time_grid_objects(self, ):
return json.loads(re.search("(?<=studentAbsenceTimeGridObjects = )(.*)(?=;)",
self.request_base_html(cache='html', get_cache='html').text).group())
def parse_new_lesson_time_grid_array(self, ):
return json.loads(re.search("(?<=newLessonTimeGridArray = )(.*)(?=;)",
self.request_base_html(cache='html', get_cache='html').text).group())
# message sending has been removed
# def send_message(sendable):
# return self.reqst(URL_SEND_MESSAGE, payload=sendable))
# TODO: homework overview
# TODO: file uploader
# TODO: entry updater
|
"""
Carlos Barona
Agile UNO Module 5
Strings and Lists
"""
from sys import exit # Import 'exit' from the 'sys' library
import sys # Import the 'sys' library
import requests # Import the 'requests' library
site_data = {} # Setting an empty dictionary
with open("sites.csv", "r") as infile: # Using a context manager to open 'sites.csv' file as 'infile'
data = infile.read() # Setting 'data' variable to 'infile' with a .read() method
sites = data.split(",") # Setting 'sites' variable to 'data' with a .split() method
for site in sites: # For loop that will iterate through 'sites'
site_data[site] = requests.get(site) # Setting 'site_data[site]' to the information received from the 'requests' module using the .get() method
for key, value in site_data.items(): # For loop that will iterate through both the 'key' and 'value' in 'site_data' using the .items() method
print(f"\n{key} : {value}\n") # Print out the formated strings of the iterated 'key', 'value' pairs
#1
###########################################
"""
Using string slicing, print out each URL extention below.
Example:
edu
com
edu
"""
extentions = [data[16:19], data[39:42], data[59:63]] # Variable set to a list of three different string slices
for i in extentions: # For loop that will iterate through 'extentions'
print(i + "\n") # Print out the iterations for 'exentions' and adding a newline inbetween each one
#2
###########################################
"""
Print out any sites that end with .com below.
"""
for key in sites: # For loop that will iterate through 'sites'
if '.com' in key: # Conditional that will trigger if '.com' is in a 'key'
print(key + "\n") # Print out any 'key' with '.com' and add a newline
#3
###########################################
"""
Convert all site names to Upper case and print out each below.
"""
for key in sites: # For loop that will iterate through the 'key's in 'sites'
print(key.upper() + "\n") # Print out all of the 'key's in upper case letters and adding a new line
#4
###########################################
"""
Using the list of sites, add a new site to it,
using the input() method to get the name of the site from the user
then reverse the order of the list and print it out.
"""
add = input("Please enter a site: ") # Setting the 'add' variable to the input of the user
if add not in sites: # Conditional that will trigger if 'add' variable's user input is not in 'sites'
sites.append(add) # 'Sites' will be appended with the .append() method adding the user input
print(sites[::-1]) # Print out the 'sites' in reverse order
#5
###########################################
"""
Print out the 'Server' of the responce of the URL request of the items from your list
look here for more information:
https://requests.readthedocs.io/en/master/user/quickstart/#responce-content
example:
print(f"{mySiteData.headers.get("Server")}\n")
"""
for i in sites: # For loop that will iterate through 'sites'
r = requests.get(i) # Setting variable 'r' to the information received through the 'requests' module using the .get() method
print("######################################################\n") # Print out a string of '#'s to help delineate between requests
print(r.headers) # Print out the information in the 'r' variable using the .headers() method
#6
###########################################
"""
Exit the program using the sys module's exit function we
imported at the beginning of the code
"""
sys.exit() # An exit function imported from 'sys' library | """
Carlos Barona
Agile UNO Module 5
Strings and Lists
"""
from sys import exit # Import 'exit' from the 'sys' library
import sys # Import the 'sys' library
import requests # Import the 'requests' library
site_data = {} # Setting an empty dictionary
with open("sites.csv", "r") as infile: # Using a context manager to open 'sites.csv' file as 'infile'
data = infile.read() # Setting 'data' variable to 'infile' with a .read() method
sites = data.split(",") # Setting 'sites' variable to 'data' with a .split() method
for site in sites: # For loop that will iterate through 'sites'
site_data[site] = requests.get(site) # Setting 'site_data[site]' to the information received from the 'requests' module using the .get() method
for key, value in site_data.items(): # For loop that will iterate through both the 'key' and 'value' in 'site_data' using the .items() method
print(f"\n{key} : {value}\n") # Print out the formated strings of the iterated 'key', 'value' pairs
#1
###########################################
"""
Using string slicing, print out each URL extention below.
Example:
edu
com
edu
"""
extentions = [data[16:19], data[39:42], data[59:63]] # Variable set to a list of three different string slices
for i in extentions: # For loop that will iterate through 'extentions'
print(i + "\n") # Print out the iterations for 'exentions' and adding a newline inbetween each one
#2
###########################################
"""
Print out any sites that end with .com below.
"""
for key in sites: # For loop that will iterate through 'sites'
if '.com' in key: # Conditional that will trigger if '.com' is in a 'key'
print(key + "\n") # Print out any 'key' with '.com' and add a newline
#3
###########################################
"""
Convert all site names to Upper case and print out each below.
"""
for key in sites: # For loop that will iterate through the 'key's in 'sites'
print(key.upper() + "\n") # Print out all of the 'key's in upper case letters and adding a new line
#4
###########################################
"""
Using the list of sites, add a new site to it,
using the input() method to get the name of the site from the user
then reverse the order of the list and print it out.
"""
add = input("Please enter a site: ") # Setting the 'add' variable to the input of the user
if add not in sites: # Conditional that will trigger if 'add' variable's user input is not in 'sites'
sites.append(add) # 'Sites' will be appended with the .append() method adding the user input
print(sites[::-1]) # Print out the 'sites' in reverse order
#5
###########################################
"""
Print out the 'Server' of the responce of the URL request of the items from your list
look here for more information:
https://requests.readthedocs.io/en/master/user/quickstart/#responce-content
example:
print(f"{mySiteData.headers.get('Server')}\n")
"""
for i in sites: # For loop that will iterate through 'sites'
r = requests.get(i) # Setting variable 'r' to the information received through the 'requests' module using the .get() method
print("######################################################\n") # Print out a string of '#'s to help delineate between requests
print(r.headers) # Print out the information in the 'r' variable using the .headers() method
#6
###########################################
"""
Exit the program using the sys module's exit function we
imported at the beginning of the code
"""
sys.exit() # An exit function imported from 'sys' library |
import CloudFlare
import os
from loguru import logger
def update(docker_records_list, ip):
ttl = os.getenv('TTL', 60)
zones = _get_zones()
logger.info('INFO: got list of all zones')
for zone in zones:
zone_id = zone['id']
controlled_records = []
control_record_id = None
old_records = None
perform_actions = False
records = _get_dns_records(zone_id)
logger.info(f'INFO: got list of all records for {zone['name']}')
for record in docker_records_list['cf']:
data = {'name': record, 'type': 'A', 'content': ip, 'ttl': ttl, 'proxied': True}
if record.endswith(zone['name']):
perform_actions = True
found = False
for cf_record in records:
if record.strip() == cf_record['name'].strip() and cf_record['type'] == 'A':
found = True
old_ip_address = cf_record['content']
controlled_records.append(record)
if ip != old_ip_address:
try:
cf.zones.dns_records.put(zone_id, cf_record['id'], data=data)
logger.info(f'UPDATED: {record} with IP address {ip}')
except CloudFlare.exceptions.CloudFlareAPIError as e:
logger.info(f'UNCHANGED: {record} already exists with IP address {ip}')
else:
logger.info(f'UNCHANGED: {record} already has IP address {ip}')
if cf_record['name'].strip() == f'_extdns_{instance_id}.{zone['name']}'.strip():
try:
old_records = cf_record['content'].split(',')
except KeyError:
old_records = []
control_record_id = cf_record['id']
if not found:
cf.zones.dns_records.post(zone_id, data=data)
logger.info(f'CREATED: {record} with IP address {ip}')
if perform_actions:
_set_extdns_record(zone_id, control_record_id, controlled_records)
_cleanup(zone_id, old_records, controlled_records, records)
def _set_extdns_record(zone_id, control_record_id, controlled_records):
extdns_record = ','.join(controlled_records)
data = {'name': f'_extdns_{instance_id}', 'type': 'TXT', 'content': f'{extdns_record}'}
if control_record_id:
if len(controlled_records) > 0:
logger.info(f'CONTROL: control record found. Updating one with list of records: {extdns_record}')
cf.zones.dns_records.put(zone_id, control_record_id, data=data)
else:
if len(controlled_records) > 0:
logger.info(f'CONTROL: control record not found ({control_record_id}). Creating one with list of '
f'records: {extdns_record}')
cf.zones.dns_records.post(zone_id, data=data)
def _cleanup(zone_id, old_records, controlled_records, records):
if old_records:
cleanup_records = list(set(old_records) - set(controlled_records))
if len(cleanup_records) > 0:
logger.info(f'CLEANUP: records to delete: {cleanup_records}')
for r in records:
if r['name'].strip() in cleanup_records:
cf.zones.dns_records.delete(zone_id, r['id'])
logger.info(f'CLEANUP: record {r['name']} ({r['id']}) was removed')
def _cf_connect():
cf_token = os.getenv('CF_TOKEN', None)
if cf_token is None:
exit('No CloudFlare credentials found!')
return CloudFlare.CloudFlare(token=cf_token)
def _get_dns_records(zone_id):
try:
return cf.zones.dns_records.get(zone_id, params={'per_page': 100})
except CloudFlare.exceptions.CloudFlareAPIError as e:
exit('/zones/dns_records.get %d %s - api call failed' % (e, e))
def _get_zones():
try:
return cf.zones.get()
except CloudFlare.exceptions.CloudFlareAPIError as e:
exit('/zones.get %d %s - api call failed' % (e, e))
except Exception as e:
exit('/zones.get - %s - api call failed' % (e))
instance_id = os.getenv('INSTANCE_ID', 0)
cf = _cf_connect()
| import CloudFlare
import os
from loguru import logger
def update(docker_records_list, ip):
ttl = os.getenv('TTL', 60)
zones = _get_zones()
logger.info('INFO: got list of all zones')
for zone in zones:
zone_id = zone['id']
controlled_records = []
control_record_id = None
old_records = None
perform_actions = False
records = _get_dns_records(zone_id)
logger.info(f'INFO: got list of all records for {zone["name"]}')
for record in docker_records_list['cf']:
data = {'name': record, 'type': 'A', 'content': ip, 'ttl': ttl, 'proxied': True}
if record.endswith(zone['name']):
perform_actions = True
found = False
for cf_record in records:
if record.strip() == cf_record['name'].strip() and cf_record['type'] == 'A':
found = True
old_ip_address = cf_record['content']
controlled_records.append(record)
if ip != old_ip_address:
try:
cf.zones.dns_records.put(zone_id, cf_record['id'], data=data)
logger.info(f'UPDATED: {record} with IP address {ip}')
except CloudFlare.exceptions.CloudFlareAPIError as e:
logger.info(f'UNCHANGED: {record} already exists with IP address {ip}')
else:
logger.info(f'UNCHANGED: {record} already has IP address {ip}')
if cf_record['name'].strip() == f'_extdns_{instance_id}.{zone["name"]}'.strip():
try:
old_records = cf_record['content'].split(',')
except KeyError:
old_records = []
control_record_id = cf_record['id']
if not found:
cf.zones.dns_records.post(zone_id, data=data)
logger.info(f'CREATED: {record} with IP address {ip}')
if perform_actions:
_set_extdns_record(zone_id, control_record_id, controlled_records)
_cleanup(zone_id, old_records, controlled_records, records)
def _set_extdns_record(zone_id, control_record_id, controlled_records):
extdns_record = ','.join(controlled_records)
data = {'name': f'_extdns_{instance_id}', 'type': 'TXT', 'content': f'{extdns_record}'}
if control_record_id:
if len(controlled_records) > 0:
logger.info(f'CONTROL: control record found. Updating one with list of records: {extdns_record}')
cf.zones.dns_records.put(zone_id, control_record_id, data=data)
else:
if len(controlled_records) > 0:
logger.info(f'CONTROL: control record not found ({control_record_id}). Creating one with list of '
f'records: {extdns_record}')
cf.zones.dns_records.post(zone_id, data=data)
def _cleanup(zone_id, old_records, controlled_records, records):
if old_records:
cleanup_records = list(set(old_records) - set(controlled_records))
if len(cleanup_records) > 0:
logger.info(f'CLEANUP: records to delete: {cleanup_records}')
for r in records:
if r['name'].strip() in cleanup_records:
cf.zones.dns_records.delete(zone_id, r['id'])
logger.info(f'CLEANUP: record {r["name"]} ({r["id"]}) was removed')
def _cf_connect():
cf_token = os.getenv('CF_TOKEN', None)
if cf_token is None:
exit('No CloudFlare credentials found!')
return CloudFlare.CloudFlare(token=cf_token)
def _get_dns_records(zone_id):
try:
return cf.zones.dns_records.get(zone_id, params={'per_page': 100})
except CloudFlare.exceptions.CloudFlareAPIError as e:
exit('/zones/dns_records.get %d %s - api call failed' % (e, e))
def _get_zones():
try:
return cf.zones.get()
except CloudFlare.exceptions.CloudFlareAPIError as e:
exit('/zones.get %d %s - api call failed' % (e, e))
except Exception as e:
exit('/zones.get - %s - api call failed' % (e))
instance_id = os.getenv('INSTANCE_ID', 0)
cf = _cf_connect()
|
from dataset import trainset
from model import ModelDic
import argparse
import glob
import sys
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
import torch.functional as F
import torch.optim as optim
import torch.nn as nn
import torch
import os
import time
save_points=[]
try:
os.mkdir("saved_models")
except:
pass
else:
pass
try:
os.mkdir("logs")
except:
pass
else:
pass
def cross_entropy_loss(output, target):
t = torch.log_softmax(output,dim=1)
loss = torch.mean(torch.sum(-t*target, dim=1), dim=0)
return loss
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', type=str,
default='0', help='which gpu')
parser.add_argument('--device', type=str,
default='cuda', help='cpu or cuda')
parser.add_argument('--bs', type=int,
default=256, help='batch size')
parser.add_argument('--lr', type=float, default=2e-3, help='learning rate')
parser.add_argument('--wd', type=float, default=0, help='weight decay')
parser.add_argument('--data', type=str,
default='../data_shuffled.npz', help='trainset path')
parser.add_argument('--type', type=str, default='res1',help='model type defined in model.py')
parser.add_argument('--save', type=str , help='model save pth')
parser.add_argument('--epoch', type=int,
default=1, help='epoch num')
parser.add_argument('--maxstep', type=int,
default=5000000000, help='max step to train')
parser.add_argument('--savestep', type=int,
default=1000, help='step to save')
parser.add_argument('--infostep', type=int,
default=100, help='step to logger')
parser.add_argument('-b', type=int,
default=6, help='block depth')
parser.add_argument('-f', type=int,
default=64, help='block channels')
opt = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = opt.gpu
device=opt.device
batch_size=opt.bs
lr=opt.lr
trainset_path=opt.data
model_type=opt.type
save_name=opt.save
maxepoch=opt.epoch
maxstep=opt.maxstep
savestep=opt.savestep
infostep=opt.infostep
blocks=opt.b
filters=opt.f
print("Loading data")
myDataSet = trainset(trainset_path)
print("Finished loading data")
totalstep = 0
file_path = f'saved_models/{save_name}.pth'
if os.path.exists(file_path):
data = torch.load(file_path)
model_param=(data['model_size'][0],data['model_size'][1])
model = ModelDic[data['model_name']](*model_param).to(device)
model.load_state_dict(data['state_dict'])
totalstep = data['step']
print(f"loaded model: type={data["model_name"]}, size={model.model_size}, totalstep={totalstep}")
else:
model = ModelDic[model_type](blocks,filters).to(device)
optimizer = optim.SGD(model.parameters(), lr=lr,momentum=0.9,weight_decay=0,nesterov=True)
dataloader = DataLoader(myDataSet, shuffle=True, batch_size=batch_size)
model.train()
time0=time.time()
loss_record=[0,0,0,1e-7]
print("Start training")
for epochs in range(maxepoch):
for step, (board, valueTarget, policyTarget) in enumerate(dataloader):
# data
board = board.to(device)
valueTarget = valueTarget.to(device)
policyTarget = policyTarget.to(device)
# optimize
optimizer.zero_grad()
value, policy = model(board)
vloss = cross_entropy_loss(value, valueTarget)
ploss = cross_entropy_loss(policy.flatten(start_dim=1), policyTarget.flatten(start_dim=1))
loss = 1.2*vloss+1.0*ploss
loss_record[0]+=vloss.detach()
loss_record[1]+=ploss.detach()
loss_record[2]+=(vloss.detach()+ploss.detach())
loss_record[3]+=1
loss.backward()
optimizer.step()
# logs
totalstep += 1
if(totalstep % infostep == 0):
print(f"time: {time.time()-time0} s, step: {totalstep}, vloss: {loss_record[0]/loss_record[3]}, ploss: {loss_record[1]/loss_record[3]}, totalloss: {loss_record[2]/loss_record[3]}")
logfile = open(f'logs/log_{save_name}.txt','a')
print(f"{save_name} {totalstep} {loss_record[0]/loss_record[3]} {loss_record[1]/loss_record[3]}",file=logfile)
logfile.close()
loss_record = [0, 0, 0, 1e-7]
time0=time.time()
if totalstep in save_points:
file_path_mid = f'saved_models/{save_name}_s{totalstep}.pth'
print(f"Finished training {totalstep} steps")
torch.save(
{'step': totalstep, 'state_dict': model.state_dict(), 'model_name': model.model_name,'model_size':model.model_size}, file_path_mid)
print('Model saved in {}\n'.format(file_path_mid))
if totalstep%savestep==0:
print(f"Finished training {totalstep} steps")
torch.save(
{'step': totalstep, 'state_dict': model.state_dict(), 'model_name': model.model_name,'model_size':model.model_size}, file_path)
print('Model saved in {}\n'.format(file_path))
if step >= maxstep:
break
print(f"Finished training {totalstep} steps")
torch.save(
{'step': totalstep, 'state_dict': model.state_dict(), 'model_name': model.model_name,
'model_size': model.model_size}, file_path)
print('Model saved in {}\n'.format(file_path)) |
from dataset import trainset
from model import ModelDic
import argparse
import glob
import sys
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
import torch.functional as F
import torch.optim as optim
import torch.nn as nn
import torch
import os
import time
save_points=[]
try:
os.mkdir("saved_models")
except:
pass
else:
pass
try:
os.mkdir("logs")
except:
pass
else:
pass
def cross_entropy_loss(output, target):
t = torch.log_softmax(output,dim=1)
loss = torch.mean(torch.sum(-t*target, dim=1), dim=0)
return loss
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', type=str,
default='0', help='which gpu')
parser.add_argument('--device', type=str,
default='cuda', help='cpu or cuda')
parser.add_argument('--bs', type=int,
default=256, help='batch size')
parser.add_argument('--lr', type=float, default=2e-3, help='learning rate')
parser.add_argument('--wd', type=float, default=0, help='weight decay')
parser.add_argument('--data', type=str,
default='../data_shuffled.npz', help='trainset path')
parser.add_argument('--type', type=str, default='res1',help='model type defined in model.py')
parser.add_argument('--save', type=str , help='model save pth')
parser.add_argument('--epoch', type=int,
default=1, help='epoch num')
parser.add_argument('--maxstep', type=int,
default=5000000000, help='max step to train')
parser.add_argument('--savestep', type=int,
default=1000, help='step to save')
parser.add_argument('--infostep', type=int,
default=100, help='step to logger')
parser.add_argument('-b', type=int,
default=6, help='block depth')
parser.add_argument('-f', type=int,
default=64, help='block channels')
opt = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = opt.gpu
device=opt.device
batch_size=opt.bs
lr=opt.lr
trainset_path=opt.data
model_type=opt.type
save_name=opt.save
maxepoch=opt.epoch
maxstep=opt.maxstep
savestep=opt.savestep
infostep=opt.infostep
blocks=opt.b
filters=opt.f
print("Loading data")
myDataSet = trainset(trainset_path)
print("Finished loading data")
totalstep = 0
file_path = f'saved_models/{save_name}.pth'
if os.path.exists(file_path):
data = torch.load(file_path)
model_param=(data['model_size'][0],data['model_size'][1])
model = ModelDic[data['model_name']](*model_param).to(device)
model.load_state_dict(data['state_dict'])
totalstep = data['step']
print(f"loaded model: type={data['model_name']}, size={model.model_size}, totalstep={totalstep}")
else:
model = ModelDic[model_type](blocks,filters).to(device)
optimizer = optim.SGD(model.parameters(), lr=lr,momentum=0.9,weight_decay=0,nesterov=True)
dataloader = DataLoader(myDataSet, shuffle=True, batch_size=batch_size)
model.train()
time0=time.time()
loss_record=[0,0,0,1e-7]
print("Start training")
for epochs in range(maxepoch):
for step, (board, valueTarget, policyTarget) in enumerate(dataloader):
# data
board = board.to(device)
valueTarget = valueTarget.to(device)
policyTarget = policyTarget.to(device)
# optimize
optimizer.zero_grad()
value, policy = model(board)
vloss = cross_entropy_loss(value, valueTarget)
ploss = cross_entropy_loss(policy.flatten(start_dim=1), policyTarget.flatten(start_dim=1))
loss = 1.2*vloss+1.0*ploss
loss_record[0]+=vloss.detach()
loss_record[1]+=ploss.detach()
loss_record[2]+=(vloss.detach()+ploss.detach())
loss_record[3]+=1
loss.backward()
optimizer.step()
# logs
totalstep += 1
if(totalstep % infostep == 0):
print(f"time: {time.time()-time0} s, step: {totalstep}, vloss: {loss_record[0]/loss_record[3]}, ploss: {loss_record[1]/loss_record[3]}, totalloss: {loss_record[2]/loss_record[3]}")
logfile = open(f'logs/log_{save_name}.txt','a')
print(f"{save_name} {totalstep} {loss_record[0]/loss_record[3]} {loss_record[1]/loss_record[3]}",file=logfile)
logfile.close()
loss_record = [0, 0, 0, 1e-7]
time0=time.time()
if totalstep in save_points:
file_path_mid = f'saved_models/{save_name}_s{totalstep}.pth'
print(f"Finished training {totalstep} steps")
torch.save(
{'step': totalstep, 'state_dict': model.state_dict(), 'model_name': model.model_name,'model_size':model.model_size}, file_path_mid)
print('Model saved in {}\n'.format(file_path_mid))
if totalstep%savestep==0:
print(f"Finished training {totalstep} steps")
torch.save(
{'step': totalstep, 'state_dict': model.state_dict(), 'model_name': model.model_name,'model_size':model.model_size}, file_path)
print('Model saved in {}\n'.format(file_path))
if step >= maxstep:
break
print(f"Finished training {totalstep} steps")
torch.save(
{'step': totalstep, 'state_dict': model.state_dict(), 'model_name': model.model_name,
'model_size': model.model_size}, file_path)
print('Model saved in {}\n'.format(file_path)) |
import logging
import os
import sys
import math
from datetime import datetime, timedelta, timezone, time
from zoneinfo import ZoneInfo
import dateparser
import hjson
import pandas as pd
import psutil
import redis
import shortuuid
from dotenv import load_dotenv
from faker import Faker
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from dateutil.parser import parse
load_dotenv("dev.env")
Faker.seed(int(os.getenv("seed")))
fake = Faker()
num_uuid = shortuuid.ShortUUID()
num_uuid.set_alphabet("0123456789")
back_range = 61
with open("config.hjson") as f:
config = hjson.load(f)
key_name = ("test_" if os.getenv("mode") == "test" else "") + "study_roles"
role_settings = config[key_name]
role_name_to_begin_hours = {role_name: float(role_info['hours'].split("-")[0]) for role_name, role_info in
role_settings.items()}
role_names = list(role_settings.keys())
num_intervals = 24 * 1
delta = timedelta(days=1)
interval = delta / num_intervals
def get_rank_categories(flatten=False, string=True):
rank_categories = {}
if flatten:
timepoints = get_earliest_timepoint(prefix=True, string=string)
else:
timepoints = get_timepoints()
if string:
timepoints = ["daily_" + str(timepoint) for timepoint in timepoints]
rank_categories["daily"] = timepoints
rank_categories["weekly"] = f"weekly_{get_week_start()}"
rank_categories["monthly"] = f"monthly_{get_month()}"
rank_categories["all_time"] = "all_time"
return rank_categories
def get_logger(job_name, filename):
logger = logging.getLogger(job_name)
logger.setLevel(logging.INFO)
handler = logging.FileHandler(filename=filename, encoding='utf-8', mode='a')
handler.setFormatter(logging.Formatter('%(message)s:%(levelname)s:%(name)s:%(process)d'))
logger.addHandler(handler)
return logger
def get_guildID():
guildID_key_name = ("test_" if os.getenv("mode") == "test" else "") + "guildID"
guildID = int(os.getenv(guildID_key_name))
return guildID
def recreate_db(Base):
redis_client = get_redis_client()
engine = get_engine()
redis_client.flushall()
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
def get_engine(echo=False):
return create_engine(
f'mysql+pymysql://{os.getenv('sql_user')}:{os.getenv('sql_password')}@{os.getenv('sql_host')}/{os.getenv('sql_database')}',
echo=echo)
def get_timezone_session():
db_var_name = ("test_" if os.getenv("mode") == "test" else "") + "timezone_db"
engine = create_engine(os.getenv(db_var_name))
session = sessionmaker(bind=engine)()
return session
def get_time():
now = datetime.utcnow()
return now
def get_num_days_this_month():
return datetime.utcnow().day
def get_day_start():
date = datetime.combine(datetime.utcnow().date(), datetime.min.time())
offset = timedelta(hours=config["business"]["update_time"])
if datetime.utcnow() < date + offset:
offset -= timedelta(days=1)
return date + offset
def get_tomorrow_start():
return get_day_start() + timedelta(days=1)
def get_week_start():
return get_day_start() - timedelta(days=get_day_start().weekday() % 7)
def get_month_start():
given_date = get_day_start()
first_day_of_month = given_date - timedelta(days=int(given_date.strftime("%d")) - 1)
return first_day_of_month
def get_earliest_start():
return datetime.utcnow() - timedelta(days=back_range)
def get_month():
return datetime.utcnow().strftime("%B")
def get_earliest_timepoint(starting_point=None, string=False, prefix=False):
if not starting_point:
starting_point = get_time() - delta
offset = interval - (starting_point - datetime(1900, 1, 1)) % interval
if offset == interval:
offset -= interval
earliest_timepoint = starting_point + offset
return f"{"daily_" if prefix else ""}{earliest_timepoint}" if string else earliest_timepoint
def parse_time(timepoint, zone_obj=ZoneInfo(config["business"]["timezone"])):
if timepoint is None:
timepoint = ""
if len(timepoint) > 30:
return
parsed = dateparser.parse(timepoint, date_formats=["%H:%M", "%H:%m", "%h:%M", "%h:%m", "%H", "%h"])
if not parsed:
return
if parsed.replace(tzinfo=zone_obj) >= datetime.now(zone_obj):
parsed -= timedelta(days=1)
return parsed
def get_closest_timepoint(full_time_point, prefix=False):
cur_time = get_time()
if full_time_point > cur_time:
full_time_point -= timedelta(days=1)
timepoint_to_use = get_earliest_timepoint(full_time_point, string=True)
return f"{"daily_" if prefix else ""}{timepoint_to_use}"
def get_timepoints():
earliest_timepoint = get_earliest_timepoint(prefix=False)
timepoints = [earliest_timepoint + i * interval for i in range(num_intervals)]
return timepoints
def timedelta_to_hours(td):
return td.total_seconds() / 3600
async def get_user_timeinfo(ctx, user, timepoint):
from timezone_bot import query_zone
user_timezone = await query_zone(user)
if user_timezone == "Not set":
await ctx.send(
f"**You can set a time zone with `.tzlist` and then `.tzset`**")
user_timezone = config["business"]["timezone"]
zone_obj = ZoneInfo(user_timezone)
# Here the placeholder is not limited to "-"
user_timepoint = parse_time(timepoint, zone_obj=zone_obj)
if user_timepoint:
user_timepoint = user_timepoint.replace(tzinfo=zone_obj)
std_zone_obj = ZoneInfo(config["business"]["timezone"])
utc_timepoint = user_timepoint.astimezone(std_zone_obj)
timepoint = get_closest_timepoint(utc_timepoint.replace(tzinfo=None), prefix=False)
else:
timepoint = get_closest_timepoint(get_earliest_timepoint(), prefix=False)
display_timepoint = dateparser.parse(timepoint).replace(
tzinfo=ZoneInfo(config["business"]["timezone"]))
display_timepoint = display_timepoint.astimezone(zone_obj).strftime(os.getenv("datetime_format").split(".")[0])
return "daily_" + timepoint, user_timezone, display_timepoint
def round_num(num, ndigits=None):
if not ndigits:
ndigits_var_name = ("test_" if os.getenv("mode") == "test" else "") + "display_num_decimal"
ndigits = int(os.getenv(ndigits_var_name))
return round(num, ndigits=ndigits)
def calc_total_time(data):
if not data:
return 0
total_time = timedelta(0)
start_idx = 0
end_idx = len(data) - 1
if data[0]["category"] == "end channel":
total_time += data[0]["creation_time"] - get_month_start()
start_idx = 1
if data[-1]["category"] == "start channel":
total_time += get_time() - data[-1]["creation_time"]
end_idx -= 1
for idx in range(start_idx, end_idx + 1, 2):
total_time += data[idx + 1]["creation_time"] - data[idx]["creation_time"]
total_time = timedelta_to_hours(total_time)
return total_time
def generate_random_number(size=1, length=18):
res = [fake.random_number(digits=length, fix_len=True) for _ in range(size)]
return res
def generate_discord_user_id(size=1, length=18):
res = []
if size >= 2:
res += [int(os.getenv("tester_human_discord_user_id")), int(os.getenv("tester_bot_token_discord_user_id"))]
size -= 2
res += generate_random_number(size, length)
return res
def generate_datetime(size=1, start_date=f'-{back_range}d'):
return sorted([fake.past_datetime(start_date=start_date, tzinfo=timezone.utc) for _ in range(size)])
def generate_username(size=1):
return [fake.user_name() for _ in range(size)]
def get_total_time_for_window(df, get_start_fn=None):
df = df.sort_values(by=['creation_time'])
total_time = timedelta(0)
start_idx = 0
end_idx = len(df)
if len(df):
if df["category"].iloc[0] == "end channel":
total_time += df["creation_time"].iloc[0] - pd.to_datetime(get_start_fn())
start_idx = 1
if df["category"].iloc[-1] == "start channel":
total_time += pd.to_datetime(get_time()) - df["creation_time"].iloc[-1]
end_idx -= 1
df = df.iloc[start_idx: end_idx]
enter_df = df[df["category"] == "start channel"]["creation_time"]
exit_df = df[df["category"] == "end channel"]["creation_time"]
total_time += pd.to_timedelta((exit_df.values - enter_df.values).sum())
total_time = timedelta_to_hours(total_time)
if total_time < 0:
raise Exception("study time below zero")
return total_time
def get_redis_client():
return redis.Redis(
host=os.getenv("redis_host"),
port=os.getenv("redis_port"),
db=int(os.getenv("redis_db_num")),
username=os.getenv("redis_username"),
password=os.getenv("redis_password"),
decode_responses=True
)
def get_role_status(role_name_to_obj, hours_cur_month):
cur_role_name = role_names[0]
next_role_name = role_names[1]
for role_name, begin_hours in role_name_to_begin_hours.items():
if begin_hours <= hours_cur_month:
cur_role_name = role_name
else:
next_role_name = role_name
break
cur_role = role_name_to_obj[cur_role_name]
# new members
if hours_cur_month < role_name_to_begin_hours[cur_role_name]:
cur_role = None
next_role, time_to_next_role = (
role_name_to_obj[next_role_name], round_num(role_name_to_begin_hours[next_role_name] - hours_cur_month)) \
if cur_role_name != role_names[-1] else (None, None)
return cur_role, next_role, time_to_next_role
def get_last_line():
try:
with open('heartbeat.log', 'rb') as f:
f.seek(-2, os.SEEK_END)
while f.read(1) != b'\n':
f.seek(-2, os.SEEK_CUR)
line = f.readline().decode()
return line
except OSError:
return None
def get_last_time(line):
last_line = " ".join(line.split()[:2])
return datetime.strptime(last_line, os.getenv("datetime_format"))
def kill_last_process(line):
if not line:
return
parts = line.split()
pid = int(parts[-1].split(":")[-1])
try:
process = psutil.Process(pid)
if "time_counter.py" in " ".join(process.cmdline()):
process.terminate()
print(f"{pid} killed")
except:
pass
async def get_redis_rank(redis_client, sorted_set_name, user_id):
rank = redis_client.zrevrank(sorted_set_name, user_id)
if rank is None:
redis_client.zadd(sorted_set_name, {user_id: 0})
rank = redis_client.zrevrank(sorted_set_name, user_id)
return 1 + rank
async def get_redis_score(redis_client, sorted_set_name, user_id):
score = redis_client.zscore(sorted_set_name, user_id) or 0
return round_num(score)
async def get_user_stats(redis_client, user_id, timepoint=get_earliest_timepoint(string=True, prefix=True)):
stats = dict()
category_key_names = list(get_rank_categories().values())
for sorted_set_name in [timepoint] + category_key_names[1:]:
stats[sorted_set_name] = {
"rank": await get_redis_rank(redis_client, sorted_set_name, user_id),
"study_time": await get_redis_score(redis_client, sorted_set_name, user_id)
}
return stats
def get_stats_diff(prev_stats, cur_stats):
prev_studytime = [item["study_time"] for item in prev_stats.values()]
cur_studytime = [item["study_time"] for item in cur_stats.values()]
diff = [round_num(cur - prev) for prev, cur in zip(prev_studytime, cur_studytime)]
return diff
def check_stats_diff(prev_stats, mid_stats, time_to_stay, multiplier, redis_tolerance):
diff = get_stats_diff(prev_stats, mid_stats)
excess = [hours * 3600 - time_to_stay * multiplier for hours in diff]
is_all_increment_right = [0 <= hours <= redis_tolerance for hours in excess]
return all(is_all_increment_right)
def sleep(seconds):
# TODO print decimals
seconds = math.ceil(seconds)
for remaining in range(seconds, 0, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds remaining.".format(remaining))
sys.stdout.flush()
import time
time.sleep(1)
def increment_studytime(category_key_names, redis_client, user_id, in_session_incrs, std_incr=None, last_time=None):
if std_incr is None:
std_incr = timedelta_to_hours(get_time() - last_time)
for i, sorted_set_name in enumerate(category_key_names):
incr = in_session_incrs[i] if i < num_intervals else std_incr
redis_client.zincrby(sorted_set_name, incr, user_id)
def commit_or_rollback(session):
try:
session.commit()
except Exception as e:
print(e)
session.rollback()
raise
| import logging
import os
import sys
import math
from datetime import datetime, timedelta, timezone, time
from zoneinfo import ZoneInfo
import dateparser
import hjson
import pandas as pd
import psutil
import redis
import shortuuid
from dotenv import load_dotenv
from faker import Faker
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from dateutil.parser import parse
load_dotenv("dev.env")
Faker.seed(int(os.getenv("seed")))
fake = Faker()
num_uuid = shortuuid.ShortUUID()
num_uuid.set_alphabet("0123456789")
back_range = 61
with open("config.hjson") as f:
config = hjson.load(f)
key_name = ("test_" if os.getenv("mode") == "test" else "") + "study_roles"
role_settings = config[key_name]
role_name_to_begin_hours = {role_name: float(role_info['hours'].split("-")[0]) for role_name, role_info in
role_settings.items()}
role_names = list(role_settings.keys())
num_intervals = 24 * 1
delta = timedelta(days=1)
interval = delta / num_intervals
def get_rank_categories(flatten=False, string=True):
rank_categories = {}
if flatten:
timepoints = get_earliest_timepoint(prefix=True, string=string)
else:
timepoints = get_timepoints()
if string:
timepoints = ["daily_" + str(timepoint) for timepoint in timepoints]
rank_categories["daily"] = timepoints
rank_categories["weekly"] = f"weekly_{get_week_start()}"
rank_categories["monthly"] = f"monthly_{get_month()}"
rank_categories["all_time"] = "all_time"
return rank_categories
def get_logger(job_name, filename):
logger = logging.getLogger(job_name)
logger.setLevel(logging.INFO)
handler = logging.FileHandler(filename=filename, encoding='utf-8', mode='a')
handler.setFormatter(logging.Formatter('%(message)s:%(levelname)s:%(name)s:%(process)d'))
logger.addHandler(handler)
return logger
def get_guildID():
guildID_key_name = ("test_" if os.getenv("mode") == "test" else "") + "guildID"
guildID = int(os.getenv(guildID_key_name))
return guildID
def recreate_db(Base):
redis_client = get_redis_client()
engine = get_engine()
redis_client.flushall()
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
def get_engine(echo=False):
return create_engine(
f'mysql+pymysql://{os.getenv("sql_user")}:{os.getenv("sql_password")}@{os.getenv("sql_host")}/{os.getenv("sql_database")}',
echo=echo)
def get_timezone_session():
db_var_name = ("test_" if os.getenv("mode") == "test" else "") + "timezone_db"
engine = create_engine(os.getenv(db_var_name))
session = sessionmaker(bind=engine)()
return session
def get_time():
now = datetime.utcnow()
return now
def get_num_days_this_month():
return datetime.utcnow().day
def get_day_start():
date = datetime.combine(datetime.utcnow().date(), datetime.min.time())
offset = timedelta(hours=config["business"]["update_time"])
if datetime.utcnow() < date + offset:
offset -= timedelta(days=1)
return date + offset
def get_tomorrow_start():
return get_day_start() + timedelta(days=1)
def get_week_start():
return get_day_start() - timedelta(days=get_day_start().weekday() % 7)
def get_month_start():
given_date = get_day_start()
first_day_of_month = given_date - timedelta(days=int(given_date.strftime("%d")) - 1)
return first_day_of_month
def get_earliest_start():
return datetime.utcnow() - timedelta(days=back_range)
def get_month():
return datetime.utcnow().strftime("%B")
def get_earliest_timepoint(starting_point=None, string=False, prefix=False):
if not starting_point:
starting_point = get_time() - delta
offset = interval - (starting_point - datetime(1900, 1, 1)) % interval
if offset == interval:
offset -= interval
earliest_timepoint = starting_point + offset
return f"{'daily_' if prefix else ''}{earliest_timepoint}" if string else earliest_timepoint
def parse_time(timepoint, zone_obj=ZoneInfo(config["business"]["timezone"])):
if timepoint is None:
timepoint = ""
if len(timepoint) > 30:
return
parsed = dateparser.parse(timepoint, date_formats=["%H:%M", "%H:%m", "%h:%M", "%h:%m", "%H", "%h"])
if not parsed:
return
if parsed.replace(tzinfo=zone_obj) >= datetime.now(zone_obj):
parsed -= timedelta(days=1)
return parsed
def get_closest_timepoint(full_time_point, prefix=False):
cur_time = get_time()
if full_time_point > cur_time:
full_time_point -= timedelta(days=1)
timepoint_to_use = get_earliest_timepoint(full_time_point, string=True)
return f"{'daily_' if prefix else ''}{timepoint_to_use}"
def get_timepoints():
earliest_timepoint = get_earliest_timepoint(prefix=False)
timepoints = [earliest_timepoint + i * interval for i in range(num_intervals)]
return timepoints
def timedelta_to_hours(td):
return td.total_seconds() / 3600
async def get_user_timeinfo(ctx, user, timepoint):
from timezone_bot import query_zone
user_timezone = await query_zone(user)
if user_timezone == "Not set":
await ctx.send(
f"**You can set a time zone with `.tzlist` and then `.tzset`**")
user_timezone = config["business"]["timezone"]
zone_obj = ZoneInfo(user_timezone)
# Here the placeholder is not limited to "-"
user_timepoint = parse_time(timepoint, zone_obj=zone_obj)
if user_timepoint:
user_timepoint = user_timepoint.replace(tzinfo=zone_obj)
std_zone_obj = ZoneInfo(config["business"]["timezone"])
utc_timepoint = user_timepoint.astimezone(std_zone_obj)
timepoint = get_closest_timepoint(utc_timepoint.replace(tzinfo=None), prefix=False)
else:
timepoint = get_closest_timepoint(get_earliest_timepoint(), prefix=False)
display_timepoint = dateparser.parse(timepoint).replace(
tzinfo=ZoneInfo(config["business"]["timezone"]))
display_timepoint = display_timepoint.astimezone(zone_obj).strftime(os.getenv("datetime_format").split(".")[0])
return "daily_" + timepoint, user_timezone, display_timepoint
def round_num(num, ndigits=None):
if not ndigits:
ndigits_var_name = ("test_" if os.getenv("mode") == "test" else "") + "display_num_decimal"
ndigits = int(os.getenv(ndigits_var_name))
return round(num, ndigits=ndigits)
def calc_total_time(data):
if not data:
return 0
total_time = timedelta(0)
start_idx = 0
end_idx = len(data) - 1
if data[0]["category"] == "end channel":
total_time += data[0]["creation_time"] - get_month_start()
start_idx = 1
if data[-1]["category"] == "start channel":
total_time += get_time() - data[-1]["creation_time"]
end_idx -= 1
for idx in range(start_idx, end_idx + 1, 2):
total_time += data[idx + 1]["creation_time"] - data[idx]["creation_time"]
total_time = timedelta_to_hours(total_time)
return total_time
def generate_random_number(size=1, length=18):
res = [fake.random_number(digits=length, fix_len=True) for _ in range(size)]
return res
def generate_discord_user_id(size=1, length=18):
res = []
if size >= 2:
res += [int(os.getenv("tester_human_discord_user_id")), int(os.getenv("tester_bot_token_discord_user_id"))]
size -= 2
res += generate_random_number(size, length)
return res
def generate_datetime(size=1, start_date=f'-{back_range}d'):
return sorted([fake.past_datetime(start_date=start_date, tzinfo=timezone.utc) for _ in range(size)])
def generate_username(size=1):
return [fake.user_name() for _ in range(size)]
def get_total_time_for_window(df, get_start_fn=None):
df = df.sort_values(by=['creation_time'])
total_time = timedelta(0)
start_idx = 0
end_idx = len(df)
if len(df):
if df["category"].iloc[0] == "end channel":
total_time += df["creation_time"].iloc[0] - pd.to_datetime(get_start_fn())
start_idx = 1
if df["category"].iloc[-1] == "start channel":
total_time += pd.to_datetime(get_time()) - df["creation_time"].iloc[-1]
end_idx -= 1
df = df.iloc[start_idx: end_idx]
enter_df = df[df["category"] == "start channel"]["creation_time"]
exit_df = df[df["category"] == "end channel"]["creation_time"]
total_time += pd.to_timedelta((exit_df.values - enter_df.values).sum())
total_time = timedelta_to_hours(total_time)
if total_time < 0:
raise Exception("study time below zero")
return total_time
def get_redis_client():
return redis.Redis(
host=os.getenv("redis_host"),
port=os.getenv("redis_port"),
db=int(os.getenv("redis_db_num")),
username=os.getenv("redis_username"),
password=os.getenv("redis_password"),
decode_responses=True
)
def get_role_status(role_name_to_obj, hours_cur_month):
cur_role_name = role_names[0]
next_role_name = role_names[1]
for role_name, begin_hours in role_name_to_begin_hours.items():
if begin_hours <= hours_cur_month:
cur_role_name = role_name
else:
next_role_name = role_name
break
cur_role = role_name_to_obj[cur_role_name]
# new members
if hours_cur_month < role_name_to_begin_hours[cur_role_name]:
cur_role = None
next_role, time_to_next_role = (
role_name_to_obj[next_role_name], round_num(role_name_to_begin_hours[next_role_name] - hours_cur_month)) \
if cur_role_name != role_names[-1] else (None, None)
return cur_role, next_role, time_to_next_role
def get_last_line():
try:
with open('heartbeat.log', 'rb') as f:
f.seek(-2, os.SEEK_END)
while f.read(1) != b'\n':
f.seek(-2, os.SEEK_CUR)
line = f.readline().decode()
return line
except OSError:
return None
def get_last_time(line):
last_line = " ".join(line.split()[:2])
return datetime.strptime(last_line, os.getenv("datetime_format"))
def kill_last_process(line):
if not line:
return
parts = line.split()
pid = int(parts[-1].split(":")[-1])
try:
process = psutil.Process(pid)
if "time_counter.py" in " ".join(process.cmdline()):
process.terminate()
print(f"{pid} killed")
except:
pass
async def get_redis_rank(redis_client, sorted_set_name, user_id):
rank = redis_client.zrevrank(sorted_set_name, user_id)
if rank is None:
redis_client.zadd(sorted_set_name, {user_id: 0})
rank = redis_client.zrevrank(sorted_set_name, user_id)
return 1 + rank
async def get_redis_score(redis_client, sorted_set_name, user_id):
score = redis_client.zscore(sorted_set_name, user_id) or 0
return round_num(score)
async def get_user_stats(redis_client, user_id, timepoint=get_earliest_timepoint(string=True, prefix=True)):
stats = dict()
category_key_names = list(get_rank_categories().values())
for sorted_set_name in [timepoint] + category_key_names[1:]:
stats[sorted_set_name] = {
"rank": await get_redis_rank(redis_client, sorted_set_name, user_id),
"study_time": await get_redis_score(redis_client, sorted_set_name, user_id)
}
return stats
def get_stats_diff(prev_stats, cur_stats):
prev_studytime = [item["study_time"] for item in prev_stats.values()]
cur_studytime = [item["study_time"] for item in cur_stats.values()]
diff = [round_num(cur - prev) for prev, cur in zip(prev_studytime, cur_studytime)]
return diff
def check_stats_diff(prev_stats, mid_stats, time_to_stay, multiplier, redis_tolerance):
diff = get_stats_diff(prev_stats, mid_stats)
excess = [hours * 3600 - time_to_stay * multiplier for hours in diff]
is_all_increment_right = [0 <= hours <= redis_tolerance for hours in excess]
return all(is_all_increment_right)
def sleep(seconds):
# TODO print decimals
seconds = math.ceil(seconds)
for remaining in range(seconds, 0, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds remaining.".format(remaining))
sys.stdout.flush()
import time
time.sleep(1)
def increment_studytime(category_key_names, redis_client, user_id, in_session_incrs, std_incr=None, last_time=None):
if std_incr is None:
std_incr = timedelta_to_hours(get_time() - last_time)
for i, sorted_set_name in enumerate(category_key_names):
incr = in_session_incrs[i] if i < num_intervals else std_incr
redis_client.zincrby(sorted_set_name, incr, user_id)
def commit_or_rollback(session):
try:
session.commit()
except Exception as e:
print(e)
session.rollback()
raise
|
import json
from textwrap import dedent
from typing import Dict, Iterator, Optional, Union
import retryrequests
from ._logger import logger
from ._sponsor import Sponsor
class GitHubV4Client:
def __init__(self, token: str) -> None:
self.__token = token
def exec_query(
self, query: str, variables: Optional[Dict[str, Union[str, int]]] = None
) -> Dict:
logger.debug(f"[query]\n{dedent(query).strip()}\n")
if variables:
logger.debug(f"[variables]\n{json.dumps(variables, indent=2)}\n")
r = retryrequests.post(
"https://api.github.com/graphql",
json={"query": query, "variables": variables},
headers={"Authorization": f"Bearer {self.__token}"},
)
r.raise_for_status()
results = r.json()
logger.debug(f"[results]\n{json.dumps(results, indent=2)}\n")
return results
def fetch_login_user_name(self) -> str:
result = self.exec_query("{ viewer { login } }")
return result["data"]["viewer"]["login"]
def __fetch_sponsors(self, login: str, after: str, avatar_size: int) -> Dict:
assert login
common_query = """
sponsorshipsAsMaintainer(first: $first, after: $after) {
totalCount
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
edges {
cursor
node {
isOneTimePayment
privacyLevel
createdAt
tier {
name
monthlyPriceInDollars
}
sponsorEntity {
... on User {
name
login
avatarUrl(size: $avatar_size)
url
}
}
}
}
}"""
query = (
"""\
query($login: String!, $avatar_size: Int!, $first: Int!, $after: String!) {
user(login: $login) {"""
+ common_query
+ """
}
"""
+ """
organization(login: $login) {"""
+ common_query
+ """
}
}
"""
)
variables: Dict[str, Union[str, int]] = {
"login": login,
"first": 100,
"after": after,
"avatar_size": avatar_size,
}
result = self.exec_query(query, variables=variables)
if result["data"]["user"]:
return result["data"]["user"]["sponsorshipsAsMaintainer"]
elif result["data"]["organization"]:
return result["data"]["organization"]["sponsorshipsAsMaintainer"]
raise RuntimeError("empty result")
def fetch_sponsors(self, login: str, avatar_size: int) -> Iterator[Sponsor]:
sponsorships = self.__fetch_sponsors(login=login, after="", avatar_size=avatar_size)
logger.debug(f"results - totalCount: {sponsorships["totalCount"]}")
for sponsor in sponsorships["edges"]:
node = sponsor["node"]
entity = node["sponsorEntity"]
if not entity:
continue
tier = node["tier"]
if not tier:
price = None
else:
price = tier["monthlyPriceInDollars"] if "monthlyPriceInDollars" in tier else None
# print(price)
yield Sponsor(
**entity, monthlyPriceInDollars=price, isOneTimePayment=node["isOneTimePayment"]
)
page_info = sponsorships["pageInfo"]
# print(page_info)
while page_info["hasNextPage"]:
sponsorships = self.__fetch_sponsors(
login=login, after=page_info["endCursor"], avatar_size=avatar_size
)
for sponsor in sponsorships["edges"]:
node = sponsor["node"]
entity = node["sponsorEntity"]
if not entity:
continue
tier = node["tier"]
if not tier:
price = None
else:
price = (
tier["monthlyPriceInDollars"] if "monthlyPriceInDollars" in tier else None
)
yield Sponsor(
**entity, monthlyPriceInDollars=price, isOneTimePayment=node["isOneTimePayment"]
)
page_info = sponsorships["pageInfo"]
# print(page_info)
| import json
from textwrap import dedent
from typing import Dict, Iterator, Optional, Union
import retryrequests
from ._logger import logger
from ._sponsor import Sponsor
class GitHubV4Client:
def __init__(self, token: str) -> None:
self.__token = token
def exec_query(
self, query: str, variables: Optional[Dict[str, Union[str, int]]] = None
) -> Dict:
logger.debug(f"[query]\n{dedent(query).strip()}\n")
if variables:
logger.debug(f"[variables]\n{json.dumps(variables, indent=2)}\n")
r = retryrequests.post(
"https://api.github.com/graphql",
json={"query": query, "variables": variables},
headers={"Authorization": f"Bearer {self.__token}"},
)
r.raise_for_status()
results = r.json()
logger.debug(f"[results]\n{json.dumps(results, indent=2)}\n")
return results
def fetch_login_user_name(self) -> str:
result = self.exec_query("{ viewer { login } }")
return result["data"]["viewer"]["login"]
def __fetch_sponsors(self, login: str, after: str, avatar_size: int) -> Dict:
assert login
common_query = """
sponsorshipsAsMaintainer(first: $first, after: $after) {
totalCount
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
edges {
cursor
node {
isOneTimePayment
privacyLevel
createdAt
tier {
name
monthlyPriceInDollars
}
sponsorEntity {
... on User {
name
login
avatarUrl(size: $avatar_size)
url
}
}
}
}
}"""
query = (
"""\
query($login: String!, $avatar_size: Int!, $first: Int!, $after: String!) {
user(login: $login) {"""
+ common_query
+ """
}
"""
+ """
organization(login: $login) {"""
+ common_query
+ """
}
}
"""
)
variables: Dict[str, Union[str, int]] = {
"login": login,
"first": 100,
"after": after,
"avatar_size": avatar_size,
}
result = self.exec_query(query, variables=variables)
if result["data"]["user"]:
return result["data"]["user"]["sponsorshipsAsMaintainer"]
elif result["data"]["organization"]:
return result["data"]["organization"]["sponsorshipsAsMaintainer"]
raise RuntimeError("empty result")
def fetch_sponsors(self, login: str, avatar_size: int) -> Iterator[Sponsor]:
sponsorships = self.__fetch_sponsors(login=login, after="", avatar_size=avatar_size)
logger.debug(f"results - totalCount: {sponsorships['totalCount']}")
for sponsor in sponsorships["edges"]:
node = sponsor["node"]
entity = node["sponsorEntity"]
if not entity:
continue
tier = node["tier"]
if not tier:
price = None
else:
price = tier["monthlyPriceInDollars"] if "monthlyPriceInDollars" in tier else None
# print(price)
yield Sponsor(
**entity, monthlyPriceInDollars=price, isOneTimePayment=node["isOneTimePayment"]
)
page_info = sponsorships["pageInfo"]
# print(page_info)
while page_info["hasNextPage"]:
sponsorships = self.__fetch_sponsors(
login=login, after=page_info["endCursor"], avatar_size=avatar_size
)
for sponsor in sponsorships["edges"]:
node = sponsor["node"]
entity = node["sponsorEntity"]
if not entity:
continue
tier = node["tier"]
if not tier:
price = None
else:
price = (
tier["monthlyPriceInDollars"] if "monthlyPriceInDollars" in tier else None
)
yield Sponsor(
**entity, monthlyPriceInDollars=price, isOneTimePayment=node["isOneTimePayment"]
)
page_info = sponsorships["pageInfo"]
# print(page_info)
|
import typing
from datetime import datetime
from ..schema import BaseTransformer
class Transformer(BaseTransformer):
"""Transform Tennessee raw data for consolidation."""
postal_code = "TN"
fields = dict(
company="Company",
location=lambda row: row["City"] or f"{row["County"]} County",
notice_date="Notice Date",
effective_date="Effective Date",
jobs="No. Of Employees",
)
date_format = (
"%Y/%m/%d",
"%m/%d/%Y",
"%B %d, %Y",
"%B %Y",
"%B%d, %Y",
"%B %d. %Y",
"%B %d,%Y",
)
date_corrections = {
"2018/4/ 27": datetime(2018, 4, 27),
"start of layoff -\xa0March 13, 2020": datetime(2020, 3, 13),
"December 15-30, 2020": datetime(2020, 12, 15),
"June 17 - June 30, 2020": datetime(2020, 6, 17),
"124": None,
"March 16, 2020 - June 30, 2020": datetime(2020, 3, 16),
"March 20-24, 2020": datetime(2020, 3, 20),
"March 4, 2020 - June 4, 2020": datetime(2020, 3, 4),
"Apri 1, 2020": datetime(2020, 4, 1),
"Beginning April 14 and ending June 30, 2020": datetime(2020, 4, 14),
"Beginning February 16 and ending February 29, 2020": datetime(2020, 2, 16),
"Beginning March 17 and ending March 30, 2020": datetime(2020, 3, 17),
"Beginning in February 2020": datetime(2020, 2, 1),
"beginning February 2020": datetime(2020, 2, 1),
"January 3, 2020 through January 31, 2020": datetime(2020, 1, 3),
"December 13, 2019 and continue until February 28, 2020": datetime(
2019, 12, 13
),
"December 1, 2019 until December 31, 2019": datetime(2019, 12, 1),
"Will begin on November 30, 2019 and will continue to December 31, 2020": datetime(
2019, 11, 30
),
"Will begin on October 7, 2019 and will continue to November 30, 2019": datetime(
2019, 10, 7
),
"Initial layoff September 4, 2019 with additional layoffs planned September 13 and September 20": datetime(
2019, 9, 4
),
"November 9 through November 23, 2019": datetime(2019, 11, 23),
"September 30, 2019 for 4 employees and October 31, 2019 for 174 employees": datetime(
2019, 9, 30
),
"Late September 2019": datetime(2019, 9, 15),
"September 20, 2019 and continuing through December 2019": datetime(
2019, 9, 20
),
"August 30, 2019 through December 31, 2019": datetime(2019, 8, 30),
"April 22, 2019, May 4, 2019, and August 7, 2019": datetime(2019, 4, 22),
"March 3, 2019, March 11, 2019,": datetime(2019, 3, 3),
"June 15, 2018, July 6, 2018, August 3, 2018": datetime(2018, 6, 15),
}
def transform_date(self, value: str) -> typing.Optional[str]:
"""Transform a raw date string into a date object.
Args:
value (str): The raw date string provided by the source
Returns: A date object ready for consolidation. Or, if the date string is invalid, a None.
"""
try:
return super().transform_date(value)
except Exception:
value = value.strip().split(" and ")[0].strip()
value = value.strip().split(" to ")[0].strip()
value = value.strip().split(" through ")[0].strip()
value = value.strip().split(" & ")[0].strip()
return super().transform_date(value)
| import typing
from datetime import datetime
from ..schema import BaseTransformer
class Transformer(BaseTransformer):
"""Transform Tennessee raw data for consolidation."""
postal_code = "TN"
fields = dict(
company="Company",
location=lambda row: row["City"] or f"{row['County']} County",
notice_date="Notice Date",
effective_date="Effective Date",
jobs="No. Of Employees",
)
date_format = (
"%Y/%m/%d",
"%m/%d/%Y",
"%B %d, %Y",
"%B %Y",
"%B%d, %Y",
"%B %d. %Y",
"%B %d,%Y",
)
date_corrections = {
"2018/4/ 27": datetime(2018, 4, 27),
"start of layoff -\xa0March 13, 2020": datetime(2020, 3, 13),
"December 15-30, 2020": datetime(2020, 12, 15),
"June 17 - June 30, 2020": datetime(2020, 6, 17),
"124": None,
"March 16, 2020 - June 30, 2020": datetime(2020, 3, 16),
"March 20-24, 2020": datetime(2020, 3, 20),
"March 4, 2020 - June 4, 2020": datetime(2020, 3, 4),
"Apri 1, 2020": datetime(2020, 4, 1),
"Beginning April 14 and ending June 30, 2020": datetime(2020, 4, 14),
"Beginning February 16 and ending February 29, 2020": datetime(2020, 2, 16),
"Beginning March 17 and ending March 30, 2020": datetime(2020, 3, 17),
"Beginning in February 2020": datetime(2020, 2, 1),
"beginning February 2020": datetime(2020, 2, 1),
"January 3, 2020 through January 31, 2020": datetime(2020, 1, 3),
"December 13, 2019 and continue until February 28, 2020": datetime(
2019, 12, 13
),
"December 1, 2019 until December 31, 2019": datetime(2019, 12, 1),
"Will begin on November 30, 2019 and will continue to December 31, 2020": datetime(
2019, 11, 30
),
"Will begin on October 7, 2019 and will continue to November 30, 2019": datetime(
2019, 10, 7
),
"Initial layoff September 4, 2019 with additional layoffs planned September 13 and September 20": datetime(
2019, 9, 4
),
"November 9 through November 23, 2019": datetime(2019, 11, 23),
"September 30, 2019 for 4 employees and October 31, 2019 for 174 employees": datetime(
2019, 9, 30
),
"Late September 2019": datetime(2019, 9, 15),
"September 20, 2019 and continuing through December 2019": datetime(
2019, 9, 20
),
"August 30, 2019 through December 31, 2019": datetime(2019, 8, 30),
"April 22, 2019, May 4, 2019, and August 7, 2019": datetime(2019, 4, 22),
"March 3, 2019, March 11, 2019,": datetime(2019, 3, 3),
"June 15, 2018, July 6, 2018, August 3, 2018": datetime(2018, 6, 15),
}
def transform_date(self, value: str) -> typing.Optional[str]:
"""Transform a raw date string into a date object.
Args:
value (str): The raw date string provided by the source
Returns: A date object ready for consolidation. Or, if the date string is invalid, a None.
"""
try:
return super().transform_date(value)
except Exception:
value = value.strip().split(" and ")[0].strip()
value = value.strip().split(" to ")[0].strip()
value = value.strip().split(" through ")[0].strip()
value = value.strip().split(" & ")[0].strip()
return super().transform_date(value)
|
from collections import defaultdict
import itertools
import logging
import typing
from typing import Any, Dict, Hashable, List, Optional, Set, Text, Tuple, Type, Iterable
import rasa.utils.train_utils
from rasa.exceptions import MissingDependencyException
from rasa.nlu.constants import COMPONENT_INDEX
from rasa.shared.exceptions import RasaException
from rasa.shared.nlu.constants import TRAINABLE_EXTRACTORS
from rasa.shared.constants import DOCS_URL_COMPONENTS
from rasa.nlu.config import RasaNLUModelConfig
from rasa.shared.exceptions import InvalidConfigException
from rasa.shared.nlu.training_data.training_data import TrainingData
from rasa.shared.nlu.training_data.message import Message
import rasa.shared.utils.io
if typing.TYPE_CHECKING:
from rasa.nlu.model import Metadata
logger = logging.getLogger(__name__)
def find_unavailable_packages(package_names: List[Text]) -> Set[Text]:
"""Tries to import all package names and returns the packages where it failed.
Args:
package_names: The package names to import.
Returns:
Package names that could not be imported.
"""
import importlib
failed_imports = set()
for package in package_names:
try:
importlib.import_module(package)
except ImportError:
failed_imports.add(package)
return failed_imports
def validate_requirements(component_names: List[Optional[Text]]) -> None:
"""Validates that all required importable python packages are installed.
Raises:
InvalidConfigException: If one of the component names is `None`, likely
indicates that a custom implementation is missing this property
or that there is an invalid configuration file that we did not
catch earlier.
Args:
component_names: The list of component names.
"""
from rasa.nlu import registry
# Validate that all required packages are installed
failed_imports = {}
for component_name in component_names:
if component_name is None:
raise InvalidConfigException(
"Your pipeline configuration contains a component that is missing "
"a name. Please double check your configuration or if this is a "
"custom component make sure to implement the name property for "
"the component."
)
component_class = registry.get_component_class(component_name)
unavailable_packages = find_unavailable_packages(
component_class.required_packages()
)
if unavailable_packages:
failed_imports[component_name] = unavailable_packages
if failed_imports: # pragma: no cover
dependency_component_map = defaultdict(list)
for component, missing_dependencies in failed_imports.items():
for dependency in missing_dependencies:
dependency_component_map[dependency].append(component)
missing_lines = [
f"{d} (needed for {", ".join(cs)})"
for d, cs in dependency_component_map.items()
]
missing = "\n - ".join(missing_lines)
raise MissingDependencyException(
f"Not all required importable packages are installed to use "
f"the configured NLU pipeline. "
f"To use this pipeline, you need to install the "
f"missing modules: \n"
f" - {missing}\n"
f"Please install the packages that contain the missing modules."
)
def validate_component_keys(
component: "Component", component_config: Dict[Text, Any]
) -> None:
"""Validates that all keys for a component are valid.
Args:
component: The component class
component_config: The user-provided config for the component in the pipeline
"""
component_name = component_config.get("name")
allowed_keys = set(component.defaults.keys())
provided_keys = set(component_config.keys())
provided_keys.discard("name")
list_separator = "\n- "
for key in provided_keys:
if key not in allowed_keys:
rasa.shared.utils.io.raise_warning(
f"You have provided an invalid key `{key}` "
f"for component `{component_name}` in your pipeline. "
f"Valid options for `{component_name}` are:\n- "
f"{list_separator.join(allowed_keys)}"
)
def validate_empty_pipeline(pipeline: List["Component"]) -> None:
"""Ensures the pipeline is not empty.
Args:
pipeline: the list of the :class:`rasa.nlu.components.Component`.
"""
if len(pipeline) == 0:
raise InvalidConfigException(
"Can not train an empty pipeline. "
"Make sure to specify a proper pipeline in "
"the configuration using the 'pipeline' key."
)
def validate_only_one_tokenizer_is_used(pipeline: List["Component"]) -> None:
"""Validates that only one tokenizer is present in the pipeline.
Args:
pipeline: the list of the :class:`rasa.nlu.components.Component`.
"""
from rasa.nlu.tokenizers.tokenizer import Tokenizer
tokenizer_names = []
for component in pipeline:
if isinstance(component, Tokenizer):
tokenizer_names.append(component.name)
if len(tokenizer_names) > 1:
raise InvalidConfigException(
f"The pipeline configuration contains more than one tokenizer, "
f"which is not possible at this time. You can only use one tokenizer. "
f"The pipeline contains the following tokenizers: {tokenizer_names}. "
)
def _required_component_in_pipeline(
required_component: Type["Component"], pipeline: List["Component"]
) -> bool:
"""Checks that required component present in the pipeline.
Args:
required_component: A class name of the required component.
pipeline: The list of the :class:`rasa.nlu.components.Component`.
Returns:
`True` if required_component is in the pipeline, `False` otherwise.
"""
for previous_component in pipeline:
if isinstance(previous_component, required_component):
return True
return False
def validate_required_components(pipeline: List["Component"]) -> None:
"""Validates that all required components are present in the pipeline.
Args:
pipeline: The list of the :class:`rasa.nlu.components.Component`.
"""
for i, component in enumerate(pipeline):
missing_components = []
for required_component in component.required_components():
if not _required_component_in_pipeline(required_component, pipeline[:i]):
missing_components.append(required_component.name)
missing_components_str = ", ".join(f"'{c}'" for c in missing_components)
if missing_components:
raise InvalidConfigException(
f"The pipeline configuration contains errors. The component "
f"'{component.name}' requires {missing_components_str} to be "
f"placed before it in the pipeline. Please "
f"add the required components to the pipeline."
)
def validate_pipeline(pipeline: List["Component"]) -> None:
"""Validates the pipeline.
Args:
pipeline: The list of the :class:`rasa.nlu.components.Component`.
"""
validate_empty_pipeline(pipeline)
validate_only_one_tokenizer_is_used(pipeline)
validate_required_components(pipeline)
def any_components_in_pipeline(
components: Iterable[Text], pipeline: List["Component"]
) -> bool:
"""Check if any of the provided components are listed in the pipeline.
Args:
components: Component class names to check.
pipeline: A list of :class:`rasa.nlu.components.Component`s.
Returns:
`True` if any of the `components` are in the `pipeline`, else `False`.
"""
return len(find_components_in_pipeline(components, pipeline)) > 0
def find_components_in_pipeline(
components: Iterable[Text], pipeline: List["Component"]
) -> Set[Text]:
"""Finds those of the given components that are present in the pipeline.
Args:
components: A list of str of component class names to check.
pipeline: A list of :class:`rasa.nlu.components.Component`s.
Returns:
A list of str of component class names that are present in the pipeline.
"""
pipeline_component_names = {c.name for c in pipeline}
return pipeline_component_names.intersection(components)
def validate_required_components_from_data(
pipeline: List["Component"], data: TrainingData
) -> None:
"""Validates that all components are present in the pipeline based on data.
Args:
pipeline: The list of the :class:`rasa.nlu.components.Component`s.
data: The :class:`rasa.shared.nlu.training_data.training_data.TrainingData`.
"""
if data.response_examples and not any_components_in_pipeline(
["ResponseSelector"], pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined training data with examples for training a response "
"selector, but your NLU pipeline does not include a response selector "
"component. To train a model on your response selector data, add a "
"'ResponseSelector' to your pipeline."
)
if data.entity_examples and not any_components_in_pipeline(
TRAINABLE_EXTRACTORS, pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined training data consisting of entity examples, but "
"your NLU pipeline does not include an entity extractor trained on "
"your training data. To extract non-pretrained entities, add one of "
f"{TRAINABLE_EXTRACTORS} to your pipeline."
)
if data.entity_examples and not any_components_in_pipeline(
{"DIETClassifier", "CRFEntityExtractor"}, pipeline
):
if data.entity_roles_groups_used():
rasa.shared.utils.io.raise_warning(
"You have defined training data with entities that have roles/groups, "
"but your NLU pipeline does not include a 'DIETClassifier' or a "
"'CRFEntityExtractor'. To train entities that have roles/groups, "
"add either 'DIETClassifier' or 'CRFEntityExtractor' to your "
"pipeline."
)
if data.regex_features and not any_components_in_pipeline(
["RegexFeaturizer", "RegexEntityExtractor"], pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined training data with regexes, but "
"your NLU pipeline does not include a 'RegexFeaturizer' or a "
"'RegexEntityExtractor'. To use regexes, include either a "
"'RegexFeaturizer' or a 'RegexEntityExtractor' in your pipeline."
)
if data.lookup_tables and not any_components_in_pipeline(
["RegexFeaturizer", "RegexEntityExtractor"], pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined training data consisting of lookup tables, but "
"your NLU pipeline does not include a 'RegexFeaturizer' or a "
"'RegexEntityExtractor'. To use lookup tables, include either a "
"'RegexFeaturizer' or a 'RegexEntityExtractor' in your pipeline."
)
if data.lookup_tables:
if not any_components_in_pipeline(
["CRFEntityExtractor", "DIETClassifier"], pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined training data consisting of lookup tables, but "
"your NLU pipeline does not include any components that use these "
"features. To make use of lookup tables, add a 'DIETClassifier' or a "
"'CRFEntityExtractor' with the 'pattern' feature to your pipeline."
)
elif any_components_in_pipeline(["CRFEntityExtractor"], pipeline):
crf_components = [c for c in pipeline if c.name == "CRFEntityExtractor"]
# check to see if any of the possible CRFEntityExtractors will
# featurize `pattern`
has_pattern_feature = False
for crf in crf_components:
crf_features = crf.component_config.get("features")
# iterate through [[before],[word],[after]] features
has_pattern_feature = "pattern" in itertools.chain(*crf_features)
if not has_pattern_feature:
rasa.shared.utils.io.raise_warning(
"You have defined training data consisting of lookup tables, but "
"your NLU pipeline's 'CRFEntityExtractor' does not include the "
"'pattern' feature. To featurize lookup tables, add the 'pattern' "
"feature to the 'CRFEntityExtractor' in your pipeline."
)
if data.entity_synonyms and not any_components_in_pipeline(
["EntitySynonymMapper"], pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined synonyms in your training data, but "
"your NLU pipeline does not include an 'EntitySynonymMapper'. "
"To map synonyms, add an 'EntitySynonymMapper' to your pipeline."
)
def warn_of_competing_extractors(pipeline: List["Component"]) -> None:
"""Warns the user when using competing extractors.
Competing extractors are e.g. `CRFEntityExtractor` and `DIETClassifier`.
Both of these look for the same entities based on the same training data
leading to ambiguity in the results.
Args:
pipeline: The list of the :class:`rasa.nlu.components.Component`s.
"""
extractors_in_pipeline = find_components_in_pipeline(TRAINABLE_EXTRACTORS, pipeline)
if len(extractors_in_pipeline) > 1:
rasa.shared.utils.io.raise_warning(
f"You have defined multiple entity extractors that do the same job "
f"in your pipeline: "
f"{", ".join(extractors_in_pipeline)}. "
f"This can lead to the same entity getting "
f"extracted multiple times. Please read the documentation section "
f"on entity extractors to make sure you understand the implications: "
f"{DOCS_URL_COMPONENTS}#entity-extractors"
)
def warn_of_competition_with_regex_extractor(
pipeline: List["Component"], data: TrainingData
) -> None:
"""Warns when regex entity extractor is competing with a general one.
This might be the case when the following conditions are all met:
* You are using a general entity extractor and the `RegexEntityExtractor`
* AND you have regex patterns for entity type A
* AND you have annotated text examples for entity type A
Args:
pipeline: The list of the :class:`rasa.nlu.components.Component`s.
data: The :class:`rasa.shared.nlu.training_data.training_data.TrainingData`.
"""
present_general_extractors = find_components_in_pipeline(
TRAINABLE_EXTRACTORS, pipeline
)
has_general_extractors = len(present_general_extractors) > 0
has_regex_extractor = any_components_in_pipeline(["RegexEntityExtractor"], pipeline)
regex_entity_types = {rf["name"] for rf in data.regex_features}
overlap_between_types = data.entities.intersection(regex_entity_types)
has_overlap = len(overlap_between_types) > 0
if has_general_extractors and has_regex_extractor and has_overlap:
rasa.shared.utils.io.raise_warning(
f"You have an overlap between the RegexEntityExtractor and the "
f"statistical entity extractors {", ".join(present_general_extractors)} "
f"in your pipeline. Specifically both types of extractors will "
f"attempt to extract entities of the types "
f"{", ".join(overlap_between_types)}. This can lead to multiple "
f"extraction of entities. Please read RegexEntityExtractor's "
f"documentation section to make sure you understand the "
f"implications: {DOCS_URL_COMPONENTS}#regexentityextractor"
)
class MissingArgumentError(ValueError):
"""Raised when not all parameters can be filled from the context / config.
Attributes:
message -- explanation of which parameter is missing
"""
def __init__(self, message: Text) -> None:
super().__init__(message)
self.message = message
def __str__(self) -> Text:
return self.message
class UnsupportedLanguageError(RasaException):
"""Raised when a component is created but the language is not supported.
Attributes:
component -- component name
language -- language that component doesn't support
"""
def __init__(self, component: Text, language: Text) -> None:
self.component = component
self.language = language
super().__init__(component, language)
def __str__(self) -> Text:
return (
f"component '{self.component}' does not support language '{self.language}'."
)
class ComponentMetaclass(type):
"""Metaclass with `name` class property."""
@property
def name(cls) -> Text:
"""The name property is a function of the class - its __name__."""
return cls.__name__
class Component(metaclass=ComponentMetaclass):
"""A component is a message processing unit in a pipeline.
Components are collected sequentially in a pipeline. Each component
is called one after another. This holds for
initialization, training, persisting and loading the components.
If a component comes first in a pipeline, its
methods will be called first.
E.g. to process an incoming message, the ``process`` method of
each component will be called. During the processing
(as well as the training, persisting and initialization)
components can pass information to other components.
The information is passed to other components by providing
attributes to the so called pipeline context. The
pipeline context contains all the information of the previous
components a component can use to do its own
processing. For example, a featurizer component can provide
features that are used by another component down
the pipeline to do intent classification.
"""
@property
def name(self) -> Text:
"""Returns the name of the component to be used in the model configuration.
Component class name is used when integrating it in a
pipeline. E.g. `[ComponentA, ComponentB]`
will be a proper pipeline definition where `ComponentA`
is the name of the first component of the pipeline.
"""
# cast due to https://github.com/python/mypy/issues/7945
return typing.cast(str, type(self).name)
@property
def unique_name(self) -> Text:
"""Gets a unique name for the component in the pipeline.
The unique name can be used to distinguish components in
a pipeline, e.g. when the pipeline contains multiple
featurizers of the same type.
"""
index = self.component_config.get(COMPONENT_INDEX)
return self.name if index is None else f"component_{index}_{self.name}"
@classmethod
def required_components(cls) -> List[Type["Component"]]:
"""Specifies which components need to be present in the pipeline.
Which components are required by this component.
Listed components should appear before the component itself in the pipeline.
Returns:
The class names of the required components.
"""
return []
# Defines the default configuration parameters of a component
# these values can be overwritten in the pipeline configuration
# of the model. The component should choose sensible defaults
# and should be able to create reasonable results with the defaults.
defaults = {}
# Defines what language(s) this component can handle.
# This attribute is designed for instance method: `can_handle_language`.
# Default value is None. if both `support_language_list` and
# `not_supported_language_list` are None, it means it can handle
# all languages. Also, only one of `support_language_list` and
# `not_supported_language_list` can be set to not None.
# This is an important feature for backwards compatibility of components.
supported_language_list = None
# Defines what language(s) this component can NOT handle.
# This attribute is designed for instance method: `can_handle_language`.
# Default value is None. if both `support_language_list` and
# `not_supported_language_list` are None, it means it can handle
# all languages. Also, only one of `support_language_list` and
# `not_supported_language_list` can be set to not None.
# This is an important feature for backwards compatibility of components.
not_supported_language_list = None
def __init__(self, component_config: Optional[Dict[Text, Any]] = None) -> None:
if not component_config:
component_config = {}
# makes sure the name of the configuration is part of the config
# this is important for e.g. persistence
component_config["name"] = self.name
self.component_config: Dict[
Text, Any
] = rasa.utils.train_utils.override_defaults(self.defaults, component_config)
self.partial_processing_pipeline = None
self.partial_processing_context = None
@classmethod
def required_packages(cls) -> List[Text]:
"""Specifies which python packages need to be installed.
E.g. ``["spacy"]``. More specifically, these should be
importable python package names e.g. `sklearn` and not package
names in the dependencies sense e.g. `scikit-learn`
This list of requirements allows us to fail early during training
if a required package is not installed.
Returns:
The list of required package names.
"""
return []
@classmethod
def load(
cls,
meta: Dict[Text, Any],
model_dir: Text,
model_metadata: Optional["Metadata"] = None,
cached_component: Optional["Component"] = None,
**kwargs: Any,
) -> "Component":
"""Loads this component from file.
After a component has been trained, it will be persisted by
calling `persist`. When the pipeline gets loaded again,
this component needs to be able to restore itself.
Components can rely on any context attributes that are
created by :meth:`components.Component.create`
calls to components previous to this one.
Args:
meta: Any configuration parameter related to the model.
model_dir: The directory to load the component from.
model_metadata: The model's :class:`rasa.nlu.model.Metadata`.
cached_component: The cached component.
Returns:
the loaded component
"""
if cached_component:
return cached_component
return cls(meta)
@classmethod
def create(
cls, component_config: Dict[Text, Any], config: RasaNLUModelConfig
) -> "Component":
"""Creates this component (e.g. before a training is started).
Method can access all configuration parameters.
Args:
component_config: The components configuration parameters.
config: The model configuration parameters.
Returns:
The created component.
"""
# Check language supporting
language = config.language
if not cls.can_handle_language(language):
# check failed
raise UnsupportedLanguageError(cls.name, language)
return cls(component_config)
def provide_context(self) -> Optional[Dict[Text, Any]]:
"""Initializes this component for a new pipeline.
This function will be called before the training
is started and before the first message is processed using
the interpreter. The component gets the opportunity to
add information to the context that is passed through
the pipeline during training and message parsing. Most
components do not need to implement this method.
It's mostly used to initialize framework environments
like MITIE and spacy
(e.g. loading word vectors for the pipeline).
Returns:
The updated component configuration.
"""
pass
def train(
self,
training_data: TrainingData,
config: Optional[RasaNLUModelConfig] = None,
**kwargs: Any,
) -> None:
"""Trains this component.
This is the components chance to train itself provided
with the training data. The component can rely on
any context attribute to be present, that gets created
by a call to :meth:`rasa.nlu.components.Component.create`
of ANY component and
on any context attributes created by a call to
:meth:`rasa.nlu.components.Component.train`
of components previous to this one.
Args:
training_data: The
:class:`rasa.shared.nlu.training_data.training_data.TrainingData`.
config: The model configuration parameters.
"""
pass
def process(self, message: Message, **kwargs: Any) -> None:
"""Processes an incoming message.
This is the components chance to process an incoming
message. The component can rely on
any context attribute to be present, that gets created
by a call to :meth:`rasa.nlu.components.Component.create`
of ANY component and
on any context attributes created by a call to
:meth:`rasa.nlu.components.Component.process`
of components previous to this one.
Args:
message: The :class:`rasa.shared.nlu.training_data.message.Message` to
process.
"""
pass
def persist(self, file_name: Text, model_dir: Text) -> Optional[Dict[Text, Any]]:
"""Persists this component to disk for future loading.
Args:
file_name: The file name of the model.
model_dir: The directory to store the model to.
Returns:
An optional dictionary with any information about the stored model.
"""
pass
@classmethod
def cache_key(
cls, component_meta: Dict[Text, Any], model_metadata: "Metadata"
) -> Optional[Text]:
"""This key is used to cache components.
If a component is unique to a model it should return None.
Otherwise, an instantiation of the
component will be reused for all models where the
metadata creates the same key.
Args:
component_meta: The component configuration.
model_metadata: The component's :class:`rasa.nlu.model.Metadata`.
Returns:
A unique caching key.
"""
return None
def __getstate__(self) -> Any:
"""Gets a copy of picklable parts of the component."""
d = self.__dict__.copy()
# these properties should not be pickled
if "partial_processing_context" in d:
del d["partial_processing_context"]
if "partial_processing_pipeline" in d:
del d["partial_processing_pipeline"]
return d
def __eq__(self, other: Any) -> bool:
return self.__dict__ == other.__dict__
def prepare_partial_processing(
self, pipeline: List["Component"], context: Dict[Text, Any]
) -> None:
"""Sets the pipeline and context used for partial processing.
The pipeline should be a list of components that are
previous to this one in the pipeline and
have already finished their training (and can therefore
be safely used to process messages).
Args:
pipeline: The list of components.
context: The context of processing.
"""
self.partial_processing_pipeline = pipeline
self.partial_processing_context = context
def partially_process(self, message: Message) -> Message:
"""Allows the component to process messages during
training (e.g. external training data).
The passed message will be processed by all components
previous to this one in the pipeline.
Args:
message: The :class:`rasa.shared.nlu.training_data.message.Message` to
process.
Returns:
The processed :class:`rasa.shared.nlu.training_data.message.Message`.
"""
if self.partial_processing_context is not None:
for component in self.partial_processing_pipeline:
component.process(message, **self.partial_processing_context)
else:
logger.info("Failed to run partial processing due to missing pipeline.")
return message
@classmethod
def can_handle_language(cls, language: Hashable) -> bool:
"""Check if component supports a specific language.
This method can be overwritten when needed. (e.g. dynamically
determine which language is supported.)
Args:
language: The language to check.
Returns:
`True` if component can handle specific language, `False` otherwise.
"""
# If both `supported_language_list` and `not_supported_language_list` are set
# to `None`,
# it means: support all languages
if language is None or (
cls.supported_language_list is None
and cls.not_supported_language_list is None
):
return True
# check language supporting settings
if cls.supported_language_list and cls.not_supported_language_list:
# When user set both language supporting settings to not None, it will lead
# to ambiguity.
raise RasaException(
"Only one of `supported_language_list` and"
"`not_supported_language_list` can be set to not None"
)
# convert to `list` for membership test
supported_language_list = (
cls.supported_language_list
if cls.supported_language_list is not None
else []
)
not_supported_language_list = (
cls.not_supported_language_list
if cls.not_supported_language_list is not None
else []
)
# check if user provided a valid setting
if not supported_language_list and not not_supported_language_list:
# One of language settings must be valid (not None and not a empty list),
# There are three combinations of settings are not valid:
# (None, []), ([], None) and ([], [])
raise RasaException(
"Empty lists for both "
"`supported_language_list` and `not_supported language_list` "
"is not a valid setting. If you meant to allow all languages "
"for the component use `None` for both of them."
)
if supported_language_list:
return language in supported_language_list
else:
return language not in not_supported_language_list
class ComponentBuilder:
"""Creates trainers and interpreters based on configurations.
Caches components for reuse.
"""
def __init__(self, use_cache: bool = True) -> None:
self.use_cache = use_cache
# Reuse nlp and featurizers where possible to save memory,
# every component that implements a cache-key will be cached
self.component_cache = {}
def __get_cached_component(
self, component_meta: Dict[Text, Any], model_metadata: "Metadata"
) -> Tuple[Optional[Component], Optional[Text]]:
"""Load a component from the cache, if it exists.
Returns the component, if found, and the cache key.
"""
from rasa.nlu import registry
# try to get class name first, else create by name
component_name = component_meta.get("class", component_meta["name"])
component_class = registry.get_component_class(component_name)
cache_key = component_class.cache_key(component_meta, model_metadata)
if (
cache_key is not None
and self.use_cache
and cache_key in self.component_cache
):
return self.component_cache[cache_key], cache_key
return None, cache_key
def __add_to_cache(self, component: Component, cache_key: Optional[Text]) -> None:
"""Add a component to the cache."""
if cache_key is not None and self.use_cache:
self.component_cache[cache_key] = component
logger.info(
f"Added '{component.name}' to component cache. Key '{cache_key}'."
)
def load_component(
self,
component_meta: Dict[Text, Any],
model_dir: Text,
model_metadata: "Metadata",
**context: Any,
) -> Optional[Component]:
"""Loads a component.
Tries to retrieve a component from the cache, else calls
``load`` to create a new component.
Args:
component_meta:
The metadata of the component to load in the pipeline.
model_dir:
The directory to read the model from.
model_metadata (Metadata):
The model's :class:`rasa.nlu.model.Metadata`.
Returns:
The loaded component.
"""
from rasa.nlu import registry
try:
cached_component, cache_key = self.__get_cached_component(
component_meta, model_metadata
)
component = registry.load_component_by_meta(
component_meta, model_dir, model_metadata, cached_component, **context
)
if not cached_component:
# If the component wasn't in the cache,
# let us add it if possible
self.__add_to_cache(component, cache_key)
return component
except MissingArgumentError as e: # pragma: no cover
raise RasaException(
f"Failed to load component from file '{component_meta.get("file")}'. "
f"Error: {e}"
)
def create_component(
self, component_config: Dict[Text, Any], cfg: RasaNLUModelConfig
) -> Component:
"""Creates a component.
Tries to retrieve a component from the cache,
calls `create` to create a new component.
Args:
component_config: The component configuration.
cfg: The model configuration.
Returns:
The created component.
"""
from rasa.nlu import registry
from rasa.nlu.model import Metadata
try:
component, cache_key = self.__get_cached_component(
component_config, Metadata(cfg.as_dict())
)
if component is None:
component = registry.create_component_by_config(component_config, cfg)
self.__add_to_cache(component, cache_key)
return component
except MissingArgumentError as e: # pragma: no cover
raise RasaException(
f"Failed to create component '{component_config["name"]}'. "
f"Error: {e}"
)
| from collections import defaultdict
import itertools
import logging
import typing
from typing import Any, Dict, Hashable, List, Optional, Set, Text, Tuple, Type, Iterable
import rasa.utils.train_utils
from rasa.exceptions import MissingDependencyException
from rasa.nlu.constants import COMPONENT_INDEX
from rasa.shared.exceptions import RasaException
from rasa.shared.nlu.constants import TRAINABLE_EXTRACTORS
from rasa.shared.constants import DOCS_URL_COMPONENTS
from rasa.nlu.config import RasaNLUModelConfig
from rasa.shared.exceptions import InvalidConfigException
from rasa.shared.nlu.training_data.training_data import TrainingData
from rasa.shared.nlu.training_data.message import Message
import rasa.shared.utils.io
if typing.TYPE_CHECKING:
from rasa.nlu.model import Metadata
logger = logging.getLogger(__name__)
def find_unavailable_packages(package_names: List[Text]) -> Set[Text]:
"""Tries to import all package names and returns the packages where it failed.
Args:
package_names: The package names to import.
Returns:
Package names that could not be imported.
"""
import importlib
failed_imports = set()
for package in package_names:
try:
importlib.import_module(package)
except ImportError:
failed_imports.add(package)
return failed_imports
def validate_requirements(component_names: List[Optional[Text]]) -> None:
"""Validates that all required importable python packages are installed.
Raises:
InvalidConfigException: If one of the component names is `None`, likely
indicates that a custom implementation is missing this property
or that there is an invalid configuration file that we did not
catch earlier.
Args:
component_names: The list of component names.
"""
from rasa.nlu import registry
# Validate that all required packages are installed
failed_imports = {}
for component_name in component_names:
if component_name is None:
raise InvalidConfigException(
"Your pipeline configuration contains a component that is missing "
"a name. Please double check your configuration or if this is a "
"custom component make sure to implement the name property for "
"the component."
)
component_class = registry.get_component_class(component_name)
unavailable_packages = find_unavailable_packages(
component_class.required_packages()
)
if unavailable_packages:
failed_imports[component_name] = unavailable_packages
if failed_imports: # pragma: no cover
dependency_component_map = defaultdict(list)
for component, missing_dependencies in failed_imports.items():
for dependency in missing_dependencies:
dependency_component_map[dependency].append(component)
missing_lines = [
f"{d} (needed for {', '.join(cs)})"
for d, cs in dependency_component_map.items()
]
missing = "\n - ".join(missing_lines)
raise MissingDependencyException(
f"Not all required importable packages are installed to use "
f"the configured NLU pipeline. "
f"To use this pipeline, you need to install the "
f"missing modules: \n"
f" - {missing}\n"
f"Please install the packages that contain the missing modules."
)
def validate_component_keys(
component: "Component", component_config: Dict[Text, Any]
) -> None:
"""Validates that all keys for a component are valid.
Args:
component: The component class
component_config: The user-provided config for the component in the pipeline
"""
component_name = component_config.get("name")
allowed_keys = set(component.defaults.keys())
provided_keys = set(component_config.keys())
provided_keys.discard("name")
list_separator = "\n- "
for key in provided_keys:
if key not in allowed_keys:
rasa.shared.utils.io.raise_warning(
f"You have provided an invalid key `{key}` "
f"for component `{component_name}` in your pipeline. "
f"Valid options for `{component_name}` are:\n- "
f"{list_separator.join(allowed_keys)}"
)
def validate_empty_pipeline(pipeline: List["Component"]) -> None:
"""Ensures the pipeline is not empty.
Args:
pipeline: the list of the :class:`rasa.nlu.components.Component`.
"""
if len(pipeline) == 0:
raise InvalidConfigException(
"Can not train an empty pipeline. "
"Make sure to specify a proper pipeline in "
"the configuration using the 'pipeline' key."
)
def validate_only_one_tokenizer_is_used(pipeline: List["Component"]) -> None:
"""Validates that only one tokenizer is present in the pipeline.
Args:
pipeline: the list of the :class:`rasa.nlu.components.Component`.
"""
from rasa.nlu.tokenizers.tokenizer import Tokenizer
tokenizer_names = []
for component in pipeline:
if isinstance(component, Tokenizer):
tokenizer_names.append(component.name)
if len(tokenizer_names) > 1:
raise InvalidConfigException(
f"The pipeline configuration contains more than one tokenizer, "
f"which is not possible at this time. You can only use one tokenizer. "
f"The pipeline contains the following tokenizers: {tokenizer_names}. "
)
def _required_component_in_pipeline(
required_component: Type["Component"], pipeline: List["Component"]
) -> bool:
"""Checks that required component present in the pipeline.
Args:
required_component: A class name of the required component.
pipeline: The list of the :class:`rasa.nlu.components.Component`.
Returns:
`True` if required_component is in the pipeline, `False` otherwise.
"""
for previous_component in pipeline:
if isinstance(previous_component, required_component):
return True
return False
def validate_required_components(pipeline: List["Component"]) -> None:
"""Validates that all required components are present in the pipeline.
Args:
pipeline: The list of the :class:`rasa.nlu.components.Component`.
"""
for i, component in enumerate(pipeline):
missing_components = []
for required_component in component.required_components():
if not _required_component_in_pipeline(required_component, pipeline[:i]):
missing_components.append(required_component.name)
missing_components_str = ", ".join(f"'{c}'" for c in missing_components)
if missing_components:
raise InvalidConfigException(
f"The pipeline configuration contains errors. The component "
f"'{component.name}' requires {missing_components_str} to be "
f"placed before it in the pipeline. Please "
f"add the required components to the pipeline."
)
def validate_pipeline(pipeline: List["Component"]) -> None:
"""Validates the pipeline.
Args:
pipeline: The list of the :class:`rasa.nlu.components.Component`.
"""
validate_empty_pipeline(pipeline)
validate_only_one_tokenizer_is_used(pipeline)
validate_required_components(pipeline)
def any_components_in_pipeline(
components: Iterable[Text], pipeline: List["Component"]
) -> bool:
"""Check if any of the provided components are listed in the pipeline.
Args:
components: Component class names to check.
pipeline: A list of :class:`rasa.nlu.components.Component`s.
Returns:
`True` if any of the `components` are in the `pipeline`, else `False`.
"""
return len(find_components_in_pipeline(components, pipeline)) > 0
def find_components_in_pipeline(
components: Iterable[Text], pipeline: List["Component"]
) -> Set[Text]:
"""Finds those of the given components that are present in the pipeline.
Args:
components: A list of str of component class names to check.
pipeline: A list of :class:`rasa.nlu.components.Component`s.
Returns:
A list of str of component class names that are present in the pipeline.
"""
pipeline_component_names = {c.name for c in pipeline}
return pipeline_component_names.intersection(components)
def validate_required_components_from_data(
pipeline: List["Component"], data: TrainingData
) -> None:
"""Validates that all components are present in the pipeline based on data.
Args:
pipeline: The list of the :class:`rasa.nlu.components.Component`s.
data: The :class:`rasa.shared.nlu.training_data.training_data.TrainingData`.
"""
if data.response_examples and not any_components_in_pipeline(
["ResponseSelector"], pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined training data with examples for training a response "
"selector, but your NLU pipeline does not include a response selector "
"component. To train a model on your response selector data, add a "
"'ResponseSelector' to your pipeline."
)
if data.entity_examples and not any_components_in_pipeline(
TRAINABLE_EXTRACTORS, pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined training data consisting of entity examples, but "
"your NLU pipeline does not include an entity extractor trained on "
"your training data. To extract non-pretrained entities, add one of "
f"{TRAINABLE_EXTRACTORS} to your pipeline."
)
if data.entity_examples and not any_components_in_pipeline(
{"DIETClassifier", "CRFEntityExtractor"}, pipeline
):
if data.entity_roles_groups_used():
rasa.shared.utils.io.raise_warning(
"You have defined training data with entities that have roles/groups, "
"but your NLU pipeline does not include a 'DIETClassifier' or a "
"'CRFEntityExtractor'. To train entities that have roles/groups, "
"add either 'DIETClassifier' or 'CRFEntityExtractor' to your "
"pipeline."
)
if data.regex_features and not any_components_in_pipeline(
["RegexFeaturizer", "RegexEntityExtractor"], pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined training data with regexes, but "
"your NLU pipeline does not include a 'RegexFeaturizer' or a "
"'RegexEntityExtractor'. To use regexes, include either a "
"'RegexFeaturizer' or a 'RegexEntityExtractor' in your pipeline."
)
if data.lookup_tables and not any_components_in_pipeline(
["RegexFeaturizer", "RegexEntityExtractor"], pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined training data consisting of lookup tables, but "
"your NLU pipeline does not include a 'RegexFeaturizer' or a "
"'RegexEntityExtractor'. To use lookup tables, include either a "
"'RegexFeaturizer' or a 'RegexEntityExtractor' in your pipeline."
)
if data.lookup_tables:
if not any_components_in_pipeline(
["CRFEntityExtractor", "DIETClassifier"], pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined training data consisting of lookup tables, but "
"your NLU pipeline does not include any components that use these "
"features. To make use of lookup tables, add a 'DIETClassifier' or a "
"'CRFEntityExtractor' with the 'pattern' feature to your pipeline."
)
elif any_components_in_pipeline(["CRFEntityExtractor"], pipeline):
crf_components = [c for c in pipeline if c.name == "CRFEntityExtractor"]
# check to see if any of the possible CRFEntityExtractors will
# featurize `pattern`
has_pattern_feature = False
for crf in crf_components:
crf_features = crf.component_config.get("features")
# iterate through [[before],[word],[after]] features
has_pattern_feature = "pattern" in itertools.chain(*crf_features)
if not has_pattern_feature:
rasa.shared.utils.io.raise_warning(
"You have defined training data consisting of lookup tables, but "
"your NLU pipeline's 'CRFEntityExtractor' does not include the "
"'pattern' feature. To featurize lookup tables, add the 'pattern' "
"feature to the 'CRFEntityExtractor' in your pipeline."
)
if data.entity_synonyms and not any_components_in_pipeline(
["EntitySynonymMapper"], pipeline
):
rasa.shared.utils.io.raise_warning(
"You have defined synonyms in your training data, but "
"your NLU pipeline does not include an 'EntitySynonymMapper'. "
"To map synonyms, add an 'EntitySynonymMapper' to your pipeline."
)
def warn_of_competing_extractors(pipeline: List["Component"]) -> None:
"""Warns the user when using competing extractors.
Competing extractors are e.g. `CRFEntityExtractor` and `DIETClassifier`.
Both of these look for the same entities based on the same training data
leading to ambiguity in the results.
Args:
pipeline: The list of the :class:`rasa.nlu.components.Component`s.
"""
extractors_in_pipeline = find_components_in_pipeline(TRAINABLE_EXTRACTORS, pipeline)
if len(extractors_in_pipeline) > 1:
rasa.shared.utils.io.raise_warning(
f"You have defined multiple entity extractors that do the same job "
f"in your pipeline: "
f"{', '.join(extractors_in_pipeline)}. "
f"This can lead to the same entity getting "
f"extracted multiple times. Please read the documentation section "
f"on entity extractors to make sure you understand the implications: "
f"{DOCS_URL_COMPONENTS}#entity-extractors"
)
def warn_of_competition_with_regex_extractor(
pipeline: List["Component"], data: TrainingData
) -> None:
"""Warns when regex entity extractor is competing with a general one.
This might be the case when the following conditions are all met:
* You are using a general entity extractor and the `RegexEntityExtractor`
* AND you have regex patterns for entity type A
* AND you have annotated text examples for entity type A
Args:
pipeline: The list of the :class:`rasa.nlu.components.Component`s.
data: The :class:`rasa.shared.nlu.training_data.training_data.TrainingData`.
"""
present_general_extractors = find_components_in_pipeline(
TRAINABLE_EXTRACTORS, pipeline
)
has_general_extractors = len(present_general_extractors) > 0
has_regex_extractor = any_components_in_pipeline(["RegexEntityExtractor"], pipeline)
regex_entity_types = {rf["name"] for rf in data.regex_features}
overlap_between_types = data.entities.intersection(regex_entity_types)
has_overlap = len(overlap_between_types) > 0
if has_general_extractors and has_regex_extractor and has_overlap:
rasa.shared.utils.io.raise_warning(
f"You have an overlap between the RegexEntityExtractor and the "
f"statistical entity extractors {', '.join(present_general_extractors)} "
f"in your pipeline. Specifically both types of extractors will "
f"attempt to extract entities of the types "
f"{', '.join(overlap_between_types)}. This can lead to multiple "
f"extraction of entities. Please read RegexEntityExtractor's "
f"documentation section to make sure you understand the "
f"implications: {DOCS_URL_COMPONENTS}#regexentityextractor"
)
class MissingArgumentError(ValueError):
"""Raised when not all parameters can be filled from the context / config.
Attributes:
message -- explanation of which parameter is missing
"""
def __init__(self, message: Text) -> None:
super().__init__(message)
self.message = message
def __str__(self) -> Text:
return self.message
class UnsupportedLanguageError(RasaException):
"""Raised when a component is created but the language is not supported.
Attributes:
component -- component name
language -- language that component doesn't support
"""
def __init__(self, component: Text, language: Text) -> None:
self.component = component
self.language = language
super().__init__(component, language)
def __str__(self) -> Text:
return (
f"component '{self.component}' does not support language '{self.language}'."
)
class ComponentMetaclass(type):
"""Metaclass with `name` class property."""
@property
def name(cls) -> Text:
"""The name property is a function of the class - its __name__."""
return cls.__name__
class Component(metaclass=ComponentMetaclass):
"""A component is a message processing unit in a pipeline.
Components are collected sequentially in a pipeline. Each component
is called one after another. This holds for
initialization, training, persisting and loading the components.
If a component comes first in a pipeline, its
methods will be called first.
E.g. to process an incoming message, the ``process`` method of
each component will be called. During the processing
(as well as the training, persisting and initialization)
components can pass information to other components.
The information is passed to other components by providing
attributes to the so called pipeline context. The
pipeline context contains all the information of the previous
components a component can use to do its own
processing. For example, a featurizer component can provide
features that are used by another component down
the pipeline to do intent classification.
"""
@property
def name(self) -> Text:
"""Returns the name of the component to be used in the model configuration.
Component class name is used when integrating it in a
pipeline. E.g. `[ComponentA, ComponentB]`
will be a proper pipeline definition where `ComponentA`
is the name of the first component of the pipeline.
"""
# cast due to https://github.com/python/mypy/issues/7945
return typing.cast(str, type(self).name)
@property
def unique_name(self) -> Text:
"""Gets a unique name for the component in the pipeline.
The unique name can be used to distinguish components in
a pipeline, e.g. when the pipeline contains multiple
featurizers of the same type.
"""
index = self.component_config.get(COMPONENT_INDEX)
return self.name if index is None else f"component_{index}_{self.name}"
@classmethod
def required_components(cls) -> List[Type["Component"]]:
"""Specifies which components need to be present in the pipeline.
Which components are required by this component.
Listed components should appear before the component itself in the pipeline.
Returns:
The class names of the required components.
"""
return []
# Defines the default configuration parameters of a component
# these values can be overwritten in the pipeline configuration
# of the model. The component should choose sensible defaults
# and should be able to create reasonable results with the defaults.
defaults = {}
# Defines what language(s) this component can handle.
# This attribute is designed for instance method: `can_handle_language`.
# Default value is None. if both `support_language_list` and
# `not_supported_language_list` are None, it means it can handle
# all languages. Also, only one of `support_language_list` and
# `not_supported_language_list` can be set to not None.
# This is an important feature for backwards compatibility of components.
supported_language_list = None
# Defines what language(s) this component can NOT handle.
# This attribute is designed for instance method: `can_handle_language`.
# Default value is None. if both `support_language_list` and
# `not_supported_language_list` are None, it means it can handle
# all languages. Also, only one of `support_language_list` and
# `not_supported_language_list` can be set to not None.
# This is an important feature for backwards compatibility of components.
not_supported_language_list = None
def __init__(self, component_config: Optional[Dict[Text, Any]] = None) -> None:
if not component_config:
component_config = {}
# makes sure the name of the configuration is part of the config
# this is important for e.g. persistence
component_config["name"] = self.name
self.component_config: Dict[
Text, Any
] = rasa.utils.train_utils.override_defaults(self.defaults, component_config)
self.partial_processing_pipeline = None
self.partial_processing_context = None
@classmethod
def required_packages(cls) -> List[Text]:
"""Specifies which python packages need to be installed.
E.g. ``["spacy"]``. More specifically, these should be
importable python package names e.g. `sklearn` and not package
names in the dependencies sense e.g. `scikit-learn`
This list of requirements allows us to fail early during training
if a required package is not installed.
Returns:
The list of required package names.
"""
return []
@classmethod
def load(
cls,
meta: Dict[Text, Any],
model_dir: Text,
model_metadata: Optional["Metadata"] = None,
cached_component: Optional["Component"] = None,
**kwargs: Any,
) -> "Component":
"""Loads this component from file.
After a component has been trained, it will be persisted by
calling `persist`. When the pipeline gets loaded again,
this component needs to be able to restore itself.
Components can rely on any context attributes that are
created by :meth:`components.Component.create`
calls to components previous to this one.
Args:
meta: Any configuration parameter related to the model.
model_dir: The directory to load the component from.
model_metadata: The model's :class:`rasa.nlu.model.Metadata`.
cached_component: The cached component.
Returns:
the loaded component
"""
if cached_component:
return cached_component
return cls(meta)
@classmethod
def create(
cls, component_config: Dict[Text, Any], config: RasaNLUModelConfig
) -> "Component":
"""Creates this component (e.g. before a training is started).
Method can access all configuration parameters.
Args:
component_config: The components configuration parameters.
config: The model configuration parameters.
Returns:
The created component.
"""
# Check language supporting
language = config.language
if not cls.can_handle_language(language):
# check failed
raise UnsupportedLanguageError(cls.name, language)
return cls(component_config)
def provide_context(self) -> Optional[Dict[Text, Any]]:
"""Initializes this component for a new pipeline.
This function will be called before the training
is started and before the first message is processed using
the interpreter. The component gets the opportunity to
add information to the context that is passed through
the pipeline during training and message parsing. Most
components do not need to implement this method.
It's mostly used to initialize framework environments
like MITIE and spacy
(e.g. loading word vectors for the pipeline).
Returns:
The updated component configuration.
"""
pass
def train(
self,
training_data: TrainingData,
config: Optional[RasaNLUModelConfig] = None,
**kwargs: Any,
) -> None:
"""Trains this component.
This is the components chance to train itself provided
with the training data. The component can rely on
any context attribute to be present, that gets created
by a call to :meth:`rasa.nlu.components.Component.create`
of ANY component and
on any context attributes created by a call to
:meth:`rasa.nlu.components.Component.train`
of components previous to this one.
Args:
training_data: The
:class:`rasa.shared.nlu.training_data.training_data.TrainingData`.
config: The model configuration parameters.
"""
pass
def process(self, message: Message, **kwargs: Any) -> None:
"""Processes an incoming message.
This is the components chance to process an incoming
message. The component can rely on
any context attribute to be present, that gets created
by a call to :meth:`rasa.nlu.components.Component.create`
of ANY component and
on any context attributes created by a call to
:meth:`rasa.nlu.components.Component.process`
of components previous to this one.
Args:
message: The :class:`rasa.shared.nlu.training_data.message.Message` to
process.
"""
pass
def persist(self, file_name: Text, model_dir: Text) -> Optional[Dict[Text, Any]]:
"""Persists this component to disk for future loading.
Args:
file_name: The file name of the model.
model_dir: The directory to store the model to.
Returns:
An optional dictionary with any information about the stored model.
"""
pass
@classmethod
def cache_key(
cls, component_meta: Dict[Text, Any], model_metadata: "Metadata"
) -> Optional[Text]:
"""This key is used to cache components.
If a component is unique to a model it should return None.
Otherwise, an instantiation of the
component will be reused for all models where the
metadata creates the same key.
Args:
component_meta: The component configuration.
model_metadata: The component's :class:`rasa.nlu.model.Metadata`.
Returns:
A unique caching key.
"""
return None
def __getstate__(self) -> Any:
"""Gets a copy of picklable parts of the component."""
d = self.__dict__.copy()
# these properties should not be pickled
if "partial_processing_context" in d:
del d["partial_processing_context"]
if "partial_processing_pipeline" in d:
del d["partial_processing_pipeline"]
return d
def __eq__(self, other: Any) -> bool:
return self.__dict__ == other.__dict__
def prepare_partial_processing(
self, pipeline: List["Component"], context: Dict[Text, Any]
) -> None:
"""Sets the pipeline and context used for partial processing.
The pipeline should be a list of components that are
previous to this one in the pipeline and
have already finished their training (and can therefore
be safely used to process messages).
Args:
pipeline: The list of components.
context: The context of processing.
"""
self.partial_processing_pipeline = pipeline
self.partial_processing_context = context
def partially_process(self, message: Message) -> Message:
"""Allows the component to process messages during
training (e.g. external training data).
The passed message will be processed by all components
previous to this one in the pipeline.
Args:
message: The :class:`rasa.shared.nlu.training_data.message.Message` to
process.
Returns:
The processed :class:`rasa.shared.nlu.training_data.message.Message`.
"""
if self.partial_processing_context is not None:
for component in self.partial_processing_pipeline:
component.process(message, **self.partial_processing_context)
else:
logger.info("Failed to run partial processing due to missing pipeline.")
return message
@classmethod
def can_handle_language(cls, language: Hashable) -> bool:
"""Check if component supports a specific language.
This method can be overwritten when needed. (e.g. dynamically
determine which language is supported.)
Args:
language: The language to check.
Returns:
`True` if component can handle specific language, `False` otherwise.
"""
# If both `supported_language_list` and `not_supported_language_list` are set
# to `None`,
# it means: support all languages
if language is None or (
cls.supported_language_list is None
and cls.not_supported_language_list is None
):
return True
# check language supporting settings
if cls.supported_language_list and cls.not_supported_language_list:
# When user set both language supporting settings to not None, it will lead
# to ambiguity.
raise RasaException(
"Only one of `supported_language_list` and"
"`not_supported_language_list` can be set to not None"
)
# convert to `list` for membership test
supported_language_list = (
cls.supported_language_list
if cls.supported_language_list is not None
else []
)
not_supported_language_list = (
cls.not_supported_language_list
if cls.not_supported_language_list is not None
else []
)
# check if user provided a valid setting
if not supported_language_list and not not_supported_language_list:
# One of language settings must be valid (not None and not a empty list),
# There are three combinations of settings are not valid:
# (None, []), ([], None) and ([], [])
raise RasaException(
"Empty lists for both "
"`supported_language_list` and `not_supported language_list` "
"is not a valid setting. If you meant to allow all languages "
"for the component use `None` for both of them."
)
if supported_language_list:
return language in supported_language_list
else:
return language not in not_supported_language_list
class ComponentBuilder:
"""Creates trainers and interpreters based on configurations.
Caches components for reuse.
"""
def __init__(self, use_cache: bool = True) -> None:
self.use_cache = use_cache
# Reuse nlp and featurizers where possible to save memory,
# every component that implements a cache-key will be cached
self.component_cache = {}
def __get_cached_component(
self, component_meta: Dict[Text, Any], model_metadata: "Metadata"
) -> Tuple[Optional[Component], Optional[Text]]:
"""Load a component from the cache, if it exists.
Returns the component, if found, and the cache key.
"""
from rasa.nlu import registry
# try to get class name first, else create by name
component_name = component_meta.get("class", component_meta["name"])
component_class = registry.get_component_class(component_name)
cache_key = component_class.cache_key(component_meta, model_metadata)
if (
cache_key is not None
and self.use_cache
and cache_key in self.component_cache
):
return self.component_cache[cache_key], cache_key
return None, cache_key
def __add_to_cache(self, component: Component, cache_key: Optional[Text]) -> None:
"""Add a component to the cache."""
if cache_key is not None and self.use_cache:
self.component_cache[cache_key] = component
logger.info(
f"Added '{component.name}' to component cache. Key '{cache_key}'."
)
def load_component(
self,
component_meta: Dict[Text, Any],
model_dir: Text,
model_metadata: "Metadata",
**context: Any,
) -> Optional[Component]:
"""Loads a component.
Tries to retrieve a component from the cache, else calls
``load`` to create a new component.
Args:
component_meta:
The metadata of the component to load in the pipeline.
model_dir:
The directory to read the model from.
model_metadata (Metadata):
The model's :class:`rasa.nlu.model.Metadata`.
Returns:
The loaded component.
"""
from rasa.nlu import registry
try:
cached_component, cache_key = self.__get_cached_component(
component_meta, model_metadata
)
component = registry.load_component_by_meta(
component_meta, model_dir, model_metadata, cached_component, **context
)
if not cached_component:
# If the component wasn't in the cache,
# let us add it if possible
self.__add_to_cache(component, cache_key)
return component
except MissingArgumentError as e: # pragma: no cover
raise RasaException(
f"Failed to load component from file '{component_meta.get('file')}'. "
f"Error: {e}"
)
def create_component(
self, component_config: Dict[Text, Any], cfg: RasaNLUModelConfig
) -> Component:
"""Creates a component.
Tries to retrieve a component from the cache,
calls `create` to create a new component.
Args:
component_config: The component configuration.
cfg: The model configuration.
Returns:
The created component.
"""
from rasa.nlu import registry
from rasa.nlu.model import Metadata
try:
component, cache_key = self.__get_cached_component(
component_config, Metadata(cfg.as_dict())
)
if component is None:
component = registry.create_component_by_config(component_config, cfg)
self.__add_to_cache(component, cache_key)
return component
except MissingArgumentError as e: # pragma: no cover
raise RasaException(
f"Failed to create component '{component_config['name']}'. "
f"Error: {e}"
)
|
# pip install cassandra-driver
from cassandra import AlreadyExists
from cassandra.cluster import Cluster
class CassandraWrapper:
def __init__(self, keyspace='lambda'):
self.cluster = Cluster(['127.0.0.1'], port=9042)
self.keyspace = keyspace
self._setup_db() # Create the keyspace
self.session = self.cluster.connect('lambda', wait_for_all_pools=True)
def execute(self, query):
return self.session.execute(query)
def _setup_db(self):
self.session = self.cluster.connect('', wait_for_all_pools=True)
self._execute_silently(
f"create keyspace {self.keyspace} WITH replication = {{"class":"SimpleStrategy", "replication_factor" : 3}};")
self.execute(f"USE {self.keyspace}")
self._execute_silently(
"create table emails ( id TEXT PRIMARY KEY, sender TEXT, receiver TEXT, timestamp TIMESTAMP, subject TEXT, body TEXT);")
def _execute_silently(self, query):
try:
self.execute(query)
except AlreadyExists:
# Silent error
pass
if __name__ == "__main__":
# Test Singleton
cassandra = CassandraWrapper()
cassandra2 = CassandraWrapper()
assert cassandra is cassandra2
| # pip install cassandra-driver
from cassandra import AlreadyExists
from cassandra.cluster import Cluster
class CassandraWrapper:
def __init__(self, keyspace='lambda'):
self.cluster = Cluster(['127.0.0.1'], port=9042)
self.keyspace = keyspace
self._setup_db() # Create the keyspace
self.session = self.cluster.connect('lambda', wait_for_all_pools=True)
def execute(self, query):
return self.session.execute(query)
def _setup_db(self):
self.session = self.cluster.connect('', wait_for_all_pools=True)
self._execute_silently(
f"create keyspace {self.keyspace} WITH replication = {{'class':'SimpleStrategy', 'replication_factor' : 3}};")
self.execute(f"USE {self.keyspace}")
self._execute_silently(
"create table emails ( id TEXT PRIMARY KEY, sender TEXT, receiver TEXT, timestamp TIMESTAMP, subject TEXT, body TEXT);")
def _execute_silently(self, query):
try:
self.execute(query)
except AlreadyExists:
# Silent error
pass
if __name__ == "__main__":
# Test Singleton
cassandra = CassandraWrapper()
cassandra2 = CassandraWrapper()
assert cassandra is cassandra2
|
from marathon import MarathonClient, MarathonHttpError
from zappa.async import task
import os
import requests
import time
import yaml
dcos_username = os.environ['DCOS_USERNAME']
dcos_password = os.environ['DCOS_PASSWORD']
config = yaml.load(open('config.yaml'))
headers = {'Content-Type': 'application/json'}
payload = '{"uid":"' + dcos_username + '", "password":"' + dcos_password + '"}'
def conn(environment):
'''
DC/OS Auth for the API is a pain. The best I can do for now is
send a POST to the ACS endpoint with username and password to fetch
a temporary JWT.
'''
marathon_url = config['dcos']['endpoints'][environment] + "/service/marathon"
auth_api_url = config['dcos']['endpoints'][environment] + "/acs/api/v1/auth/login"
r = requests.post(auth_api_url, headers=headers, data=payload)
c = MarathonClient(marathon_url, auth_token=r.json()['token'])
return c
def status(service, environment):
mc = conn(environment)
try:
service_data = mc.get_app(service)
if service_data.instances == service_data.tasks_healthy and not service_data.tasks_unhealthy:
append_msg = "Everything looks alright! :rocket:"
else:
append_msg = "Something doesn't look right... :skull_and_crossbones:"
message = (f"*{service}* is running `{service_data.container.docker.image.split(":")[1]}`. "
f"It has `{str(service_data.instances)}` instances, `{str(service_data.tasks_healthy)}` out of which are reporting to be healthy. "
f"Each of them has `{str(service_data.cpus)}` cpus and `{str(service_data.mem)}` mem. {append_msg}"
)
except MarathonHttpError as err:
message = f"I had a short circuit while processing your request. Are you sure *{service}* is the correct full ID? :zap:"
return message
@task
def restart(service, environment, response_url):
'''
This one runs as an asynchronous job as noted by the @task annotation,
as sometimes it takes a bit longer.
'''
mc = conn(environment)
try:
mc.restart_app(service, force=True)
message = f"*{service}* is now restarting on *{environment}*!"
except MarathonHttpError as err:
message = f"I had a short circuit while processing your request. Are you sure *{service}* is the correct full ID? :zap:"
data = {
'response_type': 'in_channel',
'text': message,
}
requests.post(response_url, json=data)
| from marathon import MarathonClient, MarathonHttpError
from zappa.async import task
import os
import requests
import time
import yaml
dcos_username = os.environ['DCOS_USERNAME']
dcos_password = os.environ['DCOS_PASSWORD']
config = yaml.load(open('config.yaml'))
headers = {'Content-Type': 'application/json'}
payload = '{"uid":"' + dcos_username + '", "password":"' + dcos_password + '"}'
def conn(environment):
'''
DC/OS Auth for the API is a pain. The best I can do for now is
send a POST to the ACS endpoint with username and password to fetch
a temporary JWT.
'''
marathon_url = config['dcos']['endpoints'][environment] + "/service/marathon"
auth_api_url = config['dcos']['endpoints'][environment] + "/acs/api/v1/auth/login"
r = requests.post(auth_api_url, headers=headers, data=payload)
c = MarathonClient(marathon_url, auth_token=r.json()['token'])
return c
def status(service, environment):
mc = conn(environment)
try:
service_data = mc.get_app(service)
if service_data.instances == service_data.tasks_healthy and not service_data.tasks_unhealthy:
append_msg = "Everything looks alright! :rocket:"
else:
append_msg = "Something doesn't look right... :skull_and_crossbones:"
message = (f"*{service}* is running `{service_data.container.docker.image.split(':')[1]}`. "
f"It has `{str(service_data.instances)}` instances, `{str(service_data.tasks_healthy)}` out of which are reporting to be healthy. "
f"Each of them has `{str(service_data.cpus)}` cpus and `{str(service_data.mem)}` mem. {append_msg}"
)
except MarathonHttpError as err:
message = f"I had a short circuit while processing your request. Are you sure *{service}* is the correct full ID? :zap:"
return message
@task
def restart(service, environment, response_url):
'''
This one runs as an asynchronous job as noted by the @task annotation,
as sometimes it takes a bit longer.
'''
mc = conn(environment)
try:
mc.restart_app(service, force=True)
message = f"*{service}* is now restarting on *{environment}*!"
except MarathonHttpError as err:
message = f"I had a short circuit while processing your request. Are you sure *{service}* is the correct full ID? :zap:"
data = {
'response_type': 'in_channel',
'text': message,
}
requests.post(response_url, json=data)
|
import time
import torch
import torchani
import pynvml
import gc
import os
from ase.io import read
import argparse
summary = '\n'
runcounter = 0
N = 200
last_py_speed = None
def checkgpu(device=None):
i = device if device else torch.cuda.current_device()
t = torch.cuda.get_device_properties(i).total_memory
c = torch.cuda.memory_reserved(i)
name = torch.cuda.get_device_properties(i).name
print(' GPU Memory Cached (pytorch) : {:7.1f}MB / {:.1f}MB ({})'.format(c / 1024 / 1024, t / 1024 / 1024, name))
real_i = int(os.environ['CUDA_VISIBLE_DEVICES'][0]) if 'CUDA_VISIBLE_DEVICES' in os.environ else i
pynvml.nvmlInit()
h = pynvml.nvmlDeviceGetHandleByIndex(real_i)
info = pynvml.nvmlDeviceGetMemoryInfo(h)
name = pynvml.nvmlDeviceGetName(h)
print(' GPU Memory Used (nvidia-smi): {:7.1f}MB / {:.1f}MB ({})'.format(info.used / 1024 / 1024, info.total / 1024 / 1024, name.decode()))
return f'{(info.used / 1024 / 1024):.1f}MB'
def alert(text):
print('\033[91m{}\33[0m'.format(text)) # red
def info(text):
print('\033[32m{}\33[0m'.format(text)) # green
def format_time(t):
if t < 1:
t = f'{t * 1000:.1f} ms'
else:
t = f'{t:.3f} sec'
return t
def addSummaryLine(items=None, init=False):
if init:
addSummaryEmptyLine()
items = ['RUN', 'PDB', 'Size', 'forward', 'backward', 'Others', 'Total', f'Total({N})', 'Speedup', 'GPU']
global summary
summary += items[0].ljust(20) + items[1].ljust(13) + items[2].ljust(13) + items[3].ljust(13) + items[4].ljust(13) + items[5].ljust(13) + \
items[6].ljust(13) + items[7].ljust(13) + items[8].ljust(13) + items[9].ljust(13) + '\n'
def addSummaryEmptyLine():
global summary
summary += f"{"-"*20}".ljust(20) + f"{"-"*13}".ljust(13) + f"{"-"*13}".ljust(13) + f"{"-"*13}".ljust(13) + f"{"-"*13}".ljust(13) + f"{"-"*13}".ljust(13) + \
f"{"-"*13}".ljust(13) + f"{"-"*13}".ljust(13) + f"{"-"*13}".ljust(13) + f"{"-"*13}".ljust(13) + '\n'
def benchmark(speciesPositions, aev_comp, runbackward=False, mol_info=None, verbose=True):
global runcounter
global last_py_speed
runname = f"{"cu" if aev_comp.use_cuda_extension else "py"} aev fd{"+bd" if runbackward else""}"
items = [f'{(runcounter+1):02} {runname}', f'{mol_info['name']}', f'{mol_info['atoms']}", '-', '-', '-', '-', '-', '-', '-']
forward_time = 0
force_time = 0
torch.cuda.empty_cache()
gc.collect()
torch.cuda.synchronize()
start = time.time()
aev = None
force = None
gpumem = None
for i in range(N):
species, coordinates = speciesPositions
coordinates = coordinates.requires_grad_(runbackward)
torch.cuda.synchronize()
forward_start = time.time()
try:
_, aev = aev_comp((species, coordinates))
except Exception as e:
alert(f" AEV faild: {str(e)[:50]}...")
addSummaryLine(items)
runcounter += 1
return None, None, None
torch.cuda.synchronize()
forward_time += time.time() - forward_start
if runbackward: # backward
force_start = time.time()
try:
force = -torch.autograd.grad(aev.sum(), coordinates, create_graph=True, retain_graph=True)[0]
except Exception as e:
alert(f" Force faild: {str(e)[:50]}...")
addSummaryLine(items)
runcounter += 1
return None, None, None
torch.cuda.synchronize()
force_time += time.time() - force_start
if i == 2 and verbose:
gpumem = checkgpu()
torch.cuda.synchronize()
total_time = (time.time() - start) / N
force_time = force_time / N
forward_time = forward_time / N
others_time = total_time - force_time - forward_time
if verbose:
if aev_comp.use_cuda_extension:
if last_py_speed is not None:
speed_up = last_py_speed / total_time
speed_up = f'{speed_up:.2f}'
else:
speed_up = '-'
last_py_speed = None
else:
last_py_speed = total_time
speed_up = '-'
if verbose:
print(f' Duration: {total_time * N:.2f} s')
print(f' Speed: {total_time*1000:.2f} ms/it')
if runcounter == 0:
addSummaryLine(init=True)
addSummaryEmptyLine()
if runcounter >= 0:
items = [f'{(runcounter+1):02} {runname}',
f"{mol_info["name"]}",
f"{mol_info["atoms"]}",
f'{format_time(forward_time)}',
f'{format_time(force_time)}',
f'{format_time(others_time)}',
f'{format_time(total_time)}',
f'{format_time(total_time * N)}',
f'{speed_up}',
f'{gpumem}']
addSummaryLine(items)
runcounter += 1
return aev, total_time, force
def check_speedup_error(aev, aev_ref, speed, speed_ref):
if (speed_ref is not None) and (speed is not None) and (aev is not None) and (aev_ref is not None):
speedUP = speed_ref / speed
if speedUP > 1:
info(f' Speed up: {speedUP:.2f} X\n')
else:
alert(f' Speed up (slower): {speedUP:.2f} X\n')
aev_error = torch.max(torch.abs(aev - aev_ref))
assert aev_error < 0.02, f' Error: {aev_error:.1e}\n'
def run(file, nnp_ref, nnp_cuaev, runbackward, maxatoms=10000):
filepath = os.path.join(path, f'../dataset/pdb/{file}')
mol = read(filepath)
species = torch.tensor([mol.get_atomic_numbers()], device=device)
positions = torch.tensor([mol.get_positions()], dtype=torch.float32, requires_grad=False, device=device)
spelist = list(torch.unique(species.flatten()).cpu().numpy())
species = species[:, :maxatoms]
positions = positions[:, :maxatoms, :]
speciesPositions = nnp_ref.species_converter((species, positions))
print(f'File: {file}, Molecule size: {species.shape[-1]}, Species: {spelist}\n')
if args.nsight:
torch.cuda.nvtx.range_push(file)
print('Original TorchANI:')
mol_info = {'name': file, 'atoms': species.shape[-1]}
aev_ref, delta_ref, force_ref = benchmark(speciesPositions, nnp_ref.aev_computer, runbackward, mol_info)
print()
print('CUaev:')
# warm up
_, _, _ = benchmark(speciesPositions, nnp_cuaev.aev_computer, runbackward, mol_info, verbose=False)
# run
aev, delta, force_cuaev = benchmark(speciesPositions, nnp_cuaev.aev_computer, runbackward, mol_info)
if args.nsight:
torch.cuda.nvtx.range_pop()
check_speedup_error(aev, aev_ref, delta, delta_ref)
print('-' * 70 + '\n')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--nsight',
action='store_true',
help='use nsight profile')
parser.add_argument('-b', '--backward',
action='store_true',
help='benchmark double backward')
parser.add_argument('-n', '--N',
help='Number of Repeat',
default=200, type=int)
parser.set_defaults(backward=0)
args = parser.parse_args()
path = os.path.dirname(os.path.realpath(__file__))
N = args.N
device = torch.device('cuda')
files = ['small.pdb', '1hz5.pdb', '6W8H.pdb']
# files = ['small.pdb']
nnp_ref = torchani.models.ANI2x(periodic_table_index=True, model_index=None).to(device)
nnp_cuaev = torchani.models.ANI2x(periodic_table_index=True, model_index=None).to(device)
nnp_cuaev.aev_computer.use_cuda_extension = True
if args.nsight:
N = 3
torch.cuda.profiler.start()
for file in files:
run(file, nnp_ref, nnp_cuaev, runbackward=False)
for maxatom in [6000, 10000]:
file = '1C17.pdb'
run(file, nnp_ref, nnp_cuaev, runbackward=False, maxatoms=maxatom)
addSummaryEmptyLine()
info('Add Backward\n')
for file in files:
run(file, nnp_ref, nnp_cuaev, runbackward=True)
for maxatom in [6000, 10000]:
file = '1C17.pdb'
run(file, nnp_ref, nnp_cuaev, runbackward=True, maxatoms=maxatom)
addSummaryEmptyLine()
print(summary)
if args.nsight:
torch.cuda.profiler.stop()
| import time
import torch
import torchani
import pynvml
import gc
import os
from ase.io import read
import argparse
summary = '\n'
runcounter = 0
N = 200
last_py_speed = None
def checkgpu(device=None):
i = device if device else torch.cuda.current_device()
t = torch.cuda.get_device_properties(i).total_memory
c = torch.cuda.memory_reserved(i)
name = torch.cuda.get_device_properties(i).name
print(' GPU Memory Cached (pytorch) : {:7.1f}MB / {:.1f}MB ({})'.format(c / 1024 / 1024, t / 1024 / 1024, name))
real_i = int(os.environ['CUDA_VISIBLE_DEVICES'][0]) if 'CUDA_VISIBLE_DEVICES' in os.environ else i
pynvml.nvmlInit()
h = pynvml.nvmlDeviceGetHandleByIndex(real_i)
info = pynvml.nvmlDeviceGetMemoryInfo(h)
name = pynvml.nvmlDeviceGetName(h)
print(' GPU Memory Used (nvidia-smi): {:7.1f}MB / {:.1f}MB ({})'.format(info.used / 1024 / 1024, info.total / 1024 / 1024, name.decode()))
return f'{(info.used / 1024 / 1024):.1f}MB'
def alert(text):
print('\033[91m{}\33[0m'.format(text)) # red
def info(text):
print('\033[32m{}\33[0m'.format(text)) # green
def format_time(t):
if t < 1:
t = f'{t * 1000:.1f} ms'
else:
t = f'{t:.3f} sec'
return t
def addSummaryLine(items=None, init=False):
if init:
addSummaryEmptyLine()
items = ['RUN', 'PDB', 'Size', 'forward', 'backward', 'Others', 'Total', f'Total({N})', 'Speedup', 'GPU']
global summary
summary += items[0].ljust(20) + items[1].ljust(13) + items[2].ljust(13) + items[3].ljust(13) + items[4].ljust(13) + items[5].ljust(13) + \
items[6].ljust(13) + items[7].ljust(13) + items[8].ljust(13) + items[9].ljust(13) + '\n'
def addSummaryEmptyLine():
global summary
summary += f"{'-'*20}".ljust(20) + f"{'-'*13}".ljust(13) + f"{'-'*13}".ljust(13) + f"{'-'*13}".ljust(13) + f"{'-'*13}".ljust(13) + f"{'-'*13}".ljust(13) + \
f"{'-'*13}".ljust(13) + f"{'-'*13}".ljust(13) + f"{'-'*13}".ljust(13) + f"{'-'*13}".ljust(13) + '\n'
def benchmark(speciesPositions, aev_comp, runbackward=False, mol_info=None, verbose=True):
global runcounter
global last_py_speed
runname = f"{'cu' if aev_comp.use_cuda_extension else 'py'} aev fd{'+bd' if runbackward else''}"
items = [f'{(runcounter+1):02} {runname}', f"{mol_info['name']}", f"{mol_info['atoms']}", '-', '-', '-', '-', '-', '-', '-']
forward_time = 0
force_time = 0
torch.cuda.empty_cache()
gc.collect()
torch.cuda.synchronize()
start = time.time()
aev = None
force = None
gpumem = None
for i in range(N):
species, coordinates = speciesPositions
coordinates = coordinates.requires_grad_(runbackward)
torch.cuda.synchronize()
forward_start = time.time()
try:
_, aev = aev_comp((species, coordinates))
except Exception as e:
alert(f" AEV faild: {str(e)[:50]}...")
addSummaryLine(items)
runcounter += 1
return None, None, None
torch.cuda.synchronize()
forward_time += time.time() - forward_start
if runbackward: # backward
force_start = time.time()
try:
force = -torch.autograd.grad(aev.sum(), coordinates, create_graph=True, retain_graph=True)[0]
except Exception as e:
alert(f" Force faild: {str(e)[:50]}...")
addSummaryLine(items)
runcounter += 1
return None, None, None
torch.cuda.synchronize()
force_time += time.time() - force_start
if i == 2 and verbose:
gpumem = checkgpu()
torch.cuda.synchronize()
total_time = (time.time() - start) / N
force_time = force_time / N
forward_time = forward_time / N
others_time = total_time - force_time - forward_time
if verbose:
if aev_comp.use_cuda_extension:
if last_py_speed is not None:
speed_up = last_py_speed / total_time
speed_up = f'{speed_up:.2f}'
else:
speed_up = '-'
last_py_speed = None
else:
last_py_speed = total_time
speed_up = '-'
if verbose:
print(f' Duration: {total_time * N:.2f} s')
print(f' Speed: {total_time*1000:.2f} ms/it')
if runcounter == 0:
addSummaryLine(init=True)
addSummaryEmptyLine()
if runcounter >= 0:
items = [f'{(runcounter+1):02} {runname}',
f"{mol_info['name']}",
f"{mol_info['atoms']}",
f'{format_time(forward_time)}',
f'{format_time(force_time)}',
f'{format_time(others_time)}',
f'{format_time(total_time)}',
f'{format_time(total_time * N)}',
f'{speed_up}',
f'{gpumem}']
addSummaryLine(items)
runcounter += 1
return aev, total_time, force
def check_speedup_error(aev, aev_ref, speed, speed_ref):
if (speed_ref is not None) and (speed is not None) and (aev is not None) and (aev_ref is not None):
speedUP = speed_ref / speed
if speedUP > 1:
info(f' Speed up: {speedUP:.2f} X\n')
else:
alert(f' Speed up (slower): {speedUP:.2f} X\n')
aev_error = torch.max(torch.abs(aev - aev_ref))
assert aev_error < 0.02, f' Error: {aev_error:.1e}\n'
def run(file, nnp_ref, nnp_cuaev, runbackward, maxatoms=10000):
filepath = os.path.join(path, f'../dataset/pdb/{file}')
mol = read(filepath)
species = torch.tensor([mol.get_atomic_numbers()], device=device)
positions = torch.tensor([mol.get_positions()], dtype=torch.float32, requires_grad=False, device=device)
spelist = list(torch.unique(species.flatten()).cpu().numpy())
species = species[:, :maxatoms]
positions = positions[:, :maxatoms, :]
speciesPositions = nnp_ref.species_converter((species, positions))
print(f'File: {file}, Molecule size: {species.shape[-1]}, Species: {spelist}\n')
if args.nsight:
torch.cuda.nvtx.range_push(file)
print('Original TorchANI:')
mol_info = {'name': file, 'atoms': species.shape[-1]}
aev_ref, delta_ref, force_ref = benchmark(speciesPositions, nnp_ref.aev_computer, runbackward, mol_info)
print()
print('CUaev:')
# warm up
_, _, _ = benchmark(speciesPositions, nnp_cuaev.aev_computer, runbackward, mol_info, verbose=False)
# run
aev, delta, force_cuaev = benchmark(speciesPositions, nnp_cuaev.aev_computer, runbackward, mol_info)
if args.nsight:
torch.cuda.nvtx.range_pop()
check_speedup_error(aev, aev_ref, delta, delta_ref)
print('-' * 70 + '\n')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--nsight',
action='store_true',
help='use nsight profile')
parser.add_argument('-b', '--backward',
action='store_true',
help='benchmark double backward')
parser.add_argument('-n', '--N',
help='Number of Repeat',
default=200, type=int)
parser.set_defaults(backward=0)
args = parser.parse_args()
path = os.path.dirname(os.path.realpath(__file__))
N = args.N
device = torch.device('cuda')
files = ['small.pdb', '1hz5.pdb', '6W8H.pdb']
# files = ['small.pdb']
nnp_ref = torchani.models.ANI2x(periodic_table_index=True, model_index=None).to(device)
nnp_cuaev = torchani.models.ANI2x(periodic_table_index=True, model_index=None).to(device)
nnp_cuaev.aev_computer.use_cuda_extension = True
if args.nsight:
N = 3
torch.cuda.profiler.start()
for file in files:
run(file, nnp_ref, nnp_cuaev, runbackward=False)
for maxatom in [6000, 10000]:
file = '1C17.pdb'
run(file, nnp_ref, nnp_cuaev, runbackward=False, maxatoms=maxatom)
addSummaryEmptyLine()
info('Add Backward\n')
for file in files:
run(file, nnp_ref, nnp_cuaev, runbackward=True)
for maxatom in [6000, 10000]:
file = '1C17.pdb'
run(file, nnp_ref, nnp_cuaev, runbackward=True, maxatoms=maxatom)
addSummaryEmptyLine()
print(summary)
if args.nsight:
torch.cuda.profiler.stop()
|
"""
Contains an Op for convolving input images with a set of filters. This was
developed especially for Convolutional Neural Networks.
For related ops, including downsampling and subsampling, see
tensor.signal and tensor.signal.pool.
See especially conv2d().
"""
import logging
import warnings
import numpy as np
from scipy.signal.signaltools import _bvalfromboundary, _valfrommode
from scipy.signal.sigtools import _convolve2d
import aesara
from aesara.graph.basic import Apply
from aesara.graph.op import OpenMPOp
from aesara.tensor import blas
from aesara.tensor.basic import (
as_tensor_variable,
get_scalar_constant_value,
patternbroadcast,
)
from aesara.tensor.exceptions import NotScalarConstantError
from aesara.tensor.nnet.abstract_conv import get_conv_output_shape, get_conv_shape_1axis
from aesara.tensor.type import discrete_dtypes, tensor
__docformat__ = "restructuredtext en"
_logger = logging.getLogger("aesara.tensor.nnet.conv")
def conv2d(
input,
filters,
image_shape=None,
filter_shape=None,
border_mode="valid",
subsample=(1, 1),
**kargs,
):
"""
Deprecated, old conv2d interface.
This function will build the symbolic graph for convolving a stack of
input images with a set of filters. The implementation is modelled after
Convolutional Neural Networks (CNN). It is simply a wrapper to the ConvOp
but provides a much cleaner interface.
Parameters
----------
input : symbolic 4D tensor
Mini-batch of feature map stacks, of shape
(batch size, stack size, nb row, nb col)
see the optional parameter image_shape
filters: symbolic 4D tensor
Set of filters used in CNN layer of shape
(nb filters, stack size, nb row, nb col)
see the optional parameter filter_shape
border_mode : {'valid', 'full'}
'valid'only apply filter to complete patches of the image. Generates
output of shape: image_shape - filter_shape + 1.
'full' zero-pads image to multiple of filter shape to generate output
of shape: image_shape + filter_shape - 1.
subsample: tuple of len 2
Factor by which to subsample the output. Also called strides elsewhere.
image_shape: None, tuple/list of len 4 of int, None or Constant variable
The shape of the input parameter.
Optional, used for optimization like loop unrolling
You can put None for any element of the list to tell that this element
is not constant.
filter_shape : None, tuple/list of len 4 of int, None or Constant variable
Optional, used for optimization like loop unrolling
You can put None for any element of the list
to tell that this element is not constant.
kwargs
Kwargs are passed onto ConvOp. Can be used to set the following:
unroll_batch, unroll_kern, unroll_patch, openmp (see ConvOp doc).
openmp: By default have the same value as
config.openmp. For small image, filter,
batch size, nkern and stack size, it can be
faster to disable manually openmp. A fast and
incomplete test show that with image size
6x6, filter size 4x4, batch size==1,
n kern==1 and stack size==1, it is faster
to disable it in valid mode. But if we
grow the batch size to 10, it is faster
with openmp on a core 2 duo.
Returns
-------
symbolic 4D tensor
Set of feature maps generated by convolutional layer. Tensor is
of shape (batch size, nb filters, output row, output col).
"""
warnings.warn(
"aesara.tensor.nnet.conv.conv2d is deprecated."
" Use aesara.tensor.nnet.conv2d instead."
)
# accept Constant value for image_shape and filter_shape.
if image_shape is not None:
image_shape = list(image_shape)
for i in range(len(image_shape)):
if image_shape[i] is not None:
try:
image_shape[i] = get_scalar_constant_value(
as_tensor_variable(image_shape[i])
)
except NotScalarConstantError:
raise NotScalarConstantError(
"The convolution need that the shape"
" information are constant values. We got"
" {image_shape[i]} for the image_shape parameter"
)
assert image_shape[i].dtype in discrete_dtypes
image_shape[i] = int(image_shape[i])
if filter_shape is not None:
filter_shape = list(filter_shape)
for i in range(len(filter_shape)):
if filter_shape[i] is not None:
try:
filter_shape[i] = get_scalar_constant_value(
as_tensor_variable(filter_shape[i])
)
except NotScalarConstantError:
raise NotScalarConstantError(
"The convolution need that the shape"
" information are constant values. We got"
" {filter_shape[i]} for the filter_shape "
"parameter"
)
assert filter_shape[i].dtype in discrete_dtypes
filter_shape[i] = int(filter_shape[i])
if image_shape and filter_shape:
try:
if image_shape[1] is not None and filter_shape[1] is not None:
assert image_shape[1] == filter_shape[1]
except Exception:
print("image ", image_shape, " filters ", filter_shape)
raise
if filter_shape is not None:
nkern = filter_shape[0]
kshp = filter_shape[2:]
else:
nkern, kshp = None, None
if image_shape is not None:
bsize = image_shape[0]
imshp = image_shape[1:]
else:
bsize, imshp = None, None
op = ConvOp(
output_mode=border_mode,
dx=subsample[0],
dy=subsample[1],
imshp=imshp,
kshp=kshp,
nkern=nkern,
bsize=bsize,
**kargs,
)
return op(input, filters)
class ConvOp(OpenMPOp):
r"""
This Op serves a dual purpose: it can implement a vanilla 2D convolution
(as taught in any signal processing class) or implement the
convolutional layers found in Convolutional Neural Networks.
In this setting, a set of 3D images is convolved with a set of 3D kernels,
with the particularity that their leading dimensions are of equal length.
Vanilla 2D convolution is treated as a special case of this.
The input parameter represents a mini-batch of multiple images. Its shape is:
batch size x num. input feature maps x image height x image width
The kernel parameter represents a set of 3D kernels. Its shape is:
number of filters x num. input images x filter height x filter width
The output of ConvOp is a 4D tensor, generated as follows:
output[b,k,:,:] = \sum_i input[b,i,:,:] * filter[k,i,:,:] \forall b,k
where b is the mini-batch index, k the filter index and * is the
convolution operator.
The constructor initializes a ConvOp with given output_mode (full/valid).
All other parameters are optional and are only used to generate more
optimized c code, or to enable graph optimizers to optimally replace the
ConvOp.
NOTES ON OPTIMIZATION:
There are two types of optimization. The first is the selection of the
fastest algo when bsize and nkern are provided with imshp and kshp.
By default we try to select the fastest version. You can specify it
with the unroll_batch, unroll_kern, and unroll_patch parameter.
The second type of optimization is hardcoding some dimensions into the
code when all shape are know.
This make a significant difference for the 'full' output_mode.
Sometimes, the fastest implementation on x86-64 uses
{unroll_batch=4, unroll_kern=4, unroll_patch=False}
with all other shape parameters being provided.
For optimizing other architectures, see:
Kazushige Goto and Robert A. Van De Geijn, Anatomy of High-Performance
Matrix Multiplication, (mr x nr). ACM Transactions on Mathematical
Software, May 2008.
Figure 12: (mr x nr). For x86 use 2x4, itanium 8x8, etc.
Parameters
----------
output_mode : {'valid', 'full'}
'valid' gives an output smaller then the image.
'full' gives an output bigger then the image.
See 'border_mode' in conv2d's doc.
Optional parameters: (will generate more optimal c code)
imshp : tuple of len 2 or 3: 2 for 2d image, 3 for a stack of 2d images.
Stacksize, nb image row, nb image col.
kshp : tuple of len 2
Nb kernel row, nb kernel col.
nkern : int
The number of kernel.
bsize : int
The size of the minibatch.
dx : int
Patch stride rows.
dy : int
Patch stride cols
Params which select the version of code used:
unroll_patch : bool
Use a version of c_code that unroll the patch loop that don't
request all shape information to work, but if all shape information
are present, will use it to hardcode the value in the code for
faster code.
unroll_batch : int
Use a version of c_code that unroll the batch (by unroll_batch)
and the nkern (by unroll_kern) loop. The size must by a multiple
of bsize or nkern respectively.
unroll_kern : int
Use a version of c_code that unroll the batch
(by unroll_batch) and the nkern(by unroll_kern) loop. The size
must by a multiple of bsize or nkern respectively.
verbose : int
Passed to GpuConv.
version: int or str
Passed to GpuConv, if version='no_fft', fft
optimization will be deactivated at the op level.
direction_hint: {'forward', 'bprop weights', 'bprop inputs'}
Passed to GpuConv, used by graph optimizers to aid algorithm choice.
The 3 following parameters are used internally when we generate
the gradient when dx!=1 or dy!=1.
imshp_logical
Default None. None value is equivalent to imshp value.
When imshp_logical != imshp, it tell we need to insert 0 in
the image before we do the convolution. For example, when dx==dy==2
and the image is [[1, 2], [3, 4]], we should make as if the image
was [[1, 0, 2, 0], [0, 0, 0, 0], [3, 0, 4, 0], [0, 0, 0, 0]].
Our python code insert the zero, but the c code optimize it.
imshp_logical != imshp when taking the grad again the weights or
the image when the output_mode is full and `dx != 1` or `dy != 1`.
kshp_logical
Idem but for kshp and used for the grad again the
weights when the output_mode is valid and `dx != 1` or `dy != 1`.
kshp_logical_top_aligned
Used in the same case. Default to True.
Set to False in the grad again the weight when the
output_mode is full.
"""
__attrnames = [
"imshp",
"kshp",
"nkern",
"bsize",
"dx",
"dy",
"out_mode",
"unroll_batch",
"unroll_kern",
"unroll_patch",
"imshp_logical",
"kshp_logical",
"kshp_logical_top_aligned",
]
"""These attributes uniquely identify the behaviour of this op for
given inputs. Do not set openmp here.
"""
# the value of speed_unroll_batch_kern,speed_unroll_patch_noshape,speed_unroll_patch_shape
# have bean calculated on maggie36 when their is only 1 session logged on and only this was running.
# It is an Intel(R) Xeon(R) CPU E5430 @ 2.66GHz. It is computer with aesara/tensor/nnet/tests/speed_test_conv.py
# and took 5 minutes to run.
# TODO: we should compute this table for each computer/os as this can change.
# I saw on one computer that the speed with the shape can be slower than without!
# using the real shape and the same dtype could also help.
# unroll_batch, unroll_kern, valid time, full time
speed_unroll_batch_kern = [
(1, 1, 2.4661250114440918, 6.5472931861877441),
(1, 2, 1.5869178771972656, 5.1499760150909424),
(1, 3, 1.4270510673522949, 3.6593470573425293),
(1, 4, 1.3373479843139648, 3.3451821804046631),
(1, 5, 1.2818830013275146, 3.1444568634033203),
(1, 6, 1.2521560192108154, 3.0256359577178955),
(1, 10, 1.2134110927581787, 2.9174180030822754),
(2, 1, 1.657214879989624, 4.5261678695678711),
(2, 2, 1.2123160362243652, 2.9747390747070312),
(2, 3, 1.0758891105651855, 2.5690360069274902),
(2, 4, 1.0683329105377197, 2.4233770370483398),
(2, 5, 1.0955719947814941, 2.3999948501586914),
(2, 6, 1.5935721397399902, 2.6878271102905273),
(2, 10, 1.8511250019073486, 3.2417428493499756),
(3, 1, 1.5948119163513184, 3.631148099899292),
(3, 2, 1.0761330127716064, 2.6011371612548828),
(3, 3, 1.0551531314849854, 2.4200370311737061),
(3, 4, 1.3930759429931641, 2.5211219787597656),
(3, 5, 1.4330689907073975, 2.5704989433288574),
(3, 6, 1.362138032913208, 2.5964410305023193),
(3, 10, 1.6582000255584717, 2.9907989501953125),
(4, 1, 1.4793620109558105, 3.3473429679870605),
(4, 2, 1.0671560764312744, 2.4171769618988037),
(4, 3, 1.2569692134857178, 2.2807950973510742),
(4, 4, 1.3456289768218994, 2.6219108104705811),
(4, 5, 1.4055080413818359, 2.4606490135192871),
(4, 6, 1.372107982635498, 2.551663875579834),
(4, 10, 1.599470853805542, 2.9172940254211426),
(5, 1, 1.4115700721740723, 3.2077109813690186),
(5, 2, 1.0635769367218018, 2.2648060321807861),
(5, 3, 1.3842809200286865, 2.6135518550872803),
(5, 4, 1.3470511436462402, 2.3852400779724121),
(5, 5, 1.3539440631866455, 2.5245928764343262),
(5, 6, 1.4037849903106689, 2.5985310077667236),
(5, 10, 1.6120610237121582, 2.8127608299255371),
(6, 1, 1.3623628616333008, 3.021122932434082),
(6, 2, 1.1697649955749512, 2.6285450458526611),
(6, 3, 1.2980999946594238, 2.4746189117431641),
(6, 4, 1.3739941120147705, 2.5579929351806641),
(6, 5, 1.3967819213867188, 2.5522029399871826),
(6, 6, 1.4279270172119141, 2.6127138137817383),
(6, 10, 1.605496883392334, 2.864037036895752),
(10, 1, 1.6401121616363525, 2.970099925994873),
(10, 2, 1.46710205078125, 2.7231831550598145),
(10, 3, 1.4193780422210693, 2.6087639331817627),
(10, 4, 1.4657118320465088, 2.6246678829193115),
(10, 5, 1.5052611827850342, 2.6542458534240723),
(10, 6, 1.5214400291442871, 2.7243161201477051),
(10, 10, 1.6116268634796143, 2.956165075302124),
]
# valid time, full time
speed_unroll_patch_noshape = [2.0109100341796875, 5.8175678253173828]
# valid time, full time
speed_unroll_patch_shape = [1.2967290878295898, 5.5283889770507812]
@staticmethod
def has_all_shape(imshp, kshp, nkern=1, bsize=1):
return (
nkern is not None
and bsize is not None
and all(shp is not None for shp in imshp)
and all(shp is not None for shp in kshp)
)
@staticmethod
def getOutputShape(inshp, kshp, stride=(1, 1), mode="valid"):
"""
Computes the output dimensions of convolving an image of shape "inshp"
with kernels of shape "kshp". Accepts symbolic or integer shapes.
Propagates `None`s (for unknown shapes).
Parameters
----------
inshp
(rows,cols) of input image.
kshp
(rows,cols) of filters.
mode: {'valid', 'full'}
See 'border_mode' in conv2d's doc.
Returns
-------
object
(rows,cols) of output image.
"""
# The formula would be ceil((i + s * k - s * 1) / float(d)),
# with s=1 for mode=='full' and s=-1 for mode=='valid'.
# To support symbolic shapes, we express this with integer arithmetic.
warnings.warn(
"The method `getOutputShape` is deprecated use"
"`get_conv_output_shape` instead.",
stacklevel=2,
)
return tuple(
get_conv_shape_1axis(i, k, mode, d) for i, k, d in zip(inshp, kshp, stride)
)
def __init__(
self,
imshp=None,
kshp=None,
nkern=None,
bsize=None,
dx=1,
dy=1,
output_mode="valid",
unroll_batch=None,
unroll_kern=None,
unroll_patch=None,
imshp_logical=None,
kshp_logical=None,
kshp_logical_top_aligned=True,
verbose=0,
version=-1,
direction_hint="forward",
openmp=None,
):
# Deactivate fft_optimization at the op level if specified
if version == "no_fft":
self.fft_opt = False
version = -1
else:
self.fft_opt = True
# Expand unknown image / kernel shapes into tuples of Nones
if imshp is None:
imshp = (None, None, None)
else:
imshp = tuple(imshp)
if kshp is None:
kshp = (None, None)
else:
kshp = tuple(kshp)
# Check imshp and kshp dimensionality
if len(imshp) == 2:
imshp = (1,) + imshp
elif len(imshp) != 3:
raise ValueError(f"len(imshp) must be 2 or 3, got {len(imshp)}")
if len(kshp) != 2:
raise ValueError(f"len(kshp) must be 2, got {len(kshp)}")
# We must continue to consider None as 1 for backward compatibility.
if dx is None:
dx = 1
if dy is None:
dy = 1
if int(dx) != dx:
raise TypeError("ConvOp.__init__ param dx must be an int", dx)
dx = int(dx)
if int(dy) != dy:
raise TypeError("ConvOp.__init__ param dy must be an int", dy)
dy = int(dy)
all_shape = self.has_all_shape(imshp, kshp, nkern, bsize)
if (unroll_batch or unroll_kern) and not all_shape:
raise ValueError(
"In ConvOp, when using unroll_batch and"
" unroll_nkern, all shape are needed"
)
# Init the openmp attribute
super().__init__(openmp=openmp)
if not all_shape or self.openmp:
# Only this version is parallelized
unroll_patch = True
self.imshp = imshp
self.kshp = kshp
self.nkern = nkern
self.bsize = bsize
self.dx = dx
self.dy = dy
self.verbose = verbose
self.version = version
self.direction_hint = direction_hint
# a triple
if imshp_logical is None:
self.imshp_logical = self.imshp
else:
imshp_logical = tuple(imshp_logical)
if len(imshp_logical) != 3:
raise ValueError(
f"len(imshp_logical) must be 3, got {len(imshp_logical)}"
)
self.imshp_logical = imshp_logical
# a pair
if kshp_logical is None:
self.kshp_logical = self.kshp
else:
kshp_logical = tuple(kshp_logical)
if len(kshp_logical) != 2:
raise ValueError(
f"len(kshp_logical) must be 2, got {len(kshp_logical)}"
)
self.kshp_logical = kshp_logical
# a bool
self.kshp_logical_top_aligned = kshp_logical_top_aligned
self.unroll_batch = unroll_batch
self.unroll_kern = unroll_kern
self.unroll_patch = unroll_patch
if self.unroll_batch and not self.unroll_kern:
self.unroll_kern = 1
if self.unroll_kern and not self.unroll_batch:
self.unroll_batch = 1
# downcast unroll_batch if not a divisor of batch size
if (
self.unroll_batch is not None
and self.unroll_batch > 0
and self.bsize % self.unroll_batch != 0
):
if self.bsize <= self.unroll_batch:
self.unroll_batch = self.bsize
else:
# find the maximum value under unroll_batch that would work
new = self.unroll_batch
assert new >= 1
while self.bsize % new != 0:
new -= 1
warnstr = (
"In ConvOp.__init__(): "
f"unroll_batch({self.unroll_batch}) must be 0 or a divisor of"
f" bsize({self.bsize}). We revert it to {new}. This"
" won't change the result, but may make it slower."
)
_logger.warning(warnstr)
self.unroll_batch = new
# downcast unroll_kern if not a divisor of nb of kernel
if (
self.unroll_kern is not None
and self.unroll_kern > 0
and self.nkern % self.unroll_kern != 0
):
if self.nkern <= self.unroll_kern:
self.unroll_kern = self.nkern
else:
# find the maximum value under unroll_kern that would work
new = self.unroll_kern
assert new >= 1
while self.nkern % new != 0:
new -= 1
warnstr = (
"In ConvOp.__init__(): "
f"unroll_kern({self.unroll_kern}) must be 0 or a divisor of"
f" nkern({self.nkern}). We revert it to {new}. This"
" won't change the result, but may make it slower."
)
_logger.warning(warnstr)
self.unroll_kern = new
self.outshp = get_conv_output_shape(
(None,) + self.imshp_logical,
(
None,
None,
)
+ self.kshp_logical,
output_mode,
(dx, dy),
)[2:]
self.fulloutshp = get_conv_output_shape(
(None,) + self.imshp_logical,
(
None,
None,
)
+ self.kshp_logical,
output_mode,
(1, 1),
)[2:]
self.out_mode = output_mode
if self.out_mode not in ["valid", "full"]:
raise NotImplementedError(f"Mode {self.out_mode} not implemented")
if any((shp is not None) and (shp <= 0) for shp in self.outshp):
raise ValueError(
"Bad size for the output shape. Verify that [post-"
f"supersampling] input shape ({self.imshp_logical}) and kern"
f" shape({self.kshp_logical}) are ok. (Hint: kerns must fit inside"
" image in valid mode)"
)
if (
self.unroll_kern is None
and self.unroll_batch is None
and self.unroll_patch is None
):
# no version specified. Find the faster we have
if self.bsize is None and self.nkern is None:
self.unroll_patch = True
elif self.bsize is not None and self.nkern is not None:
bsize = self.bsize
nkern = self.nkern
mode_idx = 0
if self.out_mode != "valid":
mode_idx = 1
if self.has_all_shape(self.imshp, self.kshp):
time_unroll_patch = self.speed_unroll_patch_shape[mode_idx]
else:
time_unroll_patch = self.speed_unroll_patch_noshape[mode_idx]
time_unroll_batch_kern = 9999999
for i in range(len(self.speed_unroll_batch_kern)):
if (
bsize % self.speed_unroll_batch_kern[i][0] == 0
and nkern % self.speed_unroll_batch_kern[i][1] == 0
):
if (
self.speed_unroll_batch_kern[i][2 + mode_idx]
< time_unroll_batch_kern
):
time_unroll_batch_kern = self.speed_unroll_batch_kern[i][
2 + mode_idx
]
time_unroll_batch_kern_idx = i
if time_unroll_patch < time_unroll_batch_kern:
self.unroll_patch = True
else:
self.unroll_batch = self.speed_unroll_batch_kern[
time_unroll_batch_kern_idx
][0]
self.unroll_kern = self.speed_unroll_batch_kern[
time_unroll_batch_kern_idx
][1]
self.unroll_patch = False
_logger.debug(
"AUTO FIND VERSION OF C_CODE OF CONV OP " "%s %s %s %s %s %s %s",
self.unroll_batch,
self.unroll_kern,
self.unroll_patch,
self.bsize,
self.nkern,
time_unroll_patch,
time_unroll_batch_kern,
)
self._rehash()
def __eq__(self, other):
if type(self) != type(other):
return False
for a in self.__attrnames:
if getattr(self, a) != getattr(other, a):
return False
return True
def __setstate__(self, d):
super().__setstate__(d)
self.direction_hint = d.get("direction_hint", None)
self._rehash()
def _rehash(self):
hashval = hash(type(self))
for a in self.__attrnames:
hashval = hashval ^ hash(getattr(self, a))
self.__hashval = hashval
def __hash__(self):
return self.__hashval
def __str__(self):
return (
"ConvOp{"
+ ",".join(str((a, getattr(self, a))) for a in self.__attrnames)
+ "}"
)
def flops(self, inputs, outputs):
"""
Useful with the hack in profiling to print the MFlops.
"""
images, kerns = inputs
(out,) = outputs
assert images[1] == kerns[1]
flops = 0
if self.out_mode == "valid":
# nb mul and add by output pixel
flops = kerns[2] * kerns[3] * 2
# nb flops by output image
flops *= out[2] * out[3]
# nb patch multiplied
flops *= images[1] * kerns[0] * images[0]
else:
flops = (
images[0]
* kerns[0]
* images[1]
* kerns[2]
* kerns[3]
* images[2]
* images[3]
* 2
)
return flops
def make_node(self, inputs, kerns):
# TODO: find a way to make ConvOp work for N-D (after NIPS09)
"""
Parameters
----------
inputs
4 dim: batches x stacksize x rows x cols.
kerns
4 dim: nkern x stackidx x rows x cols.
"""
_inputs = as_tensor_variable(inputs)
_kerns = as_tensor_variable(kerns)
# TODO: lift this restriction by upcasting either inputs or kerns
if _inputs.ndim != 4:
raise TypeError(
"ConvOp (make_node) requires input be a 4D tensor;"
f' received "{inputs}" ({_inputs.ndim} dims)'
)
if _kerns.ndim != 4:
raise TypeError("make_node requires 4D tensor of kernels")
if _inputs.type.dtype != _kerns.type.dtype:
raise NotImplementedError(
"The image and the kernel must have the same type."
"inputs({_inputs.dtype}), kerns({_kerns.dtype})"
)
bcastable23 = [self.outshp[0] == 1, self.outshp[1] == 1]
output = tensor(
dtype=_inputs.type.dtype,
broadcastable=[_inputs.broadcastable[0], _kerns.broadcastable[0]]
+ bcastable23,
)
return Apply(self, [_inputs, _kerns], [output])
def infer_shape(self, fgraph, node, input_shapes):
imshp = input_shapes[0] # 4D image shape
kshp = input_shapes[1] # 4D filter shape
bsize, imshp = imshp[0], list(imshp[1:])
nkern, kshp = kshp[0], list(kshp[2:])
# replace symbolic shapes with known shapes
if self.bsize is not None:
bsize = self.bsize
for i in [0, 1, 2]:
if self.imshp_logical[i] is not None:
imshp[i] = self.imshp_logical[i]
if self.nkern is not None:
nkern = self.nkern
for i in [0, 1]:
if self.kshp_logical[i] is not None:
kshp[i] = self.kshp_logical[i]
# infer output shape from what we have
res = get_conv_output_shape(
(bsize,) + tuple(imshp),
(
nkern,
None,
)
+ tuple(kshp),
self.out_mode,
(self.dx, self.dy),
)
return [res]
def perform(self, node, inp, out):
"""
By default if len(img2d.shape)==3, we TODO
"""
img2d, filtersflipped = inp
(z,) = out
# TODO: move these back out to global scope when they no longer
# cause an atexit error
imshp = self.imshp
if any(x is None for x in imshp):
imshp = tuple(img2d.shape[1:])
if imshp != img2d.shape[1:]:
raise ValueError(
"The image shape provided at build time "
"is different from the one passed at run time",
imshp,
img2d.shape[1:],
)
kshp = self.kshp
if any(x is None for x in kshp):
kshp = tuple(filtersflipped.shape[2:])
if kshp != filtersflipped.shape[2:]:
raise ValueError(
"The filter shape provided at build time "
"is different from the one passed at run time",
kshp,
filtersflipped.shape[2:],
)
bsize = self.bsize
if bsize is None:
bsize = img2d.shape[0]
elif bsize != img2d.shape[0]:
raise ValueError(
"The batch size provided at build time "
"is different from the one passed at run time",
bsize,
img2d.shape[0],
)
nkern = self.nkern
if nkern is None:
nkern = filtersflipped.shape[0]
elif nkern != filtersflipped.shape[0]:
raise ValueError(
"The number of filters provided at build time "
"is different from the one passed at run time",
nkern,
filtersflipped.shape[0],
)
imshp_logical = self.imshp_logical
if imshp_logical[0] is None:
imshp_logical = (imshp[0],) + imshp_logical[1:]
if imshp_logical[1] is None:
imshp_logical = (imshp_logical[0], imshp[1], imshp_logical[2])
if imshp_logical[2] is None:
imshp_logical = imshp_logical[:2] + (imshp[2],)
assert all(x is not None for x in imshp_logical)
kshp_logical = self.kshp_logical
if kshp_logical[0] is None:
kshp_logical = (kshp[0], kshp_logical[1])
if kshp_logical[1] is None:
kshp_logical = (kshp_logical[0], kshp[1])
assert all(x is not None for x in kshp_logical)
if all(shp is not None for shp in self.fulloutshp):
fulloutshp = tuple(self.fulloutshp)
else:
fulloutshp = get_conv_output_shape(
(None,) + imshp_logical,
(
None,
None,
)
+ kshp_logical,
self.out_mode,
(1, 1),
)[2:]
if (
z[0] is None
or z[0].shape
!= (
bsize,
nkern,
)
+ fulloutshp
):
z[0] = np.zeros(
(
bsize,
nkern,
)
+ fulloutshp,
dtype=img2d.dtype,
)
zz = z[0]
stacklen = imshp[0]
img2d = img2d.reshape((bsize,) + imshp)
filtersflipped = filtersflipped.reshape((nkern, stacklen) + kshp)
if self.imshp != self.imshp_logical:
# assuming that to get from imshp to imshp logical we insert zeros in missing spots
rstride = int(np.ceil(imshp_logical[1] / float(imshp[1])))
cstride = int(np.ceil(imshp_logical[2] / float(imshp[2])))
buf = np.zeros((bsize,) + imshp_logical, dtype=img2d.dtype)
buf[:, :, ::rstride, ::cstride] = img2d
img2d = buf
del buf, rstride, cstride
if kshp != kshp_logical:
rstride = int(np.ceil(kshp_logical[0] / float(kshp[0])))
cstride = int(np.ceil(kshp_logical[1] / float(kshp[1])))
buf = np.zeros(
(nkern, stacklen) + self.kshp_logical, dtype=filtersflipped.dtype
)
if self.kshp_logical_top_aligned:
roffset = coffset = 0
else:
roffset = (
kshp_logical[0] - (kshp[0] * rstride) - 1 + rstride
) % rstride
coffset = (
kshp_logical[1] - (kshp[1] * cstride) - 1 + cstride
) % cstride
assert roffset >= 0
assert coffset >= 0
buf[:, :, roffset::rstride, coffset::cstride] = filtersflipped
filtersflipped = buf
del buf, rstride, cstride
val = _valfrommode(self.out_mode)
bval = _bvalfromboundary("fill")
with warnings.catch_warnings():
warnings.simplefilter("ignore", np.ComplexWarning)
for b in range(bsize):
for n in range(nkern):
zz[b, n, ...].fill(0)
for im0 in range(stacklen):
# some cast generates a warning here
zz[b, n, ...] += _convolve2d(
img2d[b, im0, ...],
filtersflipped[n, im0, ...],
1,
val,
bval,
0,
)
if False:
if False and self.out_mode == "full":
img2d2 = np.zeros(
(
bsize,
stacklen,
imshp[1] + 2 * kshp[0] - 2,
imshp[2] + 2 * kshp[1] - 2,
)
)
img2d2[
:,
:,
kshp[0] - 1 : kshp[0] - 1 + imshp[1],
kshp[1] - 1 : kshp[1] - 1 + imshp[2],
] = img2d
img2d = img2d2
# N_image_shape = image_data.shape
for b in range(bsize):
for n in range(nkern):
zz[b, n, ...].fill(0)
for im0 in range(stacklen):
for row in range(0, zz.shape[2], self.dx):
for col in range(0, zz.shape[3], self.dy):
zz[b, n, row, col] += (
img2d[
b, im0, row : row + kshp[0], col : col + kshp[1]
]
* filtersflipped[n, im0, ::-1, ::-1]
).sum()
# We copy it to remove the Stride mismatch warning from DEBUG_MODE.
# The copy make that we return an object with the same stride as the c version.
# The copy don't affect the performance during our experience as in that case we
# execute the c version which is much faster.
if self.dx > 1 or self.dy > 1:
zz = zz[:, :, 0 :: self.dx, 0 :: self.dy].copy()
z[0] = zz
def R_op(self, inputs, eval_points):
rval = None
if eval_points[0] is not None:
rval = self.make_node(eval_points[0], inputs[1]).outputs[0]
if eval_points[1] is not None:
if rval is None:
rval = self.make_node(inputs[0], eval_points[1]).outputs[0]
else:
rval += self.make_node(inputs[0], eval_points[1]).outputs[0]
return [rval]
def grad(self, inp, grads):
inputs, kerns = inp
(gz,) = grads
if self.imshp != self.imshp_logical or self.kshp != self.kshp_logical:
raise NotImplementedError("todo")
if self.out_mode == "valid" and (self.dx, self.dy) != (1, 1):
raise NotImplementedError(
"ERROR: ConvOp.grad is now disabled for 'valid' convolutions with"
" stride != (1, 1); call aesara.tensor.nnet.conv2d() instead."
)
if self.dx not in (1, 2) or self.dy not in (1, 2):
raise NotImplementedError(
"ERROR: We disable ConvOp.grad now when output_mode is not"
" 'valid' and dx or dy are greater than 2, as there is a bug"
" in it. See `abstract_conv2d <>`_ for a version that support this."
)
all_shape = self.has_all_shape(self.imshp, self.kshp, self.nkern, self.bsize)
if not all_shape and (self.dx != 1 or self.dy != 1):
raise ValueError(
"ConvOp.grad when dx!=1 or dy!=1 we must have all "
"the optional shape information"
)
# Determine gradient on kernels ########
assert inputs.ndim == 4 and kerns.ndim == 4
newin = inputs.dimshuffle((1, 0, 2, 3))
newgz = gz.dimshuffle((1, 0, 2, 3))
if self.out_mode == "valid":
(img, filters) = (newin, newgz)
kshp_logical = self.fulloutshp
kshp_logical_top_aligned = False
imshp_logical = None
(bsize, nkern) = (self.imshp[0], self.nkern)
imshp = (self.bsize, self.imshp[1], self.imshp[2])
kshp = self.outshp
elif self.out_mode == "full":
(img, filters) = (newgz, newin)
kshp_logical = None
kshp_logical_top_aligned = True
imshp_logical = (self.bsize, self.fulloutshp[0], self.fulloutshp[1])
(bsize, nkern) = (self.nkern, self.imshp[0])
imshp = (self.bsize, self.outshp[0], self.outshp[1])
kshp = self.imshp[1:]
else:
raise NotImplementedError(
"Only [full,valid] modes are currently supported."
)
filters = filters[:, :, ::-1, ::-1] # flip them
dw = ConvOp(
imshp,
kshp,
nkern,
bsize,
1,
1,
output_mode="valid",
unroll_batch=None,
unroll_kern=None,
unroll_patch=None,
imshp_logical=imshp_logical,
kshp_logical=kshp_logical,
kshp_logical_top_aligned=kshp_logical_top_aligned,
version=self.version,
direction_hint="bprop weights",
verbose=self.verbose,
)
dw = dw(img, filters)
if all_shape:
assert all(o == k for o, k in zip(dw.owner.op.outshp, self.kshp))
if self.out_mode == "valid":
# before DimShuffle, dw is of shape visdim x nkern x kshp[0] x kshp[1]
dw = dw.dimshuffle((1, 0, 2, 3))
dw = dw[:, :, ::-1, ::-1]
# Determine gradient on inputs ########
mode = "valid"
if not self.out_mode == "full":
mode = "full"
filters = kerns.dimshuffle((1, 0, 2, 3))
filters = filters[:, :, ::-1, ::-1]
nkern = self.imshp[0]
imshp = (self.nkern, self.outshp[0], self.outshp[1])
imshp_logical = (self.nkern, self.fulloutshp[0], self.fulloutshp[1])
din = ConvOp(
imshp,
self.kshp,
nkern,
self.bsize,
1,
1,
output_mode=mode,
unroll_batch=None,
unroll_kern=None,
unroll_patch=None,
imshp_logical=imshp_logical,
kshp_logical=None,
version=-1, # we we change the mode, we don't forward the version.
direction_hint="bprop inputs",
verbose=self.verbose,
)
din = din(gz, filters)
assert all(
o is None or o == i for o, i in zip(din.owner.op.outshp, self.imshp[1:])
)
# din and dw should have the same broadcasting pattern as the
# parameters they are the gradient of (resp. inputs and kerns).
din = patternbroadcast(din, inputs.broadcastable)
dw = patternbroadcast(dw, kerns.broadcastable)
return [din, dw]
def c_headers(self, **kwargs):
return ["<numpy/noprefix.h>", "<iostream>", "<sstream>"]
def c_code_cache_version(self):
return (15, self.openmp, blas.blas_header_version())
def c_support_code(self, **kwargs):
return (
"""
#define STRIDES(arr) (PyArray_STRIDES(arr))
#define FULL 2
#define SAME 1
#define VALID 0
#define MOD %
using namespace std;
"""
+ blas.blas_header_text()
)
def use_blas(self):
"""Return True if we will generate code that use gemm."""
# the gemm version only support that case
if self.out_mode == "valid" and self.dx == 0 and self.dy == 0:
# We use a faster version in those case.
if (
self.imshp != self.imshp_logical
or self.kshp != self.kshp_logical
or self.unroll_patch
or self.unroll_batch > 0
or self.unroll_kern > 0
):
return False
return True
return False
def c_libraries(self, **kwargs):
if self.use_blas():
return blas.ldflags()
return []
def c_no_compile_args(self, **kwargs):
# when the ksph==(1,1) gcc 4.3.0 segfault during the
# compilation with -O3. This don't happen at -O2
if aesara.link.c.cmodule.gcc_version() in ["4.3.0"] and self.kshp == (1, 1):
return ["-O3"]
else:
return []
def c_compile_args(self, **kwargs):
ret = []
if self.use_blas():
ret = blas.ldflags(libs=False, flags=True)
if aesara.link.c.cmodule.gcc_version() in ["4.3.0"] and self.kshp == (1, 1):
ret += ["-O2"]
# Add the -fopenmp flags
ret += super().c_compile_args(**kwargs)
return ret
def c_lib_dirs(self, **kwargs):
if self.use_blas():
return blas.ldflags(libs=False, libs_dir=True)
return []
def c_header_dirs(self, **kwargs):
if self.use_blas():
return blas.ldflags(libs=False, include_dir=True)
return []
def c_code(self, node, name, inp, out, sub):
img2d, filtersflipped = inp
(z,) = out
if node.inputs[0].type.dtype != node.inputs[1].type.dtype:
raise NotImplementedError()
assert node.inputs[0].type.dtype == node.inputs[1].type.dtype
d = locals()
d.update(sub)
all_shape = self.has_all_shape(
self.imshp, self.kshp, self.nkern, self.bsize
) and self.has_all_shape(self.imshp_logical, self.kshp_logical)
d["self_out_mode"] = self.out_mode
d["self_dx"] = self.dx
d["self_dy"] = self.dy
d["mode"] = self.out_mode.upper()
d["affectation"] = "="
# Default values, will be overridden if the shape info is provided
d["self_bsize"] = f"PyArray_DIMS({d["img2d"]})[0]"
d["self_nkern"] = f"PyArray_DIMS({d["filtersflipped"]})[0]"
d["self_outshp0"] = "-1"
d["self_outshp1"] = "-1"
d["self_imshp0"] = f"PyArray_DIMS({d["img2d"]})[1]"
d["self_imshp1"] = f"PyArray_DIMS({d["img2d"]})[2]"
d["self_imshp2"] = f"PyArray_DIMS({d["img2d"]})[3]"
d["self_kshp0"] = f"PyArray_DIMS({d["filtersflipped"]})[2]"
d["self_kshp1"] = f"PyArray_DIMS({d["filtersflipped"]})[3]"
d["assert_size"] = ""
# Override the default value if we have it
if self.kshp[0] is not None:
expected = d["self_kshp0"]
value = self.kshp[0]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of rows in the filter "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_kshp0"] = self.kshp[0]
if self.kshp[1] is not None:
expected = d["self_kshp1"]
value = self.kshp[1]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of columns in the filter "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_kshp1"] = self.kshp[1]
if self.outshp[0] is not None:
expected = "dim_zz[0]"
value = self.outshp[0]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of rows in the output "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_outshp0"] = self.outshp[0]
if self.outshp[1] is not None:
expected = "dim_zz[1]"
value = self.outshp[1]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of columns in the output "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_outshp1"] = self.outshp[1]
if self.imshp[0] is not None:
expected = d["self_imshp0"]
value = self.imshp[0]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the image stack size (%%ld) "
"isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
expected = "kerns_dim[1]"
value = self.imshp[0]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the kernel stack size (%%ld) "
"isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_imshp0"] = self.imshp[0]
if self.imshp[1] is not None:
expected = d["self_imshp1"]
value = self.imshp[1]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of rows in the image "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_imshp1"] = self.imshp[1]
if self.imshp[2] is not None:
expected = d["self_imshp2"]
value = self.imshp[2]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of columns in the image "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_imshp2"] = self.imshp[2]
if self.bsize is not None:
expected = d["self_bsize"]
value = self.bsize
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the batch size (%%ld) "
"isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_bsize"] = self.bsize
if self.nkern is not None:
expected = d["self_nkern"]
value = self.nkern
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of kernels in the filter "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_nkern"] = self.nkern
# Other hard coded stuff only if we have all shapes
if all_shape:
d["self_kshp_logical_r"] = self.kshp_logical[0]
d["self_kshp_logical_c"] = self.kshp_logical[1]
d["self_kshp_logical_stride_r"] = int(
np.ceil(self.kshp_logical[0] / float(self.kshp[0]))
)
d["self_kshp_logical_stride_c"] = int(
np.ceil(self.kshp_logical[1] / float(self.kshp[1]))
)
d["self_imshp_logical_r"] = self.imshp_logical[1]
# numpy.B. 1 not 0
d["self_imshp_logical_c"] = self.imshp_logical[2]
# numpy.B. 2 not 1
d["self_imshp_logical_stride_r"] = int(
np.ceil(self.imshp_logical[1] / float(self.imshp[1]))
)
d["self_imshp_logical_stride_c"] = int(
np.ceil(self.imshp_logical[2] / float(self.imshp[2]))
)
if not self.imshp[0] == 1:
d["affectation"] = "+="
d["all_shape"] = "1"
d["dim_zz_const"] = "const"
d["dim_zz_affect"] = ""
else:
d["affectation"] = "+="
d["all_shape"] = "0"
d["dim_zz_const"] = ""
d["dim_zz_affect"] = (
"""
if (mode == FULL) {
dim_zz[0] = (int)ceil((dim_im[0]+dim_ker0-1)/float(%(self_dx)s));
dim_zz[1] = (int)ceil((dim_im[1]+dim_ker1-1)/float(%(self_dy)s));
} else {
dim_zz[0] = (int)ceil((dim_im[0]-dim_ker0+1)/float(%(self_dx)s));
dim_zz[1] = (int)ceil((dim_im[1]-dim_ker1+1)/float(%(self_dy)s));
}
"""
% d
)
d["assert_size"] += (
"""
// Check the stack size of the filter and images are equals
if(kerns_dim[1] != img2d_dim[1]){
PyErr_Format(PyExc_ValueError,
"the filter stack size (%%ld) and image stack size (%%ld) differ",
(long)kerns_dim[1], (long)img2d_dim[1]);
%(fail)s;
}
"""
% sub
)
if self.kshp_logical_top_aligned:
d["self_kshp_logical_offset_r"] = 0
d["self_kshp_logical_offset_c"] = 0
elif all_shape:
rstride = d["self_kshp_logical_stride_r"]
cstride = d["self_kshp_logical_stride_c"]
d["self_kshp_logical_offset_r"] = (
self.kshp_logical[0] - (self.kshp[0] * rstride) - 1 + rstride
) % rstride
d["self_kshp_logical_offset_c"] = (
self.kshp_logical[1] - (self.kshp[1] * cstride) - 1 + cstride
) % cstride
del rstride, cstride
if node.inputs[0].type.dtype == "float32":
d["type"] = "float"
elif node.inputs[0].type.dtype == "float64":
d["type"] = "double"
else:
raise NotImplementedError(
f"Type {node.inputs[0].type.dtype} not implemented"
)
d["gemm"] = "dgemm_"
if not d["type"] == "double":
d["gemm"] = "sgemm_"
if self.imshp != self.imshp_logical or self.kshp != self.kshp_logical:
if self.verbose:
_logger.debug(
"return imshp!=imshp_logical or"
" self.kshp != self.kshp_logical shape version"
)
return _conv_op_code_a % d
if self.unroll_patch:
if self.verbose:
_logger.debug("return unroll patch version. all_shape=%s", all_shape)
return _conv_op_code_unroll_patch % d
if (self.unroll_batch is not None and self.unroll_batch > 0) or (
self.unroll_kern is not None and self.unroll_kern > 0
):
assert self.unroll_batch > 0
assert self.unroll_kern > 0
if self.verbose:
_logger.debug(
"return unrolled batch (%s) and kern code (%s)",
str(self.unroll_batch),
str(self.unroll_kern),
)
return gen_conv_code_unroll_batch_kern(
d, self.unroll_batch, self.unroll_kern
)
# TODO: should we choose the unroll size automatically with the bigger divisor under 5?
if self.out_mode == "valid" and self.dx == 0 and self.dy == 0:
if self.verbose:
_logger.debug("return gemm version")
return _conv_op_code_valid_gemm % d
else:
if self.verbose:
_logger.debug("return no gemm version")
return _conv_op_code_a % d
_conv_op_code_a = """
const int mode=%(mode)s;
int typenum=0, typenum_f=0;
PyArrayObject *ain1=NULL, *ain2=NULL;
PyArrayObject *filtersflipped_arr=NULL, *img2d_arr=NULL, *z_arr=NULL;
const %(type)s fill_value = 0;
int type_im=PyArray_TYPE(%(img2d)s);
int type_ker=PyArray_TYPE(%(filtersflipped)s);
npy_intp dim_zz[2]={%(self_outshp0)s,%(self_outshp1)s};
npy_intp dim_im_phys[2]={%(self_imshp1)s,%(self_imshp2)s};
npy_intp dim_im_log[2]={%(self_imshp_logical_r)s,%(self_imshp_logical_c)s};
npy_intp dim_ker_phys[2]={%(self_kshp0)s,%(self_kshp1)s};
npy_intp dim_ker_log[2]={%(self_kshp_logical_r)s,%(self_kshp_logical_c)s};
PyArray_Dims img2d_shape;
npy_intp img2d_dim[4]={1,1,0,0};
img2d_shape.ptr=img2d_dim;
img2d_shape.len=4;
PyArray_Dims kerns_shape;
npy_intp kerns_dim[4]={1,1,0,0};
kerns_shape.ptr=kerns_dim;
kerns_shape.len=4;
PyObject *img2d=NULL, *contig, *filtersflipped=NULL;
if(PyArray_NDIM(%(img2d)s)==2){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==3){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==4){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[3];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[1]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else {
PyErr_SetString(PyExc_ValueError, "img don't have a good shape");
%(fail)s;
}
if(PyArray_NDIM(%(filtersflipped)s)==3){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else if(PyArray_NDIM(%(filtersflipped)s)==4){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[3];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[1]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else{
std::stringstream temp;
temp << "nddim="<<PyArray_NDIM(%(filtersflipped)s);
std::string param = temp.str();
PyErr_SetString(PyExc_ValueError,
("kernel don't have a good shape. " + param).c_str());
%(fail)s;
}
%(assert_size)s
img2d = PyArray_Newshape(%(img2d)s,&img2d_shape, NPY_CORDER);
img2d_arr = (PyArrayObject*)img2d;
if ((PyArray_STRIDES(img2d_arr)[3] != (npy_intp)sizeof(%(type)s))
|| (PyArray_STRIDES(img2d_arr)[2] != PyArray_DIMS(img2d_arr)[3]*(npy_intp)sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)img2d));
Py_DECREF(img2d);
img2d = contig;
img2d_arr = (PyArrayObject*)img2d;
if (!PyArray_ISCONTIGUOUS(img2d_arr)){
PyErr_SetString(PyExc_ValueError, "img2d isn't contiguous");
%(fail)s;
}
}
filtersflipped = PyArray_Newshape(%(filtersflipped)s,&kerns_shape, NPY_CORDER);
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if ((PyArray_STRIDES(filtersflipped_arr)[3] != (npy_intp)sizeof(%(type)s))
|| (PyArray_STRIDES(filtersflipped_arr)[2] != PyArray_DIMS(filtersflipped_arr)[3]*(npy_intp)sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)filtersflipped));
Py_DECREF(filtersflipped);
filtersflipped = contig;
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if (!PyArray_ISCONTIGUOUS(filtersflipped_arr)){
PyErr_SetString(PyExc_ValueError, "filtersflipped isn't contiguous");
%(fail)s;
}
}
if(mode != VALID && mode != FULL){
PyErr_SetString(PyExc_ValueError,
"invalid mode, only full and valid are supported");
%(fail)s;
}
typenum = PyArray_ObjectType((PyObject*)%(img2d)s, 0);
typenum_f = PyArray_ObjectType((PyObject*)%(filtersflipped)s, 0);
if (typenum < 0) {PyErr_SetString(PyExc_ValueError, "Invalid type"); %(fail)s;}
if (typenum != typenum_f) {
PyErr_SetString(PyExc_ValueError, "Input types must match");
%(fail)s;
}
if (!img2d)
{
PyErr_SetString(PyExc_AssertionError, "!img2d");
%(fail)s;
}
if (!filtersflipped)
{
PyErr_SetString(PyExc_AssertionError, "!filtersflipped");
%(fail)s;
}
if ((!%(z)s)
|| *PyArray_DIMS(%(z)s)!=4
||(PyArray_DIMS(%(z)s)[0] != %(self_bsize)s)
||(PyArray_DIMS(%(z)s)[1] != %(self_nkern)s)
||(PyArray_DIMS(%(z)s)[2] != dim_zz[0])
||(PyArray_DIMS(%(z)s)[3] != dim_zz[1])
||!PyArray_ISCONTIGUOUS(%(z)s)
)
{
{Py_XDECREF(%(z)s);}
npy_intp dims[4] = {0,0,0,0};
dims[0]=%(self_bsize)s;
dims[1]=%(self_nkern)s;
dims[2]=dim_zz[0];
dims[3]=dim_zz[1];
%(z)s = (PyArrayObject*) PyArray_ZEROS(4, dims, typenum,0);
}else{
//PyArray_FILLWBYTE((PyObject*)%(z)s,0);
}
z_arr = (PyArrayObject*) %(z)s;
int Os[2];
Os[0]=%(self_outshp0)s;
Os[1]=%(self_outshp1)s;
//assertions
if (!PyArray_ISCONTIGUOUS(%(z)s))
{
PyErr_SetString(PyExc_AssertionError, "Output (%(z)s) not contiguous");
%(fail)s;
}
for(int b=0;b< %(self_bsize)s;b++){
for(int n_kern=0;n_kern<%(self_nkern)s;n_kern++){
%(type)s * __restrict__ out=(%(type)s *)(PyArray_GETPTR2(z_arr,b,n_kern));
for (int i = 0; i < dim_zz[0]*dim_zz[1]; ++i) out[i] = 0;
for(int stack_size=0;stack_size<%(self_imshp0)s;stack_size++){
const %(type)s * __restrict__ in=(%(type)s *)(PyArray_GETPTR2(img2d_arr,b,stack_size));
const %(type)s * __restrict__ hvals=(%(type)s *)(PyArray_GETPTR2(filtersflipped_arr,n_kern,stack_size));
for (int iter_m=0; iter_m < Os[0]; iter_m++) {
// Reposition index into input image based on requested output size
//row position in logical output image
int pos_m = iter_m*%(self_dx)s;
//row anchor in logical input image (we will loop upward from here)
int new_m;
if (mode == FULL) new_m = pos_m ;
else new_m = (pos_m+dim_ker_log[0]-1);
for (int iter_n=0; iter_n < Os[1]; iter_n++) { // loop over columns
// current col position in logical output image
int pos_n=iter_n*%(self_dy)s;
%(type)s sum=0;
// Sum over kernel, if index into image is out of bounds
// fill with the value
// loop over logical rows in kernel
for (int j_log=0; j_log < %(self_kshp_logical_r)s; j_log++) {
// ind0_log: row position in logical input image
int ind0_log = (new_m-j_log);
if ((j_log < %(self_kshp_logical_offset_r)s) ||
(j_log - %(self_kshp_logical_offset_r)s) MOD %(self_kshp_logical_stride_r)s)
continue;
if (ind0_log MOD %(self_imshp_logical_stride_r)s)
continue;
int j_phys = ((j_log- %(self_kshp_logical_offset_r)s) /
%(self_kshp_logical_stride_r)s);
int ind0_phys = (ind0_log / %(self_imshp_logical_stride_r)s);
//std::cerr <<"j_log" << j_log << " j_phys " << j_phys << " " << ind0_phys << "\\n";
if(mode==FULL){
//This is a pointer to the current row of the kernel
const %(type)s * idx_hvals=&hvals[j_phys*dim_ker_phys[1]];
if(ind0_log < 0 || ind0_log >= dim_im_log[0]){
// the current row of the kernel is off the image
}else{
int k = max((int)(pos_n-dim_im_log[1])+1,0);
int max_k=min(pos_n+1,(int)dim_ker_log[1]);
const %(type)s * idx_in=&in[ind0_phys*dim_im_phys[1]];
for (int ind1_log=pos_n-k; k<max_k; k++,ind1_log--) {
if (1)
{
if ((k < %(self_kshp_logical_offset_c)s) ||
(k - %(self_kshp_logical_offset_c)s) MOD
%(self_kshp_logical_stride_c)s)
continue;
if (ind1_log MOD
%(self_imshp_logical_stride_c)s)
continue;
}
sum += idx_hvals[(k-%(self_kshp_logical_offset_c)s) /
%(self_kshp_logical_stride_c)s] *
idx_in[ind1_log / %(self_imshp_logical_stride_c)s];
}
}
}else{ // mode==VALID
//JB: should be dim_im[1] right? (was dim_im[0])
const %(type)s* idx_in=&in[ind0_phys*dim_im_phys[1]];
const %(type)s* idx_hvals=&hvals[j_phys*dim_ker_phys[1]];
int new_n = (pos_n+dim_ker_log[1]-1);
if (%(self_imshp_logical_stride_c)s != 1) // a general loop
{
for (int k=0,last=new_n; k < dim_ker_log[1]; k++,last--) {
if ((k < %(self_kshp_logical_offset_c)s) ||
(k - %(self_kshp_logical_offset_c)s) MOD
%(self_kshp_logical_stride_c)s)
continue;
else if (last MOD %(self_imshp_logical_stride_c)s)
continue;
else
{
sum+=idx_hvals[(k-%(self_kshp_logical_offset_c)s) /
%(self_kshp_logical_stride_c)s] *
idx_in[last/%(self_imshp_logical_stride_c)s];
}
}
}
else // self_imshp_stride_c == 1
{
int offset = %(self_kshp_logical_offset_c)s;
int k_phys=0;
for (int k_log=offset,last=new_n-offset;
k_log < dim_ker_log[1]; ) {
sum += idx_hvals[k_phys]*idx_in[last];
++k_phys;
last -= %(self_kshp_logical_stride_c)s;
k_log += %(self_kshp_logical_stride_c)s;
}
}
}
}//for j_log
out[iter_m*dim_zz[1]+iter_n] %(affectation)s sum;
}//for iter_n
}//for iter_m
}//for stack_size
if (0 && (mode==FULL)){
for (int i = 0; i < dim_zz[0]*dim_zz[1]; ++i)
std::cout << " " << out[i];
std::cout << "\\n";
}
}//for n_kern
}//for b
Py_XDECREF(img2d);
Py_XDECREF(filtersflipped);
"""
#########
# ConvOp c_code for valid mode (uses gemm)
#########
_conv_op_code_valid_gemm = """
int typenum=0, typenum_f=0;
PyArrayObject *ain1=NULL, *ain2=NULL, *img2d_arr=NULL, *z_arr=NULL;
const int NKERN = %(self_nkern)s;
int type_im=PyArray_TYPE(%(img2d)s);
int type_ker=PyArray_TYPE(%(filtersflipped)s);
npy_intp dim_zz[2]={%(self_outshp0)s,%(self_outshp1)s};
npy_intp dim_im[2]={%(self_imshp1)s,%(self_imshp2)s};
const npy_intp dim_ker0=%(self_kshp0)s;
const npy_intp dim_ker1=%(self_kshp1)s;
PyArray_Dims img2d_shape;
npy_intp img2d_dim[4]={1,1,0,0};
img2d_shape.ptr=img2d_dim;
img2d_shape.len=4;
PyArray_Dims kerns_shape;
npy_intp kerns_dim[4]={1,1,0,0};
kerns_shape.ptr=kerns_dim;
kerns_shape.len=4;
PyObject *img2d=NULL, *contig;
if(PyArray_NDIM(%(img2d)s)==2){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==3){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==4){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[3];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[1]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else {
PyErr_SetString(PyExc_ValueError, "img don't have a good shape");
%(fail)s;
}
if(PyArray_NDIM(%(filtersflipped)s)==3){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else if(PyArray_NDIM(%(filtersflipped)s)==4){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[3];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[1]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else{
std::stringstream temp;
temp << "nddim="<<PyArray_NDIM(%(filtersflipped)s);
std::string param = temp.str();
PyErr_SetString(PyExc_ValueError,
("kernel don't have a good shape. " + param).c_str());
%(fail)s;
}
if (NKERN != kerns_dim[0])
{
PyErr_SetString(PyExc_NotImplementedError, "nonsense nkern");
%(fail)s;
}
img2d = PyArray_Newshape(%(img2d)s,&img2d_shape, NPY_CORDER);
img2d_arr = (PyArrayObject*)img2d;
if ((PyArray_STRIDES(img2d_arr)[3] != (npy_intp)sizeof(%(type)s))
|| (PyArray_STRIDES(img2d_arr)[2] != PyArray_DIMS(img2d_arr)[3]*(npy_intp)sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)img2d));
Py_DECREF(img2d);
img2d = contig;
img2d_arr = (PyArrayObject*)img2d;
if (!PyArray_ISCONTIGUOUS(img2d_arr)){
PyErr_SetString(PyExc_ValueError, "img2d isn't contiguous");
%(fail)s;
}
}
typenum = PyArray_ObjectType((PyObject*)%(img2d)s, 0);
typenum_f = PyArray_ObjectType((PyObject*)%(filtersflipped)s, 0);
if (typenum < 0) {PyErr_SetString(PyExc_ValueError, "Invalid type"); %(fail)s;}
if (typenum != typenum_f) {PyErr_SetString(PyExc_ValueError, "Input types must match"); %(fail)s;}
if (!img2d) {
PyErr_SetString(PyExc_ValueError, "Null argument img2d");
%(fail)s;
}
if ((!%(z)s)
|| *PyArray_DIMS(%(z)s)!=4
||(PyArray_DIMS(%(z)s)[0] != %(self_bsize)s)
||(PyArray_DIMS(%(z)s)[1] != %(self_nkern)s)
||(PyArray_DIMS(%(z)s)[2] != dim_zz[0])
|| (PyArray_DIMS(%(z)s)[3] != dim_zz[1])
)
{
{Py_XDECREF(%(z)s);}
npy_intp dims[4] = {0,0,0,0};
dims[0]=%(self_bsize)s;
dims[1]=%(self_nkern)s;
dims[2]=dim_zz[0];
dims[3]=dim_zz[1];
%(z)s = (PyArrayObject*) PyArray_ZEROS(4, dims, typenum,0);
}else{
PyArray_FILLWBYTE((PyObject*)%(z)s,0);
}
z_arr = (PyArrayObject*) %(z)s;
%(assert_size)s
int Os[2];
Os[0] = dim_im[0]-dim_ker0+1;
Os[1] = dim_im[1]-dim_ker1+1;
// allocate a temporary buffer for storing the inner product of each nth kernel row
// with each row of an image
{
%(type)s * kbuf = (%(type)s *)malloc((Os[0] * NKERN + PyArray_Size((PyObject*)%(filtersflipped)s))* (npy_intp)sizeof(%(type)s));
int kbufstride = NKERN;
%(type)s * myfilters = kbuf + Os[0] * NKERN;
//copy out filtersflipped into filters un-flipped format
//std::cerr << "__filling myfilters__\\n";
for(int i=0;i < kerns_dim[0];++i){
for(int j=0;j < kerns_dim[1];++j){
for(int k=0;k < kerns_dim[2];++k){
for(int l=0;l < kerns_dim[3];++l){
%(type)s * ff = ((PyArray_NDIM(%(filtersflipped)s)) == 3)
? (%(type)s *)PyArray_GETPTR3(%(filtersflipped)s, i, kerns_dim[2]-1-k, kerns_dim[3]-1-l)
: (%(type)s *)PyArray_GETPTR4(%(filtersflipped)s, i, j, kerns_dim[2]-1-k, kerns_dim[3]-1-l);
myfilters[i * (kerns_dim[1]*kerns_dim[2]*kerns_dim[3])
+ j * (kerns_dim[2]*kerns_dim[3])
+ k * (kerns_dim[3])
+ l] = ff[0];
//std::cerr << " " << ff[0];
}
//std::cerr << "\\n";
}
//std::cerr << "(end of stack/batch " <<j << "/" << i << " ) \\n";
}
}
//std::cerr << "-----new loop ----\\n";
for(int b=0;b< %(self_bsize)s;b++){
for (int img_col = 0; img_col < Os[1]; ++img_col){
for (int filter_row = 0; filter_row < kerns_dim[2]; ++filter_row){
for (int stackidx = 0; stackidx < %(self_imshp0)s; ++stackidx){
%(type)s * img_colview =
(%(type)s *)(PyArray_GETPTR4(img2d, b, stackidx, filter_row, img_col));
%(type)s * filter_rows = myfilters + stackidx * (kerns_dim[2]*kerns_dim[3]) +
filter_row * kerns_dim[3];
//std::cerr << "filterview offset: " << filter_rows - myfilters << "\\n";
char N = 'N'; char T = 'T';
int Nz0 = Os[0];
int Nz1 = NKERN;
int K = kerns_dim[3];
%(type)s alpha = 1.0;
%(type)s beta = stackidx ? 1.0 : 0.0;
int imgview_stride = dim_im[1];
int filter_rows_stride =kerns_dim[1]*kerns_dim[2]*kerns_dim[3];
//remember, Fortran wants a column-major interpretation
assert(PyArray_STRIDES(img2d)[3] == (npy_intp)sizeof(%(type)s));
if (0){
std::cerr << "b " << b << " img_col " << img_col << " filterrow " << filter_row << " stackidx " <<stackidx << "\\n";
std::cerr << "colview (physical layout) stride: " << imgview_stride << "\\n";
for (int ii = 0; ii < Nz0; ++ii){
for (int jj = 0; jj < K; ++jj){
std::cerr << " " << img_colview[ii * imgview_stride + jj];
}
std::cerr << "\\n";
}
std::cerr << "filterview ("<<filter_row<<"'th rows) stride: " << filter_rows_stride << "\\n";
for (int ii = 0; ii < Nz1; ++ii){
for (int jj = 0; jj < K; ++jj){
std::cerr << " " << filter_rows[ii * filter_rows_stride + jj];
}
std::cerr << "\\n";
}
std::cerr << Nz1 << " " << Nz0 << " " << K << "\\n" ;
}
%(gemm)s(&T, &N,
&Nz1, &Nz0, &K,
&alpha,
filter_rows, &filter_rows_stride,
img_colview, &imgview_stride,
&beta, kbuf, &kbufstride);
if (0){
std::cerr << "z (logical layout) beta" << beta << "\\n";
for (int ii = 0; ii < Nz0; ++ii){
for (int jj = 0; jj < Nz1; ++jj){
std::cerr << " " << kbuf[ii * kbufstride + jj];
}
std::cerr << "\\n";
}
}
}
// now kbuf the sum over the stack, put it into the outbuf
for (int img_row = 0; img_row < Os[0]; ++img_row) {
for (int kernel_idx = 0; kernel_idx < NKERN; ++kernel_idx) {
%(type)s * z_p = (%(type)s *)PyArray_GETPTR4(%(z)s, b, kernel_idx, img_row, img_col);
if (0)
{
if (b >= PyArray_DIMS(%(z)s)[0]) %(fail)s;
if (kernel_idx >= PyArray_DIMS(%(z)s)[1]) %(fail)s;
if (img_row >= PyArray_DIMS(%(z)s)[2]) %(fail)s;
if (img_col >= PyArray_DIMS(%(z)s)[3]) %(fail)s;
}
z_p[0] += kbuf[img_row * kbufstride + kernel_idx];
}
}
}
}
}
free(kbuf);
}
Py_XDECREF(img2d);
"""
def gen_conv_code_unroll_batch_kern(d, unroll_bsize=1, unroll_ksize=1):
"""
c_code for ConvOp that unroll the batch size loop.
"""
assert unroll_bsize > 0 and unroll_ksize > 0
if (
"unroll_bsize" in d
or "unroll_ksize" in d
or "unroll_iter" in d
or "unroll_biter" in d
or "unroll_kiter" in d
):
raise ValueError(
"We can't use this dictionary as we will overwrite some of its content"
)
d = d.copy()
d["unroll_bsize"] = unroll_bsize
d["unroll_ksize"] = unroll_ksize
def my_dup(st, size):
s = ""
for i in range(size):
d["unroll_iter"] = i
s += st % d
return s + "\n"
def my_dup2(st):
s = ""
iter = 0
for i in range(unroll_bsize):
d["unroll_biter"] = i
for j in range(unroll_ksize):
d["unroll_kiter"] = j
d["unroll_iter"] = iter
iter += 1
s += st % d
return s + "\n"
ret = (
"""
const int mode=%(mode)s;
int typenum=0, typenum_f=0;
PyArrayObject *ain1=NULL, *ain2=NULL, *filtersflipped_arr=NULL, *img2d_arr=NULL, *z_arr=NULL;;
const %(type)s fill_value = 0;
int type_im=PyArray_TYPE(%(img2d)s);
int type_ker=PyArray_TYPE(%(filtersflipped)s);
npy_intp dim_zz[2]={%(self_outshp0)s,%(self_outshp1)s};
npy_intp dim_im[2]={%(self_imshp1)s,%(self_imshp2)s};
const npy_intp dim_ker0=%(self_kshp0)s;
const npy_intp dim_ker1=%(self_kshp1)s;
PyArray_Dims img2d_shape;
npy_intp img2d_dim[4]={1,1,0,0};
img2d_shape.ptr=img2d_dim;
img2d_shape.len=4;
PyArray_Dims kerns_shape;
npy_intp kerns_dim[4]={1,1,0,0};
kerns_shape.ptr=kerns_dim;
kerns_shape.len=4;
PyObject *img2d=NULL, *contig, *filtersflipped=NULL;
if(PyArray_NDIM(%(img2d)s)==2){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==3){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==4){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[3];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[1]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else {
std::stringstream temp;
temp << "nddim="<<PyArray_NDIM(%(img2d)s);
std::string param = temp.str();
PyErr_SetString(PyExc_ValueError,
("img don't have a good shape. " + param).c_str());
%(fail)s;
}
if(PyArray_NDIM(%(filtersflipped)s)==3){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else if(PyArray_NDIM(%(filtersflipped)s)==4){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[3];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[1]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else{
PyErr_SetString(PyExc_ValueError, "kernel don't have a good shape");
%(fail)s;
}
%(assert_size)s
img2d = PyArray_Newshape(%(img2d)s,&img2d_shape, NPY_CORDER);
img2d_arr = (PyArrayObject*)img2d;
if ((PyArray_STRIDES(img2d_arr)[3] != (npy_intp)sizeof(%(type)s))
|| (PyArray_STRIDES(img2d_arr)[2] != PyArray_DIMS(img2d_arr)[3]*(npy_intp)sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)img2d));
Py_DECREF(img2d);
img2d = contig;
img2d_arr = (PyArrayObject*)img2d;
if (!PyArray_ISCONTIGUOUS(img2d_arr)){
PyErr_SetString(PyExc_ValueError, "img2d isn't contiguous");
%(fail)s;
}
}
filtersflipped = PyArray_Newshape(%(filtersflipped)s,&kerns_shape, NPY_CORDER);
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if ((PyArray_STRIDES(filtersflipped_arr)[3] != (npy_intp)sizeof(%(type)s))
|| (PyArray_STRIDES(filtersflipped_arr)[2] != PyArray_DIMS(filtersflipped_arr)[3]*(npy_intp)sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)filtersflipped));
Py_DECREF(filtersflipped);
filtersflipped = contig;
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if (!PyArray_ISCONTIGUOUS(filtersflipped_arr)){
PyErr_SetString(PyExc_ValueError, "filtersflipped isn't contiguous");
%(fail)s;
}
}
if(mode != VALID && mode != FULL){
PyErr_SetString(PyExc_ValueError, "invalid mode, only full and valid are supported"); %(fail)s;
}
typenum = PyArray_ObjectType((PyObject*)%(img2d)s, 0);
typenum_f = PyArray_ObjectType((PyObject*)%(filtersflipped)s, 0);
if (typenum < 0) {PyErr_SetString(PyExc_ValueError, "Invalid type"); %(fail)s;}
if (typenum != typenum_f) {PyErr_SetString(PyExc_ValueError, "Input types must match"); %(fail)s;}
if (!img2d)
{
PyErr_SetString(PyExc_AssertionError, "!img2d");
%(fail)s;
}
if (!filtersflipped)
{
PyErr_SetString(PyExc_AssertionError, "!filtersflipped");
%(fail)s;
}
if ((!%(z)s)
|| *PyArray_DIMS(%(z)s)!=4
||(PyArray_DIMS(%(z)s)[0] != %(self_bsize)s)
||(PyArray_DIMS(%(z)s)[1] != %(self_nkern)s)
||(PyArray_DIMS(%(z)s)[2] != dim_zz[0])
||(PyArray_DIMS(%(z)s)[3] != dim_zz[1])
||!PyArray_ISCONTIGUOUS(%(z)s)
)
{
{Py_XDECREF(%(z)s);}
npy_intp dims[4] = {0,0,0,0};
dims[0]=%(self_bsize)s;
dims[1]=%(self_nkern)s;
dims[2]=dim_zz[0];
dims[3]=dim_zz[1];
%(z)s = (PyArrayObject*) PyArray_ZEROS(4, dims, typenum,0);
}else{
//PyArray_FILLWBYTE((PyObject*)%(z)s,0);
}
z_arr = (PyArrayObject*) %(z)s;
int Os[2];
Os[0]=%(self_outshp0)s;
Os[1]=%(self_outshp1)s;
//assertions
if (!PyArray_ISCONTIGUOUS(%(z)s))
{
PyErr_SetString(PyExc_AssertionError, "Output (%(z)s) not contiguous");
%(fail)s;
}
for(int b=0;b< %(self_bsize)s ;b+=%(unroll_bsize)s){
for(int n_kern=0;n_kern<%(self_nkern)s;n_kern+=%(unroll_ksize)s){
"""
% d
)
ret += my_dup2(
"%(type)s * __restrict__ out%(unroll_iter)s=(%(type)s *)(PyArray_GETPTR2(z_arr,b+%(unroll_biter)s,n_kern+%(unroll_kiter)s));"
)
ret += my_dup(
"for (int i = 0; i < dim_zz[0]*dim_zz[1]; ++i) out%(unroll_iter)s[i] = 0;",
unroll_bsize * unroll_ksize,
)
ret += (
"""
for(int stack_size=0;stack_size<%(self_imshp0)s;stack_size++){
"""
% d
)
ret += my_dup(
"const %(type)s * __restrict__ in%(unroll_iter)d=(%(type)s *)(PyArray_GETPTR2(img2d_arr,b+%(unroll_iter)s,stack_size));",
unroll_bsize,
)
ret += my_dup(
"const %(type)s * __restrict__ hvals%(unroll_iter)s=(%(type)s *)(PyArray_GETPTR2(filtersflipped_arr,n_kern+%(unroll_iter)s,stack_size));",
unroll_ksize,
)
ret += (
"""
int new_m;
for (int iter_m=0; iter_m < Os[0]; iter_m++) {
// Reposition index into input image based on requested output size
int pos_m = iter_m*%(self_dx)s;//The position of the patch in the image
if (mode == FULL) new_m = pos_m ;
else new_m = (pos_m+dim_ker0-1);
for (int iter_n=0; iter_n < Os[1]; iter_n++) { // loop over columns
int pos_n=iter_n*%(self_dy)s;
"""
% d
)
ret += my_dup("%(type)s sum%(unroll_iter)s=0;", unroll_bsize * unroll_ksize)
ret += (
"""
// Sum over kernel, if index into image is out of bounds
// fill with the value
for (int j=0; j < dim_ker0; j++) {
int ind0 = (new_m-j);
if(mode==FULL){
"""
% d
)
ret += my_dup(
"const %(type)s * idx_hvals%(unroll_iter)s=&hvals%(unroll_iter)s[j*dim_ker1];",
unroll_ksize,
)
ret += (
"""
if(ind0 < 0 || ind0 >= dim_im[0]){
if(fill_value!=0)
for (int k=0; k < dim_ker1; k++) {
"""
% d
)
ret += my_dup2("sum%(unroll_iter)s += idx_hvals%(unroll_kiter)s[k] * fill_value;")
ret += (
"""
}
}else{
//do the part where kernel is to the right of the img
int k=0,max_k=max((int)(pos_n-dim_im[1])+1,0);
if(fill_value!=0){
for(k=0;k<max_k;k++){
"""
% d
)
ret += my_dup2("sum%(unroll_iter)s += idx_hvals%(unroll_kiter)s[k] * fill_value;")
ret += (
"""
}
}else {k=max_k;}
//do the part where the kernel is on the img
max_k=min(pos_n+1,(int)dim_ker1);
"""
% d
)
ret += my_dup(
"const %(type)s * idx_in%(unroll_iter)s=&in%(unroll_iter)s[ind0*dim_im[1]];",
unroll_bsize,
)
ret += (
"""
for (int ind1=pos_n-k; k<max_k; k++,ind1--) {
"""
% d
)
ret += my_dup2(
"sum%(unroll_iter)s+= idx_hvals%(unroll_kiter)s[k] * idx_in%(unroll_biter)s[ind1];"
)
ret += (
"""
}
//do the part to the left of the img
if(fill_value!=0)
for(;k<dim_ker1;k++){
"""
% d
)
ret += my_dup2("sum%(unroll_iter)s += idx_hvals%(unroll_kiter)s[k] * fill_value;")
ret += (
"""
}
}
}else{//valid mode
"""
% d
)
ret += my_dup(
"const %(type)s* idx_in%(unroll_iter)s=&in%(unroll_iter)s[ind0*dim_im[1]];",
unroll_bsize,
)
ret += my_dup(
"const %(type)s* idx_hvals%(unroll_iter)s=&hvals%(unroll_iter)s[j*dim_ker1];",
unroll_ksize,
)
ret += (
"""
int new_n = (pos_n+dim_ker1-1);
for (int k=0,last=new_n; k < dim_ker1; k++,last--) {
"""
% d
)
ret += my_dup2(
"sum%(unroll_iter)s+=idx_hvals%(unroll_kiter)s[k]*idx_in%(unroll_biter)s[last];"
)
ret += (
"""
}
}
}//for j
"""
% d
)
ret += my_dup(
"out%(unroll_iter)s[iter_m*dim_zz[1]+iter_n] %(affectation)s sum%(unroll_iter)s;",
unroll_bsize * unroll_ksize,
)
ret += """
}//for n
}//for m
}//for stack_size
}//for n_kern
}//for b
Py_XDECREF(img2d);
Py_XDECREF(filtersflipped);
"""
return ret
_conv_op_code_unroll_patch = """
const int mode=%(mode)s;
int typenum=0, typenum_f=0;
PyArrayObject *ain1=NULL, *ain2=NULL, *filtersflipped_arr=NULL, *img2d_arr=NULL, *z_arr=NULL;
const %(type)s fill_value = 0;//only value of 0 are currently tested and correctly implemented
int type_im=PyArray_TYPE(%(img2d)s);
int type_ker=PyArray_TYPE(%(filtersflipped)s);
const npy_intp dim_im[2]={%(self_imshp1)s,%(self_imshp2)s};
//The following line caused gcc 4.3.0 20080428 (Red Hat 4.3.0-8) to crash
//const npy_intp dim_ker[2]={%(self_kshp0)s,%(self_kshp1)s};
// The next line had gcc don't crash.
const npy_intp dim_ker0=%(self_kshp0)s;
const npy_intp dim_ker1=%(self_kshp1)s;
%(dim_zz_const)s npy_intp dim_zz[2]={%(self_outshp0)s,%(self_outshp1)s};
%(dim_zz_affect)s
PyArray_Dims img2d_shape;
npy_intp img2d_dim[4]={1,1,0,0};
img2d_shape.ptr=img2d_dim;
img2d_shape.len=4;
PyArray_Dims kerns_shape;
npy_intp kerns_dim[4]={1,1,0,0};
kerns_shape.ptr=kerns_dim;
kerns_shape.len=4;
PyObject *img2d=NULL, *contig, *filtersflipped=NULL;
if(PyArray_NDIM(%(img2d)s)==2){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==3){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==4){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[3];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[1]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else {
PyErr_Format(PyExc_ValueError,
"image don't have a good number of dimensions %%d. ", PyArray_NDIM(%(filtersflipped)s));
%(fail)s;
}
if(PyArray_NDIM(%(filtersflipped)s)==3){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else if(PyArray_NDIM(%(filtersflipped)s)==4){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[3];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[1]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else{
PyErr_Format(PyExc_ValueError,
"kernel don't have a good number of dimensions %%d. ", PyArray_NDIM(%(filtersflipped)s));
%(fail)s;
}
%(assert_size)s
img2d = PyArray_Newshape(%(img2d)s,&img2d_shape, NPY_CORDER);
img2d_arr = (PyArrayObject*)img2d;
if ((PyArray_STRIDES(img2d_arr)[3] != sizeof(%(type)s))
|| (PyArray_STRIDES(img2d_arr)[2] != PyArray_DIMS(img2d_arr)[3]*sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)img2d));
Py_DECREF(img2d);
img2d = contig;
img2d_arr = (PyArrayObject*)img2d;
if (!PyArray_ISCONTIGUOUS(img2d_arr)){
PyErr_SetString(PyExc_ValueError, "img2d isn't contiguous");
%(fail)s;
}
}
filtersflipped = PyArray_Newshape(%(filtersflipped)s,&kerns_shape, NPY_CORDER);
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if ((PyArray_STRIDES(filtersflipped_arr)[3] != sizeof(%(type)s))
|| (PyArray_STRIDES(filtersflipped_arr)[2] != PyArray_DIMS(filtersflipped_arr)[3]*sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)filtersflipped));
Py_DECREF(filtersflipped);
filtersflipped = contig;
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if (!PyArray_ISCONTIGUOUS(filtersflipped_arr)){
PyErr_SetString(PyExc_ValueError, "filtersflipped isn't contiguous");
%(fail)s;
}
}
if(mode != VALID && mode != FULL){
PyErr_SetString(PyExc_ValueError, "invalid mode, only full and valid are supported"); %(fail)s;
}
if(dim_zz[0]<=0 || dim_zz[1]<=0){
PyErr_Format(PyExc_ValueError,
"Output dimensions are not valid %%ldx%%ld",(long int)dim_zz[0],(long int)dim_zz[1]);
%(fail)s;
}
typenum = PyArray_ObjectType((PyObject*)%(img2d)s, 0);
typenum_f = PyArray_ObjectType((PyObject*)%(filtersflipped)s, 0);
if (typenum < 0) {PyErr_SetString(PyExc_ValueError, "Invalid type"); %(fail)s;}
if (typenum != typenum_f) {PyErr_SetString(PyExc_ValueError, "Input types must match"); %(fail)s;}
if (!img2d) %(fail)s;
if (!filtersflipped) %(fail)s;
if ((!%(z)s)
|| *PyArray_DIMS(%(z)s)!=4
||(PyArray_DIMS(%(z)s)[0] != %(self_bsize)s)
||(PyArray_DIMS(%(z)s)[1] != %(self_nkern)s)
||(PyArray_DIMS(%(z)s)[2] != dim_zz[0])
|| (PyArray_DIMS(%(z)s)[3] != dim_zz[1])
)
{
if (%(z)s) Py_DECREF(%(z)s);
npy_intp dims[4] = {0,0,0,0};
if(!dims) %(fail)s;
dims[0]=%(self_bsize)s;
dims[1]=%(self_nkern)s;
dims[2]=dim_zz[0];
dims[3]=dim_zz[1];
%(z)s = (PyArrayObject*) PyArray_ZEROS(4, dims, typenum,0);
}else{
//PyArray_FILLWBYTE((PyObject*)%(z)s,0);
}
z_arr = (PyArrayObject*) %(z)s;
// assert the output is C-contiguous
if (!PyArray_ISCONTIGUOUS(%(z)s))
{
PyErr_SetString(PyExc_AssertionError, "Output (%(z)s) not contiguous");
%(fail)s;
}
//The if on the number of loop make a speed up for small array.
//with g++ 4.5.1. The compiler should be smart enough to do this himself!
#pragma omp parallel for schedule(static) if(%(self_bsize)s * %(self_nkern)s > 1)
// We merge the 2 loop into one to make it easier to parallelize on both
// This is the equivalent of those 2 lines.
//for(int b=0;b< %(self_bsize)s;b++){
// for(int n_kern=0;n_kern<%(self_nkern)s;n_kern++){
for(int batch_kern_idx=0;
batch_kern_idx < %(self_bsize)s * %(self_nkern)s;
batch_kern_idx++){
int b = batch_kern_idx / %(self_nkern)s;
int n_kern = batch_kern_idx %% %(self_nkern)s;
%(type)s * __restrict__ out=(%(type)s *)(PyArray_GETPTR2(z_arr,b,n_kern));
for (int i = 0; i < dim_zz[0]*dim_zz[1]; ++i) out[i] = 0;
for(int stack_size=0;stack_size<%(self_imshp0)s;stack_size++){
const %(type)s * __restrict__ in=(%(type)s *)(PyArray_GETPTR2(img2d_arr,b,stack_size));
const %(type)s * __restrict__ hvals=(%(type)s *)(PyArray_GETPTR2(filtersflipped_arr,n_kern,stack_size));
int new_m;
for (int iter_m=0; iter_m < dim_zz[0]; iter_m++) {
// Reposition index into input image based on requested output size
int pos_m = iter_m*%(self_dx)s;//The position of the patch in the image
if (mode == FULL) new_m = pos_m ;
else new_m = (pos_m+dim_ker0-1);
for (int iter_n=0; iter_n < dim_zz[1]; iter_n++) { // loop over columns
int pos_n=iter_n*%(self_dy)s;
%(type)s sum=0;
%(type)s sum2=0;
%(type)s sum3=0;
%(type)s sum4=0;
int nb_sum=0;
// Sum over kernel, if index into image is out of bounds
// fill with the value
for (int j=0; j < dim_ker0; j++) {
int ind0 = (new_m-j);
if(mode==FULL){
const %(type)s * idx_hvals=&hvals[j*dim_ker1];
if(ind0 < 0 || ind0 >= dim_im[0]){
if(fill_value!=0)
for (int k=0; k < dim_ker1; k++) {
sum+= idx_hvals[k] * fill_value;
}
}else{
//do the part where kernel is to the right of the img
int k=0,max_k=max((int)(pos_n-dim_im[1])+1,0);
if(fill_value!=0){
for(k=0;k<max_k;k++){
sum+= idx_hvals[k]*fill_value;
}
}else {k=max_k;}
//do the part where the kernel is on the img
max_k=min(pos_n+1,(int)dim_ker1);
const %(type)s * idx_in=&in[ind0*dim_im[1]];
if(iter_n + 4*%(self_dy)s < dim_zz[1]
&& iter_n>dim_ker1-1
&& iter_n<dim_im[1]-dim_ker1+1-3){
nb_sum=4;
for (int ind1=pos_n-k; k<max_k; k++,ind1--) {
sum+=idx_hvals[k]*idx_in[ind1];
sum2+=idx_hvals[k]*idx_in[ind1+%(self_dy)s];
sum3+=idx_hvals[k]*idx_in[ind1+2*%(self_dy)s];
sum4+=idx_hvals[k]*idx_in[ind1+3*%(self_dy)s];
}
}else if(iter_n + 2*%(self_dy)s < dim_zz[1]
&& iter_n>dim_ker1-1
&& iter_n<dim_im[1]-dim_ker1+1){
nb_sum=2;
for (int ind1=pos_n-k; k<max_k; k++,ind1--) {
sum+=idx_hvals[k]*idx_in[ind1];
sum2+=idx_hvals[k]*idx_in[ind1+%(self_dy)s];
}
}else{
nb_sum=1;
/*
%(type)s sum_=0;
if((k-max_k) & 0x1 != 0){
sum+= idx_hvals[k] * idx_in[pos_n-k];
}
for (int ind1=pos_n-k; k<max_k; k+=2,ind1-=2) {
sum+= idx_hvals[k] * idx_in[ind1];
sum_+= idx_hvals[k+1] * idx_in[ind1-1];
}
sum+=sum_;
*/
for (int ind1=pos_n-k; k<max_k; k++,ind1--) {
sum+=idx_hvals[k]*idx_in[ind1];
}
}
//do the part to the left of the img
if(fill_value!=0)
for(;k<dim_ker1;k++) sum+= idx_hvals[k]*fill_value;
}
}else{//valid mode
const %(type)s* idx_in=&in[ind0*dim_im[1]];
const %(type)s* idx_hvals=&hvals[j*dim_ker1];
if(iter_n + 4*%(self_dy)s < dim_zz[1]){
nb_sum=4;
for (int k=dim_ker1-1,im_idx=pos_n; k >=0; k--,im_idx++) {
sum+=idx_hvals[k]*idx_in[im_idx];
sum2+=idx_hvals[k]*idx_in[im_idx+%(self_dy)s];
sum3+=idx_hvals[k]*idx_in[im_idx+2*%(self_dy)s];
sum4+=idx_hvals[k]*idx_in[im_idx+3*%(self_dy)s];
}
}else if(iter_n + 2*%(self_dy)s < dim_zz[1]){
nb_sum=2;
for (int k=dim_ker1-1,im_idx=pos_n; k >=0; k--,im_idx++) {
sum+=idx_hvals[k]*idx_in[im_idx];
sum2+=idx_hvals[k]*idx_in[im_idx+%(self_dy)s];
}
}else{
nb_sum=1;
for (int k=dim_ker1-1,im_idx=pos_n; k >=0; k--,im_idx++) {
sum+=idx_hvals[k]*idx_in[im_idx];
}
}
}//else valid mode
}//for j
switch(nb_sum){
case 4: out[iter_m*dim_zz[1]+iter_n+3] %(affectation)s sum4;
case 3: out[iter_m*dim_zz[1]+iter_n+2] %(affectation)s sum3;
case 2: out[iter_m*dim_zz[1]+iter_n+1] %(affectation)s sum2;
case 1: out[iter_m*dim_zz[1]+iter_n] %(affectation)s sum;
}
iter_n+=nb_sum-1;
}//for iter_n
}//for iter_m
}//for stack_size
}//for b and n_kern
Py_XDECREF(img2d);
Py_XDECREF(filtersflipped);
"""
| """
Contains an Op for convolving input images with a set of filters. This was
developed especially for Convolutional Neural Networks.
For related ops, including downsampling and subsampling, see
tensor.signal and tensor.signal.pool.
See especially conv2d().
"""
import logging
import warnings
import numpy as np
from scipy.signal.signaltools import _bvalfromboundary, _valfrommode
from scipy.signal.sigtools import _convolve2d
import aesara
from aesara.graph.basic import Apply
from aesara.graph.op import OpenMPOp
from aesara.tensor import blas
from aesara.tensor.basic import (
as_tensor_variable,
get_scalar_constant_value,
patternbroadcast,
)
from aesara.tensor.exceptions import NotScalarConstantError
from aesara.tensor.nnet.abstract_conv import get_conv_output_shape, get_conv_shape_1axis
from aesara.tensor.type import discrete_dtypes, tensor
__docformat__ = "restructuredtext en"
_logger = logging.getLogger("aesara.tensor.nnet.conv")
def conv2d(
input,
filters,
image_shape=None,
filter_shape=None,
border_mode="valid",
subsample=(1, 1),
**kargs,
):
"""
Deprecated, old conv2d interface.
This function will build the symbolic graph for convolving a stack of
input images with a set of filters. The implementation is modelled after
Convolutional Neural Networks (CNN). It is simply a wrapper to the ConvOp
but provides a much cleaner interface.
Parameters
----------
input : symbolic 4D tensor
Mini-batch of feature map stacks, of shape
(batch size, stack size, nb row, nb col)
see the optional parameter image_shape
filters: symbolic 4D tensor
Set of filters used in CNN layer of shape
(nb filters, stack size, nb row, nb col)
see the optional parameter filter_shape
border_mode : {'valid', 'full'}
'valid'only apply filter to complete patches of the image. Generates
output of shape: image_shape - filter_shape + 1.
'full' zero-pads image to multiple of filter shape to generate output
of shape: image_shape + filter_shape - 1.
subsample: tuple of len 2
Factor by which to subsample the output. Also called strides elsewhere.
image_shape: None, tuple/list of len 4 of int, None or Constant variable
The shape of the input parameter.
Optional, used for optimization like loop unrolling
You can put None for any element of the list to tell that this element
is not constant.
filter_shape : None, tuple/list of len 4 of int, None or Constant variable
Optional, used for optimization like loop unrolling
You can put None for any element of the list
to tell that this element is not constant.
kwargs
Kwargs are passed onto ConvOp. Can be used to set the following:
unroll_batch, unroll_kern, unroll_patch, openmp (see ConvOp doc).
openmp: By default have the same value as
config.openmp. For small image, filter,
batch size, nkern and stack size, it can be
faster to disable manually openmp. A fast and
incomplete test show that with image size
6x6, filter size 4x4, batch size==1,
n kern==1 and stack size==1, it is faster
to disable it in valid mode. But if we
grow the batch size to 10, it is faster
with openmp on a core 2 duo.
Returns
-------
symbolic 4D tensor
Set of feature maps generated by convolutional layer. Tensor is
of shape (batch size, nb filters, output row, output col).
"""
warnings.warn(
"aesara.tensor.nnet.conv.conv2d is deprecated."
" Use aesara.tensor.nnet.conv2d instead."
)
# accept Constant value for image_shape and filter_shape.
if image_shape is not None:
image_shape = list(image_shape)
for i in range(len(image_shape)):
if image_shape[i] is not None:
try:
image_shape[i] = get_scalar_constant_value(
as_tensor_variable(image_shape[i])
)
except NotScalarConstantError:
raise NotScalarConstantError(
"The convolution need that the shape"
" information are constant values. We got"
" {image_shape[i]} for the image_shape parameter"
)
assert image_shape[i].dtype in discrete_dtypes
image_shape[i] = int(image_shape[i])
if filter_shape is not None:
filter_shape = list(filter_shape)
for i in range(len(filter_shape)):
if filter_shape[i] is not None:
try:
filter_shape[i] = get_scalar_constant_value(
as_tensor_variable(filter_shape[i])
)
except NotScalarConstantError:
raise NotScalarConstantError(
"The convolution need that the shape"
" information are constant values. We got"
" {filter_shape[i]} for the filter_shape "
"parameter"
)
assert filter_shape[i].dtype in discrete_dtypes
filter_shape[i] = int(filter_shape[i])
if image_shape and filter_shape:
try:
if image_shape[1] is not None and filter_shape[1] is not None:
assert image_shape[1] == filter_shape[1]
except Exception:
print("image ", image_shape, " filters ", filter_shape)
raise
if filter_shape is not None:
nkern = filter_shape[0]
kshp = filter_shape[2:]
else:
nkern, kshp = None, None
if image_shape is not None:
bsize = image_shape[0]
imshp = image_shape[1:]
else:
bsize, imshp = None, None
op = ConvOp(
output_mode=border_mode,
dx=subsample[0],
dy=subsample[1],
imshp=imshp,
kshp=kshp,
nkern=nkern,
bsize=bsize,
**kargs,
)
return op(input, filters)
class ConvOp(OpenMPOp):
r"""
This Op serves a dual purpose: it can implement a vanilla 2D convolution
(as taught in any signal processing class) or implement the
convolutional layers found in Convolutional Neural Networks.
In this setting, a set of 3D images is convolved with a set of 3D kernels,
with the particularity that their leading dimensions are of equal length.
Vanilla 2D convolution is treated as a special case of this.
The input parameter represents a mini-batch of multiple images. Its shape is:
batch size x num. input feature maps x image height x image width
The kernel parameter represents a set of 3D kernels. Its shape is:
number of filters x num. input images x filter height x filter width
The output of ConvOp is a 4D tensor, generated as follows:
output[b,k,:,:] = \sum_i input[b,i,:,:] * filter[k,i,:,:] \forall b,k
where b is the mini-batch index, k the filter index and * is the
convolution operator.
The constructor initializes a ConvOp with given output_mode (full/valid).
All other parameters are optional and are only used to generate more
optimized c code, or to enable graph optimizers to optimally replace the
ConvOp.
NOTES ON OPTIMIZATION:
There are two types of optimization. The first is the selection of the
fastest algo when bsize and nkern are provided with imshp and kshp.
By default we try to select the fastest version. You can specify it
with the unroll_batch, unroll_kern, and unroll_patch parameter.
The second type of optimization is hardcoding some dimensions into the
code when all shape are know.
This make a significant difference for the 'full' output_mode.
Sometimes, the fastest implementation on x86-64 uses
{unroll_batch=4, unroll_kern=4, unroll_patch=False}
with all other shape parameters being provided.
For optimizing other architectures, see:
Kazushige Goto and Robert A. Van De Geijn, Anatomy of High-Performance
Matrix Multiplication, (mr x nr). ACM Transactions on Mathematical
Software, May 2008.
Figure 12: (mr x nr). For x86 use 2x4, itanium 8x8, etc.
Parameters
----------
output_mode : {'valid', 'full'}
'valid' gives an output smaller then the image.
'full' gives an output bigger then the image.
See 'border_mode' in conv2d's doc.
Optional parameters: (will generate more optimal c code)
imshp : tuple of len 2 or 3: 2 for 2d image, 3 for a stack of 2d images.
Stacksize, nb image row, nb image col.
kshp : tuple of len 2
Nb kernel row, nb kernel col.
nkern : int
The number of kernel.
bsize : int
The size of the minibatch.
dx : int
Patch stride rows.
dy : int
Patch stride cols
Params which select the version of code used:
unroll_patch : bool
Use a version of c_code that unroll the patch loop that don't
request all shape information to work, but if all shape information
are present, will use it to hardcode the value in the code for
faster code.
unroll_batch : int
Use a version of c_code that unroll the batch (by unroll_batch)
and the nkern (by unroll_kern) loop. The size must by a multiple
of bsize or nkern respectively.
unroll_kern : int
Use a version of c_code that unroll the batch
(by unroll_batch) and the nkern(by unroll_kern) loop. The size
must by a multiple of bsize or nkern respectively.
verbose : int
Passed to GpuConv.
version: int or str
Passed to GpuConv, if version='no_fft', fft
optimization will be deactivated at the op level.
direction_hint: {'forward', 'bprop weights', 'bprop inputs'}
Passed to GpuConv, used by graph optimizers to aid algorithm choice.
The 3 following parameters are used internally when we generate
the gradient when dx!=1 or dy!=1.
imshp_logical
Default None. None value is equivalent to imshp value.
When imshp_logical != imshp, it tell we need to insert 0 in
the image before we do the convolution. For example, when dx==dy==2
and the image is [[1, 2], [3, 4]], we should make as if the image
was [[1, 0, 2, 0], [0, 0, 0, 0], [3, 0, 4, 0], [0, 0, 0, 0]].
Our python code insert the zero, but the c code optimize it.
imshp_logical != imshp when taking the grad again the weights or
the image when the output_mode is full and `dx != 1` or `dy != 1`.
kshp_logical
Idem but for kshp and used for the grad again the
weights when the output_mode is valid and `dx != 1` or `dy != 1`.
kshp_logical_top_aligned
Used in the same case. Default to True.
Set to False in the grad again the weight when the
output_mode is full.
"""
__attrnames = [
"imshp",
"kshp",
"nkern",
"bsize",
"dx",
"dy",
"out_mode",
"unroll_batch",
"unroll_kern",
"unroll_patch",
"imshp_logical",
"kshp_logical",
"kshp_logical_top_aligned",
]
"""These attributes uniquely identify the behaviour of this op for
given inputs. Do not set openmp here.
"""
# the value of speed_unroll_batch_kern,speed_unroll_patch_noshape,speed_unroll_patch_shape
# have bean calculated on maggie36 when their is only 1 session logged on and only this was running.
# It is an Intel(R) Xeon(R) CPU E5430 @ 2.66GHz. It is computer with aesara/tensor/nnet/tests/speed_test_conv.py
# and took 5 minutes to run.
# TODO: we should compute this table for each computer/os as this can change.
# I saw on one computer that the speed with the shape can be slower than without!
# using the real shape and the same dtype could also help.
# unroll_batch, unroll_kern, valid time, full time
speed_unroll_batch_kern = [
(1, 1, 2.4661250114440918, 6.5472931861877441),
(1, 2, 1.5869178771972656, 5.1499760150909424),
(1, 3, 1.4270510673522949, 3.6593470573425293),
(1, 4, 1.3373479843139648, 3.3451821804046631),
(1, 5, 1.2818830013275146, 3.1444568634033203),
(1, 6, 1.2521560192108154, 3.0256359577178955),
(1, 10, 1.2134110927581787, 2.9174180030822754),
(2, 1, 1.657214879989624, 4.5261678695678711),
(2, 2, 1.2123160362243652, 2.9747390747070312),
(2, 3, 1.0758891105651855, 2.5690360069274902),
(2, 4, 1.0683329105377197, 2.4233770370483398),
(2, 5, 1.0955719947814941, 2.3999948501586914),
(2, 6, 1.5935721397399902, 2.6878271102905273),
(2, 10, 1.8511250019073486, 3.2417428493499756),
(3, 1, 1.5948119163513184, 3.631148099899292),
(3, 2, 1.0761330127716064, 2.6011371612548828),
(3, 3, 1.0551531314849854, 2.4200370311737061),
(3, 4, 1.3930759429931641, 2.5211219787597656),
(3, 5, 1.4330689907073975, 2.5704989433288574),
(3, 6, 1.362138032913208, 2.5964410305023193),
(3, 10, 1.6582000255584717, 2.9907989501953125),
(4, 1, 1.4793620109558105, 3.3473429679870605),
(4, 2, 1.0671560764312744, 2.4171769618988037),
(4, 3, 1.2569692134857178, 2.2807950973510742),
(4, 4, 1.3456289768218994, 2.6219108104705811),
(4, 5, 1.4055080413818359, 2.4606490135192871),
(4, 6, 1.372107982635498, 2.551663875579834),
(4, 10, 1.599470853805542, 2.9172940254211426),
(5, 1, 1.4115700721740723, 3.2077109813690186),
(5, 2, 1.0635769367218018, 2.2648060321807861),
(5, 3, 1.3842809200286865, 2.6135518550872803),
(5, 4, 1.3470511436462402, 2.3852400779724121),
(5, 5, 1.3539440631866455, 2.5245928764343262),
(5, 6, 1.4037849903106689, 2.5985310077667236),
(5, 10, 1.6120610237121582, 2.8127608299255371),
(6, 1, 1.3623628616333008, 3.021122932434082),
(6, 2, 1.1697649955749512, 2.6285450458526611),
(6, 3, 1.2980999946594238, 2.4746189117431641),
(6, 4, 1.3739941120147705, 2.5579929351806641),
(6, 5, 1.3967819213867188, 2.5522029399871826),
(6, 6, 1.4279270172119141, 2.6127138137817383),
(6, 10, 1.605496883392334, 2.864037036895752),
(10, 1, 1.6401121616363525, 2.970099925994873),
(10, 2, 1.46710205078125, 2.7231831550598145),
(10, 3, 1.4193780422210693, 2.6087639331817627),
(10, 4, 1.4657118320465088, 2.6246678829193115),
(10, 5, 1.5052611827850342, 2.6542458534240723),
(10, 6, 1.5214400291442871, 2.7243161201477051),
(10, 10, 1.6116268634796143, 2.956165075302124),
]
# valid time, full time
speed_unroll_patch_noshape = [2.0109100341796875, 5.8175678253173828]
# valid time, full time
speed_unroll_patch_shape = [1.2967290878295898, 5.5283889770507812]
@staticmethod
def has_all_shape(imshp, kshp, nkern=1, bsize=1):
return (
nkern is not None
and bsize is not None
and all(shp is not None for shp in imshp)
and all(shp is not None for shp in kshp)
)
@staticmethod
def getOutputShape(inshp, kshp, stride=(1, 1), mode="valid"):
"""
Computes the output dimensions of convolving an image of shape "inshp"
with kernels of shape "kshp". Accepts symbolic or integer shapes.
Propagates `None`s (for unknown shapes).
Parameters
----------
inshp
(rows,cols) of input image.
kshp
(rows,cols) of filters.
mode: {'valid', 'full'}
See 'border_mode' in conv2d's doc.
Returns
-------
object
(rows,cols) of output image.
"""
# The formula would be ceil((i + s * k - s * 1) / float(d)),
# with s=1 for mode=='full' and s=-1 for mode=='valid'.
# To support symbolic shapes, we express this with integer arithmetic.
warnings.warn(
"The method `getOutputShape` is deprecated use"
"`get_conv_output_shape` instead.",
stacklevel=2,
)
return tuple(
get_conv_shape_1axis(i, k, mode, d) for i, k, d in zip(inshp, kshp, stride)
)
def __init__(
self,
imshp=None,
kshp=None,
nkern=None,
bsize=None,
dx=1,
dy=1,
output_mode="valid",
unroll_batch=None,
unroll_kern=None,
unroll_patch=None,
imshp_logical=None,
kshp_logical=None,
kshp_logical_top_aligned=True,
verbose=0,
version=-1,
direction_hint="forward",
openmp=None,
):
# Deactivate fft_optimization at the op level if specified
if version == "no_fft":
self.fft_opt = False
version = -1
else:
self.fft_opt = True
# Expand unknown image / kernel shapes into tuples of Nones
if imshp is None:
imshp = (None, None, None)
else:
imshp = tuple(imshp)
if kshp is None:
kshp = (None, None)
else:
kshp = tuple(kshp)
# Check imshp and kshp dimensionality
if len(imshp) == 2:
imshp = (1,) + imshp
elif len(imshp) != 3:
raise ValueError(f"len(imshp) must be 2 or 3, got {len(imshp)}")
if len(kshp) != 2:
raise ValueError(f"len(kshp) must be 2, got {len(kshp)}")
# We must continue to consider None as 1 for backward compatibility.
if dx is None:
dx = 1
if dy is None:
dy = 1
if int(dx) != dx:
raise TypeError("ConvOp.__init__ param dx must be an int", dx)
dx = int(dx)
if int(dy) != dy:
raise TypeError("ConvOp.__init__ param dy must be an int", dy)
dy = int(dy)
all_shape = self.has_all_shape(imshp, kshp, nkern, bsize)
if (unroll_batch or unroll_kern) and not all_shape:
raise ValueError(
"In ConvOp, when using unroll_batch and"
" unroll_nkern, all shape are needed"
)
# Init the openmp attribute
super().__init__(openmp=openmp)
if not all_shape or self.openmp:
# Only this version is parallelized
unroll_patch = True
self.imshp = imshp
self.kshp = kshp
self.nkern = nkern
self.bsize = bsize
self.dx = dx
self.dy = dy
self.verbose = verbose
self.version = version
self.direction_hint = direction_hint
# a triple
if imshp_logical is None:
self.imshp_logical = self.imshp
else:
imshp_logical = tuple(imshp_logical)
if len(imshp_logical) != 3:
raise ValueError(
f"len(imshp_logical) must be 3, got {len(imshp_logical)}"
)
self.imshp_logical = imshp_logical
# a pair
if kshp_logical is None:
self.kshp_logical = self.kshp
else:
kshp_logical = tuple(kshp_logical)
if len(kshp_logical) != 2:
raise ValueError(
f"len(kshp_logical) must be 2, got {len(kshp_logical)}"
)
self.kshp_logical = kshp_logical
# a bool
self.kshp_logical_top_aligned = kshp_logical_top_aligned
self.unroll_batch = unroll_batch
self.unroll_kern = unroll_kern
self.unroll_patch = unroll_patch
if self.unroll_batch and not self.unroll_kern:
self.unroll_kern = 1
if self.unroll_kern and not self.unroll_batch:
self.unroll_batch = 1
# downcast unroll_batch if not a divisor of batch size
if (
self.unroll_batch is not None
and self.unroll_batch > 0
and self.bsize % self.unroll_batch != 0
):
if self.bsize <= self.unroll_batch:
self.unroll_batch = self.bsize
else:
# find the maximum value under unroll_batch that would work
new = self.unroll_batch
assert new >= 1
while self.bsize % new != 0:
new -= 1
warnstr = (
"In ConvOp.__init__(): "
f"unroll_batch({self.unroll_batch}) must be 0 or a divisor of"
f" bsize({self.bsize}). We revert it to {new}. This"
" won't change the result, but may make it slower."
)
_logger.warning(warnstr)
self.unroll_batch = new
# downcast unroll_kern if not a divisor of nb of kernel
if (
self.unroll_kern is not None
and self.unroll_kern > 0
and self.nkern % self.unroll_kern != 0
):
if self.nkern <= self.unroll_kern:
self.unroll_kern = self.nkern
else:
# find the maximum value under unroll_kern that would work
new = self.unroll_kern
assert new >= 1
while self.nkern % new != 0:
new -= 1
warnstr = (
"In ConvOp.__init__(): "
f"unroll_kern({self.unroll_kern}) must be 0 or a divisor of"
f" nkern({self.nkern}). We revert it to {new}. This"
" won't change the result, but may make it slower."
)
_logger.warning(warnstr)
self.unroll_kern = new
self.outshp = get_conv_output_shape(
(None,) + self.imshp_logical,
(
None,
None,
)
+ self.kshp_logical,
output_mode,
(dx, dy),
)[2:]
self.fulloutshp = get_conv_output_shape(
(None,) + self.imshp_logical,
(
None,
None,
)
+ self.kshp_logical,
output_mode,
(1, 1),
)[2:]
self.out_mode = output_mode
if self.out_mode not in ["valid", "full"]:
raise NotImplementedError(f"Mode {self.out_mode} not implemented")
if any((shp is not None) and (shp <= 0) for shp in self.outshp):
raise ValueError(
"Bad size for the output shape. Verify that [post-"
f"supersampling] input shape ({self.imshp_logical}) and kern"
f" shape({self.kshp_logical}) are ok. (Hint: kerns must fit inside"
" image in valid mode)"
)
if (
self.unroll_kern is None
and self.unroll_batch is None
and self.unroll_patch is None
):
# no version specified. Find the faster we have
if self.bsize is None and self.nkern is None:
self.unroll_patch = True
elif self.bsize is not None and self.nkern is not None:
bsize = self.bsize
nkern = self.nkern
mode_idx = 0
if self.out_mode != "valid":
mode_idx = 1
if self.has_all_shape(self.imshp, self.kshp):
time_unroll_patch = self.speed_unroll_patch_shape[mode_idx]
else:
time_unroll_patch = self.speed_unroll_patch_noshape[mode_idx]
time_unroll_batch_kern = 9999999
for i in range(len(self.speed_unroll_batch_kern)):
if (
bsize % self.speed_unroll_batch_kern[i][0] == 0
and nkern % self.speed_unroll_batch_kern[i][1] == 0
):
if (
self.speed_unroll_batch_kern[i][2 + mode_idx]
< time_unroll_batch_kern
):
time_unroll_batch_kern = self.speed_unroll_batch_kern[i][
2 + mode_idx
]
time_unroll_batch_kern_idx = i
if time_unroll_patch < time_unroll_batch_kern:
self.unroll_patch = True
else:
self.unroll_batch = self.speed_unroll_batch_kern[
time_unroll_batch_kern_idx
][0]
self.unroll_kern = self.speed_unroll_batch_kern[
time_unroll_batch_kern_idx
][1]
self.unroll_patch = False
_logger.debug(
"AUTO FIND VERSION OF C_CODE OF CONV OP " "%s %s %s %s %s %s %s",
self.unroll_batch,
self.unroll_kern,
self.unroll_patch,
self.bsize,
self.nkern,
time_unroll_patch,
time_unroll_batch_kern,
)
self._rehash()
def __eq__(self, other):
if type(self) != type(other):
return False
for a in self.__attrnames:
if getattr(self, a) != getattr(other, a):
return False
return True
def __setstate__(self, d):
super().__setstate__(d)
self.direction_hint = d.get("direction_hint", None)
self._rehash()
def _rehash(self):
hashval = hash(type(self))
for a in self.__attrnames:
hashval = hashval ^ hash(getattr(self, a))
self.__hashval = hashval
def __hash__(self):
return self.__hashval
def __str__(self):
return (
"ConvOp{"
+ ",".join(str((a, getattr(self, a))) for a in self.__attrnames)
+ "}"
)
def flops(self, inputs, outputs):
"""
Useful with the hack in profiling to print the MFlops.
"""
images, kerns = inputs
(out,) = outputs
assert images[1] == kerns[1]
flops = 0
if self.out_mode == "valid":
# nb mul and add by output pixel
flops = kerns[2] * kerns[3] * 2
# nb flops by output image
flops *= out[2] * out[3]
# nb patch multiplied
flops *= images[1] * kerns[0] * images[0]
else:
flops = (
images[0]
* kerns[0]
* images[1]
* kerns[2]
* kerns[3]
* images[2]
* images[3]
* 2
)
return flops
def make_node(self, inputs, kerns):
# TODO: find a way to make ConvOp work for N-D (after NIPS09)
"""
Parameters
----------
inputs
4 dim: batches x stacksize x rows x cols.
kerns
4 dim: nkern x stackidx x rows x cols.
"""
_inputs = as_tensor_variable(inputs)
_kerns = as_tensor_variable(kerns)
# TODO: lift this restriction by upcasting either inputs or kerns
if _inputs.ndim != 4:
raise TypeError(
"ConvOp (make_node) requires input be a 4D tensor;"
f' received "{inputs}" ({_inputs.ndim} dims)'
)
if _kerns.ndim != 4:
raise TypeError("make_node requires 4D tensor of kernels")
if _inputs.type.dtype != _kerns.type.dtype:
raise NotImplementedError(
"The image and the kernel must have the same type."
"inputs({_inputs.dtype}), kerns({_kerns.dtype})"
)
bcastable23 = [self.outshp[0] == 1, self.outshp[1] == 1]
output = tensor(
dtype=_inputs.type.dtype,
broadcastable=[_inputs.broadcastable[0], _kerns.broadcastable[0]]
+ bcastable23,
)
return Apply(self, [_inputs, _kerns], [output])
def infer_shape(self, fgraph, node, input_shapes):
imshp = input_shapes[0] # 4D image shape
kshp = input_shapes[1] # 4D filter shape
bsize, imshp = imshp[0], list(imshp[1:])
nkern, kshp = kshp[0], list(kshp[2:])
# replace symbolic shapes with known shapes
if self.bsize is not None:
bsize = self.bsize
for i in [0, 1, 2]:
if self.imshp_logical[i] is not None:
imshp[i] = self.imshp_logical[i]
if self.nkern is not None:
nkern = self.nkern
for i in [0, 1]:
if self.kshp_logical[i] is not None:
kshp[i] = self.kshp_logical[i]
# infer output shape from what we have
res = get_conv_output_shape(
(bsize,) + tuple(imshp),
(
nkern,
None,
)
+ tuple(kshp),
self.out_mode,
(self.dx, self.dy),
)
return [res]
def perform(self, node, inp, out):
"""
By default if len(img2d.shape)==3, we TODO
"""
img2d, filtersflipped = inp
(z,) = out
# TODO: move these back out to global scope when they no longer
# cause an atexit error
imshp = self.imshp
if any(x is None for x in imshp):
imshp = tuple(img2d.shape[1:])
if imshp != img2d.shape[1:]:
raise ValueError(
"The image shape provided at build time "
"is different from the one passed at run time",
imshp,
img2d.shape[1:],
)
kshp = self.kshp
if any(x is None for x in kshp):
kshp = tuple(filtersflipped.shape[2:])
if kshp != filtersflipped.shape[2:]:
raise ValueError(
"The filter shape provided at build time "
"is different from the one passed at run time",
kshp,
filtersflipped.shape[2:],
)
bsize = self.bsize
if bsize is None:
bsize = img2d.shape[0]
elif bsize != img2d.shape[0]:
raise ValueError(
"The batch size provided at build time "
"is different from the one passed at run time",
bsize,
img2d.shape[0],
)
nkern = self.nkern
if nkern is None:
nkern = filtersflipped.shape[0]
elif nkern != filtersflipped.shape[0]:
raise ValueError(
"The number of filters provided at build time "
"is different from the one passed at run time",
nkern,
filtersflipped.shape[0],
)
imshp_logical = self.imshp_logical
if imshp_logical[0] is None:
imshp_logical = (imshp[0],) + imshp_logical[1:]
if imshp_logical[1] is None:
imshp_logical = (imshp_logical[0], imshp[1], imshp_logical[2])
if imshp_logical[2] is None:
imshp_logical = imshp_logical[:2] + (imshp[2],)
assert all(x is not None for x in imshp_logical)
kshp_logical = self.kshp_logical
if kshp_logical[0] is None:
kshp_logical = (kshp[0], kshp_logical[1])
if kshp_logical[1] is None:
kshp_logical = (kshp_logical[0], kshp[1])
assert all(x is not None for x in kshp_logical)
if all(shp is not None for shp in self.fulloutshp):
fulloutshp = tuple(self.fulloutshp)
else:
fulloutshp = get_conv_output_shape(
(None,) + imshp_logical,
(
None,
None,
)
+ kshp_logical,
self.out_mode,
(1, 1),
)[2:]
if (
z[0] is None
or z[0].shape
!= (
bsize,
nkern,
)
+ fulloutshp
):
z[0] = np.zeros(
(
bsize,
nkern,
)
+ fulloutshp,
dtype=img2d.dtype,
)
zz = z[0]
stacklen = imshp[0]
img2d = img2d.reshape((bsize,) + imshp)
filtersflipped = filtersflipped.reshape((nkern, stacklen) + kshp)
if self.imshp != self.imshp_logical:
# assuming that to get from imshp to imshp logical we insert zeros in missing spots
rstride = int(np.ceil(imshp_logical[1] / float(imshp[1])))
cstride = int(np.ceil(imshp_logical[2] / float(imshp[2])))
buf = np.zeros((bsize,) + imshp_logical, dtype=img2d.dtype)
buf[:, :, ::rstride, ::cstride] = img2d
img2d = buf
del buf, rstride, cstride
if kshp != kshp_logical:
rstride = int(np.ceil(kshp_logical[0] / float(kshp[0])))
cstride = int(np.ceil(kshp_logical[1] / float(kshp[1])))
buf = np.zeros(
(nkern, stacklen) + self.kshp_logical, dtype=filtersflipped.dtype
)
if self.kshp_logical_top_aligned:
roffset = coffset = 0
else:
roffset = (
kshp_logical[0] - (kshp[0] * rstride) - 1 + rstride
) % rstride
coffset = (
kshp_logical[1] - (kshp[1] * cstride) - 1 + cstride
) % cstride
assert roffset >= 0
assert coffset >= 0
buf[:, :, roffset::rstride, coffset::cstride] = filtersflipped
filtersflipped = buf
del buf, rstride, cstride
val = _valfrommode(self.out_mode)
bval = _bvalfromboundary("fill")
with warnings.catch_warnings():
warnings.simplefilter("ignore", np.ComplexWarning)
for b in range(bsize):
for n in range(nkern):
zz[b, n, ...].fill(0)
for im0 in range(stacklen):
# some cast generates a warning here
zz[b, n, ...] += _convolve2d(
img2d[b, im0, ...],
filtersflipped[n, im0, ...],
1,
val,
bval,
0,
)
if False:
if False and self.out_mode == "full":
img2d2 = np.zeros(
(
bsize,
stacklen,
imshp[1] + 2 * kshp[0] - 2,
imshp[2] + 2 * kshp[1] - 2,
)
)
img2d2[
:,
:,
kshp[0] - 1 : kshp[0] - 1 + imshp[1],
kshp[1] - 1 : kshp[1] - 1 + imshp[2],
] = img2d
img2d = img2d2
# N_image_shape = image_data.shape
for b in range(bsize):
for n in range(nkern):
zz[b, n, ...].fill(0)
for im0 in range(stacklen):
for row in range(0, zz.shape[2], self.dx):
for col in range(0, zz.shape[3], self.dy):
zz[b, n, row, col] += (
img2d[
b, im0, row : row + kshp[0], col : col + kshp[1]
]
* filtersflipped[n, im0, ::-1, ::-1]
).sum()
# We copy it to remove the Stride mismatch warning from DEBUG_MODE.
# The copy make that we return an object with the same stride as the c version.
# The copy don't affect the performance during our experience as in that case we
# execute the c version which is much faster.
if self.dx > 1 or self.dy > 1:
zz = zz[:, :, 0 :: self.dx, 0 :: self.dy].copy()
z[0] = zz
def R_op(self, inputs, eval_points):
rval = None
if eval_points[0] is not None:
rval = self.make_node(eval_points[0], inputs[1]).outputs[0]
if eval_points[1] is not None:
if rval is None:
rval = self.make_node(inputs[0], eval_points[1]).outputs[0]
else:
rval += self.make_node(inputs[0], eval_points[1]).outputs[0]
return [rval]
def grad(self, inp, grads):
inputs, kerns = inp
(gz,) = grads
if self.imshp != self.imshp_logical or self.kshp != self.kshp_logical:
raise NotImplementedError("todo")
if self.out_mode == "valid" and (self.dx, self.dy) != (1, 1):
raise NotImplementedError(
"ERROR: ConvOp.grad is now disabled for 'valid' convolutions with"
" stride != (1, 1); call aesara.tensor.nnet.conv2d() instead."
)
if self.dx not in (1, 2) or self.dy not in (1, 2):
raise NotImplementedError(
"ERROR: We disable ConvOp.grad now when output_mode is not"
" 'valid' and dx or dy are greater than 2, as there is a bug"
" in it. See `abstract_conv2d <>`_ for a version that support this."
)
all_shape = self.has_all_shape(self.imshp, self.kshp, self.nkern, self.bsize)
if not all_shape and (self.dx != 1 or self.dy != 1):
raise ValueError(
"ConvOp.grad when dx!=1 or dy!=1 we must have all "
"the optional shape information"
)
# Determine gradient on kernels ########
assert inputs.ndim == 4 and kerns.ndim == 4
newin = inputs.dimshuffle((1, 0, 2, 3))
newgz = gz.dimshuffle((1, 0, 2, 3))
if self.out_mode == "valid":
(img, filters) = (newin, newgz)
kshp_logical = self.fulloutshp
kshp_logical_top_aligned = False
imshp_logical = None
(bsize, nkern) = (self.imshp[0], self.nkern)
imshp = (self.bsize, self.imshp[1], self.imshp[2])
kshp = self.outshp
elif self.out_mode == "full":
(img, filters) = (newgz, newin)
kshp_logical = None
kshp_logical_top_aligned = True
imshp_logical = (self.bsize, self.fulloutshp[0], self.fulloutshp[1])
(bsize, nkern) = (self.nkern, self.imshp[0])
imshp = (self.bsize, self.outshp[0], self.outshp[1])
kshp = self.imshp[1:]
else:
raise NotImplementedError(
"Only [full,valid] modes are currently supported."
)
filters = filters[:, :, ::-1, ::-1] # flip them
dw = ConvOp(
imshp,
kshp,
nkern,
bsize,
1,
1,
output_mode="valid",
unroll_batch=None,
unroll_kern=None,
unroll_patch=None,
imshp_logical=imshp_logical,
kshp_logical=kshp_logical,
kshp_logical_top_aligned=kshp_logical_top_aligned,
version=self.version,
direction_hint="bprop weights",
verbose=self.verbose,
)
dw = dw(img, filters)
if all_shape:
assert all(o == k for o, k in zip(dw.owner.op.outshp, self.kshp))
if self.out_mode == "valid":
# before DimShuffle, dw is of shape visdim x nkern x kshp[0] x kshp[1]
dw = dw.dimshuffle((1, 0, 2, 3))
dw = dw[:, :, ::-1, ::-1]
# Determine gradient on inputs ########
mode = "valid"
if not self.out_mode == "full":
mode = "full"
filters = kerns.dimshuffle((1, 0, 2, 3))
filters = filters[:, :, ::-1, ::-1]
nkern = self.imshp[0]
imshp = (self.nkern, self.outshp[0], self.outshp[1])
imshp_logical = (self.nkern, self.fulloutshp[0], self.fulloutshp[1])
din = ConvOp(
imshp,
self.kshp,
nkern,
self.bsize,
1,
1,
output_mode=mode,
unroll_batch=None,
unroll_kern=None,
unroll_patch=None,
imshp_logical=imshp_logical,
kshp_logical=None,
version=-1, # we we change the mode, we don't forward the version.
direction_hint="bprop inputs",
verbose=self.verbose,
)
din = din(gz, filters)
assert all(
o is None or o == i for o, i in zip(din.owner.op.outshp, self.imshp[1:])
)
# din and dw should have the same broadcasting pattern as the
# parameters they are the gradient of (resp. inputs and kerns).
din = patternbroadcast(din, inputs.broadcastable)
dw = patternbroadcast(dw, kerns.broadcastable)
return [din, dw]
def c_headers(self, **kwargs):
return ["<numpy/noprefix.h>", "<iostream>", "<sstream>"]
def c_code_cache_version(self):
return (15, self.openmp, blas.blas_header_version())
def c_support_code(self, **kwargs):
return (
"""
#define STRIDES(arr) (PyArray_STRIDES(arr))
#define FULL 2
#define SAME 1
#define VALID 0
#define MOD %
using namespace std;
"""
+ blas.blas_header_text()
)
def use_blas(self):
"""Return True if we will generate code that use gemm."""
# the gemm version only support that case
if self.out_mode == "valid" and self.dx == 0 and self.dy == 0:
# We use a faster version in those case.
if (
self.imshp != self.imshp_logical
or self.kshp != self.kshp_logical
or self.unroll_patch
or self.unroll_batch > 0
or self.unroll_kern > 0
):
return False
return True
return False
def c_libraries(self, **kwargs):
if self.use_blas():
return blas.ldflags()
return []
def c_no_compile_args(self, **kwargs):
# when the ksph==(1,1) gcc 4.3.0 segfault during the
# compilation with -O3. This don't happen at -O2
if aesara.link.c.cmodule.gcc_version() in ["4.3.0"] and self.kshp == (1, 1):
return ["-O3"]
else:
return []
def c_compile_args(self, **kwargs):
ret = []
if self.use_blas():
ret = blas.ldflags(libs=False, flags=True)
if aesara.link.c.cmodule.gcc_version() in ["4.3.0"] and self.kshp == (1, 1):
ret += ["-O2"]
# Add the -fopenmp flags
ret += super().c_compile_args(**kwargs)
return ret
def c_lib_dirs(self, **kwargs):
if self.use_blas():
return blas.ldflags(libs=False, libs_dir=True)
return []
def c_header_dirs(self, **kwargs):
if self.use_blas():
return blas.ldflags(libs=False, include_dir=True)
return []
def c_code(self, node, name, inp, out, sub):
img2d, filtersflipped = inp
(z,) = out
if node.inputs[0].type.dtype != node.inputs[1].type.dtype:
raise NotImplementedError()
assert node.inputs[0].type.dtype == node.inputs[1].type.dtype
d = locals()
d.update(sub)
all_shape = self.has_all_shape(
self.imshp, self.kshp, self.nkern, self.bsize
) and self.has_all_shape(self.imshp_logical, self.kshp_logical)
d["self_out_mode"] = self.out_mode
d["self_dx"] = self.dx
d["self_dy"] = self.dy
d["mode"] = self.out_mode.upper()
d["affectation"] = "="
# Default values, will be overridden if the shape info is provided
d["self_bsize"] = f"PyArray_DIMS({d['img2d']})[0]"
d["self_nkern"] = f"PyArray_DIMS({d['filtersflipped']})[0]"
d["self_outshp0"] = "-1"
d["self_outshp1"] = "-1"
d["self_imshp0"] = f"PyArray_DIMS({d['img2d']})[1]"
d["self_imshp1"] = f"PyArray_DIMS({d['img2d']})[2]"
d["self_imshp2"] = f"PyArray_DIMS({d['img2d']})[3]"
d["self_kshp0"] = f"PyArray_DIMS({d['filtersflipped']})[2]"
d["self_kshp1"] = f"PyArray_DIMS({d['filtersflipped']})[3]"
d["assert_size"] = ""
# Override the default value if we have it
if self.kshp[0] is not None:
expected = d["self_kshp0"]
value = self.kshp[0]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of rows in the filter "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_kshp0"] = self.kshp[0]
if self.kshp[1] is not None:
expected = d["self_kshp1"]
value = self.kshp[1]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of columns in the filter "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_kshp1"] = self.kshp[1]
if self.outshp[0] is not None:
expected = "dim_zz[0]"
value = self.outshp[0]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of rows in the output "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_outshp0"] = self.outshp[0]
if self.outshp[1] is not None:
expected = "dim_zz[1]"
value = self.outshp[1]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of columns in the output "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_outshp1"] = self.outshp[1]
if self.imshp[0] is not None:
expected = d["self_imshp0"]
value = self.imshp[0]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the image stack size (%%ld) "
"isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
expected = "kerns_dim[1]"
value = self.imshp[0]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the kernel stack size (%%ld) "
"isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_imshp0"] = self.imshp[0]
if self.imshp[1] is not None:
expected = d["self_imshp1"]
value = self.imshp[1]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of rows in the image "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_imshp1"] = self.imshp[1]
if self.imshp[2] is not None:
expected = d["self_imshp2"]
value = self.imshp[2]
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of columns in the image "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_imshp2"] = self.imshp[2]
if self.bsize is not None:
expected = d["self_bsize"]
value = self.bsize
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the batch size (%%ld) "
"isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_bsize"] = self.bsize
if self.nkern is not None:
expected = d["self_nkern"]
value = self.nkern
d[
"assert_size"
] += """
if(%(value)s != %(expected)s){
PyErr_Format(PyExc_ValueError,
"The hardcoded shape for the number of kernels in the filter "
"(%%ld) isn't the run time shape (%%ld).",
(long)%(value)s, (long)%(expected)s);
%(fail)s;
}
""" % dict(
expected=expected, value=value, **sub
)
d["self_nkern"] = self.nkern
# Other hard coded stuff only if we have all shapes
if all_shape:
d["self_kshp_logical_r"] = self.kshp_logical[0]
d["self_kshp_logical_c"] = self.kshp_logical[1]
d["self_kshp_logical_stride_r"] = int(
np.ceil(self.kshp_logical[0] / float(self.kshp[0]))
)
d["self_kshp_logical_stride_c"] = int(
np.ceil(self.kshp_logical[1] / float(self.kshp[1]))
)
d["self_imshp_logical_r"] = self.imshp_logical[1]
# numpy.B. 1 not 0
d["self_imshp_logical_c"] = self.imshp_logical[2]
# numpy.B. 2 not 1
d["self_imshp_logical_stride_r"] = int(
np.ceil(self.imshp_logical[1] / float(self.imshp[1]))
)
d["self_imshp_logical_stride_c"] = int(
np.ceil(self.imshp_logical[2] / float(self.imshp[2]))
)
if not self.imshp[0] == 1:
d["affectation"] = "+="
d["all_shape"] = "1"
d["dim_zz_const"] = "const"
d["dim_zz_affect"] = ""
else:
d["affectation"] = "+="
d["all_shape"] = "0"
d["dim_zz_const"] = ""
d["dim_zz_affect"] = (
"""
if (mode == FULL) {
dim_zz[0] = (int)ceil((dim_im[0]+dim_ker0-1)/float(%(self_dx)s));
dim_zz[1] = (int)ceil((dim_im[1]+dim_ker1-1)/float(%(self_dy)s));
} else {
dim_zz[0] = (int)ceil((dim_im[0]-dim_ker0+1)/float(%(self_dx)s));
dim_zz[1] = (int)ceil((dim_im[1]-dim_ker1+1)/float(%(self_dy)s));
}
"""
% d
)
d["assert_size"] += (
"""
// Check the stack size of the filter and images are equals
if(kerns_dim[1] != img2d_dim[1]){
PyErr_Format(PyExc_ValueError,
"the filter stack size (%%ld) and image stack size (%%ld) differ",
(long)kerns_dim[1], (long)img2d_dim[1]);
%(fail)s;
}
"""
% sub
)
if self.kshp_logical_top_aligned:
d["self_kshp_logical_offset_r"] = 0
d["self_kshp_logical_offset_c"] = 0
elif all_shape:
rstride = d["self_kshp_logical_stride_r"]
cstride = d["self_kshp_logical_stride_c"]
d["self_kshp_logical_offset_r"] = (
self.kshp_logical[0] - (self.kshp[0] * rstride) - 1 + rstride
) % rstride
d["self_kshp_logical_offset_c"] = (
self.kshp_logical[1] - (self.kshp[1] * cstride) - 1 + cstride
) % cstride
del rstride, cstride
if node.inputs[0].type.dtype == "float32":
d["type"] = "float"
elif node.inputs[0].type.dtype == "float64":
d["type"] = "double"
else:
raise NotImplementedError(
f"Type {node.inputs[0].type.dtype} not implemented"
)
d["gemm"] = "dgemm_"
if not d["type"] == "double":
d["gemm"] = "sgemm_"
if self.imshp != self.imshp_logical or self.kshp != self.kshp_logical:
if self.verbose:
_logger.debug(
"return imshp!=imshp_logical or"
" self.kshp != self.kshp_logical shape version"
)
return _conv_op_code_a % d
if self.unroll_patch:
if self.verbose:
_logger.debug("return unroll patch version. all_shape=%s", all_shape)
return _conv_op_code_unroll_patch % d
if (self.unroll_batch is not None and self.unroll_batch > 0) or (
self.unroll_kern is not None and self.unroll_kern > 0
):
assert self.unroll_batch > 0
assert self.unroll_kern > 0
if self.verbose:
_logger.debug(
"return unrolled batch (%s) and kern code (%s)",
str(self.unroll_batch),
str(self.unroll_kern),
)
return gen_conv_code_unroll_batch_kern(
d, self.unroll_batch, self.unroll_kern
)
# TODO: should we choose the unroll size automatically with the bigger divisor under 5?
if self.out_mode == "valid" and self.dx == 0 and self.dy == 0:
if self.verbose:
_logger.debug("return gemm version")
return _conv_op_code_valid_gemm % d
else:
if self.verbose:
_logger.debug("return no gemm version")
return _conv_op_code_a % d
_conv_op_code_a = """
const int mode=%(mode)s;
int typenum=0, typenum_f=0;
PyArrayObject *ain1=NULL, *ain2=NULL;
PyArrayObject *filtersflipped_arr=NULL, *img2d_arr=NULL, *z_arr=NULL;
const %(type)s fill_value = 0;
int type_im=PyArray_TYPE(%(img2d)s);
int type_ker=PyArray_TYPE(%(filtersflipped)s);
npy_intp dim_zz[2]={%(self_outshp0)s,%(self_outshp1)s};
npy_intp dim_im_phys[2]={%(self_imshp1)s,%(self_imshp2)s};
npy_intp dim_im_log[2]={%(self_imshp_logical_r)s,%(self_imshp_logical_c)s};
npy_intp dim_ker_phys[2]={%(self_kshp0)s,%(self_kshp1)s};
npy_intp dim_ker_log[2]={%(self_kshp_logical_r)s,%(self_kshp_logical_c)s};
PyArray_Dims img2d_shape;
npy_intp img2d_dim[4]={1,1,0,0};
img2d_shape.ptr=img2d_dim;
img2d_shape.len=4;
PyArray_Dims kerns_shape;
npy_intp kerns_dim[4]={1,1,0,0};
kerns_shape.ptr=kerns_dim;
kerns_shape.len=4;
PyObject *img2d=NULL, *contig, *filtersflipped=NULL;
if(PyArray_NDIM(%(img2d)s)==2){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==3){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==4){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[3];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[1]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else {
PyErr_SetString(PyExc_ValueError, "img don't have a good shape");
%(fail)s;
}
if(PyArray_NDIM(%(filtersflipped)s)==3){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else if(PyArray_NDIM(%(filtersflipped)s)==4){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[3];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[1]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else{
std::stringstream temp;
temp << "nddim="<<PyArray_NDIM(%(filtersflipped)s);
std::string param = temp.str();
PyErr_SetString(PyExc_ValueError,
("kernel don't have a good shape. " + param).c_str());
%(fail)s;
}
%(assert_size)s
img2d = PyArray_Newshape(%(img2d)s,&img2d_shape, NPY_CORDER);
img2d_arr = (PyArrayObject*)img2d;
if ((PyArray_STRIDES(img2d_arr)[3] != (npy_intp)sizeof(%(type)s))
|| (PyArray_STRIDES(img2d_arr)[2] != PyArray_DIMS(img2d_arr)[3]*(npy_intp)sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)img2d));
Py_DECREF(img2d);
img2d = contig;
img2d_arr = (PyArrayObject*)img2d;
if (!PyArray_ISCONTIGUOUS(img2d_arr)){
PyErr_SetString(PyExc_ValueError, "img2d isn't contiguous");
%(fail)s;
}
}
filtersflipped = PyArray_Newshape(%(filtersflipped)s,&kerns_shape, NPY_CORDER);
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if ((PyArray_STRIDES(filtersflipped_arr)[3] != (npy_intp)sizeof(%(type)s))
|| (PyArray_STRIDES(filtersflipped_arr)[2] != PyArray_DIMS(filtersflipped_arr)[3]*(npy_intp)sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)filtersflipped));
Py_DECREF(filtersflipped);
filtersflipped = contig;
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if (!PyArray_ISCONTIGUOUS(filtersflipped_arr)){
PyErr_SetString(PyExc_ValueError, "filtersflipped isn't contiguous");
%(fail)s;
}
}
if(mode != VALID && mode != FULL){
PyErr_SetString(PyExc_ValueError,
"invalid mode, only full and valid are supported");
%(fail)s;
}
typenum = PyArray_ObjectType((PyObject*)%(img2d)s, 0);
typenum_f = PyArray_ObjectType((PyObject*)%(filtersflipped)s, 0);
if (typenum < 0) {PyErr_SetString(PyExc_ValueError, "Invalid type"); %(fail)s;}
if (typenum != typenum_f) {
PyErr_SetString(PyExc_ValueError, "Input types must match");
%(fail)s;
}
if (!img2d)
{
PyErr_SetString(PyExc_AssertionError, "!img2d");
%(fail)s;
}
if (!filtersflipped)
{
PyErr_SetString(PyExc_AssertionError, "!filtersflipped");
%(fail)s;
}
if ((!%(z)s)
|| *PyArray_DIMS(%(z)s)!=4
||(PyArray_DIMS(%(z)s)[0] != %(self_bsize)s)
||(PyArray_DIMS(%(z)s)[1] != %(self_nkern)s)
||(PyArray_DIMS(%(z)s)[2] != dim_zz[0])
||(PyArray_DIMS(%(z)s)[3] != dim_zz[1])
||!PyArray_ISCONTIGUOUS(%(z)s)
)
{
{Py_XDECREF(%(z)s);}
npy_intp dims[4] = {0,0,0,0};
dims[0]=%(self_bsize)s;
dims[1]=%(self_nkern)s;
dims[2]=dim_zz[0];
dims[3]=dim_zz[1];
%(z)s = (PyArrayObject*) PyArray_ZEROS(4, dims, typenum,0);
}else{
//PyArray_FILLWBYTE((PyObject*)%(z)s,0);
}
z_arr = (PyArrayObject*) %(z)s;
int Os[2];
Os[0]=%(self_outshp0)s;
Os[1]=%(self_outshp1)s;
//assertions
if (!PyArray_ISCONTIGUOUS(%(z)s))
{
PyErr_SetString(PyExc_AssertionError, "Output (%(z)s) not contiguous");
%(fail)s;
}
for(int b=0;b< %(self_bsize)s;b++){
for(int n_kern=0;n_kern<%(self_nkern)s;n_kern++){
%(type)s * __restrict__ out=(%(type)s *)(PyArray_GETPTR2(z_arr,b,n_kern));
for (int i = 0; i < dim_zz[0]*dim_zz[1]; ++i) out[i] = 0;
for(int stack_size=0;stack_size<%(self_imshp0)s;stack_size++){
const %(type)s * __restrict__ in=(%(type)s *)(PyArray_GETPTR2(img2d_arr,b,stack_size));
const %(type)s * __restrict__ hvals=(%(type)s *)(PyArray_GETPTR2(filtersflipped_arr,n_kern,stack_size));
for (int iter_m=0; iter_m < Os[0]; iter_m++) {
// Reposition index into input image based on requested output size
//row position in logical output image
int pos_m = iter_m*%(self_dx)s;
//row anchor in logical input image (we will loop upward from here)
int new_m;
if (mode == FULL) new_m = pos_m ;
else new_m = (pos_m+dim_ker_log[0]-1);
for (int iter_n=0; iter_n < Os[1]; iter_n++) { // loop over columns
// current col position in logical output image
int pos_n=iter_n*%(self_dy)s;
%(type)s sum=0;
// Sum over kernel, if index into image is out of bounds
// fill with the value
// loop over logical rows in kernel
for (int j_log=0; j_log < %(self_kshp_logical_r)s; j_log++) {
// ind0_log: row position in logical input image
int ind0_log = (new_m-j_log);
if ((j_log < %(self_kshp_logical_offset_r)s) ||
(j_log - %(self_kshp_logical_offset_r)s) MOD %(self_kshp_logical_stride_r)s)
continue;
if (ind0_log MOD %(self_imshp_logical_stride_r)s)
continue;
int j_phys = ((j_log- %(self_kshp_logical_offset_r)s) /
%(self_kshp_logical_stride_r)s);
int ind0_phys = (ind0_log / %(self_imshp_logical_stride_r)s);
//std::cerr <<"j_log" << j_log << " j_phys " << j_phys << " " << ind0_phys << "\\n";
if(mode==FULL){
//This is a pointer to the current row of the kernel
const %(type)s * idx_hvals=&hvals[j_phys*dim_ker_phys[1]];
if(ind0_log < 0 || ind0_log >= dim_im_log[0]){
// the current row of the kernel is off the image
}else{
int k = max((int)(pos_n-dim_im_log[1])+1,0);
int max_k=min(pos_n+1,(int)dim_ker_log[1]);
const %(type)s * idx_in=&in[ind0_phys*dim_im_phys[1]];
for (int ind1_log=pos_n-k; k<max_k; k++,ind1_log--) {
if (1)
{
if ((k < %(self_kshp_logical_offset_c)s) ||
(k - %(self_kshp_logical_offset_c)s) MOD
%(self_kshp_logical_stride_c)s)
continue;
if (ind1_log MOD
%(self_imshp_logical_stride_c)s)
continue;
}
sum += idx_hvals[(k-%(self_kshp_logical_offset_c)s) /
%(self_kshp_logical_stride_c)s] *
idx_in[ind1_log / %(self_imshp_logical_stride_c)s];
}
}
}else{ // mode==VALID
//JB: should be dim_im[1] right? (was dim_im[0])
const %(type)s* idx_in=&in[ind0_phys*dim_im_phys[1]];
const %(type)s* idx_hvals=&hvals[j_phys*dim_ker_phys[1]];
int new_n = (pos_n+dim_ker_log[1]-1);
if (%(self_imshp_logical_stride_c)s != 1) // a general loop
{
for (int k=0,last=new_n; k < dim_ker_log[1]; k++,last--) {
if ((k < %(self_kshp_logical_offset_c)s) ||
(k - %(self_kshp_logical_offset_c)s) MOD
%(self_kshp_logical_stride_c)s)
continue;
else if (last MOD %(self_imshp_logical_stride_c)s)
continue;
else
{
sum+=idx_hvals[(k-%(self_kshp_logical_offset_c)s) /
%(self_kshp_logical_stride_c)s] *
idx_in[last/%(self_imshp_logical_stride_c)s];
}
}
}
else // self_imshp_stride_c == 1
{
int offset = %(self_kshp_logical_offset_c)s;
int k_phys=0;
for (int k_log=offset,last=new_n-offset;
k_log < dim_ker_log[1]; ) {
sum += idx_hvals[k_phys]*idx_in[last];
++k_phys;
last -= %(self_kshp_logical_stride_c)s;
k_log += %(self_kshp_logical_stride_c)s;
}
}
}
}//for j_log
out[iter_m*dim_zz[1]+iter_n] %(affectation)s sum;
}//for iter_n
}//for iter_m
}//for stack_size
if (0 && (mode==FULL)){
for (int i = 0; i < dim_zz[0]*dim_zz[1]; ++i)
std::cout << " " << out[i];
std::cout << "\\n";
}
}//for n_kern
}//for b
Py_XDECREF(img2d);
Py_XDECREF(filtersflipped);
"""
#########
# ConvOp c_code for valid mode (uses gemm)
#########
_conv_op_code_valid_gemm = """
int typenum=0, typenum_f=0;
PyArrayObject *ain1=NULL, *ain2=NULL, *img2d_arr=NULL, *z_arr=NULL;
const int NKERN = %(self_nkern)s;
int type_im=PyArray_TYPE(%(img2d)s);
int type_ker=PyArray_TYPE(%(filtersflipped)s);
npy_intp dim_zz[2]={%(self_outshp0)s,%(self_outshp1)s};
npy_intp dim_im[2]={%(self_imshp1)s,%(self_imshp2)s};
const npy_intp dim_ker0=%(self_kshp0)s;
const npy_intp dim_ker1=%(self_kshp1)s;
PyArray_Dims img2d_shape;
npy_intp img2d_dim[4]={1,1,0,0};
img2d_shape.ptr=img2d_dim;
img2d_shape.len=4;
PyArray_Dims kerns_shape;
npy_intp kerns_dim[4]={1,1,0,0};
kerns_shape.ptr=kerns_dim;
kerns_shape.len=4;
PyObject *img2d=NULL, *contig;
if(PyArray_NDIM(%(img2d)s)==2){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==3){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==4){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[3];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[1]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else {
PyErr_SetString(PyExc_ValueError, "img don't have a good shape");
%(fail)s;
}
if(PyArray_NDIM(%(filtersflipped)s)==3){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else if(PyArray_NDIM(%(filtersflipped)s)==4){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[3];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[1]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else{
std::stringstream temp;
temp << "nddim="<<PyArray_NDIM(%(filtersflipped)s);
std::string param = temp.str();
PyErr_SetString(PyExc_ValueError,
("kernel don't have a good shape. " + param).c_str());
%(fail)s;
}
if (NKERN != kerns_dim[0])
{
PyErr_SetString(PyExc_NotImplementedError, "nonsense nkern");
%(fail)s;
}
img2d = PyArray_Newshape(%(img2d)s,&img2d_shape, NPY_CORDER);
img2d_arr = (PyArrayObject*)img2d;
if ((PyArray_STRIDES(img2d_arr)[3] != (npy_intp)sizeof(%(type)s))
|| (PyArray_STRIDES(img2d_arr)[2] != PyArray_DIMS(img2d_arr)[3]*(npy_intp)sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)img2d));
Py_DECREF(img2d);
img2d = contig;
img2d_arr = (PyArrayObject*)img2d;
if (!PyArray_ISCONTIGUOUS(img2d_arr)){
PyErr_SetString(PyExc_ValueError, "img2d isn't contiguous");
%(fail)s;
}
}
typenum = PyArray_ObjectType((PyObject*)%(img2d)s, 0);
typenum_f = PyArray_ObjectType((PyObject*)%(filtersflipped)s, 0);
if (typenum < 0) {PyErr_SetString(PyExc_ValueError, "Invalid type"); %(fail)s;}
if (typenum != typenum_f) {PyErr_SetString(PyExc_ValueError, "Input types must match"); %(fail)s;}
if (!img2d) {
PyErr_SetString(PyExc_ValueError, "Null argument img2d");
%(fail)s;
}
if ((!%(z)s)
|| *PyArray_DIMS(%(z)s)!=4
||(PyArray_DIMS(%(z)s)[0] != %(self_bsize)s)
||(PyArray_DIMS(%(z)s)[1] != %(self_nkern)s)
||(PyArray_DIMS(%(z)s)[2] != dim_zz[0])
|| (PyArray_DIMS(%(z)s)[3] != dim_zz[1])
)
{
{Py_XDECREF(%(z)s);}
npy_intp dims[4] = {0,0,0,0};
dims[0]=%(self_bsize)s;
dims[1]=%(self_nkern)s;
dims[2]=dim_zz[0];
dims[3]=dim_zz[1];
%(z)s = (PyArrayObject*) PyArray_ZEROS(4, dims, typenum,0);
}else{
PyArray_FILLWBYTE((PyObject*)%(z)s,0);
}
z_arr = (PyArrayObject*) %(z)s;
%(assert_size)s
int Os[2];
Os[0] = dim_im[0]-dim_ker0+1;
Os[1] = dim_im[1]-dim_ker1+1;
// allocate a temporary buffer for storing the inner product of each nth kernel row
// with each row of an image
{
%(type)s * kbuf = (%(type)s *)malloc((Os[0] * NKERN + PyArray_Size((PyObject*)%(filtersflipped)s))* (npy_intp)sizeof(%(type)s));
int kbufstride = NKERN;
%(type)s * myfilters = kbuf + Os[0] * NKERN;
//copy out filtersflipped into filters un-flipped format
//std::cerr << "__filling myfilters__\\n";
for(int i=0;i < kerns_dim[0];++i){
for(int j=0;j < kerns_dim[1];++j){
for(int k=0;k < kerns_dim[2];++k){
for(int l=0;l < kerns_dim[3];++l){
%(type)s * ff = ((PyArray_NDIM(%(filtersflipped)s)) == 3)
? (%(type)s *)PyArray_GETPTR3(%(filtersflipped)s, i, kerns_dim[2]-1-k, kerns_dim[3]-1-l)
: (%(type)s *)PyArray_GETPTR4(%(filtersflipped)s, i, j, kerns_dim[2]-1-k, kerns_dim[3]-1-l);
myfilters[i * (kerns_dim[1]*kerns_dim[2]*kerns_dim[3])
+ j * (kerns_dim[2]*kerns_dim[3])
+ k * (kerns_dim[3])
+ l] = ff[0];
//std::cerr << " " << ff[0];
}
//std::cerr << "\\n";
}
//std::cerr << "(end of stack/batch " <<j << "/" << i << " ) \\n";
}
}
//std::cerr << "-----new loop ----\\n";
for(int b=0;b< %(self_bsize)s;b++){
for (int img_col = 0; img_col < Os[1]; ++img_col){
for (int filter_row = 0; filter_row < kerns_dim[2]; ++filter_row){
for (int stackidx = 0; stackidx < %(self_imshp0)s; ++stackidx){
%(type)s * img_colview =
(%(type)s *)(PyArray_GETPTR4(img2d, b, stackidx, filter_row, img_col));
%(type)s * filter_rows = myfilters + stackidx * (kerns_dim[2]*kerns_dim[3]) +
filter_row * kerns_dim[3];
//std::cerr << "filterview offset: " << filter_rows - myfilters << "\\n";
char N = 'N'; char T = 'T';
int Nz0 = Os[0];
int Nz1 = NKERN;
int K = kerns_dim[3];
%(type)s alpha = 1.0;
%(type)s beta = stackidx ? 1.0 : 0.0;
int imgview_stride = dim_im[1];
int filter_rows_stride =kerns_dim[1]*kerns_dim[2]*kerns_dim[3];
//remember, Fortran wants a column-major interpretation
assert(PyArray_STRIDES(img2d)[3] == (npy_intp)sizeof(%(type)s));
if (0){
std::cerr << "b " << b << " img_col " << img_col << " filterrow " << filter_row << " stackidx " <<stackidx << "\\n";
std::cerr << "colview (physical layout) stride: " << imgview_stride << "\\n";
for (int ii = 0; ii < Nz0; ++ii){
for (int jj = 0; jj < K; ++jj){
std::cerr << " " << img_colview[ii * imgview_stride + jj];
}
std::cerr << "\\n";
}
std::cerr << "filterview ("<<filter_row<<"'th rows) stride: " << filter_rows_stride << "\\n";
for (int ii = 0; ii < Nz1; ++ii){
for (int jj = 0; jj < K; ++jj){
std::cerr << " " << filter_rows[ii * filter_rows_stride + jj];
}
std::cerr << "\\n";
}
std::cerr << Nz1 << " " << Nz0 << " " << K << "\\n" ;
}
%(gemm)s(&T, &N,
&Nz1, &Nz0, &K,
&alpha,
filter_rows, &filter_rows_stride,
img_colview, &imgview_stride,
&beta, kbuf, &kbufstride);
if (0){
std::cerr << "z (logical layout) beta" << beta << "\\n";
for (int ii = 0; ii < Nz0; ++ii){
for (int jj = 0; jj < Nz1; ++jj){
std::cerr << " " << kbuf[ii * kbufstride + jj];
}
std::cerr << "\\n";
}
}
}
// now kbuf the sum over the stack, put it into the outbuf
for (int img_row = 0; img_row < Os[0]; ++img_row) {
for (int kernel_idx = 0; kernel_idx < NKERN; ++kernel_idx) {
%(type)s * z_p = (%(type)s *)PyArray_GETPTR4(%(z)s, b, kernel_idx, img_row, img_col);
if (0)
{
if (b >= PyArray_DIMS(%(z)s)[0]) %(fail)s;
if (kernel_idx >= PyArray_DIMS(%(z)s)[1]) %(fail)s;
if (img_row >= PyArray_DIMS(%(z)s)[2]) %(fail)s;
if (img_col >= PyArray_DIMS(%(z)s)[3]) %(fail)s;
}
z_p[0] += kbuf[img_row * kbufstride + kernel_idx];
}
}
}
}
}
free(kbuf);
}
Py_XDECREF(img2d);
"""
def gen_conv_code_unroll_batch_kern(d, unroll_bsize=1, unroll_ksize=1):
"""
c_code for ConvOp that unroll the batch size loop.
"""
assert unroll_bsize > 0 and unroll_ksize > 0
if (
"unroll_bsize" in d
or "unroll_ksize" in d
or "unroll_iter" in d
or "unroll_biter" in d
or "unroll_kiter" in d
):
raise ValueError(
"We can't use this dictionary as we will overwrite some of its content"
)
d = d.copy()
d["unroll_bsize"] = unroll_bsize
d["unroll_ksize"] = unroll_ksize
def my_dup(st, size):
s = ""
for i in range(size):
d["unroll_iter"] = i
s += st % d
return s + "\n"
def my_dup2(st):
s = ""
iter = 0
for i in range(unroll_bsize):
d["unroll_biter"] = i
for j in range(unroll_ksize):
d["unroll_kiter"] = j
d["unroll_iter"] = iter
iter += 1
s += st % d
return s + "\n"
ret = (
"""
const int mode=%(mode)s;
int typenum=0, typenum_f=0;
PyArrayObject *ain1=NULL, *ain2=NULL, *filtersflipped_arr=NULL, *img2d_arr=NULL, *z_arr=NULL;;
const %(type)s fill_value = 0;
int type_im=PyArray_TYPE(%(img2d)s);
int type_ker=PyArray_TYPE(%(filtersflipped)s);
npy_intp dim_zz[2]={%(self_outshp0)s,%(self_outshp1)s};
npy_intp dim_im[2]={%(self_imshp1)s,%(self_imshp2)s};
const npy_intp dim_ker0=%(self_kshp0)s;
const npy_intp dim_ker1=%(self_kshp1)s;
PyArray_Dims img2d_shape;
npy_intp img2d_dim[4]={1,1,0,0};
img2d_shape.ptr=img2d_dim;
img2d_shape.len=4;
PyArray_Dims kerns_shape;
npy_intp kerns_dim[4]={1,1,0,0};
kerns_shape.ptr=kerns_dim;
kerns_shape.len=4;
PyObject *img2d=NULL, *contig, *filtersflipped=NULL;
if(PyArray_NDIM(%(img2d)s)==2){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==3){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==4){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[3];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[1]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else {
std::stringstream temp;
temp << "nddim="<<PyArray_NDIM(%(img2d)s);
std::string param = temp.str();
PyErr_SetString(PyExc_ValueError,
("img don't have a good shape. " + param).c_str());
%(fail)s;
}
if(PyArray_NDIM(%(filtersflipped)s)==3){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else if(PyArray_NDIM(%(filtersflipped)s)==4){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[3];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[1]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else{
PyErr_SetString(PyExc_ValueError, "kernel don't have a good shape");
%(fail)s;
}
%(assert_size)s
img2d = PyArray_Newshape(%(img2d)s,&img2d_shape, NPY_CORDER);
img2d_arr = (PyArrayObject*)img2d;
if ((PyArray_STRIDES(img2d_arr)[3] != (npy_intp)sizeof(%(type)s))
|| (PyArray_STRIDES(img2d_arr)[2] != PyArray_DIMS(img2d_arr)[3]*(npy_intp)sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)img2d));
Py_DECREF(img2d);
img2d = contig;
img2d_arr = (PyArrayObject*)img2d;
if (!PyArray_ISCONTIGUOUS(img2d_arr)){
PyErr_SetString(PyExc_ValueError, "img2d isn't contiguous");
%(fail)s;
}
}
filtersflipped = PyArray_Newshape(%(filtersflipped)s,&kerns_shape, NPY_CORDER);
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if ((PyArray_STRIDES(filtersflipped_arr)[3] != (npy_intp)sizeof(%(type)s))
|| (PyArray_STRIDES(filtersflipped_arr)[2] != PyArray_DIMS(filtersflipped_arr)[3]*(npy_intp)sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)filtersflipped));
Py_DECREF(filtersflipped);
filtersflipped = contig;
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if (!PyArray_ISCONTIGUOUS(filtersflipped_arr)){
PyErr_SetString(PyExc_ValueError, "filtersflipped isn't contiguous");
%(fail)s;
}
}
if(mode != VALID && mode != FULL){
PyErr_SetString(PyExc_ValueError, "invalid mode, only full and valid are supported"); %(fail)s;
}
typenum = PyArray_ObjectType((PyObject*)%(img2d)s, 0);
typenum_f = PyArray_ObjectType((PyObject*)%(filtersflipped)s, 0);
if (typenum < 0) {PyErr_SetString(PyExc_ValueError, "Invalid type"); %(fail)s;}
if (typenum != typenum_f) {PyErr_SetString(PyExc_ValueError, "Input types must match"); %(fail)s;}
if (!img2d)
{
PyErr_SetString(PyExc_AssertionError, "!img2d");
%(fail)s;
}
if (!filtersflipped)
{
PyErr_SetString(PyExc_AssertionError, "!filtersflipped");
%(fail)s;
}
if ((!%(z)s)
|| *PyArray_DIMS(%(z)s)!=4
||(PyArray_DIMS(%(z)s)[0] != %(self_bsize)s)
||(PyArray_DIMS(%(z)s)[1] != %(self_nkern)s)
||(PyArray_DIMS(%(z)s)[2] != dim_zz[0])
||(PyArray_DIMS(%(z)s)[3] != dim_zz[1])
||!PyArray_ISCONTIGUOUS(%(z)s)
)
{
{Py_XDECREF(%(z)s);}
npy_intp dims[4] = {0,0,0,0};
dims[0]=%(self_bsize)s;
dims[1]=%(self_nkern)s;
dims[2]=dim_zz[0];
dims[3]=dim_zz[1];
%(z)s = (PyArrayObject*) PyArray_ZEROS(4, dims, typenum,0);
}else{
//PyArray_FILLWBYTE((PyObject*)%(z)s,0);
}
z_arr = (PyArrayObject*) %(z)s;
int Os[2];
Os[0]=%(self_outshp0)s;
Os[1]=%(self_outshp1)s;
//assertions
if (!PyArray_ISCONTIGUOUS(%(z)s))
{
PyErr_SetString(PyExc_AssertionError, "Output (%(z)s) not contiguous");
%(fail)s;
}
for(int b=0;b< %(self_bsize)s ;b+=%(unroll_bsize)s){
for(int n_kern=0;n_kern<%(self_nkern)s;n_kern+=%(unroll_ksize)s){
"""
% d
)
ret += my_dup2(
"%(type)s * __restrict__ out%(unroll_iter)s=(%(type)s *)(PyArray_GETPTR2(z_arr,b+%(unroll_biter)s,n_kern+%(unroll_kiter)s));"
)
ret += my_dup(
"for (int i = 0; i < dim_zz[0]*dim_zz[1]; ++i) out%(unroll_iter)s[i] = 0;",
unroll_bsize * unroll_ksize,
)
ret += (
"""
for(int stack_size=0;stack_size<%(self_imshp0)s;stack_size++){
"""
% d
)
ret += my_dup(
"const %(type)s * __restrict__ in%(unroll_iter)d=(%(type)s *)(PyArray_GETPTR2(img2d_arr,b+%(unroll_iter)s,stack_size));",
unroll_bsize,
)
ret += my_dup(
"const %(type)s * __restrict__ hvals%(unroll_iter)s=(%(type)s *)(PyArray_GETPTR2(filtersflipped_arr,n_kern+%(unroll_iter)s,stack_size));",
unroll_ksize,
)
ret += (
"""
int new_m;
for (int iter_m=0; iter_m < Os[0]; iter_m++) {
// Reposition index into input image based on requested output size
int pos_m = iter_m*%(self_dx)s;//The position of the patch in the image
if (mode == FULL) new_m = pos_m ;
else new_m = (pos_m+dim_ker0-1);
for (int iter_n=0; iter_n < Os[1]; iter_n++) { // loop over columns
int pos_n=iter_n*%(self_dy)s;
"""
% d
)
ret += my_dup("%(type)s sum%(unroll_iter)s=0;", unroll_bsize * unroll_ksize)
ret += (
"""
// Sum over kernel, if index into image is out of bounds
// fill with the value
for (int j=0; j < dim_ker0; j++) {
int ind0 = (new_m-j);
if(mode==FULL){
"""
% d
)
ret += my_dup(
"const %(type)s * idx_hvals%(unroll_iter)s=&hvals%(unroll_iter)s[j*dim_ker1];",
unroll_ksize,
)
ret += (
"""
if(ind0 < 0 || ind0 >= dim_im[0]){
if(fill_value!=0)
for (int k=0; k < dim_ker1; k++) {
"""
% d
)
ret += my_dup2("sum%(unroll_iter)s += idx_hvals%(unroll_kiter)s[k] * fill_value;")
ret += (
"""
}
}else{
//do the part where kernel is to the right of the img
int k=0,max_k=max((int)(pos_n-dim_im[1])+1,0);
if(fill_value!=0){
for(k=0;k<max_k;k++){
"""
% d
)
ret += my_dup2("sum%(unroll_iter)s += idx_hvals%(unroll_kiter)s[k] * fill_value;")
ret += (
"""
}
}else {k=max_k;}
//do the part where the kernel is on the img
max_k=min(pos_n+1,(int)dim_ker1);
"""
% d
)
ret += my_dup(
"const %(type)s * idx_in%(unroll_iter)s=&in%(unroll_iter)s[ind0*dim_im[1]];",
unroll_bsize,
)
ret += (
"""
for (int ind1=pos_n-k; k<max_k; k++,ind1--) {
"""
% d
)
ret += my_dup2(
"sum%(unroll_iter)s+= idx_hvals%(unroll_kiter)s[k] * idx_in%(unroll_biter)s[ind1];"
)
ret += (
"""
}
//do the part to the left of the img
if(fill_value!=0)
for(;k<dim_ker1;k++){
"""
% d
)
ret += my_dup2("sum%(unroll_iter)s += idx_hvals%(unroll_kiter)s[k] * fill_value;")
ret += (
"""
}
}
}else{//valid mode
"""
% d
)
ret += my_dup(
"const %(type)s* idx_in%(unroll_iter)s=&in%(unroll_iter)s[ind0*dim_im[1]];",
unroll_bsize,
)
ret += my_dup(
"const %(type)s* idx_hvals%(unroll_iter)s=&hvals%(unroll_iter)s[j*dim_ker1];",
unroll_ksize,
)
ret += (
"""
int new_n = (pos_n+dim_ker1-1);
for (int k=0,last=new_n; k < dim_ker1; k++,last--) {
"""
% d
)
ret += my_dup2(
"sum%(unroll_iter)s+=idx_hvals%(unroll_kiter)s[k]*idx_in%(unroll_biter)s[last];"
)
ret += (
"""
}
}
}//for j
"""
% d
)
ret += my_dup(
"out%(unroll_iter)s[iter_m*dim_zz[1]+iter_n] %(affectation)s sum%(unroll_iter)s;",
unroll_bsize * unroll_ksize,
)
ret += """
}//for n
}//for m
}//for stack_size
}//for n_kern
}//for b
Py_XDECREF(img2d);
Py_XDECREF(filtersflipped);
"""
return ret
_conv_op_code_unroll_patch = """
const int mode=%(mode)s;
int typenum=0, typenum_f=0;
PyArrayObject *ain1=NULL, *ain2=NULL, *filtersflipped_arr=NULL, *img2d_arr=NULL, *z_arr=NULL;
const %(type)s fill_value = 0;//only value of 0 are currently tested and correctly implemented
int type_im=PyArray_TYPE(%(img2d)s);
int type_ker=PyArray_TYPE(%(filtersflipped)s);
const npy_intp dim_im[2]={%(self_imshp1)s,%(self_imshp2)s};
//The following line caused gcc 4.3.0 20080428 (Red Hat 4.3.0-8) to crash
//const npy_intp dim_ker[2]={%(self_kshp0)s,%(self_kshp1)s};
// The next line had gcc don't crash.
const npy_intp dim_ker0=%(self_kshp0)s;
const npy_intp dim_ker1=%(self_kshp1)s;
%(dim_zz_const)s npy_intp dim_zz[2]={%(self_outshp0)s,%(self_outshp1)s};
%(dim_zz_affect)s
PyArray_Dims img2d_shape;
npy_intp img2d_dim[4]={1,1,0,0};
img2d_shape.ptr=img2d_dim;
img2d_shape.len=4;
PyArray_Dims kerns_shape;
npy_intp kerns_dim[4]={1,1,0,0};
kerns_shape.ptr=kerns_dim;
kerns_shape.len=4;
PyObject *img2d=NULL, *contig, *filtersflipped=NULL;
if(PyArray_NDIM(%(img2d)s)==2){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==3){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else if(PyArray_NDIM(%(img2d)s)==4){
img2d_dim[3]=PyArray_DIMS(%(img2d)s)[3];
img2d_dim[2]=PyArray_DIMS(%(img2d)s)[2];
img2d_dim[1]=PyArray_DIMS(%(img2d)s)[1];
img2d_dim[0]=PyArray_DIMS(%(img2d)s)[0];
}else {
PyErr_Format(PyExc_ValueError,
"image don't have a good number of dimensions %%d. ", PyArray_NDIM(%(filtersflipped)s));
%(fail)s;
}
if(PyArray_NDIM(%(filtersflipped)s)==3){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else if(PyArray_NDIM(%(filtersflipped)s)==4){
kerns_dim[3]=PyArray_DIMS(%(filtersflipped)s)[3];
kerns_dim[2]=PyArray_DIMS(%(filtersflipped)s)[2];
kerns_dim[1]=PyArray_DIMS(%(filtersflipped)s)[1];
kerns_dim[0]=PyArray_DIMS(%(filtersflipped)s)[0];
}else{
PyErr_Format(PyExc_ValueError,
"kernel don't have a good number of dimensions %%d. ", PyArray_NDIM(%(filtersflipped)s));
%(fail)s;
}
%(assert_size)s
img2d = PyArray_Newshape(%(img2d)s,&img2d_shape, NPY_CORDER);
img2d_arr = (PyArrayObject*)img2d;
if ((PyArray_STRIDES(img2d_arr)[3] != sizeof(%(type)s))
|| (PyArray_STRIDES(img2d_arr)[2] != PyArray_DIMS(img2d_arr)[3]*sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)img2d));
Py_DECREF(img2d);
img2d = contig;
img2d_arr = (PyArrayObject*)img2d;
if (!PyArray_ISCONTIGUOUS(img2d_arr)){
PyErr_SetString(PyExc_ValueError, "img2d isn't contiguous");
%(fail)s;
}
}
filtersflipped = PyArray_Newshape(%(filtersflipped)s,&kerns_shape, NPY_CORDER);
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if ((PyArray_STRIDES(filtersflipped_arr)[3] != sizeof(%(type)s))
|| (PyArray_STRIDES(filtersflipped_arr)[2] != PyArray_DIMS(filtersflipped_arr)[3]*sizeof(%(type)s))){
contig = (PyObject*)(PyArray_GETCONTIGUOUS((PyArrayObject*)filtersflipped));
Py_DECREF(filtersflipped);
filtersflipped = contig;
filtersflipped_arr = (PyArrayObject*)filtersflipped;
if (!PyArray_ISCONTIGUOUS(filtersflipped_arr)){
PyErr_SetString(PyExc_ValueError, "filtersflipped isn't contiguous");
%(fail)s;
}
}
if(mode != VALID && mode != FULL){
PyErr_SetString(PyExc_ValueError, "invalid mode, only full and valid are supported"); %(fail)s;
}
if(dim_zz[0]<=0 || dim_zz[1]<=0){
PyErr_Format(PyExc_ValueError,
"Output dimensions are not valid %%ldx%%ld",(long int)dim_zz[0],(long int)dim_zz[1]);
%(fail)s;
}
typenum = PyArray_ObjectType((PyObject*)%(img2d)s, 0);
typenum_f = PyArray_ObjectType((PyObject*)%(filtersflipped)s, 0);
if (typenum < 0) {PyErr_SetString(PyExc_ValueError, "Invalid type"); %(fail)s;}
if (typenum != typenum_f) {PyErr_SetString(PyExc_ValueError, "Input types must match"); %(fail)s;}
if (!img2d) %(fail)s;
if (!filtersflipped) %(fail)s;
if ((!%(z)s)
|| *PyArray_DIMS(%(z)s)!=4
||(PyArray_DIMS(%(z)s)[0] != %(self_bsize)s)
||(PyArray_DIMS(%(z)s)[1] != %(self_nkern)s)
||(PyArray_DIMS(%(z)s)[2] != dim_zz[0])
|| (PyArray_DIMS(%(z)s)[3] != dim_zz[1])
)
{
if (%(z)s) Py_DECREF(%(z)s);
npy_intp dims[4] = {0,0,0,0};
if(!dims) %(fail)s;
dims[0]=%(self_bsize)s;
dims[1]=%(self_nkern)s;
dims[2]=dim_zz[0];
dims[3]=dim_zz[1];
%(z)s = (PyArrayObject*) PyArray_ZEROS(4, dims, typenum,0);
}else{
//PyArray_FILLWBYTE((PyObject*)%(z)s,0);
}
z_arr = (PyArrayObject*) %(z)s;
// assert the output is C-contiguous
if (!PyArray_ISCONTIGUOUS(%(z)s))
{
PyErr_SetString(PyExc_AssertionError, "Output (%(z)s) not contiguous");
%(fail)s;
}
//The if on the number of loop make a speed up for small array.
//with g++ 4.5.1. The compiler should be smart enough to do this himself!
#pragma omp parallel for schedule(static) if(%(self_bsize)s * %(self_nkern)s > 1)
// We merge the 2 loop into one to make it easier to parallelize on both
// This is the equivalent of those 2 lines.
//for(int b=0;b< %(self_bsize)s;b++){
// for(int n_kern=0;n_kern<%(self_nkern)s;n_kern++){
for(int batch_kern_idx=0;
batch_kern_idx < %(self_bsize)s * %(self_nkern)s;
batch_kern_idx++){
int b = batch_kern_idx / %(self_nkern)s;
int n_kern = batch_kern_idx %% %(self_nkern)s;
%(type)s * __restrict__ out=(%(type)s *)(PyArray_GETPTR2(z_arr,b,n_kern));
for (int i = 0; i < dim_zz[0]*dim_zz[1]; ++i) out[i] = 0;
for(int stack_size=0;stack_size<%(self_imshp0)s;stack_size++){
const %(type)s * __restrict__ in=(%(type)s *)(PyArray_GETPTR2(img2d_arr,b,stack_size));
const %(type)s * __restrict__ hvals=(%(type)s *)(PyArray_GETPTR2(filtersflipped_arr,n_kern,stack_size));
int new_m;
for (int iter_m=0; iter_m < dim_zz[0]; iter_m++) {
// Reposition index into input image based on requested output size
int pos_m = iter_m*%(self_dx)s;//The position of the patch in the image
if (mode == FULL) new_m = pos_m ;
else new_m = (pos_m+dim_ker0-1);
for (int iter_n=0; iter_n < dim_zz[1]; iter_n++) { // loop over columns
int pos_n=iter_n*%(self_dy)s;
%(type)s sum=0;
%(type)s sum2=0;
%(type)s sum3=0;
%(type)s sum4=0;
int nb_sum=0;
// Sum over kernel, if index into image is out of bounds
// fill with the value
for (int j=0; j < dim_ker0; j++) {
int ind0 = (new_m-j);
if(mode==FULL){
const %(type)s * idx_hvals=&hvals[j*dim_ker1];
if(ind0 < 0 || ind0 >= dim_im[0]){
if(fill_value!=0)
for (int k=0; k < dim_ker1; k++) {
sum+= idx_hvals[k] * fill_value;
}
}else{
//do the part where kernel is to the right of the img
int k=0,max_k=max((int)(pos_n-dim_im[1])+1,0);
if(fill_value!=0){
for(k=0;k<max_k;k++){
sum+= idx_hvals[k]*fill_value;
}
}else {k=max_k;}
//do the part where the kernel is on the img
max_k=min(pos_n+1,(int)dim_ker1);
const %(type)s * idx_in=&in[ind0*dim_im[1]];
if(iter_n + 4*%(self_dy)s < dim_zz[1]
&& iter_n>dim_ker1-1
&& iter_n<dim_im[1]-dim_ker1+1-3){
nb_sum=4;
for (int ind1=pos_n-k; k<max_k; k++,ind1--) {
sum+=idx_hvals[k]*idx_in[ind1];
sum2+=idx_hvals[k]*idx_in[ind1+%(self_dy)s];
sum3+=idx_hvals[k]*idx_in[ind1+2*%(self_dy)s];
sum4+=idx_hvals[k]*idx_in[ind1+3*%(self_dy)s];
}
}else if(iter_n + 2*%(self_dy)s < dim_zz[1]
&& iter_n>dim_ker1-1
&& iter_n<dim_im[1]-dim_ker1+1){
nb_sum=2;
for (int ind1=pos_n-k; k<max_k; k++,ind1--) {
sum+=idx_hvals[k]*idx_in[ind1];
sum2+=idx_hvals[k]*idx_in[ind1+%(self_dy)s];
}
}else{
nb_sum=1;
/*
%(type)s sum_=0;
if((k-max_k) & 0x1 != 0){
sum+= idx_hvals[k] * idx_in[pos_n-k];
}
for (int ind1=pos_n-k; k<max_k; k+=2,ind1-=2) {
sum+= idx_hvals[k] * idx_in[ind1];
sum_+= idx_hvals[k+1] * idx_in[ind1-1];
}
sum+=sum_;
*/
for (int ind1=pos_n-k; k<max_k; k++,ind1--) {
sum+=idx_hvals[k]*idx_in[ind1];
}
}
//do the part to the left of the img
if(fill_value!=0)
for(;k<dim_ker1;k++) sum+= idx_hvals[k]*fill_value;
}
}else{//valid mode
const %(type)s* idx_in=&in[ind0*dim_im[1]];
const %(type)s* idx_hvals=&hvals[j*dim_ker1];
if(iter_n + 4*%(self_dy)s < dim_zz[1]){
nb_sum=4;
for (int k=dim_ker1-1,im_idx=pos_n; k >=0; k--,im_idx++) {
sum+=idx_hvals[k]*idx_in[im_idx];
sum2+=idx_hvals[k]*idx_in[im_idx+%(self_dy)s];
sum3+=idx_hvals[k]*idx_in[im_idx+2*%(self_dy)s];
sum4+=idx_hvals[k]*idx_in[im_idx+3*%(self_dy)s];
}
}else if(iter_n + 2*%(self_dy)s < dim_zz[1]){
nb_sum=2;
for (int k=dim_ker1-1,im_idx=pos_n; k >=0; k--,im_idx++) {
sum+=idx_hvals[k]*idx_in[im_idx];
sum2+=idx_hvals[k]*idx_in[im_idx+%(self_dy)s];
}
}else{
nb_sum=1;
for (int k=dim_ker1-1,im_idx=pos_n; k >=0; k--,im_idx++) {
sum+=idx_hvals[k]*idx_in[im_idx];
}
}
}//else valid mode
}//for j
switch(nb_sum){
case 4: out[iter_m*dim_zz[1]+iter_n+3] %(affectation)s sum4;
case 3: out[iter_m*dim_zz[1]+iter_n+2] %(affectation)s sum3;
case 2: out[iter_m*dim_zz[1]+iter_n+1] %(affectation)s sum2;
case 1: out[iter_m*dim_zz[1]+iter_n] %(affectation)s sum;
}
iter_n+=nb_sum-1;
}//for iter_n
}//for iter_m
}//for stack_size
}//for b and n_kern
Py_XDECREF(img2d);
Py_XDECREF(filtersflipped);
"""
|
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from poetry.factory import Factory
if TYPE_CHECKING:
from cleo.testers.command_tester import CommandTester
from poetry.poetry import Poetry
from tests.types import CommandTesterFactory
@pytest.fixture
def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("new")
def verify_project_directory(
path: Path, package_name: str, package_path: str, include_from: str | None = None
) -> Poetry:
package_path = Path(package_path)
assert path.is_dir()
pyproject = path / "pyproject.toml"
assert pyproject.is_file()
init_file = path / package_path / "__init__.py"
assert init_file.is_file()
tests_init_file = path / "tests" / "__init__.py"
assert tests_init_file.is_file()
poetry = Factory().create_poetry(cwd=path)
assert poetry.package.name == package_name
if include_from:
package_include = {
"include": package_path.relative_to(include_from).parts[0],
"from": include_from,
}
else:
package_include = {"include": package_path.parts[0]}
packages = poetry.local_config.get("packages")
if not packages:
assert poetry.local_config.get("name") == package_include.get("include")
else:
assert len(packages) == 1
assert packages[0] == package_include
return poetry
@pytest.mark.parametrize(
"options,directory,package_name,package_path,include_from",
[
([], "package", "package", "package", None),
(["--src"], "package", "package", "src/package", "src"),
(
["--name namespace.package"],
"namespace-package",
"namespace-package",
"namespace/package",
None,
),
(
["--src", "--name namespace.package"],
"namespace-package",
"namespace-package",
"src/namespace/package",
"src",
),
(
["--name namespace.package_a"],
"namespace-package_a",
"namespace-package-a",
"namespace/package_a",
None,
),
(
["--src", "--name namespace.package_a"],
"namespace-package_a",
"namespace-package-a",
"src/namespace/package_a",
"src",
),
(
["--name namespace_package"],
"namespace-package",
"namespace-package",
"namespace_package",
None,
),
(
["--name namespace_package", "--src"],
"namespace-package",
"namespace-package",
"src/namespace_package",
"src",
),
(
["--name namespace.package"],
"package",
"namespace-package",
"namespace/package",
None,
),
(
["--name namespace.package", "--src"],
"package",
"namespace-package",
"src/namespace/package",
"src",
),
(
["--name namespace.package"],
"package",
"namespace-package",
"namespace/package",
None,
),
(
["--name namespace.package", "--src"],
"package",
"namespace-package",
"src/namespace/package",
"src",
),
([], "namespace_package", "namespace-package", "namespace_package", None),
(
["--src", "--name namespace_package"],
"namespace_package",
"namespace-package",
"src/namespace_package",
"src",
),
],
)
def test_command_new(
options: list[str],
directory: str,
package_name: str,
package_path: str,
include_from: str | None,
tester: CommandTester,
tmp_dir: str,
):
path = Path(tmp_dir) / directory
options.append(path.as_posix())
tester.execute(" ".join(options))
verify_project_directory(path, package_name, package_path, include_from)
@pytest.mark.parametrize(("fmt",), [(None,), ("md",), ("rst",), ("adoc",), ("creole",)])
def test_command_new_with_readme(fmt: str | None, tester: CommandTester, tmp_dir: str):
package = "package"
path = Path(tmp_dir) / package
options = [path.as_posix()]
if fmt:
options.insert(0, f"--readme {fmt}")
tester.execute(" ".join(options))
poetry = verify_project_directory(path, package, package, None)
assert poetry.local_config.get("readme") == f"README.{fmt or "md"}"
| from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from poetry.factory import Factory
if TYPE_CHECKING:
from cleo.testers.command_tester import CommandTester
from poetry.poetry import Poetry
from tests.types import CommandTesterFactory
@pytest.fixture
def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("new")
def verify_project_directory(
path: Path, package_name: str, package_path: str, include_from: str | None = None
) -> Poetry:
package_path = Path(package_path)
assert path.is_dir()
pyproject = path / "pyproject.toml"
assert pyproject.is_file()
init_file = path / package_path / "__init__.py"
assert init_file.is_file()
tests_init_file = path / "tests" / "__init__.py"
assert tests_init_file.is_file()
poetry = Factory().create_poetry(cwd=path)
assert poetry.package.name == package_name
if include_from:
package_include = {
"include": package_path.relative_to(include_from).parts[0],
"from": include_from,
}
else:
package_include = {"include": package_path.parts[0]}
packages = poetry.local_config.get("packages")
if not packages:
assert poetry.local_config.get("name") == package_include.get("include")
else:
assert len(packages) == 1
assert packages[0] == package_include
return poetry
@pytest.mark.parametrize(
"options,directory,package_name,package_path,include_from",
[
([], "package", "package", "package", None),
(["--src"], "package", "package", "src/package", "src"),
(
["--name namespace.package"],
"namespace-package",
"namespace-package",
"namespace/package",
None,
),
(
["--src", "--name namespace.package"],
"namespace-package",
"namespace-package",
"src/namespace/package",
"src",
),
(
["--name namespace.package_a"],
"namespace-package_a",
"namespace-package-a",
"namespace/package_a",
None,
),
(
["--src", "--name namespace.package_a"],
"namespace-package_a",
"namespace-package-a",
"src/namespace/package_a",
"src",
),
(
["--name namespace_package"],
"namespace-package",
"namespace-package",
"namespace_package",
None,
),
(
["--name namespace_package", "--src"],
"namespace-package",
"namespace-package",
"src/namespace_package",
"src",
),
(
["--name namespace.package"],
"package",
"namespace-package",
"namespace/package",
None,
),
(
["--name namespace.package", "--src"],
"package",
"namespace-package",
"src/namespace/package",
"src",
),
(
["--name namespace.package"],
"package",
"namespace-package",
"namespace/package",
None,
),
(
["--name namespace.package", "--src"],
"package",
"namespace-package",
"src/namespace/package",
"src",
),
([], "namespace_package", "namespace-package", "namespace_package", None),
(
["--src", "--name namespace_package"],
"namespace_package",
"namespace-package",
"src/namespace_package",
"src",
),
],
)
def test_command_new(
options: list[str],
directory: str,
package_name: str,
package_path: str,
include_from: str | None,
tester: CommandTester,
tmp_dir: str,
):
path = Path(tmp_dir) / directory
options.append(path.as_posix())
tester.execute(" ".join(options))
verify_project_directory(path, package_name, package_path, include_from)
@pytest.mark.parametrize(("fmt",), [(None,), ("md",), ("rst",), ("adoc",), ("creole",)])
def test_command_new_with_readme(fmt: str | None, tester: CommandTester, tmp_dir: str):
package = "package"
path = Path(tmp_dir) / package
options = [path.as_posix()]
if fmt:
options.insert(0, f"--readme {fmt}")
tester.execute(" ".join(options))
poetry = verify_project_directory(path, package, package, None)
assert poetry.local_config.get("readme") == f"README.{fmt or 'md'}"
|
#!/usr/bin/env python3
# coding: utf-8
from __future__ import absolute_import, unicode_literals
import collections
import contextlib
import copy
import datetime
import errno
import fileinput
import functools
import io
import itertools
import json
import locale
import operator
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import time
import tokenize
import traceback
import random
import unicodedata
from string import ascii_letters
from .compat import (
compat_basestring,
compat_get_terminal_size,
compat_kwargs,
compat_numeric_types,
compat_os_name,
compat_pycrypto_AES,
compat_shlex_quote,
compat_str,
compat_tokenize_tokenize,
compat_urllib_error,
compat_urllib_request,
compat_urllib_request_DataHandler,
windows_enable_vt_mode,
)
from .cookies import load_cookies
from .utils import (
age_restricted,
args_to_str,
ContentTooShortError,
date_from_str,
DateRange,
DEFAULT_OUTTMPL,
determine_ext,
determine_protocol,
DOT_DESKTOP_LINK_TEMPLATE,
DOT_URL_LINK_TEMPLATE,
DOT_WEBLOC_LINK_TEMPLATE,
DownloadError,
encode_compat_str,
encodeFilename,
EntryNotInPlaylist,
error_to_compat_str,
ExistingVideoReached,
expand_path,
ExtractorError,
float_or_none,
format_bytes,
format_field,
formatSeconds,
GeoRestrictedError,
HEADRequest,
int_or_none,
iri_to_uri,
ISO3166Utils,
LazyList,
locked_file,
make_dir,
make_HTTPS_handler,
MaxDownloadsReached,
network_exceptions,
orderedSet,
OUTTMPL_TYPES,
PagedList,
parse_filesize,
PerRequestProxyHandler,
platform_name,
Popen,
PostProcessingError,
preferredencoding,
prepend_extension,
register_socks_protocols,
RejectedVideoReached,
render_table,
replace_extension,
SameFileError,
sanitize_filename,
sanitize_path,
sanitize_url,
sanitized_Request,
std_headers,
STR_FORMAT_RE_TMPL,
STR_FORMAT_TYPES,
str_or_none,
strftime_or_none,
subtitles_filename,
supports_terminal_sequences,
TERMINAL_SEQUENCES,
ThrottledDownload,
to_high_limit_path,
traverse_obj,
try_get,
UnavailableVideoError,
url_basename,
variadic,
version_tuple,
write_json_file,
write_string,
YoutubeDLCookieProcessor,
YoutubeDLHandler,
YoutubeDLRedirectHandler,
)
from .cache import Cache
from .extractor import (
gen_extractor_classes,
get_info_extractor,
_LAZY_LOADER,
_PLUGIN_CLASSES as plugin_extractors
)
from .extractor.openload import PhantomJSwrapper
from .downloader import (
FFmpegFD,
get_suitable_downloader,
shorten_protocol_name
)
from .downloader.rtmp import rtmpdump_version
from .postprocessor import (
get_postprocessor,
EmbedThumbnailPP,
FFmpegFixupDurationPP,
FFmpegFixupM3u8PP,
FFmpegFixupM4aPP,
FFmpegFixupStretchedPP,
FFmpegFixupTimestampPP,
FFmpegMergerPP,
FFmpegPostProcessor,
MoveFilesAfterDownloadPP,
_PLUGIN_CLASSES as plugin_postprocessors
)
from .update import detect_variant
from .version import __version__
if compat_os_name == 'nt':
import ctypes
class YoutubeDL(object):
"""YoutubeDL class.
YoutubeDL objects are the ones responsible of downloading the
actual video file and writing it to disk if the user has requested
it, among some other tasks. In most cases there should be one per
program. As, given a video URL, the downloader doesn't know how to
extract all the needed information, task that InfoExtractors do, it
has to pass the URL to one of them.
For this, YoutubeDL objects have a method that allows
InfoExtractors to be registered in a given order. When it is passed
a URL, the YoutubeDL object handles it to the first InfoExtractor it
finds that reports being able to handle it. The InfoExtractor extracts
all the information about the video or videos the URL refers to, and
YoutubeDL process the extracted information, possibly using a File
Downloader to download the video.
YoutubeDL objects accept a lot of parameters. In order not to saturate
the object constructor with arguments, it receives a dictionary of
options instead. These options are available through the params
attribute for the InfoExtractors to use. The YoutubeDL also
registers itself as the downloader in charge for the InfoExtractors
that are added to it, so this is a "mutual registration".
Available options:
username: Username for authentication purposes.
password: Password for authentication purposes.
videopassword: Password for accessing a video.
ap_mso: Adobe Pass multiple-system operator identifier.
ap_username: Multiple-system operator account username.
ap_password: Multiple-system operator account password.
usenetrc: Use netrc for authentication instead.
verbose: Print additional info to stdout.
quiet: Do not print messages to stdout.
no_warnings: Do not print out anything for warnings.
forceprint: A list of templates to force print
forceurl: Force printing final URL. (Deprecated)
forcetitle: Force printing title. (Deprecated)
forceid: Force printing ID. (Deprecated)
forcethumbnail: Force printing thumbnail URL. (Deprecated)
forcedescription: Force printing description. (Deprecated)
forcefilename: Force printing final filename. (Deprecated)
forceduration: Force printing duration. (Deprecated)
forcejson: Force printing info_dict as JSON.
dump_single_json: Force printing the info_dict of the whole playlist
(or video) as a single JSON line.
force_write_download_archive: Force writing download archive regardless
of 'skip_download' or 'simulate'.
simulate: Do not download the video files. If unset (or None),
simulate only if listsubtitles, listformats or list_thumbnails is used
format: Video format code. see "FORMAT SELECTION" for more details.
allow_unplayable_formats: Allow unplayable formats to be extracted and downloaded.
ignore_no_formats_error: Ignore "No video formats" error. Usefull for
extracting metadata even if the video is not actually
available for download (experimental)
format_sort: How to sort the video formats. see "Sorting Formats"
for more details.
format_sort_force: Force the given format_sort. see "Sorting Formats"
for more details.
allow_multiple_video_streams: Allow multiple video streams to be merged
into a single file
allow_multiple_audio_streams: Allow multiple audio streams to be merged
into a single file
check_formats Whether to test if the formats are downloadable.
Can be True (check all), False (check none)
or None (check only if requested by extractor)
paths: Dictionary of output paths. The allowed keys are 'home'
'temp' and the keys of OUTTMPL_TYPES (in utils.py)
outtmpl: Dictionary of templates for output names. Allowed keys
are 'default' and the keys of OUTTMPL_TYPES (in utils.py).
For compatibility with youtube-dl, a single string can also be used
outtmpl_na_placeholder: Placeholder for unavailable meta fields.
restrictfilenames: Do not allow "&" and spaces in file names
trim_file_name: Limit length of filename (extension excluded)
windowsfilenames: Force the filenames to be windows compatible
ignoreerrors: Do not stop on download/postprocessing errors.
Can be 'only_download' to ignore only download errors.
Default is 'only_download' for CLI, but False for API
skip_playlist_after_errors: Number of allowed failures until the rest of
the playlist is skipped
force_generic_extractor: Force downloader to use the generic extractor
overwrites: Overwrite all video and metadata files if True,
overwrite only non-video files if None
and don't overwrite any file if False
For compatibility with youtube-dl,
"nooverwrites" may also be used instead
playliststart: Playlist item to start at.
playlistend: Playlist item to end at.
playlist_items: Specific indices of playlist to download.
playlistreverse: Download playlist items in reverse order.
playlistrandom: Download playlist items in random order.
matchtitle: Download only matching titles.
rejecttitle: Reject downloads for matching titles.
logger: Log messages to a logging.Logger instance.
logtostderr: Log messages to stderr instead of stdout.
consoletitle: Display progress in console window's titlebar.
writedescription: Write the video description to a .description file
writeinfojson: Write the video description to a .info.json file
clean_infojson: Remove private fields from the infojson
getcomments: Extract video comments. This will not be written to disk
unless writeinfojson is also given
writeannotations: Write the video annotations to a .annotations.xml file
writethumbnail: Write the thumbnail image to a file
allow_playlist_files: Whether to write playlists' description, infojson etc
also to disk when using the 'write*' options
write_all_thumbnails: Write all thumbnail formats to files
writelink: Write an internet shortcut file, depending on the
current platform (.url/.webloc/.desktop)
writeurllink: Write a Windows internet shortcut file (.url)
writewebloclink: Write a macOS internet shortcut file (.webloc)
writedesktoplink: Write a Linux internet shortcut file (.desktop)
writesubtitles: Write the video subtitles to a file
writeautomaticsub: Write the automatically generated subtitles to a file
allsubtitles: Deprecated - Use subtitleslangs = ['all']
Downloads all the subtitles of the video
(requires writesubtitles or writeautomaticsub)
listsubtitles: Lists all available subtitles for the video
subtitlesformat: The format code for subtitles
subtitleslangs: List of languages of the subtitles to download (can be regex).
The list may contain "all" to refer to all the available
subtitles. The language can be prefixed with a "-" to
exclude it from the requested languages. Eg: ['all', '-live_chat']
keepvideo: Keep the video file after post-processing
daterange: A DateRange object, download only if the upload_date is in the range.
skip_download: Skip the actual download of the video file
cachedir: Location of the cache files in the filesystem.
False to disable filesystem cache.
noplaylist: Download single video instead of a playlist if in doubt.
age_limit: An integer representing the user's age in years.
Unsuitable videos for the given age are skipped.
min_views: An integer representing the minimum view count the video
must have in order to not be skipped.
Videos without view count information are always
downloaded. None for no limit.
max_views: An integer representing the maximum view count.
Videos that are more popular than that are not
downloaded.
Videos without view count information are always
downloaded. None for no limit.
download_archive: File name of a file where all downloads are recorded.
Videos already present in the file are not downloaded
again.
break_on_existing: Stop the download process after attempting to download a
file that is in the archive.
break_on_reject: Stop the download process when encountering a video that
has been filtered out.
cookiefile: File name where cookies should be read from and dumped to
cookiesfrombrowser: A tuple containing the name of the browser and the profile
name/path from where cookies are loaded.
Eg: ('chrome', ) or (vivaldi, 'default')
nocheckcertificate:Do not verify SSL certificates
prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
At the moment, this is only supported by YouTube.
proxy: URL of the proxy server to use
geo_verification_proxy: URL of the proxy to use for IP address verification
on geo-restricted sites.
socket_timeout: Time to wait for unresponsive hosts, in seconds
bidi_workaround: Work around buggy terminals without bidirectional text
support, using fridibi
debug_printtraffic:Print out sent and received HTTP traffic
include_ads: Download ads as well
default_search: Prepend this string if an input url is not valid.
'auto' for elaborate guessing
encoding: Use this encoding instead of the system-specified.
extract_flat: Do not resolve URLs, return the immediate result.
Pass in 'in_playlist' to only show this behavior for
playlist items.
postprocessors: A list of dictionaries, each with an entry
* key: The name of the postprocessor. See
yt_dlp/postprocessor/__init__.py for a list.
* when: When to run the postprocessor. Can be one of
pre_process|before_dl|post_process|after_move.
Assumed to be 'post_process' if not given
post_hooks: Deprecated - Register a custom postprocessor instead
A list of functions that get called as the final step
for each video file, after all postprocessors have been
called. The filename will be passed as the only argument.
progress_hooks: A list of functions that get called on download
progress, with a dictionary with the entries
* status: One of "downloading", "error", or "finished".
Check this first and ignore unknown values.
* info_dict: The extracted info_dict
If status is one of "downloading", or "finished", the
following properties may also be present:
* filename: The final filename (always present)
* tmpfilename: The filename we're currently writing to
* downloaded_bytes: Bytes on disk
* total_bytes: Size of the whole file, None if unknown
* total_bytes_estimate: Guess of the eventual file size,
None if unavailable.
* elapsed: The number of seconds since download started.
* eta: The estimated time in seconds, None if unknown
* speed: The download speed in bytes/second, None if
unknown
* fragment_index: The counter of the currently
downloaded video fragment.
* fragment_count: The number of fragments (= individual
files that will be merged)
Progress hooks are guaranteed to be called at least once
(with status "finished") if the download is successful.
postprocessor_hooks: A list of functions that get called on postprocessing
progress, with a dictionary with the entries
* status: One of "started", "processing", or "finished".
Check this first and ignore unknown values.
* postprocessor: Name of the postprocessor
* info_dict: The extracted info_dict
Progress hooks are guaranteed to be called at least twice
(with status "started" and "finished") if the processing is successful.
merge_output_format: Extension to use when merging formats.
final_ext: Expected final extension; used to detect when the file was
already downloaded and converted. "merge_output_format" is
replaced by this extension when given
fixup: Automatically correct known faults of the file.
One of:
- "never": do nothing
- "warn": only emit a warning
- "detect_or_warn": check whether we can do anything
about it, warn otherwise (default)
source_address: Client-side IP address to bind to.
call_home: Boolean, true iff we are allowed to contact the
yt-dlp servers for debugging. (BROKEN)
sleep_interval_requests: Number of seconds to sleep between requests
during extraction
sleep_interval: Number of seconds to sleep before each download when
used alone or a lower bound of a range for randomized
sleep before each download (minimum possible number
of seconds to sleep) when used along with
max_sleep_interval.
max_sleep_interval:Upper bound of a range for randomized sleep before each
download (maximum possible number of seconds to sleep).
Must only be used along with sleep_interval.
Actual sleep time will be a random float from range
[sleep_interval; max_sleep_interval].
sleep_interval_subtitles: Number of seconds to sleep before each subtitle download
listformats: Print an overview of available video formats and exit.
list_thumbnails: Print a table of all thumbnails and exit.
match_filter: A function that gets called with the info_dict of
every video.
If it returns a message, the video is ignored.
If it returns None, the video is downloaded.
match_filter_func in utils.py is one example for this.
no_color: Do not emit color codes in output.
geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
HTTP header
geo_bypass_country:
Two-letter ISO 3166-2 country code that will be used for
explicit geographic restriction bypassing via faking
X-Forwarded-For HTTP header
geo_bypass_ip_block:
IP range in CIDR notation that will be used similarly to
geo_bypass_country
The following options determine which downloader is picked:
external_downloader: A dictionary of protocol keys and the executable of the
external downloader to use for it. The allowed protocols
are default|http|ftp|m3u8|dash|rtsp|rtmp|mms.
Set the value to 'native' to use the native downloader
hls_prefer_native: Deprecated - Use external_downloader = {'m3u8': 'native'}
or {'m3u8': 'ffmpeg'} instead.
Use the native HLS downloader instead of ffmpeg/avconv
if True, otherwise use ffmpeg/avconv if False, otherwise
use downloader suggested by extractor if None.
compat_opts: Compatibility options. See "Differences in default behavior".
The following options do not work when used through the API:
filename, abort-on-error, multistreams, no-live-chat, format-sort
no-clean-infojson, no-playlist-metafiles, no-keep-subs.
Refer __init__.py for their implementation
progress_template: Dictionary of templates for progress outputs.
Allowed keys are 'download', 'postprocess',
'download-title' (console title) and 'postprocess-title'.
The template is mapped on a dictionary with keys 'progress' and 'info'
The following parameters are not used by YoutubeDL itself, they are used by
the downloader (see yt_dlp/downloader/common.py):
nopart, updatetime, buffersize, ratelimit, throttledratelimit, min_filesize,
max_filesize, test, noresizebuffer, retries, fragment_retries, continuedl,
noprogress, xattr_set_filesize, hls_use_mpegts, http_chunk_size,
external_downloader_args.
The following options are used by the post processors:
prefer_ffmpeg: If False, use avconv instead of ffmpeg if both are available,
otherwise prefer ffmpeg. (avconv support is deprecated)
ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
to the binary or its containing directory.
postprocessor_args: A dictionary of postprocessor/executable keys (in lower case)
and a list of additional command-line arguments for the
postprocessor/executable. The dict can also have "PP+EXE" keys
which are used when the given exe is used by the given PP.
Use 'default' as the name for arguments to passed to all PP
For compatibility with youtube-dl, a single list of args
can also be used
The following options are used by the extractors:
extractor_retries: Number of times to retry for known errors
dynamic_mpd: Whether to process dynamic DASH manifests (default: True)
hls_split_discontinuity: Split HLS playlists to different formats at
discontinuities such as ad breaks (default: False)
extractor_args: A dictionary of arguments to be passed to the extractors.
See "EXTRACTOR ARGUMENTS" for details.
Eg: {'youtube': {'skip': ['dash', 'hls']}}
youtube_include_dash_manifest: Deprecated - Use extractor_args instead.
If True (default), DASH manifests and related
data will be downloaded and processed by extractor.
You can reduce network I/O by disabling it if you don't
care about DASH. (only for youtube)
youtube_include_hls_manifest: Deprecated - Use extractor_args instead.
If True (default), HLS manifests and related
data will be downloaded and processed by extractor.
You can reduce network I/O by disabling it if you don't
care about HLS. (only for youtube)
"""
_NUMERIC_FIELDS = set((
'width', 'height', 'tbr', 'abr', 'asr', 'vbr', 'fps', 'filesize', 'filesize_approx',
'timestamp', 'release_timestamp',
'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
'average_rating', 'comment_count', 'age_limit',
'start_time', 'end_time',
'chapter_number', 'season_number', 'episode_number',
'track_number', 'disc_number', 'release_year',
))
_format_selection_exts = {
'audio': {'m4a', 'mp3', 'ogg', 'aac'},
'video': {'mp4', 'flv', 'webm', '3gp'},
'storyboards': {'mhtml'},
}
params = None
_ies = {}
_pps = {'pre_process': [], 'before_dl': [], 'after_move': [], 'post_process': []}
_printed_messages = set()
_first_webpage_request = True
_download_retcode = None
_num_downloads = None
_playlist_level = 0
_playlist_urls = set()
_screen_file = None
def __init__(self, params=None, auto_init=True):
"""Create a FileDownloader object with the given options.
@param auto_init Whether to load the default extractors and print header (if verbose).
Set to 'no_verbose_header' to not ptint the header
"""
if params is None:
params = {}
self._ies = {}
self._ies_instances = {}
self._pps = {'pre_process': [], 'before_dl': [], 'after_move': [], 'post_process': []}
self._printed_messages = set()
self._first_webpage_request = True
self._post_hooks = []
self._progress_hooks = []
self._postprocessor_hooks = []
self._download_retcode = 0
self._num_downloads = 0
self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
self._err_file = sys.stderr
self.params = params
self.cache = Cache(self)
windows_enable_vt_mode()
# FIXME: This will break if we ever print color to stdout
self.params['no_color'] = self.params.get('no_color') or not supports_terminal_sequences(self._err_file)
if sys.version_info < (3, 6):
self.report_warning(
'Python version %d.%d is not supported! Please update to Python 3.6 or above' % sys.version_info[:2])
if self.params.get('allow_unplayable_formats'):
self.report_warning(
f'You have asked for {self._color_text('unplayable formats', 'blue')} to be listed/downloaded. '
'This is a developer option intended for debugging. \n'
' If you experience any issues while using this option, '
f'{self._color_text('DO NOT', 'red')} open a bug report')
def check_deprecated(param, option, suggestion):
if self.params.get(param) is not None:
self.report_warning('%s is deprecated. Use %s instead' % (option, suggestion))
return True
return False
if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
if self.params.get('geo_verification_proxy') is None:
self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
check_deprecated('useid', '--id', '-o "%(id)s.%(ext)s"')
for msg in self.params.get('warnings', []):
self.report_warning(msg)
if 'overwrites' not in self.params and self.params.get('nooverwrites') is not None:
# nooverwrites was unnecessarily changed to overwrites
# in 0c3d0f51778b153f65c21906031c2e091fcfb641
# This ensures compatibility with both keys
self.params['overwrites'] = not self.params['nooverwrites']
elif self.params.get('overwrites') is None:
self.params.pop('overwrites', None)
else:
self.params['nooverwrites'] = not self.params['overwrites']
if params.get('bidi_workaround', False):
try:
import pty
master, slave = pty.openpty()
width = compat_get_terminal_size().columns
if width is None:
width_args = []
else:
width_args = ['-w', str(width)]
sp_kwargs = dict(
stdin=subprocess.PIPE,
stdout=slave,
stderr=self._err_file)
try:
self._output_process = Popen(['bidiv'] + width_args, **sp_kwargs)
except OSError:
self._output_process = Popen(['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
self._output_channel = os.fdopen(master, 'rb')
except OSError as ose:
if ose.errno == errno.ENOENT:
self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
else:
raise
if (sys.platform != 'win32'
and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
and not params.get('restrictfilenames', False)):
# Unicode filesystem API will throw errors (#1474, #13027)
self.report_warning(
'Assuming --restrict-filenames since file system encoding '
'cannot encode all characters. '
'Set the LC_ALL environment variable to fix this.')
self.params['restrictfilenames'] = True
self.outtmpl_dict = self.parse_outtmpl()
# Creating format selector here allows us to catch syntax errors before the extraction
self.format_selector = (
None if self.params.get('format') is None
else self.build_format_selector(self.params['format']))
self._setup_opener()
if auto_init:
if auto_init != 'no_verbose_header':
self.print_debug_header()
self.add_default_info_extractors()
for pp_def_raw in self.params.get('postprocessors', []):
pp_def = dict(pp_def_raw)
when = pp_def.pop('when', 'post_process')
pp_class = get_postprocessor(pp_def.pop('key'))
pp = pp_class(self, **compat_kwargs(pp_def))
self.add_post_processor(pp, when=when)
for ph in self.params.get('post_hooks', []):
self.add_post_hook(ph)
for ph in self.params.get('progress_hooks', []):
self.add_progress_hook(ph)
register_socks_protocols()
def preload_download_archive(fn):
"""Preload the archive, if any is specified"""
if fn is None:
return False
self.write_debug('Loading archive file %r\n' % fn)
try:
with locked_file(fn, 'r', encoding='utf-8') as archive_file:
for line in archive_file:
self.archive.add(line.strip())
except IOError as ioe:
if ioe.errno != errno.ENOENT:
raise
return False
return True
self.archive = set()
preload_download_archive(self.params.get('download_archive'))
def warn_if_short_id(self, argv):
# short YouTube ID starting with dash?
idxs = [
i for i, a in enumerate(argv)
if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
if idxs:
correct_argv = (
['yt-dlp']
+ [a for i, a in enumerate(argv) if i not in idxs]
+ ['--'] + [argv[i] for i in idxs]
)
self.report_warning(
'Long argument string detected. '
'Use -- to separate parameters and URLs, like this:\n%s\n' %
args_to_str(correct_argv))
def add_info_extractor(self, ie):
"""Add an InfoExtractor object to the end of the list."""
ie_key = ie.ie_key()
self._ies[ie_key] = ie
if not isinstance(ie, type):
self._ies_instances[ie_key] = ie
ie.set_downloader(self)
def _get_info_extractor_class(self, ie_key):
ie = self._ies.get(ie_key)
if ie is None:
ie = get_info_extractor(ie_key)
self.add_info_extractor(ie)
return ie
def get_info_extractor(self, ie_key):
"""
Get an instance of an IE with name ie_key, it will try to get one from
the _ies list, if there's no instance it will create a new one and add
it to the extractor list.
"""
ie = self._ies_instances.get(ie_key)
if ie is None:
ie = get_info_extractor(ie_key)()
self.add_info_extractor(ie)
return ie
def add_default_info_extractors(self):
"""
Add the InfoExtractors returned by gen_extractors to the end of the list
"""
for ie in gen_extractor_classes():
self.add_info_extractor(ie)
def add_post_processor(self, pp, when='post_process'):
"""Add a PostProcessor object to the end of the chain."""
self._pps[when].append(pp)
pp.set_downloader(self)
def add_post_hook(self, ph):
"""Add the post hook"""
self._post_hooks.append(ph)
def add_progress_hook(self, ph):
"""Add the download progress hook"""
self._progress_hooks.append(ph)
def add_postprocessor_hook(self, ph):
"""Add the postprocessing progress hook"""
self._postprocessor_hooks.append(ph)
def _bidi_workaround(self, message):
if not hasattr(self, '_output_channel'):
return message
assert hasattr(self, '_output_process')
assert isinstance(message, compat_str)
line_count = message.count('\n') + 1
self._output_process.stdin.write((message + '\n').encode('utf-8'))
self._output_process.stdin.flush()
res = ''.join(self._output_channel.readline().decode('utf-8')
for _ in range(line_count))
return res[:-len('\n')]
def _write_string(self, message, out=None, only_once=False):
if only_once:
if message in self._printed_messages:
return
self._printed_messages.add(message)
write_string(message, out=out, encoding=self.params.get('encoding'))
def to_stdout(self, message, skip_eol=False, quiet=False):
"""Print message to stdout"""
if self.params.get('logger'):
self.params['logger'].debug(message)
elif not quiet or self.params.get('verbose'):
self._write_string(
'%s%s' % (self._bidi_workaround(message), ('' if skip_eol else '\n')),
self._err_file if quiet else self._screen_file)
def to_stderr(self, message, only_once=False):
"""Print message to stderr"""
assert isinstance(message, compat_str)
if self.params.get('logger'):
self.params['logger'].error(message)
else:
self._write_string('%s\n' % self._bidi_workaround(message), self._err_file, only_once=only_once)
def to_console_title(self, message):
if not self.params.get('consoletitle', False):
return
if compat_os_name == 'nt':
if ctypes.windll.kernel32.GetConsoleWindow():
# c_wchar_p() might not be necessary if `message` is
# already of type unicode()
ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
elif 'TERM' in os.environ:
self._write_string('\033]0;%s\007' % message, self._screen_file)
def save_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate'):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
# Save the title on stack
self._write_string('\033[22;0t', self._screen_file)
def restore_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate'):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
# Restore the title from stack
self._write_string('\033[23;0t', self._screen_file)
def __enter__(self):
self.save_console_title()
return self
def __exit__(self, *args):
self.restore_console_title()
if self.params.get('cookiefile') is not None:
self.cookiejar.save(ignore_discard=True, ignore_expires=True)
def trouble(self, message=None, tb=None):
"""Determine action to take when a download problem appears.
Depending on if the downloader has been configured to ignore
download errors or not, this method may throw an exception or
not when errors are found, after printing the message.
tb, if given, is additional traceback information.
"""
if message is not None:
self.to_stderr(message)
if self.params.get('verbose'):
if tb is None:
if sys.exc_info()[0]: # if .trouble has been called from an except block
tb = ''
if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
tb += encode_compat_str(traceback.format_exc())
else:
tb_data = traceback.format_list(traceback.extract_stack())
tb = ''.join(tb_data)
if tb:
self.to_stderr(tb)
if not self.params.get('ignoreerrors'):
if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
exc_info = sys.exc_info()[1].exc_info
else:
exc_info = sys.exc_info()
raise DownloadError(message, exc_info)
self._download_retcode = 1
def to_screen(self, message, skip_eol=False):
"""Print message to stdout if not in quiet mode"""
self.to_stdout(
message, skip_eol, quiet=self.params.get('quiet', False))
def _color_text(self, text, color):
if self.params.get('no_color'):
return text
return f'{TERMINAL_SEQUENCES[color.upper()]}{text}{TERMINAL_SEQUENCES['RESET_STYLE']}'
def report_warning(self, message, only_once=False):
'''
Print the message to stderr, it will be prefixed with 'WARNING:'
If stderr is a tty file the 'WARNING:' will be colored
'''
if self.params.get('logger') is not None:
self.params['logger'].warning(message)
else:
if self.params.get('no_warnings'):
return
self.to_stderr(f'{self._color_text('WARNING:', 'yellow')} {message}', only_once)
def report_error(self, message, tb=None):
'''
Do the same as trouble, but prefixes the message with 'ERROR:', colored
in red if stderr is a tty file.
'''
self.trouble(f'{self._color_text('ERROR:', 'red')} {message}', tb)
def write_debug(self, message, only_once=False):
'''Log debug message or Print message to stderr'''
if not self.params.get('verbose', False):
return
message = '[debug] %s' % message
if self.params.get('logger'):
self.params['logger'].debug(message)
else:
self.to_stderr(message, only_once)
def report_file_already_downloaded(self, file_name):
"""Report file has already been fully downloaded."""
try:
self.to_screen('[download] %s has already been downloaded' % file_name)
except UnicodeEncodeError:
self.to_screen('[download] The file has already been downloaded')
def report_file_delete(self, file_name):
"""Report that existing file will be deleted."""
try:
self.to_screen('Deleting existing file %s' % file_name)
except UnicodeEncodeError:
self.to_screen('Deleting existing file')
def raise_no_formats(self, info, forced=False):
has_drm = info.get('__has_drm')
msg = 'This video is DRM protected' if has_drm else 'No video formats found!'
expected = self.params.get('ignore_no_formats_error')
if forced or not expected:
raise ExtractorError(msg, video_id=info['id'], ie=info['extractor'],
expected=has_drm or expected)
else:
self.report_warning(msg)
def parse_outtmpl(self):
outtmpl_dict = self.params.get('outtmpl', {})
if not isinstance(outtmpl_dict, dict):
outtmpl_dict = {'default': outtmpl_dict}
# Remove spaces in the default template
if self.params.get('restrictfilenames'):
sanitize = lambda x: x.replace(' - ', ' ').replace(' ', '-')
else:
sanitize = lambda x: x
outtmpl_dict.update({
k: sanitize(v) for k, v in DEFAULT_OUTTMPL.items()
if outtmpl_dict.get(k) is None})
for key, val in outtmpl_dict.items():
if isinstance(val, bytes):
self.report_warning(
'Parameter outtmpl is bytes, but should be a unicode string. '
'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
return outtmpl_dict
def get_output_path(self, dir_type='', filename=None):
paths = self.params.get('paths', {})
assert isinstance(paths, dict)
path = os.path.join(
expand_path(paths.get('home', '').strip()),
expand_path(paths.get(dir_type, '').strip()) if dir_type else '',
filename or '')
# Temporary fix for #4787
# 'Treat' all problem characters by passing filename through preferredencoding
# to workaround encoding issues with subprocess on python2 @ Windows
if sys.version_info < (3, 0) and sys.platform == 'win32':
path = encodeFilename(path, True).decode(preferredencoding())
return sanitize_path(path, force=self.params.get('windowsfilenames'))
@staticmethod
def _outtmpl_expandpath(outtmpl):
# expand_path translates '%%' into '%' and '$$' into '$'
# correspondingly that is not what we want since we need to keep
# '%%' intact for template dict substitution step. Working around
# with boundary-alike separator hack.
sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep))
# outtmpl should be expand_path'ed before template dict substitution
# because meta fields may contain env variables we don't want to
# be expanded. For example, for outtmpl "%(title)s.%(ext)s" and
# title "Hello $PATH", we don't want `$PATH` to be expanded.
return expand_path(outtmpl).replace(sep, '')
@staticmethod
def escape_outtmpl(outtmpl):
''' Escape any remaining strings like %s, %abc% etc. '''
return re.sub(
STR_FORMAT_RE_TMPL.format('', '(?![%(\0])'),
lambda mobj: ('' if mobj.group('has_key') else '%') + mobj.group(0),
outtmpl)
@classmethod
def validate_outtmpl(cls, outtmpl):
''' @return None or Exception object '''
outtmpl = re.sub(
STR_FORMAT_RE_TMPL.format('[^)]*', '[ljqBU]'),
lambda mobj: f'{mobj.group(0)[:-1]}s',
cls._outtmpl_expandpath(outtmpl))
try:
cls.escape_outtmpl(outtmpl) % collections.defaultdict(int)
return None
except ValueError as err:
return err
@staticmethod
def _copy_infodict(info_dict):
info_dict = dict(info_dict)
for key in ('__original_infodict', '__postprocessors'):
info_dict.pop(key, None)
return info_dict
def prepare_outtmpl(self, outtmpl, info_dict, sanitize=None):
""" Make the outtmpl and info_dict suitable for substitution: ydl.escape_outtmpl(outtmpl) % info_dict """
info_dict.setdefault('epoch', int(time.time())) # keep epoch consistent once set
info_dict = self._copy_infodict(info_dict)
info_dict['duration_string'] = ( # %(duration>%H-%M-%S)s is wrong if duration > 24hrs
formatSeconds(info_dict['duration'], '-' if sanitize else ':')
if info_dict.get('duration', None) is not None
else None)
info_dict['autonumber'] = self.params.get('autonumber_start', 1) - 1 + self._num_downloads
if info_dict.get('resolution') is None:
info_dict['resolution'] = self.format_resolution(info_dict, default=None)
# For fields playlist_index, playlist_autonumber and autonumber convert all occurrences
# of %(field)s to %(field)0Nd for backward compatibility
field_size_compat_map = {
'playlist_index': len(str(info_dict.get('_last_playlist_index') or '')),
'playlist_autonumber': len(str(info_dict.get('n_entries') or '')),
'autonumber': self.params.get('autonumber_size') or 5,
}
TMPL_DICT = {}
EXTERNAL_FORMAT_RE = re.compile(STR_FORMAT_RE_TMPL.format('[^)]*', f'[{STR_FORMAT_TYPES}ljqBU]'))
MATH_FUNCTIONS = {
'+': float.__add__,
'-': float.__sub__,
}
# Field is of the form key1.key2...
# where keys (except first) can be string, int or slice
FIELD_RE = r'\w*(?:\.(?:\w+|{num}|{num}?(?::{num}?){{1,2}}))*'.format(num=r'(?:-?\d+)')
MATH_FIELD_RE = r'''{field}|{num}'''.format(field=FIELD_RE, num=r'-?\d+(?:.\d+)?')
MATH_OPERATORS_RE = r'(?:%s)' % '|'.join(map(re.escape, MATH_FUNCTIONS.keys()))
INTERNAL_FORMAT_RE = re.compile(r'''(?x)
(?P<negate>-)?
(?P<fields>{field})
(?P<maths>(?:{math_op}{math_field})*)
(?:>(?P<strf_format>.+?))?
(?P<alternate>(?<!\\),[^|)]+)?
(?:\|(?P<default>.*?))?
$'''.format(field=FIELD_RE, math_op=MATH_OPERATORS_RE, math_field=MATH_FIELD_RE))
def _traverse_infodict(k):
k = k.split('.')
if k[0] == '':
k.pop(0)
return traverse_obj(info_dict, k, is_user_input=True, traverse_string=True)
def get_value(mdict):
# Object traversal
value = _traverse_infodict(mdict['fields'])
# Negative
if mdict['negate']:
value = float_or_none(value)
if value is not None:
value *= -1
# Do maths
offset_key = mdict['maths']
if offset_key:
value = float_or_none(value)
operator = None
while offset_key:
item = re.match(
MATH_FIELD_RE if operator else MATH_OPERATORS_RE,
offset_key).group(0)
offset_key = offset_key[len(item):]
if operator is None:
operator = MATH_FUNCTIONS[item]
continue
item, multiplier = (item[1:], -1) if item[0] == '-' else (item, 1)
offset = float_or_none(item)
if offset is None:
offset = float_or_none(_traverse_infodict(item))
try:
value = operator(value, multiplier * offset)
except (TypeError, ZeroDivisionError):
return None
operator = None
# Datetime formatting
if mdict['strf_format']:
value = strftime_or_none(value, mdict['strf_format'].replace('\\,', ','))
return value
na = self.params.get('outtmpl_na_placeholder', 'NA')
def _dumpjson_default(obj):
if isinstance(obj, (set, LazyList)):
return list(obj)
raise TypeError(f'Object of type {type(obj).__name__} is not JSON serializable')
def create_key(outer_mobj):
if not outer_mobj.group('has_key'):
return outer_mobj.group(0)
key = outer_mobj.group('key')
mobj = re.match(INTERNAL_FORMAT_RE, key)
initial_field = mobj.group('fields').split('.')[-1] if mobj else ''
value, default = None, na
while mobj:
mobj = mobj.groupdict()
default = mobj['default'] if mobj['default'] is not None else default
value = get_value(mobj)
if value is None and mobj['alternate']:
mobj = re.match(INTERNAL_FORMAT_RE, mobj['alternate'][1:])
else:
break
fmt = outer_mobj.group('format')
if fmt == 's' and value is not None and key in field_size_compat_map.keys():
fmt = '0{:d}d'.format(field_size_compat_map[key])
value = default if value is None else value
str_fmt = f'{fmt[:-1]}s'
if fmt[-1] == 'l': # list
delim = '\n' if '#' in (outer_mobj.group('conversion') or '') else ', '
value, fmt = delim.join(variadic(value)), str_fmt
elif fmt[-1] == 'j': # json
value, fmt = json.dumps(value, default=_dumpjson_default), str_fmt
elif fmt[-1] == 'q': # quoted
value, fmt = compat_shlex_quote(str(value)), str_fmt
elif fmt[-1] == 'B': # bytes
value = f'%{str_fmt}'.encode('utf-8') % str(value).encode('utf-8')
value, fmt = value.decode('utf-8', 'ignore'), 's'
elif fmt[-1] == 'U': # unicode normalized
opts = outer_mobj.group('conversion') or ''
value, fmt = unicodedata.normalize(
# "+" = compatibility equivalence, "#" = NFD
'NF%s%s' % ('K' if '+' in opts else '', 'D' if '#' in opts else 'C'),
value), str_fmt
elif fmt[-1] == 'c':
if value:
value = str(value)[0]
else:
fmt = str_fmt
elif fmt[-1] not in 'rs': # numeric
value = float_or_none(value)
if value is None:
value, fmt = default, 's'
if sanitize:
if fmt[-1] == 'r':
# If value is an object, sanitize might convert it to a string
# So we convert it to repr first
value, fmt = repr(value), str_fmt
if fmt[-1] in 'csr':
value = sanitize(initial_field, value)
key = '%s\0%s' % (key.replace('%', '%\0'), outer_mobj.group('format'))
TMPL_DICT[key] = value
return '{prefix}%({key}){fmt}'.format(key=key, fmt=fmt, prefix=outer_mobj.group('prefix'))
return EXTERNAL_FORMAT_RE.sub(create_key, outtmpl), TMPL_DICT
def evaluate_outtmpl(self, outtmpl, info_dict, *args, **kwargs):
outtmpl, info_dict = self.prepare_outtmpl(outtmpl, info_dict, *args, **kwargs)
return self.escape_outtmpl(outtmpl) % info_dict
def _prepare_filename(self, info_dict, tmpl_type='default'):
try:
sanitize = lambda k, v: sanitize_filename(
compat_str(v),
restricted=self.params.get('restrictfilenames'),
is_id=(k == 'id' or k.endswith('_id')))
outtmpl = self._outtmpl_expandpath(self.outtmpl_dict.get(tmpl_type, self.outtmpl_dict['default']))
filename = self.evaluate_outtmpl(outtmpl, info_dict, sanitize)
force_ext = OUTTMPL_TYPES.get(tmpl_type)
if filename and force_ext is not None:
filename = replace_extension(filename, force_ext, info_dict.get('ext'))
# https://github.com/blackjack4494/youtube-dlc/issues/85
trim_file_name = self.params.get('trim_file_name', False)
if trim_file_name:
fn_groups = filename.rsplit('.')
ext = fn_groups[-1]
sub_ext = ''
if len(fn_groups) > 2:
sub_ext = fn_groups[-2]
filename = '.'.join(filter(None, [fn_groups[0][:trim_file_name], sub_ext, ext]))
return filename
except ValueError as err:
self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
return None
def prepare_filename(self, info_dict, dir_type='', warn=False):
"""Generate the output filename."""
filename = self._prepare_filename(info_dict, dir_type or 'default')
if not filename and dir_type not in ('', 'temp'):
return ''
if warn:
if not self.params.get('paths'):
pass
elif filename == '-':
self.report_warning('--paths is ignored when an outputting to stdout', only_once=True)
elif os.path.isabs(filename):
self.report_warning('--paths is ignored since an absolute path is given in output template', only_once=True)
if filename == '-' or not filename:
return filename
return self.get_output_path(dir_type, filename)
def _match_entry(self, info_dict, incomplete=False, silent=False):
""" Returns None if the file should be downloaded """
video_title = info_dict.get('title', info_dict.get('id', 'video'))
def check_filter():
if 'title' in info_dict:
# This can happen when we're just evaluating the playlist
title = info_dict['title']
matchtitle = self.params.get('matchtitle', False)
if matchtitle:
if not re.search(matchtitle, title, re.IGNORECASE):
return '"' + title + '" title did not match pattern "' + matchtitle + '"'
rejecttitle = self.params.get('rejecttitle', False)
if rejecttitle:
if re.search(rejecttitle, title, re.IGNORECASE):
return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
date = info_dict.get('upload_date')
if date is not None:
dateRange = self.params.get('daterange', DateRange())
if date not in dateRange:
return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
view_count = info_dict.get('view_count')
if view_count is not None:
min_views = self.params.get('min_views')
if min_views is not None and view_count < min_views:
return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
max_views = self.params.get('max_views')
if max_views is not None and view_count > max_views:
return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
return 'Skipping "%s" because it is age restricted' % video_title
match_filter = self.params.get('match_filter')
if match_filter is not None:
try:
ret = match_filter(info_dict, incomplete=incomplete)
except TypeError:
# For backward compatibility
ret = None if incomplete else match_filter(info_dict)
if ret is not None:
return ret
return None
if self.in_download_archive(info_dict):
reason = '%s has already been recorded in the archive' % video_title
break_opt, break_err = 'break_on_existing', ExistingVideoReached
else:
reason = check_filter()
break_opt, break_err = 'break_on_reject', RejectedVideoReached
if reason is not None:
if not silent:
self.to_screen('[download] ' + reason)
if self.params.get(break_opt, False):
raise break_err()
return reason
@staticmethod
def add_extra_info(info_dict, extra_info):
'''Set the keys from extra_info in info dict if they are missing'''
for key, value in extra_info.items():
info_dict.setdefault(key, value)
def extract_info(self, url, download=True, ie_key=None, extra_info=None,
process=True, force_generic_extractor=False):
"""
Return a list with a dictionary for each video extracted.
Arguments:
url -- URL to extract
Keyword arguments:
download -- whether to download videos during extraction
ie_key -- extractor key hint
extra_info -- dictionary containing the extra values to add to each result
process -- whether to resolve all unresolved references (URLs, playlist items),
must be True for download to work.
force_generic_extractor -- force using the generic extractor
"""
if extra_info is None:
extra_info = {}
if not ie_key and force_generic_extractor:
ie_key = 'Generic'
if ie_key:
ies = {ie_key: self._get_info_extractor_class(ie_key)}
else:
ies = self._ies
for ie_key, ie in ies.items():
if not ie.suitable(url):
continue
if not ie.working():
self.report_warning('The program functionality for this site has been marked as broken, '
'and will probably not work.')
temp_id = ie.get_temp_id(url)
if temp_id is not None and self.in_download_archive({'id': temp_id, 'ie_key': ie_key}):
self.to_screen("[%s] %s: has already been recorded in archive" % (
ie_key, temp_id))
break
return self.__extract_info(url, self.get_info_extractor(ie_key), download, extra_info, process)
else:
self.report_error('no suitable InfoExtractor for URL %s' % url)
def __handle_extraction_exceptions(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except GeoRestrictedError as e:
msg = e.msg
if e.countries:
msg += '\nThis video is available in %s.' % ', '.join(
map(ISO3166Utils.short2full, e.countries))
msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
self.report_error(msg)
except ExtractorError as e: # An error we somewhat expected
self.report_error(compat_str(e), e.format_traceback())
except ThrottledDownload:
self.to_stderr('\r')
self.report_warning('The download speed is below throttle limit. Re-extracting data')
return wrapper(self, *args, **kwargs)
except (MaxDownloadsReached, ExistingVideoReached, RejectedVideoReached, LazyList.IndexError):
raise
except Exception as e:
if self.params.get('ignoreerrors'):
self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc()))
else:
raise
return wrapper
@__handle_extraction_exceptions
def __extract_info(self, url, ie, download, extra_info, process):
ie_result = ie.extract(url)
if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
return
if isinstance(ie_result, list):
# Backwards compatibility: old IE result format
ie_result = {
'_type': 'compat_list',
'entries': ie_result,
}
if extra_info.get('original_url'):
ie_result.setdefault('original_url', extra_info['original_url'])
self.add_default_extra_info(ie_result, ie, url)
if process:
return self.process_ie_result(ie_result, download, extra_info)
else:
return ie_result
def add_default_extra_info(self, ie_result, ie, url):
if url is not None:
self.add_extra_info(ie_result, {
'webpage_url': url,
'original_url': url,
'webpage_url_basename': url_basename(url),
})
if ie is not None:
self.add_extra_info(ie_result, {
'extractor': ie.IE_NAME,
'extractor_key': ie.ie_key(),
})
def process_ie_result(self, ie_result, download=True, extra_info=None):
"""
Take the result of the ie(may be modified) and resolve all unresolved
references (URLs, playlist items).
It will also download the videos if 'download'.
Returns the resolved ie_result.
"""
if extra_info is None:
extra_info = {}
result_type = ie_result.get('_type', 'video')
if result_type in ('url', 'url_transparent'):
ie_result['url'] = sanitize_url(ie_result['url'])
if ie_result.get('original_url'):
extra_info.setdefault('original_url', ie_result['original_url'])
extract_flat = self.params.get('extract_flat', False)
if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
or extract_flat is True):
info_copy = ie_result.copy()
ie = try_get(ie_result.get('ie_key'), self.get_info_extractor)
if ie and not ie_result.get('id'):
info_copy['id'] = ie.get_temp_id(ie_result['url'])
self.add_default_extra_info(info_copy, ie, ie_result['url'])
self.add_extra_info(info_copy, extra_info)
self.__forced_printings(info_copy, self.prepare_filename(info_copy), incomplete=True)
if self.params.get('force_write_download_archive', False):
self.record_download_archive(info_copy)
return ie_result
if result_type == 'video':
self.add_extra_info(ie_result, extra_info)
ie_result = self.process_video_result(ie_result, download=download)
additional_urls = (ie_result or {}).get('additional_urls')
if additional_urls:
# TODO: Improve MetadataParserPP to allow setting a list
if isinstance(additional_urls, compat_str):
additional_urls = [additional_urls]
self.to_screen(
'[info] %s: %d additional URL(s) requested' % (ie_result['id'], len(additional_urls)))
self.write_debug('Additional URLs: "%s"' % '", "'.join(additional_urls))
ie_result['additional_entries'] = [
self.extract_info(
url, download, extra_info,
force_generic_extractor=self.params.get('force_generic_extractor'))
for url in additional_urls
]
return ie_result
elif result_type == 'url':
# We have to add extra_info to the results because it may be
# contained in a playlist
return self.extract_info(
ie_result['url'], download,
ie_key=ie_result.get('ie_key'),
extra_info=extra_info)
elif result_type == 'url_transparent':
# Use the information from the embedding page
info = self.extract_info(
ie_result['url'], ie_key=ie_result.get('ie_key'),
extra_info=extra_info, download=False, process=False)
# extract_info may return None when ignoreerrors is enabled and
# extraction failed with an error, don't crash and return early
# in this case
if not info:
return info
force_properties = dict(
(k, v) for k, v in ie_result.items() if v is not None)
for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
if f in force_properties:
del force_properties[f]
new_result = info.copy()
new_result.update(force_properties)
# Extracted info may not be a video result (i.e.
# info.get('_type', 'video') != video) but rather an url or
# url_transparent. In such cases outer metadata (from ie_result)
# should be propagated to inner one (info). For this to happen
# _type of info should be overridden with url_transparent. This
# fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
if new_result.get('_type') == 'url':
new_result['_type'] = 'url_transparent'
return self.process_ie_result(
new_result, download=download, extra_info=extra_info)
elif result_type in ('playlist', 'multi_video'):
# Protect from infinite recursion due to recursively nested playlists
# (see https://github.com/ytdl-org/youtube-dl/issues/27833)
webpage_url = ie_result['webpage_url']
if webpage_url in self._playlist_urls:
self.to_screen(
'[download] Skipping already downloaded playlist: %s'
% ie_result.get('title') or ie_result.get('id'))
return
self._playlist_level += 1
self._playlist_urls.add(webpage_url)
self._sanitize_thumbnails(ie_result)
try:
return self.__process_playlist(ie_result, download)
finally:
self._playlist_level -= 1
if not self._playlist_level:
self._playlist_urls.clear()
elif result_type == 'compat_list':
self.report_warning(
'Extractor %s returned a compat_list result. '
'It needs to be updated.' % ie_result.get('extractor'))
def _fixup(r):
self.add_extra_info(r, {
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
})
return r
ie_result['entries'] = [
self.process_ie_result(_fixup(r), download, extra_info)
for r in ie_result['entries']
]
return ie_result
else:
raise Exception('Invalid result type: %s' % result_type)
def _ensure_dir_exists(self, path):
return make_dir(path, self.report_error)
def __process_playlist(self, ie_result, download):
# We process each entry in the playlist
playlist = ie_result.get('title') or ie_result.get('id')
self.to_screen('[download] Downloading playlist: %s' % playlist)
if 'entries' not in ie_result:
raise EntryNotInPlaylist()
incomplete_entries = bool(ie_result.get('requested_entries'))
if incomplete_entries:
def fill_missing_entries(entries, indexes):
ret = [None] * max(*indexes)
for i, entry in zip(indexes, entries):
ret[i - 1] = entry
return ret
ie_result['entries'] = fill_missing_entries(ie_result['entries'], ie_result['requested_entries'])
playlist_results = []
playliststart = self.params.get('playliststart', 1)
playlistend = self.params.get('playlistend')
# For backwards compatibility, interpret -1 as whole list
if playlistend == -1:
playlistend = None
playlistitems_str = self.params.get('playlist_items')
playlistitems = None
if playlistitems_str is not None:
def iter_playlistitems(format):
for string_segment in format.split(','):
if '-' in string_segment:
start, end = string_segment.split('-')
for item in range(int(start), int(end) + 1):
yield int(item)
else:
yield int(string_segment)
playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
ie_entries = ie_result['entries']
msg = (
'Downloading %d videos' if not isinstance(ie_entries, list)
else 'Collected %d videos; downloading %%d of them' % len(ie_entries))
if isinstance(ie_entries, list):
def get_entry(i):
return ie_entries[i - 1]
else:
if not isinstance(ie_entries, PagedList):
ie_entries = LazyList(ie_entries)
def get_entry(i):
return YoutubeDL.__handle_extraction_exceptions(
lambda self, i: ie_entries[i - 1]
)(self, i)
entries = []
items = playlistitems if playlistitems is not None else itertools.count(playliststart)
for i in items:
if i == 0:
continue
if playlistitems is None and playlistend is not None and playlistend < i:
break
entry = None
try:
entry = get_entry(i)
if entry is None:
raise EntryNotInPlaylist()
except (IndexError, EntryNotInPlaylist):
if incomplete_entries:
raise EntryNotInPlaylist()
elif not playlistitems:
break
entries.append(entry)
try:
if entry is not None:
self._match_entry(entry, incomplete=True, silent=True)
except (ExistingVideoReached, RejectedVideoReached):
break
ie_result['entries'] = entries
# Save playlist_index before re-ordering
entries = [
((playlistitems[i - 1] if playlistitems else i + playliststart - 1), entry)
for i, entry in enumerate(entries, 1)
if entry is not None]
n_entries = len(entries)
if not playlistitems and (playliststart or playlistend):
playlistitems = list(range(playliststart, playliststart + n_entries))
ie_result['requested_entries'] = playlistitems
if self.params.get('allow_playlist_files', True):
ie_copy = {
'playlist': playlist,
'playlist_id': ie_result.get('id'),
'playlist_title': ie_result.get('title'),
'playlist_uploader': ie_result.get('uploader'),
'playlist_uploader_id': ie_result.get('uploader_id'),
'playlist_index': 0,
}
ie_copy.update(dict(ie_result))
if self._write_info_json('playlist', ie_result,
self.prepare_filename(ie_copy, 'pl_infojson')) is None:
return
if self._write_description('playlist', ie_result,
self.prepare_filename(ie_copy, 'pl_description')) is None:
return
# TODO: This should be passed to ThumbnailsConvertor if necessary
self._write_thumbnails('playlist', ie_copy, self.prepare_filename(ie_copy, 'pl_thumbnail'))
if self.params.get('playlistreverse', False):
entries = entries[::-1]
if self.params.get('playlistrandom', False):
random.shuffle(entries)
x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
self.to_screen('[%s] playlist %s: %s' % (ie_result['extractor'], playlist, msg % n_entries))
failures = 0
max_failures = self.params.get('skip_playlist_after_errors') or float('inf')
for i, entry_tuple in enumerate(entries, 1):
playlist_index, entry = entry_tuple
if 'playlist-index' in self.params.get('compat_opts', []):
playlist_index = playlistitems[i - 1] if playlistitems else i + playliststart - 1
self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
# This __x_forwarded_for_ip thing is a bit ugly but requires
# minimal changes
if x_forwarded_for:
entry['__x_forwarded_for_ip'] = x_forwarded_for
extra = {
'n_entries': n_entries,
'_last_playlist_index': max(playlistitems) if playlistitems else (playlistend or n_entries),
'playlist_index': playlist_index,
'playlist_autonumber': i,
'playlist': playlist,
'playlist_id': ie_result.get('id'),
'playlist_title': ie_result.get('title'),
'playlist_uploader': ie_result.get('uploader'),
'playlist_uploader_id': ie_result.get('uploader_id'),
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
if self._match_entry(entry, incomplete=True) is not None:
continue
entry_result = self.__process_iterable_entry(entry, download, extra)
if not entry_result:
failures += 1
if failures >= max_failures:
self.report_error(
'Skipping the remaining entries in playlist "%s" since %d items failed extraction' % (playlist, failures))
break
# TODO: skip failed (empty) entries?
playlist_results.append(entry_result)
ie_result['entries'] = playlist_results
self.to_screen('[download] Finished downloading playlist: %s' % playlist)
return ie_result
@__handle_extraction_exceptions
def __process_iterable_entry(self, entry, download, extra_info):
return self.process_ie_result(
entry, download=download, extra_info=extra_info)
def _build_format_filter(self, filter_spec):
" Returns a function to filter the formats according to the filter_spec "
OPERATORS = {
'<': operator.lt,
'<=': operator.le,
'>': operator.gt,
'>=': operator.ge,
'=': operator.eq,
'!=': operator.ne,
}
operator_rex = re.compile(r'''(?x)\s*
(?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)\s*
(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)\s*
''' % '|'.join(map(re.escape, OPERATORS.keys())))
m = operator_rex.fullmatch(filter_spec)
if m:
try:
comparison_value = int(m.group('value'))
except ValueError:
comparison_value = parse_filesize(m.group('value'))
if comparison_value is None:
comparison_value = parse_filesize(m.group('value') + 'B')
if comparison_value is None:
raise ValueError(
'Invalid value %r in format specification %r' % (
m.group('value'), filter_spec))
op = OPERATORS[m.group('op')]
if not m:
STR_OPERATORS = {
'=': operator.eq,
'^=': lambda attr, value: attr.startswith(value),
'$=': lambda attr, value: attr.endswith(value),
'*=': lambda attr, value: value in attr,
}
str_operator_rex = re.compile(r'''(?x)\s*
(?P<key>[a-zA-Z0-9._-]+)\s*
(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?P<value>[a-zA-Z0-9._-]+)\s*
''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
m = str_operator_rex.fullmatch(filter_spec)
if m:
comparison_value = m.group('value')
str_op = STR_OPERATORS[m.group('op')]
if m.group('negation'):
op = lambda attr, value: not str_op(attr, value)
else:
op = str_op
if not m:
raise SyntaxError('Invalid filter specification %r' % filter_spec)
def _filter(f):
actual_value = f.get(m.group('key'))
if actual_value is None:
return m.group('none_inclusive')
return op(actual_value, comparison_value)
return _filter
def _default_format_spec(self, info_dict, download=True):
def can_merge():
merger = FFmpegMergerPP(self)
return merger.available and merger.can_merge()
prefer_best = (
not self.params.get('simulate')
and download
and (
not can_merge()
or info_dict.get('is_live', False)
or self.outtmpl_dict['default'] == '-'))
compat = (
prefer_best
or self.params.get('allow_multiple_audio_streams', False)
or 'format-spec' in self.params.get('compat_opts', []))
return (
'best/bestvideo+bestaudio' if prefer_best
else 'bestvideo*+bestaudio/best' if not compat
else 'bestvideo+bestaudio/best')
def build_format_selector(self, format_spec):
def syntax_error(note, start):
message = (
'Invalid format specification: '
'{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
return SyntaxError(message)
PICKFIRST = 'PICKFIRST'
MERGE = 'MERGE'
SINGLE = 'SINGLE'
GROUP = 'GROUP'
FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
allow_multiple_streams = {'audio': self.params.get('allow_multiple_audio_streams', False),
'video': self.params.get('allow_multiple_video_streams', False)}
check_formats = self.params.get('check_formats')
def _parse_filter(tokens):
filter_parts = []
for type, string, start, _, _ in tokens:
if type == tokenize.OP and string == ']':
return ''.join(filter_parts)
else:
filter_parts.append(string)
def _remove_unused_ops(tokens):
# Remove operators that we don't use and join them with the surrounding strings
# for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
ALLOWED_OPS = ('/', '+', ',', '(', ')')
last_string, last_start, last_end, last_line = None, None, None, None
for type, string, start, end, line in tokens:
if type == tokenize.OP and string == '[':
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
# everything inside brackets will be handled by _parse_filter
for type, string, start, end, line in tokens:
yield type, string, start, end, line
if type == tokenize.OP and string == ']':
break
elif type == tokenize.OP and string in ALLOWED_OPS:
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
if not last_string:
last_string = string
last_start = start
last_end = end
else:
last_string += string
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens:
# ENCODING is only defined in python 3.x
if type == getattr(tokenize, 'ENCODING', None):
continue
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string == ')':
if not inside_group:
# ')' will be handled by the parentheses group
tokens.restore_last_token()
break
elif inside_merge and string in ['/', ',']:
tokens.restore_last_token()
break
elif inside_choice and string == ',':
tokens.restore_last_token()
break
elif string == ',':
if not current_selector:
raise syntax_error('"," must follow a format selector', start)
selectors.append(current_selector)
current_selector = None
elif string == '/':
if not current_selector:
raise syntax_error('"/" must follow a format selector', start)
first_choice = current_selector
second_choice = _parse_format_selection(tokens, inside_choice=True)
current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
elif string == '[':
if not current_selector:
current_selector = FormatSelector(SINGLE, 'best', [])
format_filter = _parse_filter(tokens)
current_selector.filters.append(format_filter)
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
group = _parse_format_selection(tokens, inside_group=True)
current_selector = FormatSelector(GROUP, group, [])
elif string == '+':
if not current_selector:
raise syntax_error('Unexpected "+"', start)
selector_1 = current_selector
selector_2 = _parse_format_selection(tokens, inside_merge=True)
if not selector_2:
raise syntax_error('Expected a selector', start)
current_selector = FormatSelector(MERGE, (selector_1, selector_2), [])
else:
raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
elif type == tokenize.ENDMARKER:
break
if current_selector:
selectors.append(current_selector)
return selectors
def _merge(formats_pair):
format_1, format_2 = formats_pair
formats_info = []
formats_info.extend(format_1.get('requested_formats', (format_1,)))
formats_info.extend(format_2.get('requested_formats', (format_2,)))
if not allow_multiple_streams['video'] or not allow_multiple_streams['audio']:
get_no_more = {'video': False, 'audio': False}
for (i, fmt_info) in enumerate(formats_info):
if fmt_info.get('acodec') == fmt_info.get('vcodec') == 'none':
formats_info.pop(i)
continue
for aud_vid in ['audio', 'video']:
if not allow_multiple_streams[aud_vid] and fmt_info.get(aud_vid[0] + 'codec') != 'none':
if get_no_more[aud_vid]:
formats_info.pop(i)
break
get_no_more[aud_vid] = True
if len(formats_info) == 1:
return formats_info[0]
video_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('vcodec') != 'none']
audio_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('acodec') != 'none']
the_only_video = video_fmts[0] if len(video_fmts) == 1 else None
the_only_audio = audio_fmts[0] if len(audio_fmts) == 1 else None
output_ext = self.params.get('merge_output_format')
if not output_ext:
if the_only_video:
output_ext = the_only_video['ext']
elif the_only_audio and not video_fmts:
output_ext = the_only_audio['ext']
else:
output_ext = 'mkv'
filtered = lambda *keys: filter(None, (traverse_obj(fmt, *keys) for fmt in formats_info))
new_dict = {
'requested_formats': formats_info,
'format': '+'.join(filtered('format')),
'format_id': '+'.join(filtered('format_id')),
'ext': output_ext,
'protocol': '+'.join(map(determine_protocol, formats_info)),
'language': '+'.join(orderedSet(filtered('language'))),
'format_note': '+'.join(orderedSet(filtered('format_note'))),
'filesize_approx': sum(filtered('filesize', 'filesize_approx')),
'tbr': sum(filtered('tbr', 'vbr', 'abr')),
}
if the_only_video:
new_dict.update({
'width': the_only_video.get('width'),
'height': the_only_video.get('height'),
'resolution': the_only_video.get('resolution') or self.format_resolution(the_only_video),
'fps': the_only_video.get('fps'),
'vcodec': the_only_video.get('vcodec'),
'vbr': the_only_video.get('vbr'),
'stretched_ratio': the_only_video.get('stretched_ratio'),
})
if the_only_audio:
new_dict.update({
'acodec': the_only_audio.get('acodec'),
'abr': the_only_audio.get('abr'),
'asr': the_only_audio.get('asr'),
})
return new_dict
def _check_formats(formats):
if not check_formats:
yield from formats
return
for f in formats:
self.to_screen('[info] Testing format %s' % f['format_id'])
temp_file = tempfile.NamedTemporaryFile(
suffix='.tmp', delete=False,
dir=self.get_output_path('temp') or None)
temp_file.close()
try:
success, _ = self.dl(temp_file.name, f, test=True)
except (DownloadError, IOError, OSError, ValueError) + network_exceptions:
success = False
finally:
if os.path.exists(temp_file.name):
try:
os.remove(temp_file.name)
except OSError:
self.report_warning('Unable to delete temporary file "%s"' % temp_file.name)
if success:
yield f
else:
self.to_screen('[info] Unable to download format %s. Skipping...' % f['format_id'])
def _build_selector_function(selector):
if isinstance(selector, list): # ,
fs = [_build_selector_function(s) for s in selector]
def selector_function(ctx):
for f in fs:
yield from f(ctx)
return selector_function
elif selector.type == GROUP: # ()
selector_function = _build_selector_function(selector.selector)
elif selector.type == PICKFIRST: # /
fs = [_build_selector_function(s) for s in selector.selector]
def selector_function(ctx):
for f in fs:
picked_formats = list(f(ctx))
if picked_formats:
return picked_formats
return []
elif selector.type == MERGE: # +
selector_1, selector_2 = map(_build_selector_function, selector.selector)
def selector_function(ctx):
for pair in itertools.product(
selector_1(copy.deepcopy(ctx)), selector_2(copy.deepcopy(ctx))):
yield _merge(pair)
elif selector.type == SINGLE: # atom
format_spec = selector.selector or 'best'
# TODO: Add allvideo, allaudio etc by generalizing the code with best/worst selector
if format_spec == 'all':
def selector_function(ctx):
yield from _check_formats(ctx['formats'])
elif format_spec == 'mergeall':
def selector_function(ctx):
formats = list(_check_formats(ctx['formats']))
if not formats:
return
merged_format = formats[-1]
for f in formats[-2::-1]:
merged_format = _merge((merged_format, f))
yield merged_format
else:
format_fallback, format_reverse, format_idx = False, True, 1
mobj = re.match(
r'(?P<bw>best|worst|b|w)(?P<type>video|audio|v|a)?(?P<mod>\*)?(?:\.(?P<n>[1-9]\d*))?$',
format_spec)
if mobj is not None:
format_idx = int_or_none(mobj.group('n'), default=1)
format_reverse = mobj.group('bw')[0] == 'b'
format_type = (mobj.group('type') or [None])[0]
not_format_type = {'v': 'a', 'a': 'v'}.get(format_type)
format_modified = mobj.group('mod') is not None
format_fallback = not format_type and not format_modified # for b, w
_filter_f = (
(lambda f: f.get('%scodec' % format_type) != 'none')
if format_type and format_modified # bv*, ba*, wv*, wa*
else (lambda f: f.get('%scodec' % not_format_type) == 'none')
if format_type # bv, ba, wv, wa
else (lambda f: f.get('vcodec') != 'none' and f.get('acodec') != 'none')
if not format_modified # b, w
else lambda f: True) # b*, w*
filter_f = lambda f: _filter_f(f) and (
f.get('vcodec') != 'none' or f.get('acodec') != 'none')
else:
if format_spec in self._format_selection_exts['audio']:
filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none'
elif format_spec in self._format_selection_exts['video']:
filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none' and f.get('vcodec') != 'none'
elif format_spec in self._format_selection_exts['storyboards']:
filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') == 'none' and f.get('vcodec') == 'none'
else:
filter_f = lambda f: f.get('format_id') == format_spec # id
def selector_function(ctx):
formats = list(ctx['formats'])
matches = list(filter(filter_f, formats)) if filter_f is not None else formats
if format_fallback and ctx['incomplete_formats'] and not matches:
# for extractors with incomplete formats (audio only (soundcloud)
# or video only (imgur)) best/worst will fallback to
# best/worst {video,audio}-only format
matches = formats
matches = LazyList(_check_formats(matches[::-1 if format_reverse else 1]))
try:
yield matches[format_idx - 1]
except IndexError:
return
filters = [self._build_format_filter(f) for f in selector.filters]
def final_selector(ctx):
ctx_copy = copy.deepcopy(ctx)
for _filter in filters:
ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
return selector_function(ctx_copy)
return final_selector
stream = io.BytesIO(format_spec.encode('utf-8'))
try:
tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
except tokenize.TokenError:
raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
class TokenIterator(object):
def __init__(self, tokens):
self.tokens = tokens
self.counter = 0
def __iter__(self):
return self
def __next__(self):
if self.counter >= len(self.tokens):
raise StopIteration()
value = self.tokens[self.counter]
self.counter += 1
return value
next = __next__
def restore_last_token(self):
self.counter -= 1
parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
return _build_selector_function(parsed_selector)
def _calc_headers(self, info_dict):
res = std_headers.copy()
add_headers = info_dict.get('http_headers')
if add_headers:
res.update(add_headers)
cookies = self._calc_cookies(info_dict)
if cookies:
res['Cookie'] = cookies
if 'X-Forwarded-For' not in res:
x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
if x_forwarded_for_ip:
res['X-Forwarded-For'] = x_forwarded_for_ip
return res
def _calc_cookies(self, info_dict):
pr = sanitized_Request(info_dict['url'])
self.cookiejar.add_cookie_header(pr)
return pr.get_header('Cookie')
def _sanitize_thumbnails(self, info_dict):
thumbnails = info_dict.get('thumbnails')
if thumbnails is None:
thumbnail = info_dict.get('thumbnail')
if thumbnail:
info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
if thumbnails:
thumbnails.sort(key=lambda t: (
t.get('preference') if t.get('preference') is not None else -1,
t.get('width') if t.get('width') is not None else -1,
t.get('height') if t.get('height') is not None else -1,
t.get('id') if t.get('id') is not None else '',
t.get('url')))
def thumbnail_tester():
def test_thumbnail(t):
self.to_screen(f'[info] Testing thumbnail {t['id']}')
try:
self.urlopen(HEADRequest(t['url']))
except network_exceptions as err:
self.to_screen(f'[info] Unable to connect to thumbnail {t['id']} URL {t['url']!r} - {err}. Skipping...')
return False
return True
return test_thumbnail
for i, t in enumerate(thumbnails):
if t.get('id') is None:
t['id'] = '%d' % i
if t.get('width') and t.get('height'):
t['resolution'] = '%dx%d' % (t['width'], t['height'])
t['url'] = sanitize_url(t['url'])
if self.params.get('check_formats'):
info_dict['thumbnails'] = LazyList(filter(thumbnail_tester(), thumbnails[::-1])).reverse()
else:
info_dict['thumbnails'] = thumbnails
def process_video_result(self, info_dict, download=True):
assert info_dict.get('_type', 'video') == 'video'
if 'id' not in info_dict:
raise ExtractorError('Missing "id" field in extractor result')
if 'title' not in info_dict:
raise ExtractorError('Missing "title" field in extractor result',
video_id=info_dict['id'], ie=info_dict['extractor'])
def report_force_conversion(field, field_not, conversion):
self.report_warning(
'"%s" field is not %s - forcing %s conversion, there is an error in extractor'
% (field, field_not, conversion))
def sanitize_string_field(info, string_field):
field = info.get(string_field)
if field is None or isinstance(field, compat_str):
return
report_force_conversion(string_field, 'a string', 'string')
info[string_field] = compat_str(field)
def sanitize_numeric_fields(info):
for numeric_field in self._NUMERIC_FIELDS:
field = info.get(numeric_field)
if field is None or isinstance(field, compat_numeric_types):
continue
report_force_conversion(numeric_field, 'numeric', 'int')
info[numeric_field] = int_or_none(field)
sanitize_string_field(info_dict, 'id')
sanitize_numeric_fields(info_dict)
if 'playlist' not in info_dict:
# It isn't part of a playlist
info_dict['playlist'] = None
info_dict['playlist_index'] = None
self._sanitize_thumbnails(info_dict)
thumbnail = info_dict.get('thumbnail')
thumbnails = info_dict.get('thumbnails')
if thumbnail:
info_dict['thumbnail'] = sanitize_url(thumbnail)
elif thumbnails:
info_dict['thumbnail'] = thumbnails[-1]['url']
if info_dict.get('display_id') is None and 'id' in info_dict:
info_dict['display_id'] = info_dict['id']
if info_dict.get('duration') is not None:
info_dict['duration_string'] = formatSeconds(info_dict['duration'])
for ts_key, date_key in (
('timestamp', 'upload_date'),
('release_timestamp', 'release_date'),
):
if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
# Working around out-of-range timestamp values (e.g. negative ones on Windows,
# see http://bugs.python.org/issue1646728)
try:
upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key])
info_dict[date_key] = upload_date.strftime('%Y%m%d')
except (ValueError, OverflowError, OSError):
pass
live_keys = ('is_live', 'was_live')
live_status = info_dict.get('live_status')
if live_status is None:
for key in live_keys:
if info_dict.get(key) is False:
continue
if info_dict.get(key):
live_status = key
break
if all(info_dict.get(key) is False for key in live_keys):
live_status = 'not_live'
if live_status:
info_dict['live_status'] = live_status
for key in live_keys:
if info_dict.get(key) is None:
info_dict[key] = (live_status == key)
# Auto generate title fields corresponding to the *_number fields when missing
# in order to always have clean titles. This is very common for TV series.
for field in ('chapter', 'season', 'episode'):
if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
for cc_kind in ('subtitles', 'automatic_captions'):
cc = info_dict.get(cc_kind)
if cc:
for _, subtitle in cc.items():
for subtitle_format in subtitle:
if subtitle_format.get('url'):
subtitle_format['url'] = sanitize_url(subtitle_format['url'])
if subtitle_format.get('ext') is None:
subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
automatic_captions = info_dict.get('automatic_captions')
subtitles = info_dict.get('subtitles')
info_dict['requested_subtitles'] = self.process_subtitles(
info_dict['id'], subtitles, automatic_captions)
# We now pick which formats have to be downloaded
if info_dict.get('formats') is None:
# There's only one format available
formats = [info_dict]
else:
formats = info_dict['formats']
info_dict['__has_drm'] = any(f.get('has_drm') for f in formats)
if not self.params.get('allow_unplayable_formats'):
formats = [f for f in formats if not f.get('has_drm')]
if not formats:
self.raise_no_formats(info_dict)
def is_wellformed(f):
url = f.get('url')
if not url:
self.report_warning(
'"url" field is missing or empty - skipping format, '
'there is an error in extractor')
return False
if isinstance(url, bytes):
sanitize_string_field(f, 'url')
return True
# Filter out malformed formats for better extraction robustness
formats = list(filter(is_wellformed, formats))
formats_dict = {}
# We check that all the formats have the format and format_id fields
for i, format in enumerate(formats):
sanitize_string_field(format, 'format_id')
sanitize_numeric_fields(format)
format['url'] = sanitize_url(format['url'])
if not format.get('format_id'):
format['format_id'] = compat_str(i)
else:
# Sanitize format_id from characters used in format selector expression
format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
format_id = format['format_id']
if format_id not in formats_dict:
formats_dict[format_id] = []
formats_dict[format_id].append(format)
# Make sure all formats have unique format_id
common_exts = set(itertools.chain(*self._format_selection_exts.values()))
for format_id, ambiguous_formats in formats_dict.items():
ambigious_id = len(ambiguous_formats) > 1
for i, format in enumerate(ambiguous_formats):
if ambigious_id:
format['format_id'] = '%s-%d' % (format_id, i)
if format.get('ext') is None:
format['ext'] = determine_ext(format['url']).lower()
# Ensure there is no conflict between id and ext in format selection
# See https://github.com/yt-dlp/yt-dlp/issues/1282
if format['format_id'] != format['ext'] and format['format_id'] in common_exts:
format['format_id'] = 'f%s' % format['format_id']
for i, format in enumerate(formats):
if format.get('format') is None:
format['format'] = '{id} - {res}{note}'.format(
id=format['format_id'],
res=self.format_resolution(format),
note=format_field(format, 'format_note', ' (%s)'),
)
if format.get('protocol') is None:
format['protocol'] = determine_protocol(format)
if format.get('resolution') is None:
format['resolution'] = self.format_resolution(format, default=None)
if format.get('dynamic_range') is None and format.get('vcodec') != 'none':
format['dynamic_range'] = 'SDR'
# Add HTTP headers, so that external programs can use them from the
# json output
full_format_info = info_dict.copy()
full_format_info.update(format)
format['http_headers'] = self._calc_headers(full_format_info)
# Remove private housekeeping stuff
if '__x_forwarded_for_ip' in info_dict:
del info_dict['__x_forwarded_for_ip']
# TODO Central sorting goes here
if not formats or formats[0] is not info_dict:
# only set the 'formats' fields if the original info_dict list them
# otherwise we end up with a circular reference, the first (and unique)
# element in the 'formats' field in info_dict is info_dict itself,
# which can't be exported to json
info_dict['formats'] = formats
info_dict, _ = self.pre_process(info_dict)
if self.params.get('list_thumbnails'):
self.list_thumbnails(info_dict)
if self.params.get('listformats'):
if not info_dict.get('formats') and not info_dict.get('url'):
self.to_screen('%s has no formats' % info_dict['id'])
else:
self.list_formats(info_dict)
if self.params.get('listsubtitles'):
if 'automatic_captions' in info_dict:
self.list_subtitles(
info_dict['id'], automatic_captions, 'automatic captions')
self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
list_only = self.params.get('simulate') is None and (
self.params.get('list_thumbnails') or self.params.get('listformats') or self.params.get('listsubtitles'))
if list_only:
# Without this printing, -F --print-json will not work
self.__forced_printings(info_dict, self.prepare_filename(info_dict), incomplete=True)
return
format_selector = self.format_selector
if format_selector is None:
req_format = self._default_format_spec(info_dict, download=download)
self.write_debug('Default format spec: %s' % req_format)
format_selector = self.build_format_selector(req_format)
# While in format selection we may need to have an access to the original
# format set in order to calculate some metrics or do some processing.
# For now we need to be able to guess whether original formats provided
# by extractor are incomplete or not (i.e. whether extractor provides only
# video-only or audio-only formats) for proper formats selection for
# extractors with such incomplete formats (see
# https://github.com/ytdl-org/youtube-dl/pull/5556).
# Since formats may be filtered during format selection and may not match
# the original formats the results may be incorrect. Thus original formats
# or pre-calculated metrics should be passed to format selection routines
# as well.
# We will pass a context object containing all necessary additional data
# instead of just formats.
# This fixes incorrect format selection issue (see
# https://github.com/ytdl-org/youtube-dl/issues/10083).
incomplete_formats = (
# All formats are video-only or
all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
# all formats are audio-only
or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
ctx = {
'formats': formats,
'incomplete_formats': incomplete_formats,
}
formats_to_download = list(format_selector(ctx))
if not formats_to_download:
if not self.params.get('ignore_no_formats_error'):
raise ExtractorError('Requested format is not available', expected=True,
video_id=info_dict['id'], ie=info_dict['extractor'])
else:
self.report_warning('Requested format is not available')
# Process what we can, even without any available formats.
self.process_info(dict(info_dict))
elif download:
self.to_screen(
'[info] %s: Downloading %d format(s): %s' % (
info_dict['id'], len(formats_to_download),
", ".join([f['format_id'] for f in formats_to_download])))
for fmt in formats_to_download:
new_info = dict(info_dict)
# Save a reference to the original info_dict so that it can be modified in process_info if needed
new_info['__original_infodict'] = info_dict
new_info.update(fmt)
self.process_info(new_info)
# We update the info dict with the best quality format (backwards compatibility)
if formats_to_download:
info_dict.update(formats_to_download[-1])
return info_dict
def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
"""Select the requested subtitles and their format"""
available_subs = {}
if normal_subtitles and self.params.get('writesubtitles'):
available_subs.update(normal_subtitles)
if automatic_captions and self.params.get('writeautomaticsub'):
for lang, cap_info in automatic_captions.items():
if lang not in available_subs:
available_subs[lang] = cap_info
if (not self.params.get('writesubtitles') and not
self.params.get('writeautomaticsub') or not
available_subs):
return None
all_sub_langs = available_subs.keys()
if self.params.get('allsubtitles', False):
requested_langs = all_sub_langs
elif self.params.get('subtitleslangs', False):
# A list is used so that the order of languages will be the same as
# given in subtitleslangs. See https://github.com/yt-dlp/yt-dlp/issues/1041
requested_langs = []
for lang_re in self.params.get('subtitleslangs'):
if lang_re == 'all':
requested_langs.extend(all_sub_langs)
continue
discard = lang_re[0] == '-'
if discard:
lang_re = lang_re[1:]
current_langs = filter(re.compile(lang_re + '$').match, all_sub_langs)
if discard:
for lang in current_langs:
while lang in requested_langs:
requested_langs.remove(lang)
else:
requested_langs.extend(current_langs)
requested_langs = orderedSet(requested_langs)
elif 'en' in available_subs:
requested_langs = ['en']
else:
requested_langs = [list(all_sub_langs)[0]]
if requested_langs:
self.write_debug('Downloading subtitles: %s' % ', '.join(requested_langs))
formats_query = self.params.get('subtitlesformat', 'best')
formats_preference = formats_query.split('/') if formats_query else []
subs = {}
for lang in requested_langs:
formats = available_subs.get(lang)
if formats is None:
self.report_warning('%s subtitles not available for %s' % (lang, video_id))
continue
for ext in formats_preference:
if ext == 'best':
f = formats[-1]
break
matches = list(filter(lambda f: f['ext'] == ext, formats))
if matches:
f = matches[-1]
break
else:
f = formats[-1]
self.report_warning(
'No subtitle format found matching "%s" for language %s, '
'using %s' % (formats_query, lang, f['ext']))
subs[lang] = f
return subs
def __forced_printings(self, info_dict, filename, incomplete):
def print_mandatory(field, actual_field=None):
if actual_field is None:
actual_field = field
if (self.params.get('force%s' % field, False)
and (not incomplete or info_dict.get(actual_field) is not None)):
self.to_stdout(info_dict[actual_field])
def print_optional(field):
if (self.params.get('force%s' % field, False)
and info_dict.get(field) is not None):
self.to_stdout(info_dict[field])
info_dict = info_dict.copy()
if filename is not None:
info_dict['filename'] = filename
if info_dict.get('requested_formats') is not None:
# For RTMP URLs, also include the playpath
info_dict['urls'] = '\n'.join(f['url'] + f.get('play_path', '') for f in info_dict['requested_formats'])
elif 'url' in info_dict:
info_dict['urls'] = info_dict['url'] + info_dict.get('play_path', '')
if self.params.get('forceprint') or self.params.get('forcejson'):
self.post_extract(info_dict)
for tmpl in self.params.get('forceprint', []):
mobj = re.match(r'\w+(=?)$', tmpl)
if mobj and mobj.group(1):
tmpl = f'{tmpl[:-1]} = %({tmpl[:-1]})s'
elif mobj:
tmpl = '%({})s'.format(tmpl)
self.to_stdout(self.evaluate_outtmpl(tmpl, info_dict))
print_mandatory('title')
print_mandatory('id')
print_mandatory('url', 'urls')
print_optional('thumbnail')
print_optional('description')
print_optional('filename')
if self.params.get('forceduration') and info_dict.get('duration') is not None:
self.to_stdout(formatSeconds(info_dict['duration']))
print_mandatory('format')
if self.params.get('forcejson'):
self.to_stdout(json.dumps(self.sanitize_info(info_dict)))
def dl(self, name, info, subtitle=False, test=False):
if not info.get('url'):
self.raise_no_formats(info, True)
if test:
verbose = self.params.get('verbose')
params = {
'test': True,
'quiet': self.params.get('quiet') or not verbose,
'verbose': verbose,
'noprogress': not verbose,
'nopart': True,
'skip_unavailable_fragments': False,
'keep_fragments': False,
'overwrites': True,
'_no_ytdl_file': True,
}
else:
params = self.params
fd = get_suitable_downloader(info, params, to_stdout=(name == '-'))(self, params)
if not test:
for ph in self._progress_hooks:
fd.add_progress_hook(ph)
urls = '", "'.join([f['url'] for f in info.get('requested_formats', [])] or [info['url']])
self.write_debug('Invoking downloader on "%s"' % urls)
new_info = copy.deepcopy(self._copy_infodict(info))
if new_info.get('http_headers') is None:
new_info['http_headers'] = self._calc_headers(new_info)
return fd.download(name, new_info, subtitle)
def process_info(self, info_dict):
"""Process a single resolved IE result."""
assert info_dict.get('_type', 'video') == 'video'
max_downloads = self.params.get('max_downloads')
if max_downloads is not None:
if self._num_downloads >= int(max_downloads):
raise MaxDownloadsReached()
# TODO: backward compatibility, to be removed
info_dict['fulltitle'] = info_dict['title']
if 'format' not in info_dict and 'ext' in info_dict:
info_dict['format'] = info_dict['ext']
if self._match_entry(info_dict) is not None:
return
self.post_extract(info_dict)
self._num_downloads += 1
# info_dict['_filename'] needs to be set for backward compatibility
info_dict['_filename'] = full_filename = self.prepare_filename(info_dict, warn=True)
temp_filename = self.prepare_filename(info_dict, 'temp')
files_to_move = {}
# Forced printings
self.__forced_printings(info_dict, full_filename, incomplete=('format' not in info_dict))
if self.params.get('simulate'):
if self.params.get('force_write_download_archive', False):
self.record_download_archive(info_dict)
# Do nothing else if in simulate mode
return
if full_filename is None:
return
if not self._ensure_dir_exists(encodeFilename(full_filename)):
return
if not self._ensure_dir_exists(encodeFilename(temp_filename)):
return
if self._write_description('video', info_dict,
self.prepare_filename(info_dict, 'description')) is None:
return
sub_files = self._write_subtitles(info_dict, temp_filename)
if sub_files is None:
return
files_to_move.update(dict(sub_files))
thumb_files = self._write_thumbnails(
'video', info_dict, temp_filename, self.prepare_filename(info_dict, 'thumbnail'))
if thumb_files is None:
return
files_to_move.update(dict(thumb_files))
infofn = self.prepare_filename(info_dict, 'infojson')
_infojson_written = self._write_info_json('video', info_dict, infofn)
if _infojson_written:
info_dict['__infojson_filename'] = infofn
elif _infojson_written is None:
return
# Note: Annotations are deprecated
annofn = None
if self.params.get('writeannotations', False):
annofn = self.prepare_filename(info_dict, 'annotation')
if annofn:
if not self._ensure_dir_exists(encodeFilename(annofn)):
return
if not self.params.get('overwrites', True) and os.path.exists(encodeFilename(annofn)):
self.to_screen('[info] Video annotations are already present')
elif not info_dict.get('annotations'):
self.report_warning('There are no annotations to write.')
else:
try:
self.to_screen('[info] Writing video annotations to: ' + annofn)
with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
annofile.write(info_dict['annotations'])
except (KeyError, TypeError):
self.report_warning('There are no annotations to write.')
except (OSError, IOError):
self.report_error('Cannot write annotations file: ' + annofn)
return
# Write internet shortcut files
url_link = webloc_link = desktop_link = False
if self.params.get('writelink', False):
if sys.platform == "darwin": # macOS.
webloc_link = True
elif sys.platform.startswith("linux"):
desktop_link = True
else: # if sys.platform in ['win32', 'cygwin']:
url_link = True
if self.params.get('writeurllink', False):
url_link = True
if self.params.get('writewebloclink', False):
webloc_link = True
if self.params.get('writedesktoplink', False):
desktop_link = True
if url_link or webloc_link or desktop_link:
if 'webpage_url' not in info_dict:
self.report_error('Cannot write internet shortcut file because the "webpage_url" field is missing in the media information')
return
ascii_url = iri_to_uri(info_dict['webpage_url'])
def _write_link_file(extension, template, newline, embed_filename):
linkfn = replace_extension(full_filename, extension, info_dict.get('ext'))
if self.params.get('overwrites', True) and os.path.exists(encodeFilename(linkfn)):
self.to_screen('[info] Internet shortcut is already present')
else:
try:
self.to_screen('[info] Writing internet shortcut to: ' + linkfn)
with io.open(encodeFilename(to_high_limit_path(linkfn)), 'w', encoding='utf-8', newline=newline) as linkfile:
template_vars = {'url': ascii_url}
if embed_filename:
template_vars['filename'] = linkfn[:-(len(extension) + 1)]
linkfile.write(template % template_vars)
except (OSError, IOError):
self.report_error('Cannot write internet shortcut ' + linkfn)
return False
return True
if url_link:
if not _write_link_file('url', DOT_URL_LINK_TEMPLATE, '\r\n', embed_filename=False):
return
if webloc_link:
if not _write_link_file('webloc', DOT_WEBLOC_LINK_TEMPLATE, '\n', embed_filename=False):
return
if desktop_link:
if not _write_link_file('desktop', DOT_DESKTOP_LINK_TEMPLATE, '\n', embed_filename=True):
return
try:
info_dict, files_to_move = self.pre_process(info_dict, 'before_dl', files_to_move)
except PostProcessingError as err:
self.report_error('Preprocessing: %s' % str(err))
return
must_record_download_archive = False
if self.params.get('skip_download', False):
info_dict['filepath'] = temp_filename
info_dict['__finaldir'] = os.path.dirname(os.path.abspath(encodeFilename(full_filename)))
info_dict['__files_to_move'] = files_to_move
info_dict = self.run_pp(MoveFilesAfterDownloadPP(self, False), info_dict)
else:
# Download
info_dict.setdefault('__postprocessors', [])
try:
def existing_file(*filepaths):
ext = info_dict.get('ext')
final_ext = self.params.get('final_ext', ext)
existing_files = []
for file in orderedSet(filepaths):
if final_ext != ext:
converted = replace_extension(file, final_ext, ext)
if os.path.exists(encodeFilename(converted)):
existing_files.append(converted)
if os.path.exists(encodeFilename(file)):
existing_files.append(file)
if not existing_files or self.params.get('overwrites', False):
for file in orderedSet(existing_files):
self.report_file_delete(file)
os.remove(encodeFilename(file))
return None
info_dict['ext'] = os.path.splitext(existing_files[0])[1][1:]
return existing_files[0]
success = True
if info_dict.get('requested_formats') is not None:
def compatible_formats(formats):
# TODO: some formats actually allow this (mkv, webm, ogg, mp4), but not all of them.
video_formats = [format for format in formats if format.get('vcodec') != 'none']
audio_formats = [format for format in formats if format.get('acodec') != 'none']
if len(video_formats) > 2 or len(audio_formats) > 2:
return False
# Check extension
exts = set(format.get('ext') for format in formats)
COMPATIBLE_EXTS = (
set(('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma')),
set(('webm',)),
)
for ext_sets in COMPATIBLE_EXTS:
if ext_sets.issuperset(exts):
return True
# TODO: Check acodec/vcodec
return False
requested_formats = info_dict['requested_formats']
old_ext = info_dict['ext']
if self.params.get('merge_output_format') is None:
if not compatible_formats(requested_formats):
info_dict['ext'] = 'mkv'
self.report_warning(
'Requested formats are incompatible for merge and will be merged into mkv')
if (info_dict['ext'] == 'webm'
and info_dict.get('thumbnails')
# check with type instead of pp_key, __name__, or isinstance
# since we dont want any custom PPs to trigger this
and any(type(pp) == EmbedThumbnailPP for pp in self._pps['post_process'])):
info_dict['ext'] = 'mkv'
self.report_warning(
'webm doesn\'t support embedding a thumbnail, mkv will be used')
new_ext = info_dict['ext']
def correct_ext(filename, ext=new_ext):
if filename == '-':
return filename
filename_real_ext = os.path.splitext(filename)[1][1:]
filename_wo_ext = (
os.path.splitext(filename)[0]
if filename_real_ext in (old_ext, new_ext)
else filename)
return '%s.%s' % (filename_wo_ext, ext)
# Ensure filename always has a correct extension for successful merge
full_filename = correct_ext(full_filename)
temp_filename = correct_ext(temp_filename)
dl_filename = existing_file(full_filename, temp_filename)
info_dict['__real_download'] = False
if dl_filename is not None:
self.report_file_already_downloaded(dl_filename)
elif get_suitable_downloader(info_dict, self.params, to_stdout=temp_filename == '-'):
info_dict['url'] = '\n'.join(f['url'] for f in requested_formats)
success, real_download = self.dl(temp_filename, info_dict)
info_dict['__real_download'] = real_download
else:
downloaded = []
merger = FFmpegMergerPP(self)
if self.params.get('allow_unplayable_formats'):
self.report_warning(
'You have requested merging of multiple formats '
'while also allowing unplayable formats to be downloaded. '
'The formats won\'t be merged to prevent data corruption.')
elif not merger.available:
self.report_warning(
'You have requested merging of multiple formats but ffmpeg is not installed. '
'The formats won\'t be merged.')
if temp_filename == '-':
reason = ('using a downloader other than ffmpeg' if FFmpegFD.can_merge_formats(info_dict)
else 'but the formats are incompatible for simultaneous download' if merger.available
else 'but ffmpeg is not installed')
self.report_warning(
f'You have requested downloading multiple formats to stdout {reason}. '
'The formats will be streamed one after the other')
fname = temp_filename
for f in requested_formats:
new_info = dict(info_dict)
del new_info['requested_formats']
new_info.update(f)
if temp_filename != '-':
fname = prepend_extension(
correct_ext(temp_filename, new_info['ext']),
'f%s' % f['format_id'], new_info['ext'])
if not self._ensure_dir_exists(fname):
return
f['filepath'] = fname
downloaded.append(fname)
partial_success, real_download = self.dl(fname, new_info)
info_dict['__real_download'] = info_dict['__real_download'] or real_download
success = success and partial_success
if merger.available and not self.params.get('allow_unplayable_formats'):
info_dict['__postprocessors'].append(merger)
info_dict['__files_to_merge'] = downloaded
# Even if there were no downloads, it is being merged only now
info_dict['__real_download'] = True
else:
for file in downloaded:
files_to_move[file] = None
else:
# Just a single file
dl_filename = existing_file(full_filename, temp_filename)
if dl_filename is None or dl_filename == temp_filename:
# dl_filename == temp_filename could mean that the file was partially downloaded with --no-part.
# So we should try to resume the download
success, real_download = self.dl(temp_filename, info_dict)
info_dict['__real_download'] = real_download
else:
self.report_file_already_downloaded(dl_filename)
dl_filename = dl_filename or temp_filename
info_dict['__finaldir'] = os.path.dirname(os.path.abspath(encodeFilename(full_filename)))
except network_exceptions as err:
self.report_error('unable to download video data: %s' % error_to_compat_str(err))
return
except (OSError, IOError) as err:
raise UnavailableVideoError(err)
except (ContentTooShortError, ) as err:
self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
return
if success and full_filename != '-':
def fixup():
do_fixup = True
fixup_policy = self.params.get('fixup')
vid = info_dict['id']
if fixup_policy in ('ignore', 'never'):
return
elif fixup_policy == 'warn':
do_fixup = False
elif fixup_policy != 'force':
assert fixup_policy in ('detect_or_warn', None)
if not info_dict.get('__real_download'):
do_fixup = False
def ffmpeg_fixup(cndn, msg, cls):
if not cndn:
return
if not do_fixup:
self.report_warning(f'{vid}: {msg}')
return
pp = cls(self)
if pp.available:
info_dict['__postprocessors'].append(pp)
else:
self.report_warning(f'{vid}: {msg}. Install ffmpeg to fix this automatically')
stretched_ratio = info_dict.get('stretched_ratio')
ffmpeg_fixup(
stretched_ratio not in (1, None),
f'Non-uniform pixel ratio {stretched_ratio}',
FFmpegFixupStretchedPP)
ffmpeg_fixup(
(info_dict.get('requested_formats') is None
and info_dict.get('container') == 'm4a_dash'
and info_dict.get('ext') == 'm4a'),
'writing DASH m4a. Only some players support this container',
FFmpegFixupM4aPP)
downloader = get_suitable_downloader(info_dict, self.params) if 'protocol' in info_dict else None
downloader = downloader.__name__ if downloader else None
ffmpeg_fixup(info_dict.get('requested_formats') is None and downloader == 'HlsFD',
'malformed AAC bitstream detected', FFmpegFixupM3u8PP)
ffmpeg_fixup(downloader == 'WebSocketFragmentFD', 'malformed timestamps detected', FFmpegFixupTimestampPP)
ffmpeg_fixup(downloader == 'WebSocketFragmentFD', 'malformed duration detected', FFmpegFixupDurationPP)
fixup()
try:
info_dict = self.post_process(dl_filename, info_dict, files_to_move)
except PostProcessingError as err:
self.report_error('Postprocessing: %s' % str(err))
return
try:
for ph in self._post_hooks:
ph(info_dict['filepath'])
except Exception as err:
self.report_error('post hooks: %s' % str(err))
return
must_record_download_archive = True
if must_record_download_archive or self.params.get('force_write_download_archive', False):
self.record_download_archive(info_dict)
max_downloads = self.params.get('max_downloads')
if max_downloads is not None and self._num_downloads >= int(max_downloads):
raise MaxDownloadsReached()
def download(self, url_list):
"""Download a given list of URLs."""
outtmpl = self.outtmpl_dict['default']
if (len(url_list) > 1
and outtmpl != '-'
and '%' not in outtmpl
and self.params.get('max_downloads') != 1):
raise SameFileError(outtmpl)
for url in url_list:
try:
# It also downloads the videos
res = self.extract_info(
url, force_generic_extractor=self.params.get('force_generic_extractor', False))
except UnavailableVideoError:
self.report_error('unable to download video')
except MaxDownloadsReached:
self.to_screen('[info] Maximum number of downloads reached')
raise
except ExistingVideoReached:
self.to_screen('[info] Encountered a video that is already in the archive, stopping due to --break-on-existing')
raise
except RejectedVideoReached:
self.to_screen('[info] Encountered a video that did not match filter, stopping due to --break-on-reject')
raise
else:
if self.params.get('dump_single_json', False):
self.post_extract(res)
self.to_stdout(json.dumps(self.sanitize_info(res)))
return self._download_retcode
def download_with_info_file(self, info_filename):
with contextlib.closing(fileinput.FileInput(
[info_filename], mode='r',
openhook=fileinput.hook_encoded('utf-8'))) as f:
# FileInput doesn't have a read method, we can't call json.load
info = self.sanitize_info(json.loads('\n'.join(f)), self.params.get('clean_infojson', True))
try:
self.process_ie_result(info, download=True)
except (DownloadError, EntryNotInPlaylist, ThrottledDownload):
webpage_url = info.get('webpage_url')
if webpage_url is not None:
self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
return self.download([webpage_url])
else:
raise
return self._download_retcode
@staticmethod
def sanitize_info(info_dict, remove_private_keys=False):
''' Sanitize the infodict for converting to json '''
if info_dict is None:
return info_dict
info_dict.setdefault('epoch', int(time.time()))
remove_keys = {'__original_infodict'} # Always remove this since this may contain a copy of the entire dict
keep_keys = ['_type'], # Always keep this to facilitate load-info-json
if remove_private_keys:
remove_keys |= {
'requested_formats', 'requested_subtitles', 'requested_entries',
'filepath', 'entries', 'original_url', 'playlist_autonumber',
}
empty_values = (None, {}, [], set(), tuple())
reject = lambda k, v: k not in keep_keys and (
k.startswith('_') or k in remove_keys or v in empty_values)
else:
reject = lambda k, v: k in remove_keys
filter_fn = lambda obj: (
list(map(filter_fn, obj)) if isinstance(obj, (LazyList, list, tuple, set))
else obj if not isinstance(obj, dict)
else dict((k, filter_fn(v)) for k, v in obj.items() if not reject(k, v)))
return filter_fn(info_dict)
@staticmethod
def filter_requested_info(info_dict, actually_filter=True):
''' Alias of sanitize_info for backward compatibility '''
return YoutubeDL.sanitize_info(info_dict, actually_filter)
def run_pp(self, pp, infodict):
files_to_delete = []
if '__files_to_move' not in infodict:
infodict['__files_to_move'] = {}
try:
files_to_delete, infodict = pp.run(infodict)
except PostProcessingError as e:
# Must be True and not 'only_download'
if self.params.get('ignoreerrors') is True:
self.report_error(e)
return infodict
raise
if not files_to_delete:
return infodict
if self.params.get('keepvideo', False):
for f in files_to_delete:
infodict['__files_to_move'].setdefault(f, '')
else:
for old_filename in set(files_to_delete):
self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
try:
os.remove(encodeFilename(old_filename))
except (IOError, OSError):
self.report_warning('Unable to remove downloaded original file')
if old_filename in infodict['__files_to_move']:
del infodict['__files_to_move'][old_filename]
return infodict
@staticmethod
def post_extract(info_dict):
def actual_post_extract(info_dict):
if info_dict.get('_type') in ('playlist', 'multi_video'):
for video_dict in info_dict.get('entries', {}):
actual_post_extract(video_dict or {})
return
post_extractor = info_dict.get('__post_extractor') or (lambda: {})
extra = post_extractor().items()
info_dict.update(extra)
info_dict.pop('__post_extractor', None)
original_infodict = info_dict.get('__original_infodict') or {}
original_infodict.update(extra)
original_infodict.pop('__post_extractor', None)
actual_post_extract(info_dict or {})
def pre_process(self, ie_info, key='pre_process', files_to_move=None):
info = dict(ie_info)
info['__files_to_move'] = files_to_move or {}
for pp in self._pps[key]:
info = self.run_pp(pp, info)
return info, info.pop('__files_to_move', None)
def post_process(self, filename, ie_info, files_to_move=None):
"""Run all the postprocessors on the given file."""
info = dict(ie_info)
info['filepath'] = filename
info['__files_to_move'] = files_to_move or {}
for pp in ie_info.get('__postprocessors', []) + self._pps['post_process']:
info = self.run_pp(pp, info)
info = self.run_pp(MoveFilesAfterDownloadPP(self), info)
del info['__files_to_move']
for pp in self._pps['after_move']:
info = self.run_pp(pp, info)
return info
def _make_archive_id(self, info_dict):
video_id = info_dict.get('id')
if not video_id:
return
# Future-proof against any change in case
# and backwards compatibility with prior versions
extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
if extractor is None:
url = str_or_none(info_dict.get('url'))
if not url:
return
# Try to find matching extractor for the URL and take its ie_key
for ie_key, ie in self._ies.items():
if ie.suitable(url):
extractor = ie_key
break
else:
return
return '%s %s' % (extractor.lower(), video_id)
def in_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return False
vid_id = self._make_archive_id(info_dict)
if not vid_id:
return False # Incomplete video information
return vid_id in self.archive
def record_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return
vid_id = self._make_archive_id(info_dict)
assert vid_id
with locked_file(fn, 'a', encoding='utf-8') as archive_file:
archive_file.write(vid_id + '\n')
self.archive.add(vid_id)
@staticmethod
def format_resolution(format, default='unknown'):
is_images = format.get('vcodec') == 'none' and format.get('acodec') == 'none'
if format.get('vcodec') == 'none' and format.get('acodec') != 'none':
return 'audio only'
if format.get('resolution') is not None:
return format['resolution']
if format.get('width') and format.get('height'):
res = '%dx%d' % (format['width'], format['height'])
elif format.get('height'):
res = '%sp' % format['height']
elif format.get('width'):
res = '%dx?' % format['width']
elif is_images:
return 'images'
else:
return default
return f'{res} images' if is_images else res
def _format_note(self, fdict):
res = ''
if fdict.get('ext') in ['f4f', 'f4m']:
res += '(unsupported) '
if fdict.get('language'):
if res:
res += ' '
res += '[%s] ' % fdict['language']
if fdict.get('format_note') is not None:
res += fdict['format_note'] + ' '
if fdict.get('tbr') is not None:
res += '%4dk ' % fdict['tbr']
if fdict.get('container') is not None:
if res:
res += ', '
res += '%s container' % fdict['container']
if (fdict.get('vcodec') is not None
and fdict.get('vcodec') != 'none'):
if res:
res += ', '
res += fdict['vcodec']
if fdict.get('vbr') is not None:
res += '@'
elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
res += 'video@'
if fdict.get('vbr') is not None:
res += '%4dk' % fdict['vbr']
if fdict.get('fps') is not None:
if res:
res += ', '
res += '%sfps' % fdict['fps']
if fdict.get('acodec') is not None:
if res:
res += ', '
if fdict['acodec'] == 'none':
res += 'video only'
else:
res += '%-5s' % fdict['acodec']
elif fdict.get('abr') is not None:
if res:
res += ', '
res += 'audio'
if fdict.get('abr') is not None:
res += '@%3dk' % fdict['abr']
if fdict.get('asr') is not None:
res += ' (%5dHz)' % fdict['asr']
if fdict.get('filesize') is not None:
if res:
res += ', '
res += format_bytes(fdict['filesize'])
elif fdict.get('filesize_approx') is not None:
if res:
res += ', '
res += '~' + format_bytes(fdict['filesize_approx'])
return res
def list_formats(self, info_dict):
formats = info_dict.get('formats', [info_dict])
new_format = (
'list-formats' not in self.params.get('compat_opts', [])
and self.params.get('listformats_table', True) is not False)
if new_format:
table = [
[
format_field(f, 'format_id'),
format_field(f, 'ext'),
self.format_resolution(f),
format_field(f, 'fps', '%d'),
format_field(f, 'dynamic_range', '%s', ignore=(None, 'SDR')).replace('HDR', ''),
'|',
format_field(f, 'filesize', ' %s', func=format_bytes) + format_field(f, 'filesize_approx', '~%s', func=format_bytes),
format_field(f, 'tbr', '%4dk'),
shorten_protocol_name(f.get('protocol', '').replace("native", "n")),
'|',
format_field(f, 'vcodec', default='unknown').replace('none', ''),
format_field(f, 'vbr', '%4dk'),
format_field(f, 'acodec', default='unknown').replace('none', ''),
format_field(f, 'abr', '%3dk'),
format_field(f, 'asr', '%5dHz'),
', '.join(filter(None, (
'UNSUPPORTED' if f.get('ext') in ('f4f', 'f4m') else '',
format_field(f, 'language', '[%s]'),
format_field(f, 'format_note'),
format_field(f, 'container', ignore=(None, f.get('ext'))),
))),
] for f in formats if f.get('preference') is None or f['preference'] >= -1000]
header_line = ['ID', 'EXT', 'RESOLUTION', 'FPS', 'HDR', '|', ' FILESIZE', ' TBR', 'PROTO',
'|', 'VCODEC', ' VBR', 'ACODEC', ' ABR', ' ASR', 'MORE INFO']
else:
table = [
[
format_field(f, 'format_id'),
format_field(f, 'ext'),
self.format_resolution(f),
self._format_note(f)]
for f in formats
if f.get('preference') is None or f['preference'] >= -1000]
header_line = ['format code', 'extension', 'resolution', 'note']
self.to_screen(
'[info] Available formats for %s:' % info_dict['id'])
self.to_stdout(render_table(
header_line, table, delim=new_format, extraGap=(0 if new_format else 1), hideEmpty=new_format))
def list_thumbnails(self, info_dict):
thumbnails = list(info_dict.get('thumbnails'))
if not thumbnails:
self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
return
self.to_screen(
'[info] Thumbnails for %s:' % info_dict['id'])
self.to_stdout(render_table(
['ID', 'width', 'height', 'URL'],
[[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
def list_subtitles(self, video_id, subtitles, name='subtitles'):
if not subtitles:
self.to_screen('%s has no %s' % (video_id, name))
return
self.to_screen(
'Available %s for %s:' % (name, video_id))
def _row(lang, formats):
exts, names = zip(*((f['ext'], f.get('name') or 'unknown') for f in reversed(formats)))
if len(set(names)) == 1:
names = [] if names[0] == 'unknown' else names[:1]
return [lang, ', '.join(names), ', '.join(exts)]
self.to_stdout(render_table(
['Language', 'Name', 'Formats'],
[_row(lang, formats) for lang, formats in subtitles.items()],
hideEmpty=True))
def urlopen(self, req):
""" Start an HTTP download """
if isinstance(req, compat_basestring):
req = sanitized_Request(req)
return self._opener.open(req, timeout=self._socket_timeout)
def print_debug_header(self):
if not self.params.get('verbose'):
return
get_encoding = lambda stream: getattr(stream, 'encoding', 'missing (%s)' % type(stream).__name__)
encoding_str = (
'[debug] Encodings: locale %s, fs %s, stdout %s, stderr %s, pref %s\n' % (
locale.getpreferredencoding(),
sys.getfilesystemencoding(),
get_encoding(self._screen_file), get_encoding(self._err_file),
self.get_encoding()))
logger = self.params.get('logger')
if logger:
write_debug = lambda msg: logger.debug(f'[debug] {msg}')
write_debug(encoding_str)
else:
write_debug = lambda msg: self._write_string(f'[debug] {msg}')
write_string(encoding_str, encoding=None)
source = detect_variant()
write_debug('yt-dlp version %s%s\n' % (__version__, '' if source == 'unknown' else f' ({source})'))
if _LAZY_LOADER:
write_debug('Lazy loading extractors enabled\n')
if plugin_extractors or plugin_postprocessors:
write_debug('Plugins: %s\n' % [
'%s%s' % (klass.__name__, '' if klass.__name__ == name else f' as {name}')
for name, klass in itertools.chain(plugin_extractors.items(), plugin_postprocessors.items())])
if self.params.get('compat_opts'):
write_debug('Compatibility options: %s\n' % ', '.join(self.params.get('compat_opts')))
try:
sp = Popen(
['git', 'rev-parse', '--short', 'HEAD'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=os.path.dirname(os.path.abspath(__file__)))
out, err = sp.communicate_or_kill()
out = out.decode().strip()
if re.match('[0-9a-f]+', out):
write_debug('Git HEAD: %s\n' % out)
except Exception:
try:
sys.exc_clear()
except Exception:
pass
def python_implementation():
impl_name = platform.python_implementation()
if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'):
return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3]
return impl_name
write_debug('Python version %s (%s %s) - %s\n' % (
platform.python_version(),
python_implementation(),
platform.architecture()[0],
platform_name()))
exe_versions = FFmpegPostProcessor.get_versions(self)
exe_versions['rtmpdump'] = rtmpdump_version()
exe_versions['phantomjs'] = PhantomJSwrapper._version()
exe_str = ', '.join(
f'{exe} {v}' for exe, v in sorted(exe_versions.items()) if v
) or 'none'
write_debug('exe versions: %s\n' % exe_str)
from .downloader.websocket import has_websockets
from .postprocessor.embedthumbnail import has_mutagen
from .cookies import SQLITE_AVAILABLE, KEYRING_AVAILABLE
lib_str = ', '.join(sorted(filter(None, (
compat_pycrypto_AES and compat_pycrypto_AES.__name__.split('.')[0],
has_websockets and 'websockets',
has_mutagen and 'mutagen',
SQLITE_AVAILABLE and 'sqlite',
KEYRING_AVAILABLE and 'keyring',
)))) or 'none'
write_debug('Optional libraries: %s\n' % lib_str)
write_debug('ANSI escape support: stdout = %s, stderr = %s\n' % (
supports_terminal_sequences(self._screen_file),
supports_terminal_sequences(self._err_file)))
proxy_map = {}
for handler in self._opener.handlers:
if hasattr(handler, 'proxies'):
proxy_map.update(handler.proxies)
write_debug('Proxy map: ' + compat_str(proxy_map) + '\n')
if self.params.get('call_home', False):
ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
write_debug('Public IP address: %s\n' % ipaddr)
return
latest_version = self.urlopen(
'https://yt-dl.org/latest/version').read().decode('utf-8')
if version_tuple(latest_version) > version_tuple(__version__):
self.report_warning(
'You are using an outdated version (newest version: %s)! '
'See https://yt-dl.org/update if you need help updating.' %
latest_version)
def _setup_opener(self):
timeout_val = self.params.get('socket_timeout')
self._socket_timeout = 20 if timeout_val is None else float(timeout_val)
opts_cookiesfrombrowser = self.params.get('cookiesfrombrowser')
opts_cookiefile = self.params.get('cookiefile')
opts_proxy = self.params.get('proxy')
self.cookiejar = load_cookies(opts_cookiefile, opts_cookiesfrombrowser, self)
cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
if opts_proxy is not None:
if opts_proxy == '':
proxies = {}
else:
proxies = {'http': opts_proxy, 'https': opts_proxy}
else:
proxies = compat_urllib_request.getproxies()
# Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
if 'http' in proxies and 'https' not in proxies:
proxies['https'] = proxies['http']
proxy_handler = PerRequestProxyHandler(proxies)
debuglevel = 1 if self.params.get('debug_printtraffic') else 0
https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
redirect_handler = YoutubeDLRedirectHandler()
data_handler = compat_urllib_request_DataHandler()
# When passing our own FileHandler instance, build_opener won't add the
# default FileHandler and allows us to disable the file protocol, which
# can be used for malicious purposes (see
# https://github.com/ytdl-org/youtube-dl/issues/8227)
file_handler = compat_urllib_request.FileHandler()
def file_open(*args, **kwargs):
raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in yt-dlp for security reasons')
file_handler.file_open = file_open
opener = compat_urllib_request.build_opener(
proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler)
# Delete the default user-agent header, which would otherwise apply in
# cases where our custom HTTP handler doesn't come into play
# (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
opener.addheaders = []
self._opener = opener
def encode(self, s):
if isinstance(s, bytes):
return s # Already encoded
try:
return s.encode(self.get_encoding())
except UnicodeEncodeError as err:
err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
raise
def get_encoding(self):
encoding = self.params.get('encoding')
if encoding is None:
encoding = preferredencoding()
return encoding
def _write_info_json(self, label, ie_result, infofn):
''' Write infojson and returns True = written, False = skip, None = error '''
if not self.params.get('writeinfojson'):
return False
elif not infofn:
self.write_debug(f'Skipping writing {label} infojson')
return False
elif not self._ensure_dir_exists(infofn):
return None
elif not self.params.get('overwrites', True) and os.path.exists(infofn):
self.to_screen(f'[info] {label.title()} metadata is already present')
else:
self.to_screen(f'[info] Writing {label} metadata as JSON to: {infofn}')
try:
write_json_file(self.sanitize_info(ie_result, self.params.get('clean_infojson', True)), infofn)
except (OSError, IOError):
self.report_error(f'Cannot write {label} metadata to JSON file {infofn}')
return None
return True
def _write_description(self, label, ie_result, descfn):
''' Write description and returns True = written, False = skip, None = error '''
if not self.params.get('writedescription'):
return False
elif not descfn:
self.write_debug(f'Skipping writing {label} description')
return False
elif not self._ensure_dir_exists(descfn):
return None
elif not self.params.get('overwrites', True) and os.path.exists(descfn):
self.to_screen(f'[info] {label.title()} description is already present')
elif ie_result.get('description') is None:
self.report_warning(f'There\'s no {label} description to write')
return False
else:
try:
self.to_screen(f'[info] Writing {label} description to: {descfn}')
with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
descfile.write(ie_result['description'])
except (OSError, IOError):
self.report_error(f'Cannot write {label} description file {descfn}')
return None
return True
def _write_subtitles(self, info_dict, filename):
''' Write subtitles to file and return list of (sub_filename, final_sub_filename); or None if error'''
ret = []
subtitles = info_dict.get('requested_subtitles')
if not subtitles or not (self.params.get('writesubtitles') or self.params.get('writeautomaticsub')):
# subtitles download errors are already managed as troubles in relevant IE
# that way it will silently go on when used with unsupporting IE
return ret
sub_filename_base = self.prepare_filename(info_dict, 'subtitle')
if not sub_filename_base:
self.to_screen('[info] Skipping writing video subtitles')
return ret
for sub_lang, sub_info in subtitles.items():
sub_format = sub_info['ext']
sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
sub_filename_final = subtitles_filename(sub_filename_base, sub_lang, sub_format, info_dict.get('ext'))
if not self.params.get('overwrites', True) and os.path.exists(sub_filename):
self.to_screen(f'[info] Video subtitle {sub_lang}.{sub_format} is already present')
sub_info['filepath'] = sub_filename
ret.append((sub_filename, sub_filename_final))
continue
self.to_screen(f'[info] Writing video subtitles to: {sub_filename}')
if sub_info.get('data') is not None:
try:
# Use newline='' to prevent conversion of newline characters
# See https://github.com/ytdl-org/youtube-dl/issues/10268
with io.open(sub_filename, 'w', encoding='utf-8', newline='') as subfile:
subfile.write(sub_info['data'])
sub_info['filepath'] = sub_filename
ret.append((sub_filename, sub_filename_final))
continue
except (OSError, IOError):
self.report_error(f'Cannot write video subtitles file {sub_filename}')
return None
try:
sub_copy = sub_info.copy()
sub_copy.setdefault('http_headers', info_dict.get('http_headers'))
self.dl(sub_filename, sub_copy, subtitle=True)
sub_info['filepath'] = sub_filename
ret.append((sub_filename, sub_filename_final))
except (ExtractorError, IOError, OSError, ValueError) + network_exceptions as err:
self.report_warning(f'Unable to download video subtitles for {sub_lang!r}: {err}')
continue
return ret
def _write_thumbnails(self, label, info_dict, filename, thumb_filename_base=None):
''' Write thumbnails to file and return list of (thumb_filename, final_thumb_filename) '''
write_all = self.params.get('write_all_thumbnails', False)
thumbnails, ret = [], []
if write_all or self.params.get('writethumbnail', False):
thumbnails = info_dict.get('thumbnails') or []
multiple = write_all and len(thumbnails) > 1
if thumb_filename_base is None:
thumb_filename_base = filename
if thumbnails and not thumb_filename_base:
self.write_debug(f'Skipping writing {label} thumbnail')
return ret
for t in thumbnails[::-1]:
thumb_ext = (f'{t['id']}.' if multiple else '') + determine_ext(t['url'], 'jpg')
thumb_display_id = f'{label} thumbnail' + (f' {t['id']}' if multiple else '')
thumb_filename = replace_extension(filename, thumb_ext, info_dict.get('ext'))
thumb_filename_final = replace_extension(thumb_filename_base, thumb_ext, info_dict.get('ext'))
if not self.params.get('overwrites', True) and os.path.exists(thumb_filename):
ret.append((thumb_filename, thumb_filename_final))
t['filepath'] = thumb_filename
self.to_screen(f'[info] {thumb_display_id.title()} is already present')
else:
self.to_screen(f'[info] Downloading {thumb_display_id} ...')
try:
uf = self.urlopen(t['url'])
self.to_screen(f'[info] Writing {thumb_display_id} to: {thumb_filename}')
with open(encodeFilename(thumb_filename), 'wb') as thumbf:
shutil.copyfileobj(uf, thumbf)
ret.append((thumb_filename, thumb_filename_final))
t['filepath'] = thumb_filename
except network_exceptions as err:
self.report_warning(f'Unable to download {thumb_display_id}: {err}')
if ret and not write_all:
break
return ret
| #!/usr/bin/env python3
# coding: utf-8
from __future__ import absolute_import, unicode_literals
import collections
import contextlib
import copy
import datetime
import errno
import fileinput
import functools
import io
import itertools
import json
import locale
import operator
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import time
import tokenize
import traceback
import random
import unicodedata
from string import ascii_letters
from .compat import (
compat_basestring,
compat_get_terminal_size,
compat_kwargs,
compat_numeric_types,
compat_os_name,
compat_pycrypto_AES,
compat_shlex_quote,
compat_str,
compat_tokenize_tokenize,
compat_urllib_error,
compat_urllib_request,
compat_urllib_request_DataHandler,
windows_enable_vt_mode,
)
from .cookies import load_cookies
from .utils import (
age_restricted,
args_to_str,
ContentTooShortError,
date_from_str,
DateRange,
DEFAULT_OUTTMPL,
determine_ext,
determine_protocol,
DOT_DESKTOP_LINK_TEMPLATE,
DOT_URL_LINK_TEMPLATE,
DOT_WEBLOC_LINK_TEMPLATE,
DownloadError,
encode_compat_str,
encodeFilename,
EntryNotInPlaylist,
error_to_compat_str,
ExistingVideoReached,
expand_path,
ExtractorError,
float_or_none,
format_bytes,
format_field,
formatSeconds,
GeoRestrictedError,
HEADRequest,
int_or_none,
iri_to_uri,
ISO3166Utils,
LazyList,
locked_file,
make_dir,
make_HTTPS_handler,
MaxDownloadsReached,
network_exceptions,
orderedSet,
OUTTMPL_TYPES,
PagedList,
parse_filesize,
PerRequestProxyHandler,
platform_name,
Popen,
PostProcessingError,
preferredencoding,
prepend_extension,
register_socks_protocols,
RejectedVideoReached,
render_table,
replace_extension,
SameFileError,
sanitize_filename,
sanitize_path,
sanitize_url,
sanitized_Request,
std_headers,
STR_FORMAT_RE_TMPL,
STR_FORMAT_TYPES,
str_or_none,
strftime_or_none,
subtitles_filename,
supports_terminal_sequences,
TERMINAL_SEQUENCES,
ThrottledDownload,
to_high_limit_path,
traverse_obj,
try_get,
UnavailableVideoError,
url_basename,
variadic,
version_tuple,
write_json_file,
write_string,
YoutubeDLCookieProcessor,
YoutubeDLHandler,
YoutubeDLRedirectHandler,
)
from .cache import Cache
from .extractor import (
gen_extractor_classes,
get_info_extractor,
_LAZY_LOADER,
_PLUGIN_CLASSES as plugin_extractors
)
from .extractor.openload import PhantomJSwrapper
from .downloader import (
FFmpegFD,
get_suitable_downloader,
shorten_protocol_name
)
from .downloader.rtmp import rtmpdump_version
from .postprocessor import (
get_postprocessor,
EmbedThumbnailPP,
FFmpegFixupDurationPP,
FFmpegFixupM3u8PP,
FFmpegFixupM4aPP,
FFmpegFixupStretchedPP,
FFmpegFixupTimestampPP,
FFmpegMergerPP,
FFmpegPostProcessor,
MoveFilesAfterDownloadPP,
_PLUGIN_CLASSES as plugin_postprocessors
)
from .update import detect_variant
from .version import __version__
if compat_os_name == 'nt':
import ctypes
class YoutubeDL(object):
"""YoutubeDL class.
YoutubeDL objects are the ones responsible of downloading the
actual video file and writing it to disk if the user has requested
it, among some other tasks. In most cases there should be one per
program. As, given a video URL, the downloader doesn't know how to
extract all the needed information, task that InfoExtractors do, it
has to pass the URL to one of them.
For this, YoutubeDL objects have a method that allows
InfoExtractors to be registered in a given order. When it is passed
a URL, the YoutubeDL object handles it to the first InfoExtractor it
finds that reports being able to handle it. The InfoExtractor extracts
all the information about the video or videos the URL refers to, and
YoutubeDL process the extracted information, possibly using a File
Downloader to download the video.
YoutubeDL objects accept a lot of parameters. In order not to saturate
the object constructor with arguments, it receives a dictionary of
options instead. These options are available through the params
attribute for the InfoExtractors to use. The YoutubeDL also
registers itself as the downloader in charge for the InfoExtractors
that are added to it, so this is a "mutual registration".
Available options:
username: Username for authentication purposes.
password: Password for authentication purposes.
videopassword: Password for accessing a video.
ap_mso: Adobe Pass multiple-system operator identifier.
ap_username: Multiple-system operator account username.
ap_password: Multiple-system operator account password.
usenetrc: Use netrc for authentication instead.
verbose: Print additional info to stdout.
quiet: Do not print messages to stdout.
no_warnings: Do not print out anything for warnings.
forceprint: A list of templates to force print
forceurl: Force printing final URL. (Deprecated)
forcetitle: Force printing title. (Deprecated)
forceid: Force printing ID. (Deprecated)
forcethumbnail: Force printing thumbnail URL. (Deprecated)
forcedescription: Force printing description. (Deprecated)
forcefilename: Force printing final filename. (Deprecated)
forceduration: Force printing duration. (Deprecated)
forcejson: Force printing info_dict as JSON.
dump_single_json: Force printing the info_dict of the whole playlist
(or video) as a single JSON line.
force_write_download_archive: Force writing download archive regardless
of 'skip_download' or 'simulate'.
simulate: Do not download the video files. If unset (or None),
simulate only if listsubtitles, listformats or list_thumbnails is used
format: Video format code. see "FORMAT SELECTION" for more details.
allow_unplayable_formats: Allow unplayable formats to be extracted and downloaded.
ignore_no_formats_error: Ignore "No video formats" error. Usefull for
extracting metadata even if the video is not actually
available for download (experimental)
format_sort: How to sort the video formats. see "Sorting Formats"
for more details.
format_sort_force: Force the given format_sort. see "Sorting Formats"
for more details.
allow_multiple_video_streams: Allow multiple video streams to be merged
into a single file
allow_multiple_audio_streams: Allow multiple audio streams to be merged
into a single file
check_formats Whether to test if the formats are downloadable.
Can be True (check all), False (check none)
or None (check only if requested by extractor)
paths: Dictionary of output paths. The allowed keys are 'home'
'temp' and the keys of OUTTMPL_TYPES (in utils.py)
outtmpl: Dictionary of templates for output names. Allowed keys
are 'default' and the keys of OUTTMPL_TYPES (in utils.py).
For compatibility with youtube-dl, a single string can also be used
outtmpl_na_placeholder: Placeholder for unavailable meta fields.
restrictfilenames: Do not allow "&" and spaces in file names
trim_file_name: Limit length of filename (extension excluded)
windowsfilenames: Force the filenames to be windows compatible
ignoreerrors: Do not stop on download/postprocessing errors.
Can be 'only_download' to ignore only download errors.
Default is 'only_download' for CLI, but False for API
skip_playlist_after_errors: Number of allowed failures until the rest of
the playlist is skipped
force_generic_extractor: Force downloader to use the generic extractor
overwrites: Overwrite all video and metadata files if True,
overwrite only non-video files if None
and don't overwrite any file if False
For compatibility with youtube-dl,
"nooverwrites" may also be used instead
playliststart: Playlist item to start at.
playlistend: Playlist item to end at.
playlist_items: Specific indices of playlist to download.
playlistreverse: Download playlist items in reverse order.
playlistrandom: Download playlist items in random order.
matchtitle: Download only matching titles.
rejecttitle: Reject downloads for matching titles.
logger: Log messages to a logging.Logger instance.
logtostderr: Log messages to stderr instead of stdout.
consoletitle: Display progress in console window's titlebar.
writedescription: Write the video description to a .description file
writeinfojson: Write the video description to a .info.json file
clean_infojson: Remove private fields from the infojson
getcomments: Extract video comments. This will not be written to disk
unless writeinfojson is also given
writeannotations: Write the video annotations to a .annotations.xml file
writethumbnail: Write the thumbnail image to a file
allow_playlist_files: Whether to write playlists' description, infojson etc
also to disk when using the 'write*' options
write_all_thumbnails: Write all thumbnail formats to files
writelink: Write an internet shortcut file, depending on the
current platform (.url/.webloc/.desktop)
writeurllink: Write a Windows internet shortcut file (.url)
writewebloclink: Write a macOS internet shortcut file (.webloc)
writedesktoplink: Write a Linux internet shortcut file (.desktop)
writesubtitles: Write the video subtitles to a file
writeautomaticsub: Write the automatically generated subtitles to a file
allsubtitles: Deprecated - Use subtitleslangs = ['all']
Downloads all the subtitles of the video
(requires writesubtitles or writeautomaticsub)
listsubtitles: Lists all available subtitles for the video
subtitlesformat: The format code for subtitles
subtitleslangs: List of languages of the subtitles to download (can be regex).
The list may contain "all" to refer to all the available
subtitles. The language can be prefixed with a "-" to
exclude it from the requested languages. Eg: ['all', '-live_chat']
keepvideo: Keep the video file after post-processing
daterange: A DateRange object, download only if the upload_date is in the range.
skip_download: Skip the actual download of the video file
cachedir: Location of the cache files in the filesystem.
False to disable filesystem cache.
noplaylist: Download single video instead of a playlist if in doubt.
age_limit: An integer representing the user's age in years.
Unsuitable videos for the given age are skipped.
min_views: An integer representing the minimum view count the video
must have in order to not be skipped.
Videos without view count information are always
downloaded. None for no limit.
max_views: An integer representing the maximum view count.
Videos that are more popular than that are not
downloaded.
Videos without view count information are always
downloaded. None for no limit.
download_archive: File name of a file where all downloads are recorded.
Videos already present in the file are not downloaded
again.
break_on_existing: Stop the download process after attempting to download a
file that is in the archive.
break_on_reject: Stop the download process when encountering a video that
has been filtered out.
cookiefile: File name where cookies should be read from and dumped to
cookiesfrombrowser: A tuple containing the name of the browser and the profile
name/path from where cookies are loaded.
Eg: ('chrome', ) or (vivaldi, 'default')
nocheckcertificate:Do not verify SSL certificates
prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
At the moment, this is only supported by YouTube.
proxy: URL of the proxy server to use
geo_verification_proxy: URL of the proxy to use for IP address verification
on geo-restricted sites.
socket_timeout: Time to wait for unresponsive hosts, in seconds
bidi_workaround: Work around buggy terminals without bidirectional text
support, using fridibi
debug_printtraffic:Print out sent and received HTTP traffic
include_ads: Download ads as well
default_search: Prepend this string if an input url is not valid.
'auto' for elaborate guessing
encoding: Use this encoding instead of the system-specified.
extract_flat: Do not resolve URLs, return the immediate result.
Pass in 'in_playlist' to only show this behavior for
playlist items.
postprocessors: A list of dictionaries, each with an entry
* key: The name of the postprocessor. See
yt_dlp/postprocessor/__init__.py for a list.
* when: When to run the postprocessor. Can be one of
pre_process|before_dl|post_process|after_move.
Assumed to be 'post_process' if not given
post_hooks: Deprecated - Register a custom postprocessor instead
A list of functions that get called as the final step
for each video file, after all postprocessors have been
called. The filename will be passed as the only argument.
progress_hooks: A list of functions that get called on download
progress, with a dictionary with the entries
* status: One of "downloading", "error", or "finished".
Check this first and ignore unknown values.
* info_dict: The extracted info_dict
If status is one of "downloading", or "finished", the
following properties may also be present:
* filename: The final filename (always present)
* tmpfilename: The filename we're currently writing to
* downloaded_bytes: Bytes on disk
* total_bytes: Size of the whole file, None if unknown
* total_bytes_estimate: Guess of the eventual file size,
None if unavailable.
* elapsed: The number of seconds since download started.
* eta: The estimated time in seconds, None if unknown
* speed: The download speed in bytes/second, None if
unknown
* fragment_index: The counter of the currently
downloaded video fragment.
* fragment_count: The number of fragments (= individual
files that will be merged)
Progress hooks are guaranteed to be called at least once
(with status "finished") if the download is successful.
postprocessor_hooks: A list of functions that get called on postprocessing
progress, with a dictionary with the entries
* status: One of "started", "processing", or "finished".
Check this first and ignore unknown values.
* postprocessor: Name of the postprocessor
* info_dict: The extracted info_dict
Progress hooks are guaranteed to be called at least twice
(with status "started" and "finished") if the processing is successful.
merge_output_format: Extension to use when merging formats.
final_ext: Expected final extension; used to detect when the file was
already downloaded and converted. "merge_output_format" is
replaced by this extension when given
fixup: Automatically correct known faults of the file.
One of:
- "never": do nothing
- "warn": only emit a warning
- "detect_or_warn": check whether we can do anything
about it, warn otherwise (default)
source_address: Client-side IP address to bind to.
call_home: Boolean, true iff we are allowed to contact the
yt-dlp servers for debugging. (BROKEN)
sleep_interval_requests: Number of seconds to sleep between requests
during extraction
sleep_interval: Number of seconds to sleep before each download when
used alone or a lower bound of a range for randomized
sleep before each download (minimum possible number
of seconds to sleep) when used along with
max_sleep_interval.
max_sleep_interval:Upper bound of a range for randomized sleep before each
download (maximum possible number of seconds to sleep).
Must only be used along with sleep_interval.
Actual sleep time will be a random float from range
[sleep_interval; max_sleep_interval].
sleep_interval_subtitles: Number of seconds to sleep before each subtitle download
listformats: Print an overview of available video formats and exit.
list_thumbnails: Print a table of all thumbnails and exit.
match_filter: A function that gets called with the info_dict of
every video.
If it returns a message, the video is ignored.
If it returns None, the video is downloaded.
match_filter_func in utils.py is one example for this.
no_color: Do not emit color codes in output.
geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
HTTP header
geo_bypass_country:
Two-letter ISO 3166-2 country code that will be used for
explicit geographic restriction bypassing via faking
X-Forwarded-For HTTP header
geo_bypass_ip_block:
IP range in CIDR notation that will be used similarly to
geo_bypass_country
The following options determine which downloader is picked:
external_downloader: A dictionary of protocol keys and the executable of the
external downloader to use for it. The allowed protocols
are default|http|ftp|m3u8|dash|rtsp|rtmp|mms.
Set the value to 'native' to use the native downloader
hls_prefer_native: Deprecated - Use external_downloader = {'m3u8': 'native'}
or {'m3u8': 'ffmpeg'} instead.
Use the native HLS downloader instead of ffmpeg/avconv
if True, otherwise use ffmpeg/avconv if False, otherwise
use downloader suggested by extractor if None.
compat_opts: Compatibility options. See "Differences in default behavior".
The following options do not work when used through the API:
filename, abort-on-error, multistreams, no-live-chat, format-sort
no-clean-infojson, no-playlist-metafiles, no-keep-subs.
Refer __init__.py for their implementation
progress_template: Dictionary of templates for progress outputs.
Allowed keys are 'download', 'postprocess',
'download-title' (console title) and 'postprocess-title'.
The template is mapped on a dictionary with keys 'progress' and 'info'
The following parameters are not used by YoutubeDL itself, they are used by
the downloader (see yt_dlp/downloader/common.py):
nopart, updatetime, buffersize, ratelimit, throttledratelimit, min_filesize,
max_filesize, test, noresizebuffer, retries, fragment_retries, continuedl,
noprogress, xattr_set_filesize, hls_use_mpegts, http_chunk_size,
external_downloader_args.
The following options are used by the post processors:
prefer_ffmpeg: If False, use avconv instead of ffmpeg if both are available,
otherwise prefer ffmpeg. (avconv support is deprecated)
ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
to the binary or its containing directory.
postprocessor_args: A dictionary of postprocessor/executable keys (in lower case)
and a list of additional command-line arguments for the
postprocessor/executable. The dict can also have "PP+EXE" keys
which are used when the given exe is used by the given PP.
Use 'default' as the name for arguments to passed to all PP
For compatibility with youtube-dl, a single list of args
can also be used
The following options are used by the extractors:
extractor_retries: Number of times to retry for known errors
dynamic_mpd: Whether to process dynamic DASH manifests (default: True)
hls_split_discontinuity: Split HLS playlists to different formats at
discontinuities such as ad breaks (default: False)
extractor_args: A dictionary of arguments to be passed to the extractors.
See "EXTRACTOR ARGUMENTS" for details.
Eg: {'youtube': {'skip': ['dash', 'hls']}}
youtube_include_dash_manifest: Deprecated - Use extractor_args instead.
If True (default), DASH manifests and related
data will be downloaded and processed by extractor.
You can reduce network I/O by disabling it if you don't
care about DASH. (only for youtube)
youtube_include_hls_manifest: Deprecated - Use extractor_args instead.
If True (default), HLS manifests and related
data will be downloaded and processed by extractor.
You can reduce network I/O by disabling it if you don't
care about HLS. (only for youtube)
"""
_NUMERIC_FIELDS = set((
'width', 'height', 'tbr', 'abr', 'asr', 'vbr', 'fps', 'filesize', 'filesize_approx',
'timestamp', 'release_timestamp',
'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
'average_rating', 'comment_count', 'age_limit',
'start_time', 'end_time',
'chapter_number', 'season_number', 'episode_number',
'track_number', 'disc_number', 'release_year',
))
_format_selection_exts = {
'audio': {'m4a', 'mp3', 'ogg', 'aac'},
'video': {'mp4', 'flv', 'webm', '3gp'},
'storyboards': {'mhtml'},
}
params = None
_ies = {}
_pps = {'pre_process': [], 'before_dl': [], 'after_move': [], 'post_process': []}
_printed_messages = set()
_first_webpage_request = True
_download_retcode = None
_num_downloads = None
_playlist_level = 0
_playlist_urls = set()
_screen_file = None
def __init__(self, params=None, auto_init=True):
"""Create a FileDownloader object with the given options.
@param auto_init Whether to load the default extractors and print header (if verbose).
Set to 'no_verbose_header' to not ptint the header
"""
if params is None:
params = {}
self._ies = {}
self._ies_instances = {}
self._pps = {'pre_process': [], 'before_dl': [], 'after_move': [], 'post_process': []}
self._printed_messages = set()
self._first_webpage_request = True
self._post_hooks = []
self._progress_hooks = []
self._postprocessor_hooks = []
self._download_retcode = 0
self._num_downloads = 0
self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
self._err_file = sys.stderr
self.params = params
self.cache = Cache(self)
windows_enable_vt_mode()
# FIXME: This will break if we ever print color to stdout
self.params['no_color'] = self.params.get('no_color') or not supports_terminal_sequences(self._err_file)
if sys.version_info < (3, 6):
self.report_warning(
'Python version %d.%d is not supported! Please update to Python 3.6 or above' % sys.version_info[:2])
if self.params.get('allow_unplayable_formats'):
self.report_warning(
f'You have asked for {self._color_text("unplayable formats", "blue")} to be listed/downloaded. '
'This is a developer option intended for debugging. \n'
' If you experience any issues while using this option, '
f'{self._color_text("DO NOT", "red")} open a bug report')
def check_deprecated(param, option, suggestion):
if self.params.get(param) is not None:
self.report_warning('%s is deprecated. Use %s instead' % (option, suggestion))
return True
return False
if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
if self.params.get('geo_verification_proxy') is None:
self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
check_deprecated('useid', '--id', '-o "%(id)s.%(ext)s"')
for msg in self.params.get('warnings', []):
self.report_warning(msg)
if 'overwrites' not in self.params and self.params.get('nooverwrites') is not None:
# nooverwrites was unnecessarily changed to overwrites
# in 0c3d0f51778b153f65c21906031c2e091fcfb641
# This ensures compatibility with both keys
self.params['overwrites'] = not self.params['nooverwrites']
elif self.params.get('overwrites') is None:
self.params.pop('overwrites', None)
else:
self.params['nooverwrites'] = not self.params['overwrites']
if params.get('bidi_workaround', False):
try:
import pty
master, slave = pty.openpty()
width = compat_get_terminal_size().columns
if width is None:
width_args = []
else:
width_args = ['-w', str(width)]
sp_kwargs = dict(
stdin=subprocess.PIPE,
stdout=slave,
stderr=self._err_file)
try:
self._output_process = Popen(['bidiv'] + width_args, **sp_kwargs)
except OSError:
self._output_process = Popen(['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
self._output_channel = os.fdopen(master, 'rb')
except OSError as ose:
if ose.errno == errno.ENOENT:
self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
else:
raise
if (sys.platform != 'win32'
and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
and not params.get('restrictfilenames', False)):
# Unicode filesystem API will throw errors (#1474, #13027)
self.report_warning(
'Assuming --restrict-filenames since file system encoding '
'cannot encode all characters. '
'Set the LC_ALL environment variable to fix this.')
self.params['restrictfilenames'] = True
self.outtmpl_dict = self.parse_outtmpl()
# Creating format selector here allows us to catch syntax errors before the extraction
self.format_selector = (
None if self.params.get('format') is None
else self.build_format_selector(self.params['format']))
self._setup_opener()
if auto_init:
if auto_init != 'no_verbose_header':
self.print_debug_header()
self.add_default_info_extractors()
for pp_def_raw in self.params.get('postprocessors', []):
pp_def = dict(pp_def_raw)
when = pp_def.pop('when', 'post_process')
pp_class = get_postprocessor(pp_def.pop('key'))
pp = pp_class(self, **compat_kwargs(pp_def))
self.add_post_processor(pp, when=when)
for ph in self.params.get('post_hooks', []):
self.add_post_hook(ph)
for ph in self.params.get('progress_hooks', []):
self.add_progress_hook(ph)
register_socks_protocols()
def preload_download_archive(fn):
"""Preload the archive, if any is specified"""
if fn is None:
return False
self.write_debug('Loading archive file %r\n' % fn)
try:
with locked_file(fn, 'r', encoding='utf-8') as archive_file:
for line in archive_file:
self.archive.add(line.strip())
except IOError as ioe:
if ioe.errno != errno.ENOENT:
raise
return False
return True
self.archive = set()
preload_download_archive(self.params.get('download_archive'))
def warn_if_short_id(self, argv):
# short YouTube ID starting with dash?
idxs = [
i for i, a in enumerate(argv)
if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
if idxs:
correct_argv = (
['yt-dlp']
+ [a for i, a in enumerate(argv) if i not in idxs]
+ ['--'] + [argv[i] for i in idxs]
)
self.report_warning(
'Long argument string detected. '
'Use -- to separate parameters and URLs, like this:\n%s\n' %
args_to_str(correct_argv))
def add_info_extractor(self, ie):
"""Add an InfoExtractor object to the end of the list."""
ie_key = ie.ie_key()
self._ies[ie_key] = ie
if not isinstance(ie, type):
self._ies_instances[ie_key] = ie
ie.set_downloader(self)
def _get_info_extractor_class(self, ie_key):
ie = self._ies.get(ie_key)
if ie is None:
ie = get_info_extractor(ie_key)
self.add_info_extractor(ie)
return ie
def get_info_extractor(self, ie_key):
"""
Get an instance of an IE with name ie_key, it will try to get one from
the _ies list, if there's no instance it will create a new one and add
it to the extractor list.
"""
ie = self._ies_instances.get(ie_key)
if ie is None:
ie = get_info_extractor(ie_key)()
self.add_info_extractor(ie)
return ie
def add_default_info_extractors(self):
"""
Add the InfoExtractors returned by gen_extractors to the end of the list
"""
for ie in gen_extractor_classes():
self.add_info_extractor(ie)
def add_post_processor(self, pp, when='post_process'):
"""Add a PostProcessor object to the end of the chain."""
self._pps[when].append(pp)
pp.set_downloader(self)
def add_post_hook(self, ph):
"""Add the post hook"""
self._post_hooks.append(ph)
def add_progress_hook(self, ph):
"""Add the download progress hook"""
self._progress_hooks.append(ph)
def add_postprocessor_hook(self, ph):
"""Add the postprocessing progress hook"""
self._postprocessor_hooks.append(ph)
def _bidi_workaround(self, message):
if not hasattr(self, '_output_channel'):
return message
assert hasattr(self, '_output_process')
assert isinstance(message, compat_str)
line_count = message.count('\n') + 1
self._output_process.stdin.write((message + '\n').encode('utf-8'))
self._output_process.stdin.flush()
res = ''.join(self._output_channel.readline().decode('utf-8')
for _ in range(line_count))
return res[:-len('\n')]
def _write_string(self, message, out=None, only_once=False):
if only_once:
if message in self._printed_messages:
return
self._printed_messages.add(message)
write_string(message, out=out, encoding=self.params.get('encoding'))
def to_stdout(self, message, skip_eol=False, quiet=False):
"""Print message to stdout"""
if self.params.get('logger'):
self.params['logger'].debug(message)
elif not quiet or self.params.get('verbose'):
self._write_string(
'%s%s' % (self._bidi_workaround(message), ('' if skip_eol else '\n')),
self._err_file if quiet else self._screen_file)
def to_stderr(self, message, only_once=False):
"""Print message to stderr"""
assert isinstance(message, compat_str)
if self.params.get('logger'):
self.params['logger'].error(message)
else:
self._write_string('%s\n' % self._bidi_workaround(message), self._err_file, only_once=only_once)
def to_console_title(self, message):
if not self.params.get('consoletitle', False):
return
if compat_os_name == 'nt':
if ctypes.windll.kernel32.GetConsoleWindow():
# c_wchar_p() might not be necessary if `message` is
# already of type unicode()
ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
elif 'TERM' in os.environ:
self._write_string('\033]0;%s\007' % message, self._screen_file)
def save_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate'):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
# Save the title on stack
self._write_string('\033[22;0t', self._screen_file)
def restore_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate'):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
# Restore the title from stack
self._write_string('\033[23;0t', self._screen_file)
def __enter__(self):
self.save_console_title()
return self
def __exit__(self, *args):
self.restore_console_title()
if self.params.get('cookiefile') is not None:
self.cookiejar.save(ignore_discard=True, ignore_expires=True)
def trouble(self, message=None, tb=None):
"""Determine action to take when a download problem appears.
Depending on if the downloader has been configured to ignore
download errors or not, this method may throw an exception or
not when errors are found, after printing the message.
tb, if given, is additional traceback information.
"""
if message is not None:
self.to_stderr(message)
if self.params.get('verbose'):
if tb is None:
if sys.exc_info()[0]: # if .trouble has been called from an except block
tb = ''
if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
tb += encode_compat_str(traceback.format_exc())
else:
tb_data = traceback.format_list(traceback.extract_stack())
tb = ''.join(tb_data)
if tb:
self.to_stderr(tb)
if not self.params.get('ignoreerrors'):
if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
exc_info = sys.exc_info()[1].exc_info
else:
exc_info = sys.exc_info()
raise DownloadError(message, exc_info)
self._download_retcode = 1
def to_screen(self, message, skip_eol=False):
"""Print message to stdout if not in quiet mode"""
self.to_stdout(
message, skip_eol, quiet=self.params.get('quiet', False))
def _color_text(self, text, color):
if self.params.get('no_color'):
return text
return f'{TERMINAL_SEQUENCES[color.upper()]}{text}{TERMINAL_SEQUENCES["RESET_STYLE"]}'
def report_warning(self, message, only_once=False):
'''
Print the message to stderr, it will be prefixed with 'WARNING:'
If stderr is a tty file the 'WARNING:' will be colored
'''
if self.params.get('logger') is not None:
self.params['logger'].warning(message)
else:
if self.params.get('no_warnings'):
return
self.to_stderr(f'{self._color_text("WARNING:", "yellow")} {message}', only_once)
def report_error(self, message, tb=None):
'''
Do the same as trouble, but prefixes the message with 'ERROR:', colored
in red if stderr is a tty file.
'''
self.trouble(f'{self._color_text("ERROR:", "red")} {message}', tb)
def write_debug(self, message, only_once=False):
'''Log debug message or Print message to stderr'''
if not self.params.get('verbose', False):
return
message = '[debug] %s' % message
if self.params.get('logger'):
self.params['logger'].debug(message)
else:
self.to_stderr(message, only_once)
def report_file_already_downloaded(self, file_name):
"""Report file has already been fully downloaded."""
try:
self.to_screen('[download] %s has already been downloaded' % file_name)
except UnicodeEncodeError:
self.to_screen('[download] The file has already been downloaded')
def report_file_delete(self, file_name):
"""Report that existing file will be deleted."""
try:
self.to_screen('Deleting existing file %s' % file_name)
except UnicodeEncodeError:
self.to_screen('Deleting existing file')
def raise_no_formats(self, info, forced=False):
has_drm = info.get('__has_drm')
msg = 'This video is DRM protected' if has_drm else 'No video formats found!'
expected = self.params.get('ignore_no_formats_error')
if forced or not expected:
raise ExtractorError(msg, video_id=info['id'], ie=info['extractor'],
expected=has_drm or expected)
else:
self.report_warning(msg)
def parse_outtmpl(self):
outtmpl_dict = self.params.get('outtmpl', {})
if not isinstance(outtmpl_dict, dict):
outtmpl_dict = {'default': outtmpl_dict}
# Remove spaces in the default template
if self.params.get('restrictfilenames'):
sanitize = lambda x: x.replace(' - ', ' ').replace(' ', '-')
else:
sanitize = lambda x: x
outtmpl_dict.update({
k: sanitize(v) for k, v in DEFAULT_OUTTMPL.items()
if outtmpl_dict.get(k) is None})
for key, val in outtmpl_dict.items():
if isinstance(val, bytes):
self.report_warning(
'Parameter outtmpl is bytes, but should be a unicode string. '
'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
return outtmpl_dict
def get_output_path(self, dir_type='', filename=None):
paths = self.params.get('paths', {})
assert isinstance(paths, dict)
path = os.path.join(
expand_path(paths.get('home', '').strip()),
expand_path(paths.get(dir_type, '').strip()) if dir_type else '',
filename or '')
# Temporary fix for #4787
# 'Treat' all problem characters by passing filename through preferredencoding
# to workaround encoding issues with subprocess on python2 @ Windows
if sys.version_info < (3, 0) and sys.platform == 'win32':
path = encodeFilename(path, True).decode(preferredencoding())
return sanitize_path(path, force=self.params.get('windowsfilenames'))
@staticmethod
def _outtmpl_expandpath(outtmpl):
# expand_path translates '%%' into '%' and '$$' into '$'
# correspondingly that is not what we want since we need to keep
# '%%' intact for template dict substitution step. Working around
# with boundary-alike separator hack.
sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep))
# outtmpl should be expand_path'ed before template dict substitution
# because meta fields may contain env variables we don't want to
# be expanded. For example, for outtmpl "%(title)s.%(ext)s" and
# title "Hello $PATH", we don't want `$PATH` to be expanded.
return expand_path(outtmpl).replace(sep, '')
@staticmethod
def escape_outtmpl(outtmpl):
''' Escape any remaining strings like %s, %abc% etc. '''
return re.sub(
STR_FORMAT_RE_TMPL.format('', '(?![%(\0])'),
lambda mobj: ('' if mobj.group('has_key') else '%') + mobj.group(0),
outtmpl)
@classmethod
def validate_outtmpl(cls, outtmpl):
''' @return None or Exception object '''
outtmpl = re.sub(
STR_FORMAT_RE_TMPL.format('[^)]*', '[ljqBU]'),
lambda mobj: f'{mobj.group(0)[:-1]}s',
cls._outtmpl_expandpath(outtmpl))
try:
cls.escape_outtmpl(outtmpl) % collections.defaultdict(int)
return None
except ValueError as err:
return err
@staticmethod
def _copy_infodict(info_dict):
info_dict = dict(info_dict)
for key in ('__original_infodict', '__postprocessors'):
info_dict.pop(key, None)
return info_dict
def prepare_outtmpl(self, outtmpl, info_dict, sanitize=None):
""" Make the outtmpl and info_dict suitable for substitution: ydl.escape_outtmpl(outtmpl) % info_dict """
info_dict.setdefault('epoch', int(time.time())) # keep epoch consistent once set
info_dict = self._copy_infodict(info_dict)
info_dict['duration_string'] = ( # %(duration>%H-%M-%S)s is wrong if duration > 24hrs
formatSeconds(info_dict['duration'], '-' if sanitize else ':')
if info_dict.get('duration', None) is not None
else None)
info_dict['autonumber'] = self.params.get('autonumber_start', 1) - 1 + self._num_downloads
if info_dict.get('resolution') is None:
info_dict['resolution'] = self.format_resolution(info_dict, default=None)
# For fields playlist_index, playlist_autonumber and autonumber convert all occurrences
# of %(field)s to %(field)0Nd for backward compatibility
field_size_compat_map = {
'playlist_index': len(str(info_dict.get('_last_playlist_index') or '')),
'playlist_autonumber': len(str(info_dict.get('n_entries') or '')),
'autonumber': self.params.get('autonumber_size') or 5,
}
TMPL_DICT = {}
EXTERNAL_FORMAT_RE = re.compile(STR_FORMAT_RE_TMPL.format('[^)]*', f'[{STR_FORMAT_TYPES}ljqBU]'))
MATH_FUNCTIONS = {
'+': float.__add__,
'-': float.__sub__,
}
# Field is of the form key1.key2...
# where keys (except first) can be string, int or slice
FIELD_RE = r'\w*(?:\.(?:\w+|{num}|{num}?(?::{num}?){{1,2}}))*'.format(num=r'(?:-?\d+)')
MATH_FIELD_RE = r'''{field}|{num}'''.format(field=FIELD_RE, num=r'-?\d+(?:.\d+)?')
MATH_OPERATORS_RE = r'(?:%s)' % '|'.join(map(re.escape, MATH_FUNCTIONS.keys()))
INTERNAL_FORMAT_RE = re.compile(r'''(?x)
(?P<negate>-)?
(?P<fields>{field})
(?P<maths>(?:{math_op}{math_field})*)
(?:>(?P<strf_format>.+?))?
(?P<alternate>(?<!\\),[^|)]+)?
(?:\|(?P<default>.*?))?
$'''.format(field=FIELD_RE, math_op=MATH_OPERATORS_RE, math_field=MATH_FIELD_RE))
def _traverse_infodict(k):
k = k.split('.')
if k[0] == '':
k.pop(0)
return traverse_obj(info_dict, k, is_user_input=True, traverse_string=True)
def get_value(mdict):
# Object traversal
value = _traverse_infodict(mdict['fields'])
# Negative
if mdict['negate']:
value = float_or_none(value)
if value is not None:
value *= -1
# Do maths
offset_key = mdict['maths']
if offset_key:
value = float_or_none(value)
operator = None
while offset_key:
item = re.match(
MATH_FIELD_RE if operator else MATH_OPERATORS_RE,
offset_key).group(0)
offset_key = offset_key[len(item):]
if operator is None:
operator = MATH_FUNCTIONS[item]
continue
item, multiplier = (item[1:], -1) if item[0] == '-' else (item, 1)
offset = float_or_none(item)
if offset is None:
offset = float_or_none(_traverse_infodict(item))
try:
value = operator(value, multiplier * offset)
except (TypeError, ZeroDivisionError):
return None
operator = None
# Datetime formatting
if mdict['strf_format']:
value = strftime_or_none(value, mdict['strf_format'].replace('\\,', ','))
return value
na = self.params.get('outtmpl_na_placeholder', 'NA')
def _dumpjson_default(obj):
if isinstance(obj, (set, LazyList)):
return list(obj)
raise TypeError(f'Object of type {type(obj).__name__} is not JSON serializable')
def create_key(outer_mobj):
if not outer_mobj.group('has_key'):
return outer_mobj.group(0)
key = outer_mobj.group('key')
mobj = re.match(INTERNAL_FORMAT_RE, key)
initial_field = mobj.group('fields').split('.')[-1] if mobj else ''
value, default = None, na
while mobj:
mobj = mobj.groupdict()
default = mobj['default'] if mobj['default'] is not None else default
value = get_value(mobj)
if value is None and mobj['alternate']:
mobj = re.match(INTERNAL_FORMAT_RE, mobj['alternate'][1:])
else:
break
fmt = outer_mobj.group('format')
if fmt == 's' and value is not None and key in field_size_compat_map.keys():
fmt = '0{:d}d'.format(field_size_compat_map[key])
value = default if value is None else value
str_fmt = f'{fmt[:-1]}s'
if fmt[-1] == 'l': # list
delim = '\n' if '#' in (outer_mobj.group('conversion') or '') else ', '
value, fmt = delim.join(variadic(value)), str_fmt
elif fmt[-1] == 'j': # json
value, fmt = json.dumps(value, default=_dumpjson_default), str_fmt
elif fmt[-1] == 'q': # quoted
value, fmt = compat_shlex_quote(str(value)), str_fmt
elif fmt[-1] == 'B': # bytes
value = f'%{str_fmt}'.encode('utf-8') % str(value).encode('utf-8')
value, fmt = value.decode('utf-8', 'ignore'), 's'
elif fmt[-1] == 'U': # unicode normalized
opts = outer_mobj.group('conversion') or ''
value, fmt = unicodedata.normalize(
# "+" = compatibility equivalence, "#" = NFD
'NF%s%s' % ('K' if '+' in opts else '', 'D' if '#' in opts else 'C'),
value), str_fmt
elif fmt[-1] == 'c':
if value:
value = str(value)[0]
else:
fmt = str_fmt
elif fmt[-1] not in 'rs': # numeric
value = float_or_none(value)
if value is None:
value, fmt = default, 's'
if sanitize:
if fmt[-1] == 'r':
# If value is an object, sanitize might convert it to a string
# So we convert it to repr first
value, fmt = repr(value), str_fmt
if fmt[-1] in 'csr':
value = sanitize(initial_field, value)
key = '%s\0%s' % (key.replace('%', '%\0'), outer_mobj.group('format'))
TMPL_DICT[key] = value
return '{prefix}%({key}){fmt}'.format(key=key, fmt=fmt, prefix=outer_mobj.group('prefix'))
return EXTERNAL_FORMAT_RE.sub(create_key, outtmpl), TMPL_DICT
def evaluate_outtmpl(self, outtmpl, info_dict, *args, **kwargs):
outtmpl, info_dict = self.prepare_outtmpl(outtmpl, info_dict, *args, **kwargs)
return self.escape_outtmpl(outtmpl) % info_dict
def _prepare_filename(self, info_dict, tmpl_type='default'):
try:
sanitize = lambda k, v: sanitize_filename(
compat_str(v),
restricted=self.params.get('restrictfilenames'),
is_id=(k == 'id' or k.endswith('_id')))
outtmpl = self._outtmpl_expandpath(self.outtmpl_dict.get(tmpl_type, self.outtmpl_dict['default']))
filename = self.evaluate_outtmpl(outtmpl, info_dict, sanitize)
force_ext = OUTTMPL_TYPES.get(tmpl_type)
if filename and force_ext is not None:
filename = replace_extension(filename, force_ext, info_dict.get('ext'))
# https://github.com/blackjack4494/youtube-dlc/issues/85
trim_file_name = self.params.get('trim_file_name', False)
if trim_file_name:
fn_groups = filename.rsplit('.')
ext = fn_groups[-1]
sub_ext = ''
if len(fn_groups) > 2:
sub_ext = fn_groups[-2]
filename = '.'.join(filter(None, [fn_groups[0][:trim_file_name], sub_ext, ext]))
return filename
except ValueError as err:
self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
return None
def prepare_filename(self, info_dict, dir_type='', warn=False):
"""Generate the output filename."""
filename = self._prepare_filename(info_dict, dir_type or 'default')
if not filename and dir_type not in ('', 'temp'):
return ''
if warn:
if not self.params.get('paths'):
pass
elif filename == '-':
self.report_warning('--paths is ignored when an outputting to stdout', only_once=True)
elif os.path.isabs(filename):
self.report_warning('--paths is ignored since an absolute path is given in output template', only_once=True)
if filename == '-' or not filename:
return filename
return self.get_output_path(dir_type, filename)
def _match_entry(self, info_dict, incomplete=False, silent=False):
""" Returns None if the file should be downloaded """
video_title = info_dict.get('title', info_dict.get('id', 'video'))
def check_filter():
if 'title' in info_dict:
# This can happen when we're just evaluating the playlist
title = info_dict['title']
matchtitle = self.params.get('matchtitle', False)
if matchtitle:
if not re.search(matchtitle, title, re.IGNORECASE):
return '"' + title + '" title did not match pattern "' + matchtitle + '"'
rejecttitle = self.params.get('rejecttitle', False)
if rejecttitle:
if re.search(rejecttitle, title, re.IGNORECASE):
return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
date = info_dict.get('upload_date')
if date is not None:
dateRange = self.params.get('daterange', DateRange())
if date not in dateRange:
return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
view_count = info_dict.get('view_count')
if view_count is not None:
min_views = self.params.get('min_views')
if min_views is not None and view_count < min_views:
return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
max_views = self.params.get('max_views')
if max_views is not None and view_count > max_views:
return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
return 'Skipping "%s" because it is age restricted' % video_title
match_filter = self.params.get('match_filter')
if match_filter is not None:
try:
ret = match_filter(info_dict, incomplete=incomplete)
except TypeError:
# For backward compatibility
ret = None if incomplete else match_filter(info_dict)
if ret is not None:
return ret
return None
if self.in_download_archive(info_dict):
reason = '%s has already been recorded in the archive' % video_title
break_opt, break_err = 'break_on_existing', ExistingVideoReached
else:
reason = check_filter()
break_opt, break_err = 'break_on_reject', RejectedVideoReached
if reason is not None:
if not silent:
self.to_screen('[download] ' + reason)
if self.params.get(break_opt, False):
raise break_err()
return reason
@staticmethod
def add_extra_info(info_dict, extra_info):
'''Set the keys from extra_info in info dict if they are missing'''
for key, value in extra_info.items():
info_dict.setdefault(key, value)
def extract_info(self, url, download=True, ie_key=None, extra_info=None,
process=True, force_generic_extractor=False):
"""
Return a list with a dictionary for each video extracted.
Arguments:
url -- URL to extract
Keyword arguments:
download -- whether to download videos during extraction
ie_key -- extractor key hint
extra_info -- dictionary containing the extra values to add to each result
process -- whether to resolve all unresolved references (URLs, playlist items),
must be True for download to work.
force_generic_extractor -- force using the generic extractor
"""
if extra_info is None:
extra_info = {}
if not ie_key and force_generic_extractor:
ie_key = 'Generic'
if ie_key:
ies = {ie_key: self._get_info_extractor_class(ie_key)}
else:
ies = self._ies
for ie_key, ie in ies.items():
if not ie.suitable(url):
continue
if not ie.working():
self.report_warning('The program functionality for this site has been marked as broken, '
'and will probably not work.')
temp_id = ie.get_temp_id(url)
if temp_id is not None and self.in_download_archive({'id': temp_id, 'ie_key': ie_key}):
self.to_screen("[%s] %s: has already been recorded in archive" % (
ie_key, temp_id))
break
return self.__extract_info(url, self.get_info_extractor(ie_key), download, extra_info, process)
else:
self.report_error('no suitable InfoExtractor for URL %s' % url)
def __handle_extraction_exceptions(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except GeoRestrictedError as e:
msg = e.msg
if e.countries:
msg += '\nThis video is available in %s.' % ', '.join(
map(ISO3166Utils.short2full, e.countries))
msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
self.report_error(msg)
except ExtractorError as e: # An error we somewhat expected
self.report_error(compat_str(e), e.format_traceback())
except ThrottledDownload:
self.to_stderr('\r')
self.report_warning('The download speed is below throttle limit. Re-extracting data')
return wrapper(self, *args, **kwargs)
except (MaxDownloadsReached, ExistingVideoReached, RejectedVideoReached, LazyList.IndexError):
raise
except Exception as e:
if self.params.get('ignoreerrors'):
self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc()))
else:
raise
return wrapper
@__handle_extraction_exceptions
def __extract_info(self, url, ie, download, extra_info, process):
ie_result = ie.extract(url)
if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
return
if isinstance(ie_result, list):
# Backwards compatibility: old IE result format
ie_result = {
'_type': 'compat_list',
'entries': ie_result,
}
if extra_info.get('original_url'):
ie_result.setdefault('original_url', extra_info['original_url'])
self.add_default_extra_info(ie_result, ie, url)
if process:
return self.process_ie_result(ie_result, download, extra_info)
else:
return ie_result
def add_default_extra_info(self, ie_result, ie, url):
if url is not None:
self.add_extra_info(ie_result, {
'webpage_url': url,
'original_url': url,
'webpage_url_basename': url_basename(url),
})
if ie is not None:
self.add_extra_info(ie_result, {
'extractor': ie.IE_NAME,
'extractor_key': ie.ie_key(),
})
def process_ie_result(self, ie_result, download=True, extra_info=None):
"""
Take the result of the ie(may be modified) and resolve all unresolved
references (URLs, playlist items).
It will also download the videos if 'download'.
Returns the resolved ie_result.
"""
if extra_info is None:
extra_info = {}
result_type = ie_result.get('_type', 'video')
if result_type in ('url', 'url_transparent'):
ie_result['url'] = sanitize_url(ie_result['url'])
if ie_result.get('original_url'):
extra_info.setdefault('original_url', ie_result['original_url'])
extract_flat = self.params.get('extract_flat', False)
if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
or extract_flat is True):
info_copy = ie_result.copy()
ie = try_get(ie_result.get('ie_key'), self.get_info_extractor)
if ie and not ie_result.get('id'):
info_copy['id'] = ie.get_temp_id(ie_result['url'])
self.add_default_extra_info(info_copy, ie, ie_result['url'])
self.add_extra_info(info_copy, extra_info)
self.__forced_printings(info_copy, self.prepare_filename(info_copy), incomplete=True)
if self.params.get('force_write_download_archive', False):
self.record_download_archive(info_copy)
return ie_result
if result_type == 'video':
self.add_extra_info(ie_result, extra_info)
ie_result = self.process_video_result(ie_result, download=download)
additional_urls = (ie_result or {}).get('additional_urls')
if additional_urls:
# TODO: Improve MetadataParserPP to allow setting a list
if isinstance(additional_urls, compat_str):
additional_urls = [additional_urls]
self.to_screen(
'[info] %s: %d additional URL(s) requested' % (ie_result['id'], len(additional_urls)))
self.write_debug('Additional URLs: "%s"' % '", "'.join(additional_urls))
ie_result['additional_entries'] = [
self.extract_info(
url, download, extra_info,
force_generic_extractor=self.params.get('force_generic_extractor'))
for url in additional_urls
]
return ie_result
elif result_type == 'url':
# We have to add extra_info to the results because it may be
# contained in a playlist
return self.extract_info(
ie_result['url'], download,
ie_key=ie_result.get('ie_key'),
extra_info=extra_info)
elif result_type == 'url_transparent':
# Use the information from the embedding page
info = self.extract_info(
ie_result['url'], ie_key=ie_result.get('ie_key'),
extra_info=extra_info, download=False, process=False)
# extract_info may return None when ignoreerrors is enabled and
# extraction failed with an error, don't crash and return early
# in this case
if not info:
return info
force_properties = dict(
(k, v) for k, v in ie_result.items() if v is not None)
for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
if f in force_properties:
del force_properties[f]
new_result = info.copy()
new_result.update(force_properties)
# Extracted info may not be a video result (i.e.
# info.get('_type', 'video') != video) but rather an url or
# url_transparent. In such cases outer metadata (from ie_result)
# should be propagated to inner one (info). For this to happen
# _type of info should be overridden with url_transparent. This
# fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
if new_result.get('_type') == 'url':
new_result['_type'] = 'url_transparent'
return self.process_ie_result(
new_result, download=download, extra_info=extra_info)
elif result_type in ('playlist', 'multi_video'):
# Protect from infinite recursion due to recursively nested playlists
# (see https://github.com/ytdl-org/youtube-dl/issues/27833)
webpage_url = ie_result['webpage_url']
if webpage_url in self._playlist_urls:
self.to_screen(
'[download] Skipping already downloaded playlist: %s'
% ie_result.get('title') or ie_result.get('id'))
return
self._playlist_level += 1
self._playlist_urls.add(webpage_url)
self._sanitize_thumbnails(ie_result)
try:
return self.__process_playlist(ie_result, download)
finally:
self._playlist_level -= 1
if not self._playlist_level:
self._playlist_urls.clear()
elif result_type == 'compat_list':
self.report_warning(
'Extractor %s returned a compat_list result. '
'It needs to be updated.' % ie_result.get('extractor'))
def _fixup(r):
self.add_extra_info(r, {
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
})
return r
ie_result['entries'] = [
self.process_ie_result(_fixup(r), download, extra_info)
for r in ie_result['entries']
]
return ie_result
else:
raise Exception('Invalid result type: %s' % result_type)
def _ensure_dir_exists(self, path):
return make_dir(path, self.report_error)
def __process_playlist(self, ie_result, download):
# We process each entry in the playlist
playlist = ie_result.get('title') or ie_result.get('id')
self.to_screen('[download] Downloading playlist: %s' % playlist)
if 'entries' not in ie_result:
raise EntryNotInPlaylist()
incomplete_entries = bool(ie_result.get('requested_entries'))
if incomplete_entries:
def fill_missing_entries(entries, indexes):
ret = [None] * max(*indexes)
for i, entry in zip(indexes, entries):
ret[i - 1] = entry
return ret
ie_result['entries'] = fill_missing_entries(ie_result['entries'], ie_result['requested_entries'])
playlist_results = []
playliststart = self.params.get('playliststart', 1)
playlistend = self.params.get('playlistend')
# For backwards compatibility, interpret -1 as whole list
if playlistend == -1:
playlistend = None
playlistitems_str = self.params.get('playlist_items')
playlistitems = None
if playlistitems_str is not None:
def iter_playlistitems(format):
for string_segment in format.split(','):
if '-' in string_segment:
start, end = string_segment.split('-')
for item in range(int(start), int(end) + 1):
yield int(item)
else:
yield int(string_segment)
playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
ie_entries = ie_result['entries']
msg = (
'Downloading %d videos' if not isinstance(ie_entries, list)
else 'Collected %d videos; downloading %%d of them' % len(ie_entries))
if isinstance(ie_entries, list):
def get_entry(i):
return ie_entries[i - 1]
else:
if not isinstance(ie_entries, PagedList):
ie_entries = LazyList(ie_entries)
def get_entry(i):
return YoutubeDL.__handle_extraction_exceptions(
lambda self, i: ie_entries[i - 1]
)(self, i)
entries = []
items = playlistitems if playlistitems is not None else itertools.count(playliststart)
for i in items:
if i == 0:
continue
if playlistitems is None and playlistend is not None and playlistend < i:
break
entry = None
try:
entry = get_entry(i)
if entry is None:
raise EntryNotInPlaylist()
except (IndexError, EntryNotInPlaylist):
if incomplete_entries:
raise EntryNotInPlaylist()
elif not playlistitems:
break
entries.append(entry)
try:
if entry is not None:
self._match_entry(entry, incomplete=True, silent=True)
except (ExistingVideoReached, RejectedVideoReached):
break
ie_result['entries'] = entries
# Save playlist_index before re-ordering
entries = [
((playlistitems[i - 1] if playlistitems else i + playliststart - 1), entry)
for i, entry in enumerate(entries, 1)
if entry is not None]
n_entries = len(entries)
if not playlistitems and (playliststart or playlistend):
playlistitems = list(range(playliststart, playliststart + n_entries))
ie_result['requested_entries'] = playlistitems
if self.params.get('allow_playlist_files', True):
ie_copy = {
'playlist': playlist,
'playlist_id': ie_result.get('id'),
'playlist_title': ie_result.get('title'),
'playlist_uploader': ie_result.get('uploader'),
'playlist_uploader_id': ie_result.get('uploader_id'),
'playlist_index': 0,
}
ie_copy.update(dict(ie_result))
if self._write_info_json('playlist', ie_result,
self.prepare_filename(ie_copy, 'pl_infojson')) is None:
return
if self._write_description('playlist', ie_result,
self.prepare_filename(ie_copy, 'pl_description')) is None:
return
# TODO: This should be passed to ThumbnailsConvertor if necessary
self._write_thumbnails('playlist', ie_copy, self.prepare_filename(ie_copy, 'pl_thumbnail'))
if self.params.get('playlistreverse', False):
entries = entries[::-1]
if self.params.get('playlistrandom', False):
random.shuffle(entries)
x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
self.to_screen('[%s] playlist %s: %s' % (ie_result['extractor'], playlist, msg % n_entries))
failures = 0
max_failures = self.params.get('skip_playlist_after_errors') or float('inf')
for i, entry_tuple in enumerate(entries, 1):
playlist_index, entry = entry_tuple
if 'playlist-index' in self.params.get('compat_opts', []):
playlist_index = playlistitems[i - 1] if playlistitems else i + playliststart - 1
self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
# This __x_forwarded_for_ip thing is a bit ugly but requires
# minimal changes
if x_forwarded_for:
entry['__x_forwarded_for_ip'] = x_forwarded_for
extra = {
'n_entries': n_entries,
'_last_playlist_index': max(playlistitems) if playlistitems else (playlistend or n_entries),
'playlist_index': playlist_index,
'playlist_autonumber': i,
'playlist': playlist,
'playlist_id': ie_result.get('id'),
'playlist_title': ie_result.get('title'),
'playlist_uploader': ie_result.get('uploader'),
'playlist_uploader_id': ie_result.get('uploader_id'),
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
if self._match_entry(entry, incomplete=True) is not None:
continue
entry_result = self.__process_iterable_entry(entry, download, extra)
if not entry_result:
failures += 1
if failures >= max_failures:
self.report_error(
'Skipping the remaining entries in playlist "%s" since %d items failed extraction' % (playlist, failures))
break
# TODO: skip failed (empty) entries?
playlist_results.append(entry_result)
ie_result['entries'] = playlist_results
self.to_screen('[download] Finished downloading playlist: %s' % playlist)
return ie_result
@__handle_extraction_exceptions
def __process_iterable_entry(self, entry, download, extra_info):
return self.process_ie_result(
entry, download=download, extra_info=extra_info)
def _build_format_filter(self, filter_spec):
" Returns a function to filter the formats according to the filter_spec "
OPERATORS = {
'<': operator.lt,
'<=': operator.le,
'>': operator.gt,
'>=': operator.ge,
'=': operator.eq,
'!=': operator.ne,
}
operator_rex = re.compile(r'''(?x)\s*
(?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)\s*
(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)\s*
''' % '|'.join(map(re.escape, OPERATORS.keys())))
m = operator_rex.fullmatch(filter_spec)
if m:
try:
comparison_value = int(m.group('value'))
except ValueError:
comparison_value = parse_filesize(m.group('value'))
if comparison_value is None:
comparison_value = parse_filesize(m.group('value') + 'B')
if comparison_value is None:
raise ValueError(
'Invalid value %r in format specification %r' % (
m.group('value'), filter_spec))
op = OPERATORS[m.group('op')]
if not m:
STR_OPERATORS = {
'=': operator.eq,
'^=': lambda attr, value: attr.startswith(value),
'$=': lambda attr, value: attr.endswith(value),
'*=': lambda attr, value: value in attr,
}
str_operator_rex = re.compile(r'''(?x)\s*
(?P<key>[a-zA-Z0-9._-]+)\s*
(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?P<value>[a-zA-Z0-9._-]+)\s*
''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
m = str_operator_rex.fullmatch(filter_spec)
if m:
comparison_value = m.group('value')
str_op = STR_OPERATORS[m.group('op')]
if m.group('negation'):
op = lambda attr, value: not str_op(attr, value)
else:
op = str_op
if not m:
raise SyntaxError('Invalid filter specification %r' % filter_spec)
def _filter(f):
actual_value = f.get(m.group('key'))
if actual_value is None:
return m.group('none_inclusive')
return op(actual_value, comparison_value)
return _filter
def _default_format_spec(self, info_dict, download=True):
def can_merge():
merger = FFmpegMergerPP(self)
return merger.available and merger.can_merge()
prefer_best = (
not self.params.get('simulate')
and download
and (
not can_merge()
or info_dict.get('is_live', False)
or self.outtmpl_dict['default'] == '-'))
compat = (
prefer_best
or self.params.get('allow_multiple_audio_streams', False)
or 'format-spec' in self.params.get('compat_opts', []))
return (
'best/bestvideo+bestaudio' if prefer_best
else 'bestvideo*+bestaudio/best' if not compat
else 'bestvideo+bestaudio/best')
def build_format_selector(self, format_spec):
def syntax_error(note, start):
message = (
'Invalid format specification: '
'{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
return SyntaxError(message)
PICKFIRST = 'PICKFIRST'
MERGE = 'MERGE'
SINGLE = 'SINGLE'
GROUP = 'GROUP'
FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
allow_multiple_streams = {'audio': self.params.get('allow_multiple_audio_streams', False),
'video': self.params.get('allow_multiple_video_streams', False)}
check_formats = self.params.get('check_formats')
def _parse_filter(tokens):
filter_parts = []
for type, string, start, _, _ in tokens:
if type == tokenize.OP and string == ']':
return ''.join(filter_parts)
else:
filter_parts.append(string)
def _remove_unused_ops(tokens):
# Remove operators that we don't use and join them with the surrounding strings
# for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
ALLOWED_OPS = ('/', '+', ',', '(', ')')
last_string, last_start, last_end, last_line = None, None, None, None
for type, string, start, end, line in tokens:
if type == tokenize.OP and string == '[':
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
# everything inside brackets will be handled by _parse_filter
for type, string, start, end, line in tokens:
yield type, string, start, end, line
if type == tokenize.OP and string == ']':
break
elif type == tokenize.OP and string in ALLOWED_OPS:
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
if not last_string:
last_string = string
last_start = start
last_end = end
else:
last_string += string
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens:
# ENCODING is only defined in python 3.x
if type == getattr(tokenize, 'ENCODING', None):
continue
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string == ')':
if not inside_group:
# ')' will be handled by the parentheses group
tokens.restore_last_token()
break
elif inside_merge and string in ['/', ',']:
tokens.restore_last_token()
break
elif inside_choice and string == ',':
tokens.restore_last_token()
break
elif string == ',':
if not current_selector:
raise syntax_error('"," must follow a format selector', start)
selectors.append(current_selector)
current_selector = None
elif string == '/':
if not current_selector:
raise syntax_error('"/" must follow a format selector', start)
first_choice = current_selector
second_choice = _parse_format_selection(tokens, inside_choice=True)
current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
elif string == '[':
if not current_selector:
current_selector = FormatSelector(SINGLE, 'best', [])
format_filter = _parse_filter(tokens)
current_selector.filters.append(format_filter)
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
group = _parse_format_selection(tokens, inside_group=True)
current_selector = FormatSelector(GROUP, group, [])
elif string == '+':
if not current_selector:
raise syntax_error('Unexpected "+"', start)
selector_1 = current_selector
selector_2 = _parse_format_selection(tokens, inside_merge=True)
if not selector_2:
raise syntax_error('Expected a selector', start)
current_selector = FormatSelector(MERGE, (selector_1, selector_2), [])
else:
raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
elif type == tokenize.ENDMARKER:
break
if current_selector:
selectors.append(current_selector)
return selectors
def _merge(formats_pair):
format_1, format_2 = formats_pair
formats_info = []
formats_info.extend(format_1.get('requested_formats', (format_1,)))
formats_info.extend(format_2.get('requested_formats', (format_2,)))
if not allow_multiple_streams['video'] or not allow_multiple_streams['audio']:
get_no_more = {'video': False, 'audio': False}
for (i, fmt_info) in enumerate(formats_info):
if fmt_info.get('acodec') == fmt_info.get('vcodec') == 'none':
formats_info.pop(i)
continue
for aud_vid in ['audio', 'video']:
if not allow_multiple_streams[aud_vid] and fmt_info.get(aud_vid[0] + 'codec') != 'none':
if get_no_more[aud_vid]:
formats_info.pop(i)
break
get_no_more[aud_vid] = True
if len(formats_info) == 1:
return formats_info[0]
video_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('vcodec') != 'none']
audio_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('acodec') != 'none']
the_only_video = video_fmts[0] if len(video_fmts) == 1 else None
the_only_audio = audio_fmts[0] if len(audio_fmts) == 1 else None
output_ext = self.params.get('merge_output_format')
if not output_ext:
if the_only_video:
output_ext = the_only_video['ext']
elif the_only_audio and not video_fmts:
output_ext = the_only_audio['ext']
else:
output_ext = 'mkv'
filtered = lambda *keys: filter(None, (traverse_obj(fmt, *keys) for fmt in formats_info))
new_dict = {
'requested_formats': formats_info,
'format': '+'.join(filtered('format')),
'format_id': '+'.join(filtered('format_id')),
'ext': output_ext,
'protocol': '+'.join(map(determine_protocol, formats_info)),
'language': '+'.join(orderedSet(filtered('language'))),
'format_note': '+'.join(orderedSet(filtered('format_note'))),
'filesize_approx': sum(filtered('filesize', 'filesize_approx')),
'tbr': sum(filtered('tbr', 'vbr', 'abr')),
}
if the_only_video:
new_dict.update({
'width': the_only_video.get('width'),
'height': the_only_video.get('height'),
'resolution': the_only_video.get('resolution') or self.format_resolution(the_only_video),
'fps': the_only_video.get('fps'),
'vcodec': the_only_video.get('vcodec'),
'vbr': the_only_video.get('vbr'),
'stretched_ratio': the_only_video.get('stretched_ratio'),
})
if the_only_audio:
new_dict.update({
'acodec': the_only_audio.get('acodec'),
'abr': the_only_audio.get('abr'),
'asr': the_only_audio.get('asr'),
})
return new_dict
def _check_formats(formats):
if not check_formats:
yield from formats
return
for f in formats:
self.to_screen('[info] Testing format %s' % f['format_id'])
temp_file = tempfile.NamedTemporaryFile(
suffix='.tmp', delete=False,
dir=self.get_output_path('temp') or None)
temp_file.close()
try:
success, _ = self.dl(temp_file.name, f, test=True)
except (DownloadError, IOError, OSError, ValueError) + network_exceptions:
success = False
finally:
if os.path.exists(temp_file.name):
try:
os.remove(temp_file.name)
except OSError:
self.report_warning('Unable to delete temporary file "%s"' % temp_file.name)
if success:
yield f
else:
self.to_screen('[info] Unable to download format %s. Skipping...' % f['format_id'])
def _build_selector_function(selector):
if isinstance(selector, list): # ,
fs = [_build_selector_function(s) for s in selector]
def selector_function(ctx):
for f in fs:
yield from f(ctx)
return selector_function
elif selector.type == GROUP: # ()
selector_function = _build_selector_function(selector.selector)
elif selector.type == PICKFIRST: # /
fs = [_build_selector_function(s) for s in selector.selector]
def selector_function(ctx):
for f in fs:
picked_formats = list(f(ctx))
if picked_formats:
return picked_formats
return []
elif selector.type == MERGE: # +
selector_1, selector_2 = map(_build_selector_function, selector.selector)
def selector_function(ctx):
for pair in itertools.product(
selector_1(copy.deepcopy(ctx)), selector_2(copy.deepcopy(ctx))):
yield _merge(pair)
elif selector.type == SINGLE: # atom
format_spec = selector.selector or 'best'
# TODO: Add allvideo, allaudio etc by generalizing the code with best/worst selector
if format_spec == 'all':
def selector_function(ctx):
yield from _check_formats(ctx['formats'])
elif format_spec == 'mergeall':
def selector_function(ctx):
formats = list(_check_formats(ctx['formats']))
if not formats:
return
merged_format = formats[-1]
for f in formats[-2::-1]:
merged_format = _merge((merged_format, f))
yield merged_format
else:
format_fallback, format_reverse, format_idx = False, True, 1
mobj = re.match(
r'(?P<bw>best|worst|b|w)(?P<type>video|audio|v|a)?(?P<mod>\*)?(?:\.(?P<n>[1-9]\d*))?$',
format_spec)
if mobj is not None:
format_idx = int_or_none(mobj.group('n'), default=1)
format_reverse = mobj.group('bw')[0] == 'b'
format_type = (mobj.group('type') or [None])[0]
not_format_type = {'v': 'a', 'a': 'v'}.get(format_type)
format_modified = mobj.group('mod') is not None
format_fallback = not format_type and not format_modified # for b, w
_filter_f = (
(lambda f: f.get('%scodec' % format_type) != 'none')
if format_type and format_modified # bv*, ba*, wv*, wa*
else (lambda f: f.get('%scodec' % not_format_type) == 'none')
if format_type # bv, ba, wv, wa
else (lambda f: f.get('vcodec') != 'none' and f.get('acodec') != 'none')
if not format_modified # b, w
else lambda f: True) # b*, w*
filter_f = lambda f: _filter_f(f) and (
f.get('vcodec') != 'none' or f.get('acodec') != 'none')
else:
if format_spec in self._format_selection_exts['audio']:
filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none'
elif format_spec in self._format_selection_exts['video']:
filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none' and f.get('vcodec') != 'none'
elif format_spec in self._format_selection_exts['storyboards']:
filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') == 'none' and f.get('vcodec') == 'none'
else:
filter_f = lambda f: f.get('format_id') == format_spec # id
def selector_function(ctx):
formats = list(ctx['formats'])
matches = list(filter(filter_f, formats)) if filter_f is not None else formats
if format_fallback and ctx['incomplete_formats'] and not matches:
# for extractors with incomplete formats (audio only (soundcloud)
# or video only (imgur)) best/worst will fallback to
# best/worst {video,audio}-only format
matches = formats
matches = LazyList(_check_formats(matches[::-1 if format_reverse else 1]))
try:
yield matches[format_idx - 1]
except IndexError:
return
filters = [self._build_format_filter(f) for f in selector.filters]
def final_selector(ctx):
ctx_copy = copy.deepcopy(ctx)
for _filter in filters:
ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
return selector_function(ctx_copy)
return final_selector
stream = io.BytesIO(format_spec.encode('utf-8'))
try:
tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
except tokenize.TokenError:
raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
class TokenIterator(object):
def __init__(self, tokens):
self.tokens = tokens
self.counter = 0
def __iter__(self):
return self
def __next__(self):
if self.counter >= len(self.tokens):
raise StopIteration()
value = self.tokens[self.counter]
self.counter += 1
return value
next = __next__
def restore_last_token(self):
self.counter -= 1
parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
return _build_selector_function(parsed_selector)
def _calc_headers(self, info_dict):
res = std_headers.copy()
add_headers = info_dict.get('http_headers')
if add_headers:
res.update(add_headers)
cookies = self._calc_cookies(info_dict)
if cookies:
res['Cookie'] = cookies
if 'X-Forwarded-For' not in res:
x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
if x_forwarded_for_ip:
res['X-Forwarded-For'] = x_forwarded_for_ip
return res
def _calc_cookies(self, info_dict):
pr = sanitized_Request(info_dict['url'])
self.cookiejar.add_cookie_header(pr)
return pr.get_header('Cookie')
def _sanitize_thumbnails(self, info_dict):
thumbnails = info_dict.get('thumbnails')
if thumbnails is None:
thumbnail = info_dict.get('thumbnail')
if thumbnail:
info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
if thumbnails:
thumbnails.sort(key=lambda t: (
t.get('preference') if t.get('preference') is not None else -1,
t.get('width') if t.get('width') is not None else -1,
t.get('height') if t.get('height') is not None else -1,
t.get('id') if t.get('id') is not None else '',
t.get('url')))
def thumbnail_tester():
def test_thumbnail(t):
self.to_screen(f'[info] Testing thumbnail {t["id"]}')
try:
self.urlopen(HEADRequest(t['url']))
except network_exceptions as err:
self.to_screen(f'[info] Unable to connect to thumbnail {t["id"]} URL {t["url"]!r} - {err}. Skipping...')
return False
return True
return test_thumbnail
for i, t in enumerate(thumbnails):
if t.get('id') is None:
t['id'] = '%d' % i
if t.get('width') and t.get('height'):
t['resolution'] = '%dx%d' % (t['width'], t['height'])
t['url'] = sanitize_url(t['url'])
if self.params.get('check_formats'):
info_dict['thumbnails'] = LazyList(filter(thumbnail_tester(), thumbnails[::-1])).reverse()
else:
info_dict['thumbnails'] = thumbnails
def process_video_result(self, info_dict, download=True):
assert info_dict.get('_type', 'video') == 'video'
if 'id' not in info_dict:
raise ExtractorError('Missing "id" field in extractor result')
if 'title' not in info_dict:
raise ExtractorError('Missing "title" field in extractor result',
video_id=info_dict['id'], ie=info_dict['extractor'])
def report_force_conversion(field, field_not, conversion):
self.report_warning(
'"%s" field is not %s - forcing %s conversion, there is an error in extractor'
% (field, field_not, conversion))
def sanitize_string_field(info, string_field):
field = info.get(string_field)
if field is None or isinstance(field, compat_str):
return
report_force_conversion(string_field, 'a string', 'string')
info[string_field] = compat_str(field)
def sanitize_numeric_fields(info):
for numeric_field in self._NUMERIC_FIELDS:
field = info.get(numeric_field)
if field is None or isinstance(field, compat_numeric_types):
continue
report_force_conversion(numeric_field, 'numeric', 'int')
info[numeric_field] = int_or_none(field)
sanitize_string_field(info_dict, 'id')
sanitize_numeric_fields(info_dict)
if 'playlist' not in info_dict:
# It isn't part of a playlist
info_dict['playlist'] = None
info_dict['playlist_index'] = None
self._sanitize_thumbnails(info_dict)
thumbnail = info_dict.get('thumbnail')
thumbnails = info_dict.get('thumbnails')
if thumbnail:
info_dict['thumbnail'] = sanitize_url(thumbnail)
elif thumbnails:
info_dict['thumbnail'] = thumbnails[-1]['url']
if info_dict.get('display_id') is None and 'id' in info_dict:
info_dict['display_id'] = info_dict['id']
if info_dict.get('duration') is not None:
info_dict['duration_string'] = formatSeconds(info_dict['duration'])
for ts_key, date_key in (
('timestamp', 'upload_date'),
('release_timestamp', 'release_date'),
):
if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
# Working around out-of-range timestamp values (e.g. negative ones on Windows,
# see http://bugs.python.org/issue1646728)
try:
upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key])
info_dict[date_key] = upload_date.strftime('%Y%m%d')
except (ValueError, OverflowError, OSError):
pass
live_keys = ('is_live', 'was_live')
live_status = info_dict.get('live_status')
if live_status is None:
for key in live_keys:
if info_dict.get(key) is False:
continue
if info_dict.get(key):
live_status = key
break
if all(info_dict.get(key) is False for key in live_keys):
live_status = 'not_live'
if live_status:
info_dict['live_status'] = live_status
for key in live_keys:
if info_dict.get(key) is None:
info_dict[key] = (live_status == key)
# Auto generate title fields corresponding to the *_number fields when missing
# in order to always have clean titles. This is very common for TV series.
for field in ('chapter', 'season', 'episode'):
if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
for cc_kind in ('subtitles', 'automatic_captions'):
cc = info_dict.get(cc_kind)
if cc:
for _, subtitle in cc.items():
for subtitle_format in subtitle:
if subtitle_format.get('url'):
subtitle_format['url'] = sanitize_url(subtitle_format['url'])
if subtitle_format.get('ext') is None:
subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
automatic_captions = info_dict.get('automatic_captions')
subtitles = info_dict.get('subtitles')
info_dict['requested_subtitles'] = self.process_subtitles(
info_dict['id'], subtitles, automatic_captions)
# We now pick which formats have to be downloaded
if info_dict.get('formats') is None:
# There's only one format available
formats = [info_dict]
else:
formats = info_dict['formats']
info_dict['__has_drm'] = any(f.get('has_drm') for f in formats)
if not self.params.get('allow_unplayable_formats'):
formats = [f for f in formats if not f.get('has_drm')]
if not formats:
self.raise_no_formats(info_dict)
def is_wellformed(f):
url = f.get('url')
if not url:
self.report_warning(
'"url" field is missing or empty - skipping format, '
'there is an error in extractor')
return False
if isinstance(url, bytes):
sanitize_string_field(f, 'url')
return True
# Filter out malformed formats for better extraction robustness
formats = list(filter(is_wellformed, formats))
formats_dict = {}
# We check that all the formats have the format and format_id fields
for i, format in enumerate(formats):
sanitize_string_field(format, 'format_id')
sanitize_numeric_fields(format)
format['url'] = sanitize_url(format['url'])
if not format.get('format_id'):
format['format_id'] = compat_str(i)
else:
# Sanitize format_id from characters used in format selector expression
format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
format_id = format['format_id']
if format_id not in formats_dict:
formats_dict[format_id] = []
formats_dict[format_id].append(format)
# Make sure all formats have unique format_id
common_exts = set(itertools.chain(*self._format_selection_exts.values()))
for format_id, ambiguous_formats in formats_dict.items():
ambigious_id = len(ambiguous_formats) > 1
for i, format in enumerate(ambiguous_formats):
if ambigious_id:
format['format_id'] = '%s-%d' % (format_id, i)
if format.get('ext') is None:
format['ext'] = determine_ext(format['url']).lower()
# Ensure there is no conflict between id and ext in format selection
# See https://github.com/yt-dlp/yt-dlp/issues/1282
if format['format_id'] != format['ext'] and format['format_id'] in common_exts:
format['format_id'] = 'f%s' % format['format_id']
for i, format in enumerate(formats):
if format.get('format') is None:
format['format'] = '{id} - {res}{note}'.format(
id=format['format_id'],
res=self.format_resolution(format),
note=format_field(format, 'format_note', ' (%s)'),
)
if format.get('protocol') is None:
format['protocol'] = determine_protocol(format)
if format.get('resolution') is None:
format['resolution'] = self.format_resolution(format, default=None)
if format.get('dynamic_range') is None and format.get('vcodec') != 'none':
format['dynamic_range'] = 'SDR'
# Add HTTP headers, so that external programs can use them from the
# json output
full_format_info = info_dict.copy()
full_format_info.update(format)
format['http_headers'] = self._calc_headers(full_format_info)
# Remove private housekeeping stuff
if '__x_forwarded_for_ip' in info_dict:
del info_dict['__x_forwarded_for_ip']
# TODO Central sorting goes here
if not formats or formats[0] is not info_dict:
# only set the 'formats' fields if the original info_dict list them
# otherwise we end up with a circular reference, the first (and unique)
# element in the 'formats' field in info_dict is info_dict itself,
# which can't be exported to json
info_dict['formats'] = formats
info_dict, _ = self.pre_process(info_dict)
if self.params.get('list_thumbnails'):
self.list_thumbnails(info_dict)
if self.params.get('listformats'):
if not info_dict.get('formats') and not info_dict.get('url'):
self.to_screen('%s has no formats' % info_dict['id'])
else:
self.list_formats(info_dict)
if self.params.get('listsubtitles'):
if 'automatic_captions' in info_dict:
self.list_subtitles(
info_dict['id'], automatic_captions, 'automatic captions')
self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
list_only = self.params.get('simulate') is None and (
self.params.get('list_thumbnails') or self.params.get('listformats') or self.params.get('listsubtitles'))
if list_only:
# Without this printing, -F --print-json will not work
self.__forced_printings(info_dict, self.prepare_filename(info_dict), incomplete=True)
return
format_selector = self.format_selector
if format_selector is None:
req_format = self._default_format_spec(info_dict, download=download)
self.write_debug('Default format spec: %s' % req_format)
format_selector = self.build_format_selector(req_format)
# While in format selection we may need to have an access to the original
# format set in order to calculate some metrics or do some processing.
# For now we need to be able to guess whether original formats provided
# by extractor are incomplete or not (i.e. whether extractor provides only
# video-only or audio-only formats) for proper formats selection for
# extractors with such incomplete formats (see
# https://github.com/ytdl-org/youtube-dl/pull/5556).
# Since formats may be filtered during format selection and may not match
# the original formats the results may be incorrect. Thus original formats
# or pre-calculated metrics should be passed to format selection routines
# as well.
# We will pass a context object containing all necessary additional data
# instead of just formats.
# This fixes incorrect format selection issue (see
# https://github.com/ytdl-org/youtube-dl/issues/10083).
incomplete_formats = (
# All formats are video-only or
all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
# all formats are audio-only
or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
ctx = {
'formats': formats,
'incomplete_formats': incomplete_formats,
}
formats_to_download = list(format_selector(ctx))
if not formats_to_download:
if not self.params.get('ignore_no_formats_error'):
raise ExtractorError('Requested format is not available', expected=True,
video_id=info_dict['id'], ie=info_dict['extractor'])
else:
self.report_warning('Requested format is not available')
# Process what we can, even without any available formats.
self.process_info(dict(info_dict))
elif download:
self.to_screen(
'[info] %s: Downloading %d format(s): %s' % (
info_dict['id'], len(formats_to_download),
", ".join([f['format_id'] for f in formats_to_download])))
for fmt in formats_to_download:
new_info = dict(info_dict)
# Save a reference to the original info_dict so that it can be modified in process_info if needed
new_info['__original_infodict'] = info_dict
new_info.update(fmt)
self.process_info(new_info)
# We update the info dict with the best quality format (backwards compatibility)
if formats_to_download:
info_dict.update(formats_to_download[-1])
return info_dict
def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
"""Select the requested subtitles and their format"""
available_subs = {}
if normal_subtitles and self.params.get('writesubtitles'):
available_subs.update(normal_subtitles)
if automatic_captions and self.params.get('writeautomaticsub'):
for lang, cap_info in automatic_captions.items():
if lang not in available_subs:
available_subs[lang] = cap_info
if (not self.params.get('writesubtitles') and not
self.params.get('writeautomaticsub') or not
available_subs):
return None
all_sub_langs = available_subs.keys()
if self.params.get('allsubtitles', False):
requested_langs = all_sub_langs
elif self.params.get('subtitleslangs', False):
# A list is used so that the order of languages will be the same as
# given in subtitleslangs. See https://github.com/yt-dlp/yt-dlp/issues/1041
requested_langs = []
for lang_re in self.params.get('subtitleslangs'):
if lang_re == 'all':
requested_langs.extend(all_sub_langs)
continue
discard = lang_re[0] == '-'
if discard:
lang_re = lang_re[1:]
current_langs = filter(re.compile(lang_re + '$').match, all_sub_langs)
if discard:
for lang in current_langs:
while lang in requested_langs:
requested_langs.remove(lang)
else:
requested_langs.extend(current_langs)
requested_langs = orderedSet(requested_langs)
elif 'en' in available_subs:
requested_langs = ['en']
else:
requested_langs = [list(all_sub_langs)[0]]
if requested_langs:
self.write_debug('Downloading subtitles: %s' % ', '.join(requested_langs))
formats_query = self.params.get('subtitlesformat', 'best')
formats_preference = formats_query.split('/') if formats_query else []
subs = {}
for lang in requested_langs:
formats = available_subs.get(lang)
if formats is None:
self.report_warning('%s subtitles not available for %s' % (lang, video_id))
continue
for ext in formats_preference:
if ext == 'best':
f = formats[-1]
break
matches = list(filter(lambda f: f['ext'] == ext, formats))
if matches:
f = matches[-1]
break
else:
f = formats[-1]
self.report_warning(
'No subtitle format found matching "%s" for language %s, '
'using %s' % (formats_query, lang, f['ext']))
subs[lang] = f
return subs
def __forced_printings(self, info_dict, filename, incomplete):
def print_mandatory(field, actual_field=None):
if actual_field is None:
actual_field = field
if (self.params.get('force%s' % field, False)
and (not incomplete or info_dict.get(actual_field) is not None)):
self.to_stdout(info_dict[actual_field])
def print_optional(field):
if (self.params.get('force%s' % field, False)
and info_dict.get(field) is not None):
self.to_stdout(info_dict[field])
info_dict = info_dict.copy()
if filename is not None:
info_dict['filename'] = filename
if info_dict.get('requested_formats') is not None:
# For RTMP URLs, also include the playpath
info_dict['urls'] = '\n'.join(f['url'] + f.get('play_path', '') for f in info_dict['requested_formats'])
elif 'url' in info_dict:
info_dict['urls'] = info_dict['url'] + info_dict.get('play_path', '')
if self.params.get('forceprint') or self.params.get('forcejson'):
self.post_extract(info_dict)
for tmpl in self.params.get('forceprint', []):
mobj = re.match(r'\w+(=?)$', tmpl)
if mobj and mobj.group(1):
tmpl = f'{tmpl[:-1]} = %({tmpl[:-1]})s'
elif mobj:
tmpl = '%({})s'.format(tmpl)
self.to_stdout(self.evaluate_outtmpl(tmpl, info_dict))
print_mandatory('title')
print_mandatory('id')
print_mandatory('url', 'urls')
print_optional('thumbnail')
print_optional('description')
print_optional('filename')
if self.params.get('forceduration') and info_dict.get('duration') is not None:
self.to_stdout(formatSeconds(info_dict['duration']))
print_mandatory('format')
if self.params.get('forcejson'):
self.to_stdout(json.dumps(self.sanitize_info(info_dict)))
def dl(self, name, info, subtitle=False, test=False):
if not info.get('url'):
self.raise_no_formats(info, True)
if test:
verbose = self.params.get('verbose')
params = {
'test': True,
'quiet': self.params.get('quiet') or not verbose,
'verbose': verbose,
'noprogress': not verbose,
'nopart': True,
'skip_unavailable_fragments': False,
'keep_fragments': False,
'overwrites': True,
'_no_ytdl_file': True,
}
else:
params = self.params
fd = get_suitable_downloader(info, params, to_stdout=(name == '-'))(self, params)
if not test:
for ph in self._progress_hooks:
fd.add_progress_hook(ph)
urls = '", "'.join([f['url'] for f in info.get('requested_formats', [])] or [info['url']])
self.write_debug('Invoking downloader on "%s"' % urls)
new_info = copy.deepcopy(self._copy_infodict(info))
if new_info.get('http_headers') is None:
new_info['http_headers'] = self._calc_headers(new_info)
return fd.download(name, new_info, subtitle)
def process_info(self, info_dict):
"""Process a single resolved IE result."""
assert info_dict.get('_type', 'video') == 'video'
max_downloads = self.params.get('max_downloads')
if max_downloads is not None:
if self._num_downloads >= int(max_downloads):
raise MaxDownloadsReached()
# TODO: backward compatibility, to be removed
info_dict['fulltitle'] = info_dict['title']
if 'format' not in info_dict and 'ext' in info_dict:
info_dict['format'] = info_dict['ext']
if self._match_entry(info_dict) is not None:
return
self.post_extract(info_dict)
self._num_downloads += 1
# info_dict['_filename'] needs to be set for backward compatibility
info_dict['_filename'] = full_filename = self.prepare_filename(info_dict, warn=True)
temp_filename = self.prepare_filename(info_dict, 'temp')
files_to_move = {}
# Forced printings
self.__forced_printings(info_dict, full_filename, incomplete=('format' not in info_dict))
if self.params.get('simulate'):
if self.params.get('force_write_download_archive', False):
self.record_download_archive(info_dict)
# Do nothing else if in simulate mode
return
if full_filename is None:
return
if not self._ensure_dir_exists(encodeFilename(full_filename)):
return
if not self._ensure_dir_exists(encodeFilename(temp_filename)):
return
if self._write_description('video', info_dict,
self.prepare_filename(info_dict, 'description')) is None:
return
sub_files = self._write_subtitles(info_dict, temp_filename)
if sub_files is None:
return
files_to_move.update(dict(sub_files))
thumb_files = self._write_thumbnails(
'video', info_dict, temp_filename, self.prepare_filename(info_dict, 'thumbnail'))
if thumb_files is None:
return
files_to_move.update(dict(thumb_files))
infofn = self.prepare_filename(info_dict, 'infojson')
_infojson_written = self._write_info_json('video', info_dict, infofn)
if _infojson_written:
info_dict['__infojson_filename'] = infofn
elif _infojson_written is None:
return
# Note: Annotations are deprecated
annofn = None
if self.params.get('writeannotations', False):
annofn = self.prepare_filename(info_dict, 'annotation')
if annofn:
if not self._ensure_dir_exists(encodeFilename(annofn)):
return
if not self.params.get('overwrites', True) and os.path.exists(encodeFilename(annofn)):
self.to_screen('[info] Video annotations are already present')
elif not info_dict.get('annotations'):
self.report_warning('There are no annotations to write.')
else:
try:
self.to_screen('[info] Writing video annotations to: ' + annofn)
with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
annofile.write(info_dict['annotations'])
except (KeyError, TypeError):
self.report_warning('There are no annotations to write.')
except (OSError, IOError):
self.report_error('Cannot write annotations file: ' + annofn)
return
# Write internet shortcut files
url_link = webloc_link = desktop_link = False
if self.params.get('writelink', False):
if sys.platform == "darwin": # macOS.
webloc_link = True
elif sys.platform.startswith("linux"):
desktop_link = True
else: # if sys.platform in ['win32', 'cygwin']:
url_link = True
if self.params.get('writeurllink', False):
url_link = True
if self.params.get('writewebloclink', False):
webloc_link = True
if self.params.get('writedesktoplink', False):
desktop_link = True
if url_link or webloc_link or desktop_link:
if 'webpage_url' not in info_dict:
self.report_error('Cannot write internet shortcut file because the "webpage_url" field is missing in the media information')
return
ascii_url = iri_to_uri(info_dict['webpage_url'])
def _write_link_file(extension, template, newline, embed_filename):
linkfn = replace_extension(full_filename, extension, info_dict.get('ext'))
if self.params.get('overwrites', True) and os.path.exists(encodeFilename(linkfn)):
self.to_screen('[info] Internet shortcut is already present')
else:
try:
self.to_screen('[info] Writing internet shortcut to: ' + linkfn)
with io.open(encodeFilename(to_high_limit_path(linkfn)), 'w', encoding='utf-8', newline=newline) as linkfile:
template_vars = {'url': ascii_url}
if embed_filename:
template_vars['filename'] = linkfn[:-(len(extension) + 1)]
linkfile.write(template % template_vars)
except (OSError, IOError):
self.report_error('Cannot write internet shortcut ' + linkfn)
return False
return True
if url_link:
if not _write_link_file('url', DOT_URL_LINK_TEMPLATE, '\r\n', embed_filename=False):
return
if webloc_link:
if not _write_link_file('webloc', DOT_WEBLOC_LINK_TEMPLATE, '\n', embed_filename=False):
return
if desktop_link:
if not _write_link_file('desktop', DOT_DESKTOP_LINK_TEMPLATE, '\n', embed_filename=True):
return
try:
info_dict, files_to_move = self.pre_process(info_dict, 'before_dl', files_to_move)
except PostProcessingError as err:
self.report_error('Preprocessing: %s' % str(err))
return
must_record_download_archive = False
if self.params.get('skip_download', False):
info_dict['filepath'] = temp_filename
info_dict['__finaldir'] = os.path.dirname(os.path.abspath(encodeFilename(full_filename)))
info_dict['__files_to_move'] = files_to_move
info_dict = self.run_pp(MoveFilesAfterDownloadPP(self, False), info_dict)
else:
# Download
info_dict.setdefault('__postprocessors', [])
try:
def existing_file(*filepaths):
ext = info_dict.get('ext')
final_ext = self.params.get('final_ext', ext)
existing_files = []
for file in orderedSet(filepaths):
if final_ext != ext:
converted = replace_extension(file, final_ext, ext)
if os.path.exists(encodeFilename(converted)):
existing_files.append(converted)
if os.path.exists(encodeFilename(file)):
existing_files.append(file)
if not existing_files or self.params.get('overwrites', False):
for file in orderedSet(existing_files):
self.report_file_delete(file)
os.remove(encodeFilename(file))
return None
info_dict['ext'] = os.path.splitext(existing_files[0])[1][1:]
return existing_files[0]
success = True
if info_dict.get('requested_formats') is not None:
def compatible_formats(formats):
# TODO: some formats actually allow this (mkv, webm, ogg, mp4), but not all of them.
video_formats = [format for format in formats if format.get('vcodec') != 'none']
audio_formats = [format for format in formats if format.get('acodec') != 'none']
if len(video_formats) > 2 or len(audio_formats) > 2:
return False
# Check extension
exts = set(format.get('ext') for format in formats)
COMPATIBLE_EXTS = (
set(('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma')),
set(('webm',)),
)
for ext_sets in COMPATIBLE_EXTS:
if ext_sets.issuperset(exts):
return True
# TODO: Check acodec/vcodec
return False
requested_formats = info_dict['requested_formats']
old_ext = info_dict['ext']
if self.params.get('merge_output_format') is None:
if not compatible_formats(requested_formats):
info_dict['ext'] = 'mkv'
self.report_warning(
'Requested formats are incompatible for merge and will be merged into mkv')
if (info_dict['ext'] == 'webm'
and info_dict.get('thumbnails')
# check with type instead of pp_key, __name__, or isinstance
# since we dont want any custom PPs to trigger this
and any(type(pp) == EmbedThumbnailPP for pp in self._pps['post_process'])):
info_dict['ext'] = 'mkv'
self.report_warning(
'webm doesn\'t support embedding a thumbnail, mkv will be used')
new_ext = info_dict['ext']
def correct_ext(filename, ext=new_ext):
if filename == '-':
return filename
filename_real_ext = os.path.splitext(filename)[1][1:]
filename_wo_ext = (
os.path.splitext(filename)[0]
if filename_real_ext in (old_ext, new_ext)
else filename)
return '%s.%s' % (filename_wo_ext, ext)
# Ensure filename always has a correct extension for successful merge
full_filename = correct_ext(full_filename)
temp_filename = correct_ext(temp_filename)
dl_filename = existing_file(full_filename, temp_filename)
info_dict['__real_download'] = False
if dl_filename is not None:
self.report_file_already_downloaded(dl_filename)
elif get_suitable_downloader(info_dict, self.params, to_stdout=temp_filename == '-'):
info_dict['url'] = '\n'.join(f['url'] for f in requested_formats)
success, real_download = self.dl(temp_filename, info_dict)
info_dict['__real_download'] = real_download
else:
downloaded = []
merger = FFmpegMergerPP(self)
if self.params.get('allow_unplayable_formats'):
self.report_warning(
'You have requested merging of multiple formats '
'while also allowing unplayable formats to be downloaded. '
'The formats won\'t be merged to prevent data corruption.')
elif not merger.available:
self.report_warning(
'You have requested merging of multiple formats but ffmpeg is not installed. '
'The formats won\'t be merged.')
if temp_filename == '-':
reason = ('using a downloader other than ffmpeg' if FFmpegFD.can_merge_formats(info_dict)
else 'but the formats are incompatible for simultaneous download' if merger.available
else 'but ffmpeg is not installed')
self.report_warning(
f'You have requested downloading multiple formats to stdout {reason}. '
'The formats will be streamed one after the other')
fname = temp_filename
for f in requested_formats:
new_info = dict(info_dict)
del new_info['requested_formats']
new_info.update(f)
if temp_filename != '-':
fname = prepend_extension(
correct_ext(temp_filename, new_info['ext']),
'f%s' % f['format_id'], new_info['ext'])
if not self._ensure_dir_exists(fname):
return
f['filepath'] = fname
downloaded.append(fname)
partial_success, real_download = self.dl(fname, new_info)
info_dict['__real_download'] = info_dict['__real_download'] or real_download
success = success and partial_success
if merger.available and not self.params.get('allow_unplayable_formats'):
info_dict['__postprocessors'].append(merger)
info_dict['__files_to_merge'] = downloaded
# Even if there were no downloads, it is being merged only now
info_dict['__real_download'] = True
else:
for file in downloaded:
files_to_move[file] = None
else:
# Just a single file
dl_filename = existing_file(full_filename, temp_filename)
if dl_filename is None or dl_filename == temp_filename:
# dl_filename == temp_filename could mean that the file was partially downloaded with --no-part.
# So we should try to resume the download
success, real_download = self.dl(temp_filename, info_dict)
info_dict['__real_download'] = real_download
else:
self.report_file_already_downloaded(dl_filename)
dl_filename = dl_filename or temp_filename
info_dict['__finaldir'] = os.path.dirname(os.path.abspath(encodeFilename(full_filename)))
except network_exceptions as err:
self.report_error('unable to download video data: %s' % error_to_compat_str(err))
return
except (OSError, IOError) as err:
raise UnavailableVideoError(err)
except (ContentTooShortError, ) as err:
self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
return
if success and full_filename != '-':
def fixup():
do_fixup = True
fixup_policy = self.params.get('fixup')
vid = info_dict['id']
if fixup_policy in ('ignore', 'never'):
return
elif fixup_policy == 'warn':
do_fixup = False
elif fixup_policy != 'force':
assert fixup_policy in ('detect_or_warn', None)
if not info_dict.get('__real_download'):
do_fixup = False
def ffmpeg_fixup(cndn, msg, cls):
if not cndn:
return
if not do_fixup:
self.report_warning(f'{vid}: {msg}')
return
pp = cls(self)
if pp.available:
info_dict['__postprocessors'].append(pp)
else:
self.report_warning(f'{vid}: {msg}. Install ffmpeg to fix this automatically')
stretched_ratio = info_dict.get('stretched_ratio')
ffmpeg_fixup(
stretched_ratio not in (1, None),
f'Non-uniform pixel ratio {stretched_ratio}',
FFmpegFixupStretchedPP)
ffmpeg_fixup(
(info_dict.get('requested_formats') is None
and info_dict.get('container') == 'm4a_dash'
and info_dict.get('ext') == 'm4a'),
'writing DASH m4a. Only some players support this container',
FFmpegFixupM4aPP)
downloader = get_suitable_downloader(info_dict, self.params) if 'protocol' in info_dict else None
downloader = downloader.__name__ if downloader else None
ffmpeg_fixup(info_dict.get('requested_formats') is None and downloader == 'HlsFD',
'malformed AAC bitstream detected', FFmpegFixupM3u8PP)
ffmpeg_fixup(downloader == 'WebSocketFragmentFD', 'malformed timestamps detected', FFmpegFixupTimestampPP)
ffmpeg_fixup(downloader == 'WebSocketFragmentFD', 'malformed duration detected', FFmpegFixupDurationPP)
fixup()
try:
info_dict = self.post_process(dl_filename, info_dict, files_to_move)
except PostProcessingError as err:
self.report_error('Postprocessing: %s' % str(err))
return
try:
for ph in self._post_hooks:
ph(info_dict['filepath'])
except Exception as err:
self.report_error('post hooks: %s' % str(err))
return
must_record_download_archive = True
if must_record_download_archive or self.params.get('force_write_download_archive', False):
self.record_download_archive(info_dict)
max_downloads = self.params.get('max_downloads')
if max_downloads is not None and self._num_downloads >= int(max_downloads):
raise MaxDownloadsReached()
def download(self, url_list):
"""Download a given list of URLs."""
outtmpl = self.outtmpl_dict['default']
if (len(url_list) > 1
and outtmpl != '-'
and '%' not in outtmpl
and self.params.get('max_downloads') != 1):
raise SameFileError(outtmpl)
for url in url_list:
try:
# It also downloads the videos
res = self.extract_info(
url, force_generic_extractor=self.params.get('force_generic_extractor', False))
except UnavailableVideoError:
self.report_error('unable to download video')
except MaxDownloadsReached:
self.to_screen('[info] Maximum number of downloads reached')
raise
except ExistingVideoReached:
self.to_screen('[info] Encountered a video that is already in the archive, stopping due to --break-on-existing')
raise
except RejectedVideoReached:
self.to_screen('[info] Encountered a video that did not match filter, stopping due to --break-on-reject')
raise
else:
if self.params.get('dump_single_json', False):
self.post_extract(res)
self.to_stdout(json.dumps(self.sanitize_info(res)))
return self._download_retcode
def download_with_info_file(self, info_filename):
with contextlib.closing(fileinput.FileInput(
[info_filename], mode='r',
openhook=fileinput.hook_encoded('utf-8'))) as f:
# FileInput doesn't have a read method, we can't call json.load
info = self.sanitize_info(json.loads('\n'.join(f)), self.params.get('clean_infojson', True))
try:
self.process_ie_result(info, download=True)
except (DownloadError, EntryNotInPlaylist, ThrottledDownload):
webpage_url = info.get('webpage_url')
if webpage_url is not None:
self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
return self.download([webpage_url])
else:
raise
return self._download_retcode
@staticmethod
def sanitize_info(info_dict, remove_private_keys=False):
''' Sanitize the infodict for converting to json '''
if info_dict is None:
return info_dict
info_dict.setdefault('epoch', int(time.time()))
remove_keys = {'__original_infodict'} # Always remove this since this may contain a copy of the entire dict
keep_keys = ['_type'], # Always keep this to facilitate load-info-json
if remove_private_keys:
remove_keys |= {
'requested_formats', 'requested_subtitles', 'requested_entries',
'filepath', 'entries', 'original_url', 'playlist_autonumber',
}
empty_values = (None, {}, [], set(), tuple())
reject = lambda k, v: k not in keep_keys and (
k.startswith('_') or k in remove_keys or v in empty_values)
else:
reject = lambda k, v: k in remove_keys
filter_fn = lambda obj: (
list(map(filter_fn, obj)) if isinstance(obj, (LazyList, list, tuple, set))
else obj if not isinstance(obj, dict)
else dict((k, filter_fn(v)) for k, v in obj.items() if not reject(k, v)))
return filter_fn(info_dict)
@staticmethod
def filter_requested_info(info_dict, actually_filter=True):
''' Alias of sanitize_info for backward compatibility '''
return YoutubeDL.sanitize_info(info_dict, actually_filter)
def run_pp(self, pp, infodict):
files_to_delete = []
if '__files_to_move' not in infodict:
infodict['__files_to_move'] = {}
try:
files_to_delete, infodict = pp.run(infodict)
except PostProcessingError as e:
# Must be True and not 'only_download'
if self.params.get('ignoreerrors') is True:
self.report_error(e)
return infodict
raise
if not files_to_delete:
return infodict
if self.params.get('keepvideo', False):
for f in files_to_delete:
infodict['__files_to_move'].setdefault(f, '')
else:
for old_filename in set(files_to_delete):
self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
try:
os.remove(encodeFilename(old_filename))
except (IOError, OSError):
self.report_warning('Unable to remove downloaded original file')
if old_filename in infodict['__files_to_move']:
del infodict['__files_to_move'][old_filename]
return infodict
@staticmethod
def post_extract(info_dict):
def actual_post_extract(info_dict):
if info_dict.get('_type') in ('playlist', 'multi_video'):
for video_dict in info_dict.get('entries', {}):
actual_post_extract(video_dict or {})
return
post_extractor = info_dict.get('__post_extractor') or (lambda: {})
extra = post_extractor().items()
info_dict.update(extra)
info_dict.pop('__post_extractor', None)
original_infodict = info_dict.get('__original_infodict') or {}
original_infodict.update(extra)
original_infodict.pop('__post_extractor', None)
actual_post_extract(info_dict or {})
def pre_process(self, ie_info, key='pre_process', files_to_move=None):
info = dict(ie_info)
info['__files_to_move'] = files_to_move or {}
for pp in self._pps[key]:
info = self.run_pp(pp, info)
return info, info.pop('__files_to_move', None)
def post_process(self, filename, ie_info, files_to_move=None):
"""Run all the postprocessors on the given file."""
info = dict(ie_info)
info['filepath'] = filename
info['__files_to_move'] = files_to_move or {}
for pp in ie_info.get('__postprocessors', []) + self._pps['post_process']:
info = self.run_pp(pp, info)
info = self.run_pp(MoveFilesAfterDownloadPP(self), info)
del info['__files_to_move']
for pp in self._pps['after_move']:
info = self.run_pp(pp, info)
return info
def _make_archive_id(self, info_dict):
video_id = info_dict.get('id')
if not video_id:
return
# Future-proof against any change in case
# and backwards compatibility with prior versions
extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
if extractor is None:
url = str_or_none(info_dict.get('url'))
if not url:
return
# Try to find matching extractor for the URL and take its ie_key
for ie_key, ie in self._ies.items():
if ie.suitable(url):
extractor = ie_key
break
else:
return
return '%s %s' % (extractor.lower(), video_id)
def in_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return False
vid_id = self._make_archive_id(info_dict)
if not vid_id:
return False # Incomplete video information
return vid_id in self.archive
def record_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return
vid_id = self._make_archive_id(info_dict)
assert vid_id
with locked_file(fn, 'a', encoding='utf-8') as archive_file:
archive_file.write(vid_id + '\n')
self.archive.add(vid_id)
@staticmethod
def format_resolution(format, default='unknown'):
is_images = format.get('vcodec') == 'none' and format.get('acodec') == 'none'
if format.get('vcodec') == 'none' and format.get('acodec') != 'none':
return 'audio only'
if format.get('resolution') is not None:
return format['resolution']
if format.get('width') and format.get('height'):
res = '%dx%d' % (format['width'], format['height'])
elif format.get('height'):
res = '%sp' % format['height']
elif format.get('width'):
res = '%dx?' % format['width']
elif is_images:
return 'images'
else:
return default
return f'{res} images' if is_images else res
def _format_note(self, fdict):
res = ''
if fdict.get('ext') in ['f4f', 'f4m']:
res += '(unsupported) '
if fdict.get('language'):
if res:
res += ' '
res += '[%s] ' % fdict['language']
if fdict.get('format_note') is not None:
res += fdict['format_note'] + ' '
if fdict.get('tbr') is not None:
res += '%4dk ' % fdict['tbr']
if fdict.get('container') is not None:
if res:
res += ', '
res += '%s container' % fdict['container']
if (fdict.get('vcodec') is not None
and fdict.get('vcodec') != 'none'):
if res:
res += ', '
res += fdict['vcodec']
if fdict.get('vbr') is not None:
res += '@'
elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
res += 'video@'
if fdict.get('vbr') is not None:
res += '%4dk' % fdict['vbr']
if fdict.get('fps') is not None:
if res:
res += ', '
res += '%sfps' % fdict['fps']
if fdict.get('acodec') is not None:
if res:
res += ', '
if fdict['acodec'] == 'none':
res += 'video only'
else:
res += '%-5s' % fdict['acodec']
elif fdict.get('abr') is not None:
if res:
res += ', '
res += 'audio'
if fdict.get('abr') is not None:
res += '@%3dk' % fdict['abr']
if fdict.get('asr') is not None:
res += ' (%5dHz)' % fdict['asr']
if fdict.get('filesize') is not None:
if res:
res += ', '
res += format_bytes(fdict['filesize'])
elif fdict.get('filesize_approx') is not None:
if res:
res += ', '
res += '~' + format_bytes(fdict['filesize_approx'])
return res
def list_formats(self, info_dict):
formats = info_dict.get('formats', [info_dict])
new_format = (
'list-formats' not in self.params.get('compat_opts', [])
and self.params.get('listformats_table', True) is not False)
if new_format:
table = [
[
format_field(f, 'format_id'),
format_field(f, 'ext'),
self.format_resolution(f),
format_field(f, 'fps', '%d'),
format_field(f, 'dynamic_range', '%s', ignore=(None, 'SDR')).replace('HDR', ''),
'|',
format_field(f, 'filesize', ' %s', func=format_bytes) + format_field(f, 'filesize_approx', '~%s', func=format_bytes),
format_field(f, 'tbr', '%4dk'),
shorten_protocol_name(f.get('protocol', '').replace("native", "n")),
'|',
format_field(f, 'vcodec', default='unknown').replace('none', ''),
format_field(f, 'vbr', '%4dk'),
format_field(f, 'acodec', default='unknown').replace('none', ''),
format_field(f, 'abr', '%3dk'),
format_field(f, 'asr', '%5dHz'),
', '.join(filter(None, (
'UNSUPPORTED' if f.get('ext') in ('f4f', 'f4m') else '',
format_field(f, 'language', '[%s]'),
format_field(f, 'format_note'),
format_field(f, 'container', ignore=(None, f.get('ext'))),
))),
] for f in formats if f.get('preference') is None or f['preference'] >= -1000]
header_line = ['ID', 'EXT', 'RESOLUTION', 'FPS', 'HDR', '|', ' FILESIZE', ' TBR', 'PROTO',
'|', 'VCODEC', ' VBR', 'ACODEC', ' ABR', ' ASR', 'MORE INFO']
else:
table = [
[
format_field(f, 'format_id'),
format_field(f, 'ext'),
self.format_resolution(f),
self._format_note(f)]
for f in formats
if f.get('preference') is None or f['preference'] >= -1000]
header_line = ['format code', 'extension', 'resolution', 'note']
self.to_screen(
'[info] Available formats for %s:' % info_dict['id'])
self.to_stdout(render_table(
header_line, table, delim=new_format, extraGap=(0 if new_format else 1), hideEmpty=new_format))
def list_thumbnails(self, info_dict):
thumbnails = list(info_dict.get('thumbnails'))
if not thumbnails:
self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
return
self.to_screen(
'[info] Thumbnails for %s:' % info_dict['id'])
self.to_stdout(render_table(
['ID', 'width', 'height', 'URL'],
[[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
def list_subtitles(self, video_id, subtitles, name='subtitles'):
if not subtitles:
self.to_screen('%s has no %s' % (video_id, name))
return
self.to_screen(
'Available %s for %s:' % (name, video_id))
def _row(lang, formats):
exts, names = zip(*((f['ext'], f.get('name') or 'unknown') for f in reversed(formats)))
if len(set(names)) == 1:
names = [] if names[0] == 'unknown' else names[:1]
return [lang, ', '.join(names), ', '.join(exts)]
self.to_stdout(render_table(
['Language', 'Name', 'Formats'],
[_row(lang, formats) for lang, formats in subtitles.items()],
hideEmpty=True))
def urlopen(self, req):
""" Start an HTTP download """
if isinstance(req, compat_basestring):
req = sanitized_Request(req)
return self._opener.open(req, timeout=self._socket_timeout)
def print_debug_header(self):
if not self.params.get('verbose'):
return
get_encoding = lambda stream: getattr(stream, 'encoding', 'missing (%s)' % type(stream).__name__)
encoding_str = (
'[debug] Encodings: locale %s, fs %s, stdout %s, stderr %s, pref %s\n' % (
locale.getpreferredencoding(),
sys.getfilesystemencoding(),
get_encoding(self._screen_file), get_encoding(self._err_file),
self.get_encoding()))
logger = self.params.get('logger')
if logger:
write_debug = lambda msg: logger.debug(f'[debug] {msg}')
write_debug(encoding_str)
else:
write_debug = lambda msg: self._write_string(f'[debug] {msg}')
write_string(encoding_str, encoding=None)
source = detect_variant()
write_debug('yt-dlp version %s%s\n' % (__version__, '' if source == 'unknown' else f' ({source})'))
if _LAZY_LOADER:
write_debug('Lazy loading extractors enabled\n')
if plugin_extractors or plugin_postprocessors:
write_debug('Plugins: %s\n' % [
'%s%s' % (klass.__name__, '' if klass.__name__ == name else f' as {name}')
for name, klass in itertools.chain(plugin_extractors.items(), plugin_postprocessors.items())])
if self.params.get('compat_opts'):
write_debug('Compatibility options: %s\n' % ', '.join(self.params.get('compat_opts')))
try:
sp = Popen(
['git', 'rev-parse', '--short', 'HEAD'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=os.path.dirname(os.path.abspath(__file__)))
out, err = sp.communicate_or_kill()
out = out.decode().strip()
if re.match('[0-9a-f]+', out):
write_debug('Git HEAD: %s\n' % out)
except Exception:
try:
sys.exc_clear()
except Exception:
pass
def python_implementation():
impl_name = platform.python_implementation()
if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'):
return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3]
return impl_name
write_debug('Python version %s (%s %s) - %s\n' % (
platform.python_version(),
python_implementation(),
platform.architecture()[0],
platform_name()))
exe_versions = FFmpegPostProcessor.get_versions(self)
exe_versions['rtmpdump'] = rtmpdump_version()
exe_versions['phantomjs'] = PhantomJSwrapper._version()
exe_str = ', '.join(
f'{exe} {v}' for exe, v in sorted(exe_versions.items()) if v
) or 'none'
write_debug('exe versions: %s\n' % exe_str)
from .downloader.websocket import has_websockets
from .postprocessor.embedthumbnail import has_mutagen
from .cookies import SQLITE_AVAILABLE, KEYRING_AVAILABLE
lib_str = ', '.join(sorted(filter(None, (
compat_pycrypto_AES and compat_pycrypto_AES.__name__.split('.')[0],
has_websockets and 'websockets',
has_mutagen and 'mutagen',
SQLITE_AVAILABLE and 'sqlite',
KEYRING_AVAILABLE and 'keyring',
)))) or 'none'
write_debug('Optional libraries: %s\n' % lib_str)
write_debug('ANSI escape support: stdout = %s, stderr = %s\n' % (
supports_terminal_sequences(self._screen_file),
supports_terminal_sequences(self._err_file)))
proxy_map = {}
for handler in self._opener.handlers:
if hasattr(handler, 'proxies'):
proxy_map.update(handler.proxies)
write_debug('Proxy map: ' + compat_str(proxy_map) + '\n')
if self.params.get('call_home', False):
ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
write_debug('Public IP address: %s\n' % ipaddr)
return
latest_version = self.urlopen(
'https://yt-dl.org/latest/version').read().decode('utf-8')
if version_tuple(latest_version) > version_tuple(__version__):
self.report_warning(
'You are using an outdated version (newest version: %s)! '
'See https://yt-dl.org/update if you need help updating.' %
latest_version)
def _setup_opener(self):
timeout_val = self.params.get('socket_timeout')
self._socket_timeout = 20 if timeout_val is None else float(timeout_val)
opts_cookiesfrombrowser = self.params.get('cookiesfrombrowser')
opts_cookiefile = self.params.get('cookiefile')
opts_proxy = self.params.get('proxy')
self.cookiejar = load_cookies(opts_cookiefile, opts_cookiesfrombrowser, self)
cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
if opts_proxy is not None:
if opts_proxy == '':
proxies = {}
else:
proxies = {'http': opts_proxy, 'https': opts_proxy}
else:
proxies = compat_urllib_request.getproxies()
# Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
if 'http' in proxies and 'https' not in proxies:
proxies['https'] = proxies['http']
proxy_handler = PerRequestProxyHandler(proxies)
debuglevel = 1 if self.params.get('debug_printtraffic') else 0
https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
redirect_handler = YoutubeDLRedirectHandler()
data_handler = compat_urllib_request_DataHandler()
# When passing our own FileHandler instance, build_opener won't add the
# default FileHandler and allows us to disable the file protocol, which
# can be used for malicious purposes (see
# https://github.com/ytdl-org/youtube-dl/issues/8227)
file_handler = compat_urllib_request.FileHandler()
def file_open(*args, **kwargs):
raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in yt-dlp for security reasons')
file_handler.file_open = file_open
opener = compat_urllib_request.build_opener(
proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler)
# Delete the default user-agent header, which would otherwise apply in
# cases where our custom HTTP handler doesn't come into play
# (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
opener.addheaders = []
self._opener = opener
def encode(self, s):
if isinstance(s, bytes):
return s # Already encoded
try:
return s.encode(self.get_encoding())
except UnicodeEncodeError as err:
err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
raise
def get_encoding(self):
encoding = self.params.get('encoding')
if encoding is None:
encoding = preferredencoding()
return encoding
def _write_info_json(self, label, ie_result, infofn):
''' Write infojson and returns True = written, False = skip, None = error '''
if not self.params.get('writeinfojson'):
return False
elif not infofn:
self.write_debug(f'Skipping writing {label} infojson')
return False
elif not self._ensure_dir_exists(infofn):
return None
elif not self.params.get('overwrites', True) and os.path.exists(infofn):
self.to_screen(f'[info] {label.title()} metadata is already present')
else:
self.to_screen(f'[info] Writing {label} metadata as JSON to: {infofn}')
try:
write_json_file(self.sanitize_info(ie_result, self.params.get('clean_infojson', True)), infofn)
except (OSError, IOError):
self.report_error(f'Cannot write {label} metadata to JSON file {infofn}')
return None
return True
def _write_description(self, label, ie_result, descfn):
''' Write description and returns True = written, False = skip, None = error '''
if not self.params.get('writedescription'):
return False
elif not descfn:
self.write_debug(f'Skipping writing {label} description')
return False
elif not self._ensure_dir_exists(descfn):
return None
elif not self.params.get('overwrites', True) and os.path.exists(descfn):
self.to_screen(f'[info] {label.title()} description is already present')
elif ie_result.get('description') is None:
self.report_warning(f'There\'s no {label} description to write')
return False
else:
try:
self.to_screen(f'[info] Writing {label} description to: {descfn}')
with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
descfile.write(ie_result['description'])
except (OSError, IOError):
self.report_error(f'Cannot write {label} description file {descfn}')
return None
return True
def _write_subtitles(self, info_dict, filename):
''' Write subtitles to file and return list of (sub_filename, final_sub_filename); or None if error'''
ret = []
subtitles = info_dict.get('requested_subtitles')
if not subtitles or not (self.params.get('writesubtitles') or self.params.get('writeautomaticsub')):
# subtitles download errors are already managed as troubles in relevant IE
# that way it will silently go on when used with unsupporting IE
return ret
sub_filename_base = self.prepare_filename(info_dict, 'subtitle')
if not sub_filename_base:
self.to_screen('[info] Skipping writing video subtitles')
return ret
for sub_lang, sub_info in subtitles.items():
sub_format = sub_info['ext']
sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
sub_filename_final = subtitles_filename(sub_filename_base, sub_lang, sub_format, info_dict.get('ext'))
if not self.params.get('overwrites', True) and os.path.exists(sub_filename):
self.to_screen(f'[info] Video subtitle {sub_lang}.{sub_format} is already present')
sub_info['filepath'] = sub_filename
ret.append((sub_filename, sub_filename_final))
continue
self.to_screen(f'[info] Writing video subtitles to: {sub_filename}')
if sub_info.get('data') is not None:
try:
# Use newline='' to prevent conversion of newline characters
# See https://github.com/ytdl-org/youtube-dl/issues/10268
with io.open(sub_filename, 'w', encoding='utf-8', newline='') as subfile:
subfile.write(sub_info['data'])
sub_info['filepath'] = sub_filename
ret.append((sub_filename, sub_filename_final))
continue
except (OSError, IOError):
self.report_error(f'Cannot write video subtitles file {sub_filename}')
return None
try:
sub_copy = sub_info.copy()
sub_copy.setdefault('http_headers', info_dict.get('http_headers'))
self.dl(sub_filename, sub_copy, subtitle=True)
sub_info['filepath'] = sub_filename
ret.append((sub_filename, sub_filename_final))
except (ExtractorError, IOError, OSError, ValueError) + network_exceptions as err:
self.report_warning(f'Unable to download video subtitles for {sub_lang!r}: {err}')
continue
return ret
def _write_thumbnails(self, label, info_dict, filename, thumb_filename_base=None):
''' Write thumbnails to file and return list of (thumb_filename, final_thumb_filename) '''
write_all = self.params.get('write_all_thumbnails', False)
thumbnails, ret = [], []
if write_all or self.params.get('writethumbnail', False):
thumbnails = info_dict.get('thumbnails') or []
multiple = write_all and len(thumbnails) > 1
if thumb_filename_base is None:
thumb_filename_base = filename
if thumbnails and not thumb_filename_base:
self.write_debug(f'Skipping writing {label} thumbnail')
return ret
for t in thumbnails[::-1]:
thumb_ext = (f'{t["id"]}.' if multiple else '') + determine_ext(t['url'], 'jpg')
thumb_display_id = f'{label} thumbnail' + (f' {t["id"]}' if multiple else '')
thumb_filename = replace_extension(filename, thumb_ext, info_dict.get('ext'))
thumb_filename_final = replace_extension(thumb_filename_base, thumb_ext, info_dict.get('ext'))
if not self.params.get('overwrites', True) and os.path.exists(thumb_filename):
ret.append((thumb_filename, thumb_filename_final))
t['filepath'] = thumb_filename
self.to_screen(f'[info] {thumb_display_id.title()} is already present')
else:
self.to_screen(f'[info] Downloading {thumb_display_id} ...')
try:
uf = self.urlopen(t['url'])
self.to_screen(f'[info] Writing {thumb_display_id} to: {thumb_filename}')
with open(encodeFilename(thumb_filename), 'wb') as thumbf:
shutil.copyfileobj(uf, thumbf)
ret.append((thumb_filename, thumb_filename_final))
t['filepath'] = thumb_filename
except network_exceptions as err:
self.report_warning(f'Unable to download {thumb_display_id}: {err}')
if ret and not write_all:
break
return ret
|
from __future__ import annotations
from itertools import zip_longest
from math import floor
from typing import List, Tuple, Union
class Category:
STR_SIZE = 30
ledger: List[dict]
balance: int
def __init__(self, name: str):
self.name = name
self.ledger = []
def deposit(self, amount: Union[float, int], description: str = ""):
self.ledger += [{"amount": float(amount), "description": description}]
return self
def withdraw(self, amount: Union[float, int], description: str = "") -> bool:
if not self.check_funds(amount):
return False
self.deposit(-amount, description)
return True
def get_balance(self) -> Union[float, int]:
return sum([i["amount"] for i in self.ledger])
def transfer(self, amount: Union[float, int], destination: Category):
is_ok = self.withdraw(amount, f"Transfer to {destination.name}")
if not is_ok:
return False
destination.deposit(amount, f"Transfer from {self.name}")
return True
def check_funds(self, amount: Union[float, int]) -> bool:
could_be_processed = self.get_balance() >= amount
return could_be_processed
def __str__(self):
title = self.name.center(self.STR_SIZE, "*")
# modifying for more than 2 decimals won't work
def format_item(amount: Union[int, float], description: str) -> str:
amount_lon = len(str(float(amount)))
if int(amount) == float(amount):
# add extra space to 1.00 instead of 1.0 py default
amount_lon += 1
description_cut = description[: self.STR_SIZE - amount_lon - 1]
description_size = self.STR_SIZE - amount_lon - 1
ITEM_TEMPLATE = f"{{:{description_size}}} {{:>{amount_lon}.2f}}"
return ITEM_TEMPLATE.format(description_cut, amount)
items = "\n".join([format_item(**i) for i in self.ledger])
total = f"Total: {self.get_balance():.2f}"
return "\n".join([title, items, total])
def create_spend_chart(categories: List[Category]):
"""we use categories index order"""
TITLE = "Percentage spent by category"
def get_total_withdraws(cat: Category) -> int:
"""transfer counts as a withdraw, return absolute spend money"""
amounts = [i["amount"] for i in cat.ledger]
return abs(sum(filter(lambda x: x < 1, amounts)))
total_spent: Union[float, int] = sum(map(get_total_withdraws, categories))
# cat stands for category
cat_spent: Tuple = tuple(get_total_withdraws(c) for c in categories)
cat_percentages = tuple((spent / total_spent) * 100 for spent in cat_spent)
ABSTRACT_PERCENTAGE_LINE = "{percentage:>3}| "
# add spaces for each category
ABSTRACT_PERCENTAGE_LINE += " ".join(["{}"] * len(categories))
def get_repr(to_check: Union[float, int], value_expected: Union[float, int]) -> str:
is_major = floor(to_check) >= value_expected
return "o" if is_major else " "
percentage_chart: List[str] = []
for actual_percentage in range(100, -1, -10):
representations = [get_repr(p, actual_percentage) for p in cat_percentages]
percentage_chart += [
ABSTRACT_PERCENTAGE_LINE.format(
percentage=actual_percentage,
*representations,
),
]
# specific modification to pass tests
percentage_chart = [line + " " for line in percentage_chart]
# separator_line
chart_max_len = max(map(len, percentage_chart))
separator_line = f'{'':<4}{'':->{chart_max_len-4}}'
cat_names = [c.name for c in categories]
# iterates trough every char every index of every cat name
# shortest names are filled with blank spaces
name_lines = zip_longest(*cat_names, fillvalue=" ")
# minor adjustment
ABSTRACT_NAME_LINE = f'{'':>5}'
ABSTRACT_NAME_LINE += " ".join(["{}"] * len(categories))
# specific modification to pass tests
ABSTRACT_NAME_LINE += " "
name_lines = [ABSTRACT_NAME_LINE.format(*chars) for chars in name_lines]
return "\n".join([TITLE, *percentage_chart, separator_line, *name_lines])
| from __future__ import annotations
from itertools import zip_longest
from math import floor
from typing import List, Tuple, Union
class Category:
STR_SIZE = 30
ledger: List[dict]
balance: int
def __init__(self, name: str):
self.name = name
self.ledger = []
def deposit(self, amount: Union[float, int], description: str = ""):
self.ledger += [{"amount": float(amount), "description": description}]
return self
def withdraw(self, amount: Union[float, int], description: str = "") -> bool:
if not self.check_funds(amount):
return False
self.deposit(-amount, description)
return True
def get_balance(self) -> Union[float, int]:
return sum([i["amount"] for i in self.ledger])
def transfer(self, amount: Union[float, int], destination: Category):
is_ok = self.withdraw(amount, f"Transfer to {destination.name}")
if not is_ok:
return False
destination.deposit(amount, f"Transfer from {self.name}")
return True
def check_funds(self, amount: Union[float, int]) -> bool:
could_be_processed = self.get_balance() >= amount
return could_be_processed
def __str__(self):
title = self.name.center(self.STR_SIZE, "*")
# modifying for more than 2 decimals won't work
def format_item(amount: Union[int, float], description: str) -> str:
amount_lon = len(str(float(amount)))
if int(amount) == float(amount):
# add extra space to 1.00 instead of 1.0 py default
amount_lon += 1
description_cut = description[: self.STR_SIZE - amount_lon - 1]
description_size = self.STR_SIZE - amount_lon - 1
ITEM_TEMPLATE = f"{{:{description_size}}} {{:>{amount_lon}.2f}}"
return ITEM_TEMPLATE.format(description_cut, amount)
items = "\n".join([format_item(**i) for i in self.ledger])
total = f"Total: {self.get_balance():.2f}"
return "\n".join([title, items, total])
def create_spend_chart(categories: List[Category]):
"""we use categories index order"""
TITLE = "Percentage spent by category"
def get_total_withdraws(cat: Category) -> int:
"""transfer counts as a withdraw, return absolute spend money"""
amounts = [i["amount"] for i in cat.ledger]
return abs(sum(filter(lambda x: x < 1, amounts)))
total_spent: Union[float, int] = sum(map(get_total_withdraws, categories))
# cat stands for category
cat_spent: Tuple = tuple(get_total_withdraws(c) for c in categories)
cat_percentages = tuple((spent / total_spent) * 100 for spent in cat_spent)
ABSTRACT_PERCENTAGE_LINE = "{percentage:>3}| "
# add spaces for each category
ABSTRACT_PERCENTAGE_LINE += " ".join(["{}"] * len(categories))
def get_repr(to_check: Union[float, int], value_expected: Union[float, int]) -> str:
is_major = floor(to_check) >= value_expected
return "o" if is_major else " "
percentage_chart: List[str] = []
for actual_percentage in range(100, -1, -10):
representations = [get_repr(p, actual_percentage) for p in cat_percentages]
percentage_chart += [
ABSTRACT_PERCENTAGE_LINE.format(
percentage=actual_percentage,
*representations,
),
]
# specific modification to pass tests
percentage_chart = [line + " " for line in percentage_chart]
# separator_line
chart_max_len = max(map(len, percentage_chart))
separator_line = f'{"":<4}{"":->{chart_max_len-4}}'
cat_names = [c.name for c in categories]
# iterates trough every char every index of every cat name
# shortest names are filled with blank spaces
name_lines = zip_longest(*cat_names, fillvalue=" ")
# minor adjustment
ABSTRACT_NAME_LINE = f'{"":>5}'
ABSTRACT_NAME_LINE += " ".join(["{}"] * len(categories))
# specific modification to pass tests
ABSTRACT_NAME_LINE += " "
name_lines = [ABSTRACT_NAME_LINE.format(*chars) for chars in name_lines]
return "\n".join([TITLE, *percentage_chart, separator_line, *name_lines])
|
"""Main classes to add caching features to ``requests.Session``
.. autosummary::
:nosignatures:
CachedSession
CacheMixin
.. Explicitly show inherited method docs on CachedSession instead of CachedMixin
.. autoclass:: requests_cache.session.CachedSession
:show-inheritance:
:inherited-members:
.. autoclass:: requests_cache.session.CacheMixin
"""
from contextlib import contextmanager
from logging import getLogger
from threading import RLock
from typing import TYPE_CHECKING, Callable, Dict, Iterable, Optional
from requests import PreparedRequest, Response
from requests import Session as OriginalSession
from requests.hooks import dispatch_hook
from urllib3 import filepost
from ._utils import get_valid_kwargs
from .backends import BackendSpecifier, init_backend
from .cache_control import CacheActions, ExpirationTime, get_expiration_seconds
from .models import AnyResponse, CachedResponse, set_response_defaults
__all__ = ['ALL_METHODS', 'CachedSession', 'CacheMixin']
ALL_METHODS = ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
FILTER_FN = Callable[[AnyResponse], bool]
logger = getLogger(__name__)
if TYPE_CHECKING:
MIXIN_BASE = OriginalSession
else:
MIXIN_BASE = object
class CacheMixin(MIXIN_BASE):
"""Mixin class that extends :py:class:`requests.Session` with caching features.
See :py:class:`.CachedSession` for usage details.
"""
def __init__(
self,
cache_name: str = 'http_cache',
backend: BackendSpecifier = None,
expire_after: ExpirationTime = -1,
urls_expire_after: Dict[str, ExpirationTime] = None,
cache_control: bool = False,
allowable_codes: Iterable[int] = (200,),
allowable_methods: Iterable[str] = ('GET', 'HEAD'),
filter_fn: FILTER_FN = None,
stale_if_error: bool = False,
**kwargs,
):
self.cache = init_backend(cache_name, backend, **kwargs)
self.allowable_codes = allowable_codes
self.allowable_methods = allowable_methods
self.expire_after = expire_after
self.urls_expire_after = urls_expire_after
self.cache_control = cache_control
self.filter_fn = filter_fn or (lambda r: True)
self.stale_if_error = stale_if_error or kwargs.pop('old_data_on_error', False)
self._disabled = False
self._lock = RLock()
# If the superclass is custom Session, pass along any valid kwargs
session_kwargs = get_valid_kwargs(super().__init__, kwargs)
super().__init__(**session_kwargs) # type: ignore
def request( # type: ignore # Note: An extra param (expire_after) is added here
self,
method: str,
url: str,
*args,
expire_after: ExpirationTime = None,
**kwargs,
) -> AnyResponse:
"""This method prepares and sends a request while automatically performing any necessary
caching operations. This will be called by any other method-specific ``requests`` functions
(get, post, etc.). This does not include prepared requests, which will still be cached via
``send()``.
See :py:meth:`requests.Session.request` for parameters. Additional parameters:
Args:
expire_after: Expiration time to set only for this request; see details below.
Overrides ``CachedSession.expire_after``. Accepts all the same values as
``CachedSession.expire_after``. Use ``-1`` to disable expiration.
Returns:
Either a new or cached response
**Order of operations:** For reference, a request will pass through the following methods:
1. :py:func:`requests.get`/:py:meth:`requests.Session.get` or other method-specific functions (optional)
2. :py:meth:`.CachedSession.request`
3. :py:meth:`requests.Session.request`
4. :py:meth:`.CachedSession.send`
5. :py:meth:`.BaseCache.get_response`
6. :py:meth:`requests.Session.send` (if not previously cached)
7. :py:meth:`.BaseCache.save_response` (if not previously cached)
"""
# If present, set per-request expiration as a request header, to be handled in send()
if expire_after is not None:
kwargs.setdefault('headers', {})
kwargs['headers']['Cache-Control'] = f'max-age={get_expiration_seconds(expire_after)}'
with patch_form_boundary(**kwargs):
return super().request(method, url, *args, **kwargs)
def send(
self, request: PreparedRequest, expire_after: ExpirationTime = None, **kwargs
) -> AnyResponse:
"""Send a prepared request, with caching. See :py:meth:`.request` for notes on behavior, and
see :py:meth:`requests.Session.send` for parameters. Additional parameters:
Args:
expire_after: Expiration time to set only for this request
"""
# Determine which actions to take based on request info and cache settings
cache_key = self.cache.create_key(request, **kwargs)
actions = CacheActions.from_request(
cache_key=cache_key,
request=request,
request_expire_after=expire_after,
session_expire_after=self.expire_after,
urls_expire_after=self.urls_expire_after,
cache_control=self.cache_control,
**kwargs,
)
# Attempt to fetch a cached response
cached_response: Optional[CachedResponse] = None
if not (self._disabled or actions.skip_read):
cached_response = self.cache.get_response(cache_key)
actions.update_from_cached_response(cached_response)
is_expired = getattr(cached_response, 'is_expired', False)
# If the response is expired or missing, or the cache is disabled, then fetch a new response
if cached_response is None:
response = self._send_and_cache(request, actions, **kwargs)
elif is_expired and self.stale_if_error:
response = self._resend_and_ignore(request, actions, cached_response, **kwargs)
elif is_expired:
response = self._resend(request, actions, cached_response, **kwargs)
else:
response = cached_response
# If the request has been filtered out and was previously cached, delete it
if not self.filter_fn(response):
logger.debug(f'Deleting filtered response for URL: {response.url}')
self.cache.delete(cache_key)
return response
# Dispatch any hooks here, because they are removed before pickling
return dispatch_hook('response', request.hooks, response, **kwargs)
def _is_cacheable(self, response: Response, actions: CacheActions) -> bool:
"""Perform all checks needed to determine if the given response should be saved to the cache"""
cache_criteria = {
'disabled cache': self._disabled,
'disabled method': str(response.request.method) not in self.allowable_methods,
'disabled status': response.status_code not in self.allowable_codes,
'disabled by filter': not self.filter_fn(response),
'disabled by headers or expiration params': actions.skip_write,
}
logger.debug(f'Pre-cache checks for response from {response.url}: {cache_criteria}')
return not any(cache_criteria.values())
def _send_and_cache(
self,
request: PreparedRequest,
actions: CacheActions,
cached_response: CachedResponse = None,
**kwargs,
) -> AnyResponse:
"""Send the request and cache the response, unless disabled by settings or headers.
If applicable, also add headers to make a conditional request. If we get a 304 Not Modified
response, return the stale cache item.
"""
request.headers.update(actions.validation_headers)
response = super().send(request, **kwargs)
actions.update_from_response(response)
if self._is_cacheable(response, actions):
self.cache.save_response(response, actions.cache_key, actions.expires)
elif cached_response and response.status_code == 304:
return self._update_revalidated_response(actions, response, cached_response)
else:
logger.debug(f'Skipping cache write for URL: {request.url}')
return set_response_defaults(response, actions.cache_key)
def _resend(
self,
request: PreparedRequest,
actions: CacheActions,
cached_response: CachedResponse,
**kwargs,
) -> AnyResponse:
"""Attempt to resend the request and cache the new response. If the request fails, delete
the stale cache item.
"""
logger.debug('Stale response; attempting to re-send request')
try:
return self._send_and_cache(request, actions, cached_response, **kwargs)
except Exception:
self.cache.delete(actions.cache_key)
raise
def _resend_and_ignore(
self,
request: PreparedRequest,
actions: CacheActions,
cached_response: CachedResponse,
**kwargs,
) -> AnyResponse:
"""Attempt to resend the request and cache the new response. If there are any errors, ignore
them and and return the stale cache item.
"""
# Attempt to send the request and cache the new response
logger.debug('Stale response; attempting to re-send request')
try:
response = self._send_and_cache(request, actions, cached_response, **kwargs)
response.raise_for_status()
return response
except Exception:
logger.warning(
f'Request for URL {request.url} failed; using cached response', exc_info=True
)
return cached_response
def _update_revalidated_response(
self, actions: CacheActions, response: Response, cached_response: CachedResponse
) -> CachedResponse:
"""After revalidation, update the cached response's headers and reset its expiration"""
logger.debug(
f'Response for URL {response.request.url} has not been modified; updating and using cached response'
)
cached_response.headers.update(response.headers)
actions.update_from_response(cached_response)
cached_response.expires = actions.expires
self.cache.save_response(cached_response, actions.cache_key, actions.expires)
return cached_response
@contextmanager
def cache_disabled(self):
"""
Context manager for temporary disabling the cache
.. warning:: This method is not thread-safe.
Example:
>>> s = CachedSession()
>>> with s.cache_disabled():
... s.get('http://httpbin.org/ip')
"""
if self._disabled:
yield
else:
self._disabled = True
try:
yield
finally:
self._disabled = False
def remove_expired_responses(self, expire_after: ExpirationTime = None):
"""Remove expired responses from the cache, optionally with revalidation
Args:
expire_after: A new expiration time used to revalidate the cache
"""
self.cache.remove_expired_responses(expire_after)
def __repr__(self):
repr_attrs = [
'cache',
'expire_after',
'urls_expire_after',
'allowable_codes',
'allowable_methods',
'stale_if_error',
'cache_control',
]
attr_strs = [f'{k}={repr(getattr(self, k))}' for k in repr_attrs]
return f'<CachedSession({', '.join(attr_strs)})>'
class CachedSession(CacheMixin, OriginalSession):
"""Session class that extends :py:class:`requests.Session` with caching features.
See individual :py:mod:`backend classes <requests_cache.backends>` for additional backend-specific arguments.
Also see :ref:`user-guide` for more details and examples on how the following arguments
affect cache behavior.
Args:
cache_name: Cache prefix or namespace, depending on backend
backend: Cache backend name or instance; name may be one of
``['sqlite', 'filesystem', 'mongodb', 'gridfs', 'redis', 'dynamodb', 'memory']``
serializer: Serializer name or instance; name may be one of
``['pickle', 'json', 'yaml', 'bson']``.
expire_after: Time after which cached items will expire
urls_expire_after: Expiration times to apply for different URL patterns
cache_control: Use Cache-Control headers to set expiration
allowable_codes: Only cache responses with one of these status codes
allowable_methods: Cache only responses for one of these HTTP methods
match_headers: Match request headers when reading from the cache; may be either a boolean
or a list of specific headers to match
ignored_parameters: List of request parameters to not match against, and exclude from the cache
filter_fn: Function that takes a :py:class:`~requests.Response` object and returns a boolean
indicating whether or not that response should be cached. Will be applied to both new
and previously cached responses.
key_fn: Function for generating custom cache keys based on request info
stale_if_error: Return stale cache data if a new request raises an exception
"""
@contextmanager
def patch_form_boundary(**request_kwargs):
"""If the ``files`` param is present, patch the form boundary used to separate multipart
uploads. ``requests`` does not provide a way to pass a custom boundary to urllib3, so this just
monkey-patches it instead.
"""
if request_kwargs.get('files'):
original_boundary = filepost.choose_boundary
filepost.choose_boundary = lambda: '##requests-cache-form-boundary##'
yield
filepost.choose_boundary = original_boundary
else:
yield
| """Main classes to add caching features to ``requests.Session``
.. autosummary::
:nosignatures:
CachedSession
CacheMixin
.. Explicitly show inherited method docs on CachedSession instead of CachedMixin
.. autoclass:: requests_cache.session.CachedSession
:show-inheritance:
:inherited-members:
.. autoclass:: requests_cache.session.CacheMixin
"""
from contextlib import contextmanager
from logging import getLogger
from threading import RLock
from typing import TYPE_CHECKING, Callable, Dict, Iterable, Optional
from requests import PreparedRequest, Response
from requests import Session as OriginalSession
from requests.hooks import dispatch_hook
from urllib3 import filepost
from ._utils import get_valid_kwargs
from .backends import BackendSpecifier, init_backend
from .cache_control import CacheActions, ExpirationTime, get_expiration_seconds
from .models import AnyResponse, CachedResponse, set_response_defaults
__all__ = ['ALL_METHODS', 'CachedSession', 'CacheMixin']
ALL_METHODS = ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
FILTER_FN = Callable[[AnyResponse], bool]
logger = getLogger(__name__)
if TYPE_CHECKING:
MIXIN_BASE = OriginalSession
else:
MIXIN_BASE = object
class CacheMixin(MIXIN_BASE):
"""Mixin class that extends :py:class:`requests.Session` with caching features.
See :py:class:`.CachedSession` for usage details.
"""
def __init__(
self,
cache_name: str = 'http_cache',
backend: BackendSpecifier = None,
expire_after: ExpirationTime = -1,
urls_expire_after: Dict[str, ExpirationTime] = None,
cache_control: bool = False,
allowable_codes: Iterable[int] = (200,),
allowable_methods: Iterable[str] = ('GET', 'HEAD'),
filter_fn: FILTER_FN = None,
stale_if_error: bool = False,
**kwargs,
):
self.cache = init_backend(cache_name, backend, **kwargs)
self.allowable_codes = allowable_codes
self.allowable_methods = allowable_methods
self.expire_after = expire_after
self.urls_expire_after = urls_expire_after
self.cache_control = cache_control
self.filter_fn = filter_fn or (lambda r: True)
self.stale_if_error = stale_if_error or kwargs.pop('old_data_on_error', False)
self._disabled = False
self._lock = RLock()
# If the superclass is custom Session, pass along any valid kwargs
session_kwargs = get_valid_kwargs(super().__init__, kwargs)
super().__init__(**session_kwargs) # type: ignore
def request( # type: ignore # Note: An extra param (expire_after) is added here
self,
method: str,
url: str,
*args,
expire_after: ExpirationTime = None,
**kwargs,
) -> AnyResponse:
"""This method prepares and sends a request while automatically performing any necessary
caching operations. This will be called by any other method-specific ``requests`` functions
(get, post, etc.). This does not include prepared requests, which will still be cached via
``send()``.
See :py:meth:`requests.Session.request` for parameters. Additional parameters:
Args:
expire_after: Expiration time to set only for this request; see details below.
Overrides ``CachedSession.expire_after``. Accepts all the same values as
``CachedSession.expire_after``. Use ``-1`` to disable expiration.
Returns:
Either a new or cached response
**Order of operations:** For reference, a request will pass through the following methods:
1. :py:func:`requests.get`/:py:meth:`requests.Session.get` or other method-specific functions (optional)
2. :py:meth:`.CachedSession.request`
3. :py:meth:`requests.Session.request`
4. :py:meth:`.CachedSession.send`
5. :py:meth:`.BaseCache.get_response`
6. :py:meth:`requests.Session.send` (if not previously cached)
7. :py:meth:`.BaseCache.save_response` (if not previously cached)
"""
# If present, set per-request expiration as a request header, to be handled in send()
if expire_after is not None:
kwargs.setdefault('headers', {})
kwargs['headers']['Cache-Control'] = f'max-age={get_expiration_seconds(expire_after)}'
with patch_form_boundary(**kwargs):
return super().request(method, url, *args, **kwargs)
def send(
self, request: PreparedRequest, expire_after: ExpirationTime = None, **kwargs
) -> AnyResponse:
"""Send a prepared request, with caching. See :py:meth:`.request` for notes on behavior, and
see :py:meth:`requests.Session.send` for parameters. Additional parameters:
Args:
expire_after: Expiration time to set only for this request
"""
# Determine which actions to take based on request info and cache settings
cache_key = self.cache.create_key(request, **kwargs)
actions = CacheActions.from_request(
cache_key=cache_key,
request=request,
request_expire_after=expire_after,
session_expire_after=self.expire_after,
urls_expire_after=self.urls_expire_after,
cache_control=self.cache_control,
**kwargs,
)
# Attempt to fetch a cached response
cached_response: Optional[CachedResponse] = None
if not (self._disabled or actions.skip_read):
cached_response = self.cache.get_response(cache_key)
actions.update_from_cached_response(cached_response)
is_expired = getattr(cached_response, 'is_expired', False)
# If the response is expired or missing, or the cache is disabled, then fetch a new response
if cached_response is None:
response = self._send_and_cache(request, actions, **kwargs)
elif is_expired and self.stale_if_error:
response = self._resend_and_ignore(request, actions, cached_response, **kwargs)
elif is_expired:
response = self._resend(request, actions, cached_response, **kwargs)
else:
response = cached_response
# If the request has been filtered out and was previously cached, delete it
if not self.filter_fn(response):
logger.debug(f'Deleting filtered response for URL: {response.url}')
self.cache.delete(cache_key)
return response
# Dispatch any hooks here, because they are removed before pickling
return dispatch_hook('response', request.hooks, response, **kwargs)
def _is_cacheable(self, response: Response, actions: CacheActions) -> bool:
"""Perform all checks needed to determine if the given response should be saved to the cache"""
cache_criteria = {
'disabled cache': self._disabled,
'disabled method': str(response.request.method) not in self.allowable_methods,
'disabled status': response.status_code not in self.allowable_codes,
'disabled by filter': not self.filter_fn(response),
'disabled by headers or expiration params': actions.skip_write,
}
logger.debug(f'Pre-cache checks for response from {response.url}: {cache_criteria}')
return not any(cache_criteria.values())
def _send_and_cache(
self,
request: PreparedRequest,
actions: CacheActions,
cached_response: CachedResponse = None,
**kwargs,
) -> AnyResponse:
"""Send the request and cache the response, unless disabled by settings or headers.
If applicable, also add headers to make a conditional request. If we get a 304 Not Modified
response, return the stale cache item.
"""
request.headers.update(actions.validation_headers)
response = super().send(request, **kwargs)
actions.update_from_response(response)
if self._is_cacheable(response, actions):
self.cache.save_response(response, actions.cache_key, actions.expires)
elif cached_response and response.status_code == 304:
return self._update_revalidated_response(actions, response, cached_response)
else:
logger.debug(f'Skipping cache write for URL: {request.url}')
return set_response_defaults(response, actions.cache_key)
def _resend(
self,
request: PreparedRequest,
actions: CacheActions,
cached_response: CachedResponse,
**kwargs,
) -> AnyResponse:
"""Attempt to resend the request and cache the new response. If the request fails, delete
the stale cache item.
"""
logger.debug('Stale response; attempting to re-send request')
try:
return self._send_and_cache(request, actions, cached_response, **kwargs)
except Exception:
self.cache.delete(actions.cache_key)
raise
def _resend_and_ignore(
self,
request: PreparedRequest,
actions: CacheActions,
cached_response: CachedResponse,
**kwargs,
) -> AnyResponse:
"""Attempt to resend the request and cache the new response. If there are any errors, ignore
them and and return the stale cache item.
"""
# Attempt to send the request and cache the new response
logger.debug('Stale response; attempting to re-send request')
try:
response = self._send_and_cache(request, actions, cached_response, **kwargs)
response.raise_for_status()
return response
except Exception:
logger.warning(
f'Request for URL {request.url} failed; using cached response', exc_info=True
)
return cached_response
def _update_revalidated_response(
self, actions: CacheActions, response: Response, cached_response: CachedResponse
) -> CachedResponse:
"""After revalidation, update the cached response's headers and reset its expiration"""
logger.debug(
f'Response for URL {response.request.url} has not been modified; updating and using cached response'
)
cached_response.headers.update(response.headers)
actions.update_from_response(cached_response)
cached_response.expires = actions.expires
self.cache.save_response(cached_response, actions.cache_key, actions.expires)
return cached_response
@contextmanager
def cache_disabled(self):
"""
Context manager for temporary disabling the cache
.. warning:: This method is not thread-safe.
Example:
>>> s = CachedSession()
>>> with s.cache_disabled():
... s.get('http://httpbin.org/ip')
"""
if self._disabled:
yield
else:
self._disabled = True
try:
yield
finally:
self._disabled = False
def remove_expired_responses(self, expire_after: ExpirationTime = None):
"""Remove expired responses from the cache, optionally with revalidation
Args:
expire_after: A new expiration time used to revalidate the cache
"""
self.cache.remove_expired_responses(expire_after)
def __repr__(self):
repr_attrs = [
'cache',
'expire_after',
'urls_expire_after',
'allowable_codes',
'allowable_methods',
'stale_if_error',
'cache_control',
]
attr_strs = [f'{k}={repr(getattr(self, k))}' for k in repr_attrs]
return f'<CachedSession({", ".join(attr_strs)})>'
class CachedSession(CacheMixin, OriginalSession):
"""Session class that extends :py:class:`requests.Session` with caching features.
See individual :py:mod:`backend classes <requests_cache.backends>` for additional backend-specific arguments.
Also see :ref:`user-guide` for more details and examples on how the following arguments
affect cache behavior.
Args:
cache_name: Cache prefix or namespace, depending on backend
backend: Cache backend name or instance; name may be one of
``['sqlite', 'filesystem', 'mongodb', 'gridfs', 'redis', 'dynamodb', 'memory']``
serializer: Serializer name or instance; name may be one of
``['pickle', 'json', 'yaml', 'bson']``.
expire_after: Time after which cached items will expire
urls_expire_after: Expiration times to apply for different URL patterns
cache_control: Use Cache-Control headers to set expiration
allowable_codes: Only cache responses with one of these status codes
allowable_methods: Cache only responses for one of these HTTP methods
match_headers: Match request headers when reading from the cache; may be either a boolean
or a list of specific headers to match
ignored_parameters: List of request parameters to not match against, and exclude from the cache
filter_fn: Function that takes a :py:class:`~requests.Response` object and returns a boolean
indicating whether or not that response should be cached. Will be applied to both new
and previously cached responses.
key_fn: Function for generating custom cache keys based on request info
stale_if_error: Return stale cache data if a new request raises an exception
"""
@contextmanager
def patch_form_boundary(**request_kwargs):
"""If the ``files`` param is present, patch the form boundary used to separate multipart
uploads. ``requests`` does not provide a way to pass a custom boundary to urllib3, so this just
monkey-patches it instead.
"""
if request_kwargs.get('files'):
original_boundary = filepost.choose_boundary
filepost.choose_boundary = lambda: '##requests-cache-form-boundary##'
yield
filepost.choose_boundary = original_boundary
else:
yield
|
from .segmenter import tools
my_id = "test:read_fluorescence"
__version__ = "0.1"
def register(meta):
meta.id = my_id
meta.name = "Stack loop"
meta.category = "Test"
#meta.run_dep = "simple_stack_reader", "stack"
meta.run_ret = "i_frame", "i_channel"
loop_dependencies = ((my_id, ("_i_frame", "_i_channel")),
("", "stack"))
meta.set_fun("loop_first", loop_next)
meta.set_ret("loop_first", ("_i_frame", "_i_channel"))
meta.set_dep("loop_first", loop_dependencies)
meta.set_ret("loop_next", ("_i_frame", "_i_channel"))
meta.set_dep("loop_next", loop_dependencies)
meta.set_dep("loop_end", loop_dependencies)
def run(_):
return {"_i_frame": 0, "_i_channel": -1}
def loop_next(d):
i_channel = d[my_id]["_i_channel"]
i_frame = d[my_id]["_i_frame"]
stack = d[""]["stack"]
i_channel += 1
if i_channel >= stack.n_channels:
i_channel = 0
i_frame += 1
if i_frame >= stack.n_frames:
raise StopIteration
print("Getting stack")
frame = stack.get_image(frame=i_frame, channel=i_channel)
print("Interpolating")
bg = tools.interpolate_background(frame)
print("Segmenting")
regions = tools.segment_frame(frame, bg)
print("Setting ROIs")
stack.set_rois(regions, "raw", i_frame)
print(f"{my_id}.loop_next: frame={i_frame} channel={i_channel}")
return {"_i_channel": i_channel, "_i_frame": i_frame}
def loop_end(d):
print(f"{my_id}.loop_end: iterated over {d[my_id]["_i_frame"]} frames.")
| from .segmenter import tools
my_id = "test:read_fluorescence"
__version__ = "0.1"
def register(meta):
meta.id = my_id
meta.name = "Stack loop"
meta.category = "Test"
#meta.run_dep = "simple_stack_reader", "stack"
meta.run_ret = "i_frame", "i_channel"
loop_dependencies = ((my_id, ("_i_frame", "_i_channel")),
("", "stack"))
meta.set_fun("loop_first", loop_next)
meta.set_ret("loop_first", ("_i_frame", "_i_channel"))
meta.set_dep("loop_first", loop_dependencies)
meta.set_ret("loop_next", ("_i_frame", "_i_channel"))
meta.set_dep("loop_next", loop_dependencies)
meta.set_dep("loop_end", loop_dependencies)
def run(_):
return {"_i_frame": 0, "_i_channel": -1}
def loop_next(d):
i_channel = d[my_id]["_i_channel"]
i_frame = d[my_id]["_i_frame"]
stack = d[""]["stack"]
i_channel += 1
if i_channel >= stack.n_channels:
i_channel = 0
i_frame += 1
if i_frame >= stack.n_frames:
raise StopIteration
print("Getting stack")
frame = stack.get_image(frame=i_frame, channel=i_channel)
print("Interpolating")
bg = tools.interpolate_background(frame)
print("Segmenting")
regions = tools.segment_frame(frame, bg)
print("Setting ROIs")
stack.set_rois(regions, "raw", i_frame)
print(f"{my_id}.loop_next: frame={i_frame} channel={i_channel}")
return {"_i_channel": i_channel, "_i_frame": i_frame}
def loop_end(d):
print(f"{my_id}.loop_end: iterated over {d[my_id]['_i_frame']} frames.")
|
import asyncio
import enum
import functools
import gzip
import hashlib
import html
import http
import http.cookies
import importlib.util
import inspect
import io
import json
import math
import os
import re
import stat
import sys
import tempfile
import traceback
import typing
from collections import namedtuple
from collections.abc import Sequence
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit, unquote_plus
from enum import Enum
from typing import Any, AsyncGenerator, Iterator
from email.utils import parsedate
from aiofiles.os import stat as aio_stat
from enum import Enum
from email.utils import formatdate
from mimetypes import guess_type
from urllib.parse import quote_plus
from collections.abc import Mapping
try:
import contextvars # Python 3.7+ only.
except ImportError: # pragma: no cover
contextvars = None # type: ignore
# Implemented Feb 27-2021 By Author
if sys.version_info >= (3, 7): # pragma: no cover
from asyncio import create_task
else: # pragma: no cover
from asyncio import ensure_future as create_task
try:
from multipart.multipart import parse_options_header
except ImportError: # pragma: nocover
parse_options_header = None # type: ignore
try:
import aiofiles
from aiofiles.os import stat as aio_stat
except ImportError: # pragma: nocover
aiofiles = None # type: ignore
aio_stat = None # type: ignore
try:
import ujson
except ImportError: # pragma: nocover
ujson = None
try:
import jinja2
except ImportError: # pragma: nocover
jinja2 = None # type: ignore
# type: ignore
#---------------------------------- Configuration --------------
SERVER_PUSH_HEADERS_TO_COPY = {
"accept",
"accept-encoding",
"accept-language",
"cache-control",
"user-agent",
}
#------------- Typing ----------------------------------
Scope = typing.MutableMapping[str, typing.Any]
Message = typing.MutableMapping[str, typing.Any]
Receive = typing.Callable[[], typing.Awaitable[Message]]
Send = typing.Callable[[Message], typing.Awaitable[None]]
ASGIApp = typing.Callable[[Scope, Receive, Send], typing.Awaitable[None]]
#----------------- Concurrency ------------------------------
T = typing.TypeVar("T")
# Implemented Feb 27-2021 By Author Update from starlette 1.3
async def run_until_first_complete(*args: typing.Tuple[typing.Callable, dict]) -> None:
tasks = [create_task(handler(**kwargs)) for handler, kwargs in args]
(done, pending) = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
[task.cancel() for task in pending]
[task.result() for task in done]
async def run_in_threadpool(
func: typing.Callable[..., T], *args: typing.Any, **kwargs: typing.Any
) -> T:
loop = asyncio.get_event_loop()
if contextvars is not None: # pragma: no cover
# Ensure we run in the same context
child = functools.partial(func, *args, **kwargs)
context = contextvars.copy_context()
func = context.run
args = (child,)
elif kwargs: # pragma: no cover
# loop.run_in_executor doesn't accept 'kwargs', so bind them in here
func = functools.partial(func, **kwargs)
return await loop.run_in_executor(None, func, *args)
class _StopIteration(Exception):
pass
def _next(iterator: Iterator) -> Any:
# We can't raise `StopIteration` from within the threadpool iterator
# and catch it outside that context, so we coerce them into a different
# exception type.
try:
return next(iterator)
except StopIteration:
raise _StopIteration
async def iterate_in_threadpool(iterator: Iterator) -> AsyncGenerator:
while True:
try:
yield await run_in_threadpool(_next, iterator)
except _StopIteration:
break
#----------------------------- exceptions ----------------------------------
class HTTPException(Exception):
def __init__(self, status_code: int, detail: str = None) -> None:
if detail is None:
detail = http.HTTPStatus(status_code).phrase
self.status_code = status_code
self.detail = detail
def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"
#---------------- Datastructures ----------------------------
Address = namedtuple("Address", ["host", "port"])
class URL:
def __init__(
self, url: str = "", scope: Scope = None, **components: typing.Any
) -> None:
if scope is not None:
assert not url, 'Cannot set both "url" and "scope".'
assert not components, 'Cannot set both "scope" and "**components".'
scheme = scope.get("scheme", "http")
server = scope.get("server", None)
path = scope.get("root_path", "") + scope["path"]
query_string = scope.get("query_string", b"")
host_header = None
for key, value in scope["headers"]:
if key == b"host":
host_header = value.decode("latin-1")
break
if host_header is not None:
url = f"{scheme}://{host_header}{path}"
elif server is None:
url = path
else:
host, port = server
default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme]
if port == default_port:
url = f"{scheme}://{host}{path}"
else:
url = f"{scheme}://{host}:{port}{path}"
if query_string:
url += "?" + query_string.decode()
elif components:
assert not url, 'Cannot set both "url" and "**components".'
url = URL("").replace(**components).components.geturl()
self._url = url
@property
def components(self) -> SplitResult:
if not hasattr(self, "_components"):
self._components = urlsplit(self._url)
return self._components
@property
def scheme(self) -> str:
return self.components.scheme
@property
def netloc(self) -> str:
return self.components.netloc
@property
def path(self) -> str:
return self.components.path
@property
def query(self) -> str:
return self.components.query
@property
def fragment(self) -> str:
return self.components.fragment
@property
def username(self) -> typing.Union[None, str]:
return self.components.username
@property
def password(self) -> typing.Union[None, str]:
return self.components.password
@property
def hostname(self) -> typing.Union[None, str]:
return self.components.hostname
@property
def port(self) -> typing.Optional[int]:
return self.components.port
@property
def is_secure(self) -> bool:
return self.scheme in ("https", "wss")
def replace(self, **kwargs: typing.Any) -> "URL":
if (
"username" in kwargs
or "password" in kwargs
or "hostname" in kwargs
or "port" in kwargs
):
hostname = kwargs.pop("hostname", self.hostname)
port = kwargs.pop("port", self.port)
username = kwargs.pop("username", self.username)
password = kwargs.pop("password", self.password)
netloc = hostname
if port is not None:
netloc += f":{port}"
if username is not None:
userpass = username
if password is not None:
userpass += f":{password}"
netloc = f"{userpass}@{netloc}"
kwargs["netloc"] = netloc
components = self.components._replace(**kwargs)
return self.__class__(components.geturl())
def include_query_params(self, **kwargs: typing.Any) -> "URL":
params = MultiDict(parse_qsl(self.query, keep_blank_values=True))
params.update({str(key): str(value) for key, value in kwargs.items()})
query = urlencode(params.multi_items())
return self.replace(query=query)
def replace_query_params(self, **kwargs: typing.Any) -> "URL":
query = urlencode([(str(key), str(value)) for key, value in kwargs.items()])
return self.replace(query=query)
def remove_query_params(
self, keys: typing.Union[str, typing.Sequence[str]]
) -> "URL":
if isinstance(keys, str):
keys = [keys]
params = MultiDict(parse_qsl(self.query, keep_blank_values=True))
for key in keys:
params.pop(key, None)
query = urlencode(params.multi_items())
return self.replace(query=query)
def __eq__(self, other: typing.Any) -> bool:
return str(self) == str(other)
def __str__(self) -> str:
return self._url
def __repr__(self) -> str:
url = str(self)
if self.password:
url = str(self.replace(password="********"))
return f"{self.__class__.__name__}({repr(url)})"
class URLPath(str):
"""
A URL path string that may also hold an associated protocol and/or host.
Used by the routing to return `url_path_for` matches.
"""
def __new__(cls, path: str, protocol: str = "", host: str = "") -> "URLPath":
assert protocol in ("http", "websocket", "")
return str.__new__(cls, path) # type: ignore
def __init__(self, path: str, protocol: str = "", host: str = "") -> None:
self.protocol = protocol
self.host = host
def make_absolute_url(self, base_url: typing.Union[str, URL]) -> str:
if isinstance(base_url, str):
base_url = URL(base_url)
if self.protocol:
scheme = {
"http": {True: "https", False: "http"},
"websocket": {True: "wss", False: "ws"},
}[self.protocol][base_url.is_secure]
else:
scheme = base_url.scheme
if self.host:
netloc = self.host
else:
netloc = base_url.netloc
path = base_url.path.rstrip("/") + str(self)
return str(URL(scheme=scheme, netloc=netloc, path=path))
class Secret:
"""
Holds a string value that should not be revealed in tracebacks etc.
You should cast the value to `str` at the point it is required.
"""
def __init__(self, value: str):
self._value = value
def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}('**********')"
def __str__(self) -> str:
return self._value
class CommaSeparatedStrings(Sequence):
def __init__(self, value: typing.Union[str, typing.Sequence[str]]):
if isinstance(value, str):
splitter = shlex(value, posix=True)
splitter.whitespace = ","
splitter.whitespace_split = True
self._items = [item.strip() for item in splitter]
else:
self._items = list(value)
def __len__(self) -> int:
return len(self._items)
def __getitem__(self, index: typing.Union[int, slice]) -> typing.Any:
return self._items[index]
def __iter__(self) -> typing.Iterator[str]:
return iter(self._items)
def __repr__(self) -> str:
class_name = self.__class__.__name__
items = [item for item in self]
return f"{class_name}({items!r})"
def __str__(self) -> str:
return ", ".join([repr(item) for item in self])
class ImmutableMultiDict(typing.Mapping):
def __init__(
self,
*args: typing.Union[
"ImmutableMultiDict",
typing.Mapping,
typing.List[typing.Tuple[typing.Any, typing.Any]],
],
**kwargs: typing.Any,
) -> None:
assert len(args) < 2, "Too many arguments."
if args:
value = args[0]
else:
value = []
if kwargs:
value = (
ImmutableMultiDict(value).multi_items()
+ ImmutableMultiDict(kwargs).multi_items()
)
if not value:
_items = [] # type: typing.List[typing.Tuple[typing.Any, typing.Any]]
elif hasattr(value, "multi_items"):
value = typing.cast(ImmutableMultiDict, value)
_items = list(value.multi_items())
elif hasattr(value, "items"):
value = typing.cast(typing.Mapping, value)
_items = list(value.items())
else:
value = typing.cast(
typing.List[typing.Tuple[typing.Any, typing.Any]], value
)
_items = list(value)
self._dict = {k: v for k, v in _items}
self._list = _items
def getlist(self, key: typing.Any) -> typing.List[str]:
return [item_value for item_key, item_value in self._list if item_key == key]
def keys(self) -> typing.KeysView:
return self._dict.keys()
def values(self) -> typing.ValuesView:
return self._dict.values()
def items(self) -> typing.ItemsView:
return self._dict.items()
def multi_items(self) -> typing.List[typing.Tuple[str, str]]:
return list(self._list)
def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:
if key in self._dict:
return self._dict[key]
return default
def __getitem__(self, key: typing.Any) -> str:
return self._dict[key]
def __contains__(self, key: typing.Any) -> bool:
return key in self._dict
def __iter__(self) -> typing.Iterator[typing.Any]:
return iter(self.keys())
def __len__(self) -> int:
return len(self._dict)
def __eq__(self, other: typing.Any) -> bool:
if not isinstance(other, self.__class__):
return False
return sorted(self._list) == sorted(other._list)
def __repr__(self) -> str:
class_name = self.__class__.__name__
items = self.multi_items()
return f"{class_name}({items!r})"
class MultiDict(ImmutableMultiDict):
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
self.setlist(key, [value])
def __delitem__(self, key: typing.Any) -> None:
self._list = [(k, v) for k, v in self._list if k != key]
del self._dict[key]
def pop(self, key: typing.Any, default: typing.Any = None) -> typing.Any:
self._list = [(k, v) for k, v in self._list if k != key]
return self._dict.pop(key, default)
def popitem(self) -> typing.Tuple:
key, value = self._dict.popitem()
self._list = [(k, v) for k, v in self._list if k != key]
return key, value
def poplist(self, key: typing.Any) -> typing.List:
values = [v for k, v in self._list if k == key]
self.pop(key)
return values
def clear(self) -> None:
self._dict.clear()
self._list.clear()
def setdefault(self, key: typing.Any, default: typing.Any = None) -> typing.Any:
if key not in self:
self._dict[key] = default
self._list.append((key, default))
return self[key]
def setlist(self, key: typing.Any, values: typing.List) -> None:
if not values:
self.pop(key, None)
else:
existing_items = [(k, v) for (k, v) in self._list if k != key]
self._list = existing_items + [(key, value) for value in values]
self._dict[key] = values[-1]
def append(self, key: typing.Any, value: typing.Any) -> None:
self._list.append((key, value))
self._dict[key] = value
def update(
self,
*args: typing.Union[
"MultiDict",
typing.Mapping,
typing.List[typing.Tuple[typing.Any, typing.Any]],
],
**kwargs: typing.Any,
) -> None:
value = MultiDict(*args, **kwargs)
existing_items = [(k, v) for (k, v) in self._list if k not in value.keys()]
self._list = existing_items + value.multi_items()
self._dict.update(value)
class QueryParams(ImmutableMultiDict):
"""
An immutable multidict.
"""
def __init__(
self,
*args: typing.Union[
"ImmutableMultiDict",
typing.Mapping,
typing.List[typing.Tuple[typing.Any, typing.Any]],
str,
bytes,
],
**kwargs: typing.Any,
) -> None:
assert len(args) < 2, "Too many arguments."
value = args[0] if args else []
if isinstance(value, str):
super().__init__(parse_qsl(value, keep_blank_values=True), **kwargs)
elif isinstance(value, bytes):
super().__init__(
parse_qsl(value.decode("latin-1"), keep_blank_values=True), **kwargs
)
else:
super().__init__(*args, **kwargs) # type: ignore
self._list = [(str(k), str(v)) for k, v in self._list]
self._dict = {str(k): str(v) for k, v in self._dict.items()}
def __str__(self) -> str:
return urlencode(self._list)
def __repr__(self) -> str:
class_name = self.__class__.__name__
query_string = str(self)
return f"{class_name}({query_string!r})"
class UploadFile:
"""
An uploaded file included as part of the request data.
"""
spool_max_size = 1024 * 1024
def __init__(
self, filename: str, file: typing.IO = None, content_type: str = ""
) -> None:
self.filename = filename
self.content_type = content_type
if file is None:
file = tempfile.SpooledTemporaryFile(max_size=self.spool_max_size)
self.file = file
async def write(self, data: typing.Union[bytes, str]) -> None:
await run_in_threadpool(self.file.write, data)
async def read(self, size: int = None) -> typing.Union[bytes, str]:
return await run_in_threadpool(self.file.read, size)
async def seek(self, offset: int) -> None:
await run_in_threadpool(self.file.seek, offset)
async def close(self) -> None:
await run_in_threadpool(self.file.close)
class FormData(ImmutableMultiDict):
"""
An immutable multidict, containing both file uploads and text input.
"""
def __init__(
self,
*args: typing.Union[
"FormData",
typing.Mapping[str, typing.Union[str, UploadFile]],
typing.List[typing.Tuple[str, typing.Union[str, UploadFile]]],
],
**kwargs: typing.Union[str, UploadFile],
) -> None:
super().__init__(*args, **kwargs) # type: ignore
async def close(self) -> None:
for key, value in self.multi_items():
if isinstance(value, UploadFile):
await value.close()
class Headers(typing.Mapping[str, str]):
"""
An immutable, case-insensitive multidict.
"""
def __init__(
self,
headers: typing.Mapping[str, str] = None,
raw: typing.List[typing.Tuple[bytes, bytes]] = None,
scope: Scope = None,
) -> None:
self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]
if headers is not None:
assert raw is None, 'Cannot set both "headers" and "raw".'
assert scope is None, 'Cannot set both "headers" and "scope".'
self._list = [
(key.lower().encode("latin-1"), value.encode("latin-1"))
for key, value in headers.items()
]
elif raw is not None:
assert scope is None, 'Cannot set both "raw" and "scope".'
self._list = raw
elif scope is not None:
self._list = scope["headers"]
@property
def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:
return list(self._list)
def keys(self) -> typing.List[str]: # type: ignore
return [key.decode("latin-1") for key, value in self._list]
def values(self) -> typing.List[str]: # type: ignore
return [value.decode("latin-1") for key, value in self._list]
def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore
return [
(key.decode("latin-1"), value.decode("latin-1"))
for key, value in self._list
]
def get(self, key: str, default: typing.Any = None) -> typing.Any:
try:
return self[key]
except KeyError:
return default
def getlist(self, key: str) -> typing.List[str]:
get_header_key = key.lower().encode("latin-1")
return [
item_value.decode("latin-1")
for item_key, item_value in self._list
if item_key == get_header_key
]
def mutablecopy(self) -> "MutableHeaders":
return MutableHeaders(raw=self._list[:])
def __getitem__(self, key: str) -> str:
get_header_key = key.lower().encode("latin-1")
for header_key, header_value in self._list:
if header_key == get_header_key:
return header_value.decode("latin-1")
raise KeyError(key)
def __contains__(self, key: typing.Any) -> bool:
get_header_key = key.lower().encode("latin-1")
for header_key, header_value in self._list:
if header_key == get_header_key:
return True
return False
def __iter__(self) -> typing.Iterator[typing.Any]:
return iter(self.keys())
def __len__(self) -> int:
return len(self._list)
def __eq__(self, other: typing.Any) -> bool:
if not isinstance(other, Headers):
return False
return sorted(self._list) == sorted(other._list)
def __repr__(self) -> str:
class_name = self.__class__.__name__
as_dict = dict(self.items())
if len(as_dict) == len(self):
return f"{class_name}({as_dict!r})"
return f"{class_name}(raw={self.raw!r})"
class MutableHeaders(Headers):
def __setitem__(self, key: str, value: str) -> None:
"""
Set the header `key` to `value`, removing any duplicate entries.
Retains insertion order.
"""
set_key = key.lower().encode("latin-1")
set_value = value.encode("latin-1")
found_indexes = []
for idx, (item_key, item_value) in enumerate(self._list):
if item_key == set_key:
found_indexes.append(idx)
for idx in reversed(found_indexes[1:]):
del self._list[idx]
if found_indexes:
idx = found_indexes[0]
self._list[idx] = (set_key, set_value)
else:
self._list.append((set_key, set_value))
def __delitem__(self, key: str) -> None:
"""
Remove the header `key`.
"""
del_key = key.lower().encode("latin-1")
pop_indexes = []
for idx, (item_key, item_value) in enumerate(self._list):
if item_key == del_key:
pop_indexes.append(idx)
for idx in reversed(pop_indexes):
del self._list[idx]
@property
def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:
return self._list
def setdefault(self, key: str, value: str) -> str:
"""
If the header `key` does not exist, then set it to `value`.
Returns the header value.
"""
set_key = key.lower().encode("latin-1")
set_value = value.encode("latin-1")
for idx, (item_key, item_value) in enumerate(self._list):
if item_key == set_key:
return item_value.decode("latin-1")
self._list.append((set_key, set_value))
return value
def update(self, other: dict) -> None:
for key, val in other.items():
self[key] = val
def append(self, key: str, value: str) -> None:
"""
Append a header, preserving any duplicate entries.
"""
append_key = key.lower().encode("latin-1")
append_value = value.encode("latin-1")
self._list.append((append_key, append_value))
def add_vary_header(self, vary: str) -> None:
existing = self.get("vary")
if existing is not None:
vary = ", ".join([existing, vary])
self["vary"] = vary
class State(object):
"""
An object that can be used to store arbitrary state.
Used for `request.state` and `app.state`.
"""
def __init__(self, state: typing.Dict = None):
if state is None:
state = {}
super(State, self).__setattr__("_state", state)
def __setattr__(self, key: typing.Any, value: typing.Any) -> None:
self._state[key] = value
def __getattr__(self, key: typing.Any) -> typing.Any:
return self._state.get(key, AttributeError( f"{self.__class__.__name__} Object missing attribute {key}" ))
def __delattr__(self, key: typing.Any) -> None:
try:
del self._state[key]
except KeyError:
return AttributeError( f"{self.__class__.__name__} Object missing attribute {key}" )
#------------------------- Form Parsers ---------------------------------------
try:
from multipart.multipart import parse_options_header
import multipart
except ImportError: # pragma: nocover
parse_options_header = None # type: ignore
multipart = None # type: ignore
class FormMessage(Enum):
FIELD_START = 1
FIELD_NAME = 2
FIELD_DATA = 3
FIELD_END = 4
END = 5
class MultiPartMessage(Enum):
PART_BEGIN = 1
PART_DATA = 2
PART_END = 3
HEADER_FIELD = 4
HEADER_VALUE = 5
HEADER_END = 6
HEADERS_FINISHED = 7
END = 8
def _user_safe_decode(src: bytes, codec: str) -> str:
try:
return src.decode(codec)
except (UnicodeDecodeError, LookupError):
return src.decode("latin-1")
class FormParser:
def __init__(
self, headers: Headers, stream: typing.AsyncGenerator[bytes, None]
) -> None:
assert (
multipart is not None
), "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
self.messages = [] # type: typing.List[typing.Tuple[FormMessage, bytes]]
def on_field_start(self) -> None:
message = (FormMessage.FIELD_START, b"")
self.messages.append(message)
def on_field_name(self, data: bytes, start: int, end: int) -> None:
message = (FormMessage.FIELD_NAME, data[start:end])
self.messages.append(message)
def on_field_data(self, data: bytes, start: int, end: int) -> None:
message = (FormMessage.FIELD_DATA, data[start:end])
self.messages.append(message)
def on_field_end(self) -> None:
message = (FormMessage.FIELD_END, b"")
self.messages.append(message)
def on_end(self) -> None:
message = (FormMessage.END, b"")
self.messages.append(message)
async def parse(self) -> FormData:
# Callbacks dictionary.
callbacks = {
"on_field_start": self.on_field_start,
"on_field_name": self.on_field_name,
"on_field_data": self.on_field_data,
"on_field_end": self.on_field_end,
"on_end": self.on_end,
}
# Create the parser.
parser = multipart.QuerystringParser(callbacks)
field_name = b""
field_value = b""
items = (
[]
) # type: typing.List[typing.Tuple[str, typing.Union[str, UploadFile]]]
# Feed the parser with data from the request.
async for chunk in self.stream:
if chunk:
parser.write(chunk)
else:
parser.finalize()
messages = list(self.messages)
self.messages.clear()
for message_type, message_bytes in messages:
if message_type == FormMessage.FIELD_START:
field_name = b""
field_value = b""
elif message_type == FormMessage.FIELD_NAME:
field_name += message_bytes
elif message_type == FormMessage.FIELD_DATA:
field_value += message_bytes
elif message_type == FormMessage.FIELD_END:
name = unquote_plus(field_name.decode("latin-1"))
value = unquote_plus(field_value.decode("latin-1"))
items.append((name, value))
elif message_type == FormMessage.END:
pass
return FormData(items)
class MultiPartParser:
def __init__(
self, headers: Headers, stream: typing.AsyncGenerator[bytes, None]
) -> None:
assert (
multipart is not None
), "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
self.messages = [] # type: typing.List[typing.Tuple[MultiPartMessage, bytes]]
def on_part_begin(self) -> None:
message = (MultiPartMessage.PART_BEGIN, b"")
self.messages.append(message)
def on_part_data(self, data: bytes, start: int, end: int) -> None:
message = (MultiPartMessage.PART_DATA, data[start:end])
self.messages.append(message)
def on_part_end(self) -> None:
message = (MultiPartMessage.PART_END, b"")
self.messages.append(message)
def on_header_field(self, data: bytes, start: int, end: int) -> None:
message = (MultiPartMessage.HEADER_FIELD, data[start:end])
self.messages.append(message)
def on_header_value(self, data: bytes, start: int, end: int) -> None:
message = (MultiPartMessage.HEADER_VALUE, data[start:end])
self.messages.append(message)
def on_header_end(self) -> None:
message = (MultiPartMessage.HEADER_END, b"")
self.messages.append(message)
def on_headers_finished(self) -> None:
message = (MultiPartMessage.HEADERS_FINISHED, b"")
self.messages.append(message)
def on_end(self) -> None:
message = (MultiPartMessage.END, b"")
self.messages.append(message)
async def parse(self) -> FormData:
# Parse the Content-Type header to get the multipart boundary.
content_type, params = parse_options_header(self.headers["Content-Type"])
charset = params.get(b"charset", "utf-8")
if type(charset) == bytes:
charset = charset.decode("latin-1")
boundary = params.get(b"boundary")
# Callbacks dictionary.
callbacks = {
"on_part_begin": self.on_part_begin,
"on_part_data": self.on_part_data,
"on_part_end": self.on_part_end,
"on_header_field": self.on_header_field,
"on_header_value": self.on_header_value,
"on_header_end": self.on_header_end,
"on_headers_finished": self.on_headers_finished,
"on_end": self.on_end,
}
# Create the parser.
parser = multipart.MultipartParser(boundary, callbacks)
header_field = b""
header_value = b""
content_disposition = None
content_type = b""
field_name = ""
data = b""
file = None # type: typing.Optional[UploadFile]
items = (
[]
) # type: typing.List[typing.Tuple[str, typing.Union[str, UploadFile]]]
# Feed the parser with data from the request.
async for chunk in self.stream:
parser.write(chunk)
messages = list(self.messages)
self.messages.clear()
for message_type, message_bytes in messages:
if message_type == MultiPartMessage.PART_BEGIN:
content_disposition = None
content_type = b""
data = b""
elif message_type == MultiPartMessage.HEADER_FIELD:
header_field += message_bytes
elif message_type == MultiPartMessage.HEADER_VALUE:
header_value += message_bytes
elif message_type == MultiPartMessage.HEADER_END:
field = header_field.lower()
if field == b"content-disposition":
content_disposition = header_value
elif field == b"content-type":
content_type = header_value
header_field = b""
header_value = b""
elif message_type == MultiPartMessage.HEADERS_FINISHED:
disposition, options = parse_options_header(content_disposition)
field_name = _user_safe_decode(options[b"name"], charset)
if b"filename" in options:
filename = _user_safe_decode(options[b"filename"], charset)
file = UploadFile(
filename=filename,
content_type=content_type.decode("latin-1"),
)
else:
file = None
elif message_type == MultiPartMessage.PART_DATA:
if file is None:
data += message_bytes
else:
await file.write(message_bytes)
elif message_type == MultiPartMessage.PART_END:
if file is None:
items.append((field_name, _user_safe_decode(data, charset)))
else:
await file.seek(0)
items.append((field_name, file))
elif message_type == MultiPartMessage.END:
pass
parser.finalize()
return FormData(items)
#------------------------------------ converters ----------------------------------
class Convertor:
regex = ""
def convert(self, value: str) -> typing.Any:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: typing.Any) -> str:
raise NotImplementedError() # pragma: no cover
class StringConvertor(Convertor):
regex = "[^/]+"
def convert(self, value: str) -> typing.Any:
return value
def to_string(self, value: typing.Any) -> str:
value = str(value)
assert "/" not in value, "May not contain path seperators"
assert value, "Must not be empty"
return value
class PathConvertor(Convertor):
regex = ".*"
def convert(self, value: str) -> typing.Any:
return str(value)
def to_string(self, value: typing.Any) -> str:
return str(value)
class IntegerConvertor(Convertor):
regex = "[0-9]+"
def convert(self, value: str) -> typing.Any:
return int(value)
def to_string(self, value: typing.Any) -> str:
value = int(value)
assert value >= 0, "Negative integers are not supported"
return str(value)
class FloatConvertor(Convertor):
regex = "[0-9]+(.[0-9]+)?"
def convert(self, value: str) -> typing.Any:
return float(value)
def to_string(self, value: typing.Any) -> str:
value = float(value)
assert value >= 0.0, "Negative floats are not supported"
assert not math.isnan(value), "NaN values are not supported"
assert not math.isinf(value), "Infinite values are not supported"
return ("%0.20f" % value).rstrip("0").rstrip(".")
CONVERTOR_TYPES = {
"str": StringConvertor(),
"path": PathConvertor(),
"int": IntegerConvertor(),
"float": FloatConvertor(),
}
class EndpointInfo(typing.NamedTuple):
path: str
http_method: str
func: typing.Callable
#-------------------------- Background Tasks ------------------------------
class BackgroundTask:
def __init__(
self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any
) -> None:
self.func = func
self.args = args
self.kwargs = kwargs
self.is_async = asyncio.iscoroutinefunction(func)
async def __call__(self) -> None:
if self.is_async:
await self.func(*self.args, **self.kwargs)
else:
await run_in_threadpool(self.func, *self.args, **self.kwargs)
class BackgroundTasks(BackgroundTask):
def __init__(self, tasks: typing.Sequence[BackgroundTask] = []):
self.tasks = list(tasks)
def add_task(
self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any
) -> None:
task = BackgroundTask(func, *args, **kwargs)
self.tasks.append(task)
async def __call__(self) -> None:
for task in self.tasks:
await task()
#---------------------------- Requests ------------------------------
class ClientDisconnect(Exception):
pass
class HTTPConnection(Mapping):
"""
A base class for incoming HTTP connections, that is used to provide
any functionality that is common to both `Request` and `WebSocket`.
"""
def __init__(self, scope: Scope, receive: Receive = None) -> None:
assert scope["type"] in ("http", "websocket")
self.scope = scope
def __getitem__(self, key: str) -> str:
return self.scope[key]
def __iter__(self) -> typing.Iterator[str]:
return iter(self.scope)
def __len__(self) -> int:
return len(self.scope)
@property
def app(self) -> typing.Any:
return self.scope["app"]
@property
def url(self) -> URL:
if not hasattr(self, "_url"):
self._url = URL(scope=self.scope)
return self._url
@property
def base_url(self) -> URL:
if not hasattr(self, "_base_url"):
base_url_scope = dict(self.scope)
base_url_scope["path"] = "/"
base_url_scope["query_string"] = b""
base_url_scope["root_path"] = base_url_scope.get(
"app_root_path", base_url_scope.get("root_path", "")
)
self._base_url = URL(scope=base_url_scope)
return self._base_url
@property
def headers(self) -> Headers:
if not hasattr(self, "_headers"):
self._headers = Headers(scope=self.scope)
return self._headers
@property
def query_params(self) -> QueryParams:
if not hasattr(self, "_query_params"):
self._query_params = QueryParams(self.scope["query_string"])
return self._query_params
@property
def path_params(self) -> dict:
return self.scope.get("path_params", {})
@property
def cookies(self) -> typing.Dict[str, str]:
if not hasattr(self, "_cookies"):
cookies = {}
cookie_header = self.headers.get("cookie")
if cookie_header:
cookie = http.cookies.SimpleCookie() # type: http.cookies.BaseCookie
cookie.load(cookie_header)
for key, morsel in cookie.items():
cookies[key] = morsel.value
self._cookies = cookies
return self._cookies
@property
def client(self) -> Address:
host, port = self.scope.get("client") or (None, None)
return Address(host=host, port=port)
@property
def session(self) -> dict:
assert (
"session" in self.scope
), "SessionMiddleware must be installed to access request.session"
return self.scope["session"]
@property
def auth(self) -> typing.Any:
assert (
"auth" in self.scope
), "AuthenticationMiddleware must be installed to access request.auth"
return self.scope["auth"]
@property
def user(self) -> typing.Any:
assert (
"user" in self.scope
), "AuthenticationMiddleware must be installed to access request.user"
return self.scope["user"]
@property
def state(self) -> State:
if not hasattr(self, "_state"):
# Ensure 'state' has an empty dict if it's not already populated.
self.scope.setdefault("state", {})
# Create a state instance with a reference to the dict in which it should store info
self._state = State(self.scope["state"])
return self._state
def url_for(self, name: str, **path_params: typing.Any) -> str:
router = self.scope["router"]
url_path = router.url_path_for(name, **path_params)
return url_path.make_absolute_url(base_url=self.base_url)
async def empty_receive() -> Message:
raise RuntimeError("Receive channel has not been made available")
async def empty_send(message: Message) -> None:
raise RuntimeError("Send channel has not been made available")
class Request(HTTPConnection):
def __init__(
self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send
):
super().__init__(scope)
assert scope["type"] == "http"
self._receive = receive
self._send = send
self._stream_consumed = False
self._is_disconnected = False
@property
def method(self) -> str:
return self.scope["method"]
@property
def receive(self) -> Receive:
return self._receive
async def stream(self) -> typing.AsyncGenerator[bytes, None]:
if hasattr(self, "_body"):
yield self._body
yield b""
return
if self._stream_consumed:
raise RuntimeError("Stream consumed")
self._stream_consumed = True
while True:
message = await self._receive()
if message["type"] == "http.request":
body = message.get("body", b"")
if body:
yield body
if not message.get("more_body", False):
break
elif message["type"] == "http.disconnect":
self._is_disconnected = True
raise ClientDisconnect()
yield b""
async def body(self) -> bytes:
if not hasattr(self, "_body"):
chunks = []
async for chunk in self.stream():
chunks.append(chunk)
self._body = b"".join(chunks)
return self._body
async def json(self) -> typing.Any:
if not hasattr(self, "_json"):
body = await self.body()
self._json = json.loads(body)
return self._json
async def form(self) -> FormData:
if not hasattr(self, "_form"):
assert (
parse_options_header is not None
), "The `python-multipart` library must be installed to use form parsing."
content_type_header = self.headers.get("Content-Type")
content_type, options = parse_options_header(content_type_header)
if content_type == b"multipart/form-data":
multipart_parser = MultiPartParser(self.headers, self.stream())
self._form = await multipart_parser.parse()
elif content_type == b"application/x-www-form-urlencoded":
form_parser = FormParser(self.headers, self.stream())
self._form = await form_parser.parse()
else:
self._form = FormData()
return self._form
async def close(self) -> None:
if hasattr(self, "_form"):
await self._form.close()
async def is_disconnected(self) -> bool:
if not self._is_disconnected:
try:
message = await asyncio.wait_for(self._receive(), timeout=0.0000001)
except asyncio.TimeoutError:
message = {}
if message.get("type") == "http.disconnect":
self._is_disconnected = True
return self._is_disconnected
async def send_push_promise(self, path: str) -> None:
if "http.response.push" in self.scope.get("extensions", {}):
raw_headers = []
for name in SERVER_PUSH_HEADERS_TO_COPY:
for value in self.headers.getlist(name):
raw_headers.append(
(name.encode("latin-1"), value.encode("latin-1"))
)
await self._send(
{"type": "http.response.push", "path": path, "headers": raw_headers}
)
#------------------------- Responses ------------------------------
class Response:
media_type = None
charset = "utf-8"
def __init__(
self,
content: typing.Any = None,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
) -> None:
self.body = self.render(content)
self.status_code = status_code
if media_type is not None:
self.media_type = media_type
self.background = background
self.init_headers(headers)
def render(self, content: typing.Any) -> bytes:
if content is None:
return b""
if isinstance(content, bytes):
return content
return content.encode(self.charset)
def init_headers(self, headers: typing.Mapping[str, str] = None) -> None:
if headers is None:
raw_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
populate_content_length = True
populate_content_type = True
else:
raw_headers = [
(k.lower().encode("latin-1"), v.encode("latin-1"))
for k, v in headers.items()
]
keys = [h[0] for h in raw_headers]
populate_content_length = b"content-length" not in keys
populate_content_type = b"content-type" not in keys
body = getattr(self, "body", b"")
if body and populate_content_length:
content_length = str(len(body))
raw_headers.append((b"content-length", content_length.encode("latin-1")))
content_type = self.media_type
if content_type is not None and populate_content_type:
if content_type.startswith("text/"):
content_type += "; charset=" + self.charset
raw_headers.append((b"content-type", content_type.encode("latin-1")))
self.raw_headers = raw_headers
@property
def headers(self) -> MutableHeaders:
if not hasattr(self, "_headers"):
self._headers = MutableHeaders(raw=self.raw_headers)
return self._headers
def set_cookie(
self,
key: str,
value: str = "",
max_age: int = None,
expires: int = None,
path: str = "/",
domain: str = None,
secure: bool = False,
httponly: bool = False,
) -> None:
cookie = http.cookies.SimpleCookie() # type: http.cookies.BaseCookie
cookie[key] = value
if max_age is not None:
cookie[key]["max-age"] = max_age # type: ignore
if expires is not None:
cookie[key]["expires"] = expires # type: ignore
if path is not None:
cookie[key]["path"] = path
if domain is not None:
cookie[key]["domain"] = domain
if secure:
cookie[key]["secure"] = True # type: ignore
if httponly:
cookie[key]["httponly"] = True # type: ignore
cookie_val = cookie.output(header="").strip()
self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
def delete_cookie(self, key: str, path: str = "/", domain: str = None) -> None:
self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
await send({"type": "http.response.body", "body": self.body})
if self.background is not None:
await self.background()
class HTMLResponse(Response):
media_type = "text/html"
class PlainTextResponse(Response):
media_type = "text/plain"
class JSONResponse(Response):
media_type = "application/json"
def render(self, content: typing.Any) -> bytes:
return json.dumps(
content,
ensure_ascii=False,
allow_nan=False,
indent=None,
separators=(",", ":"),
).encode("utf-8")
class UJSONResponse(JSONResponse):
media_type = "application/json"
def render(self, content: typing.Any) -> bytes:
return ujson.dumps(content, ensure_ascii=False).encode("utf-8")
class RedirectResponse(Response):
def __init__(
self, url: typing.Union[str, URL], status_code: int = 307, headers: dict = None
) -> None:
super().__init__(content=b"", status_code=status_code, headers=headers)
self.headers["location"] = quote_plus(str(url), safe=":/%#?&=@[]!$&'()*+,;")
class StreamingResponse(Response):
def __init__(
self,
content: typing.Any,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
) -> None:
if inspect.isasyncgen(content):
self.body_iterator = content
else:
self.body_iterator = iterate_in_threadpool(content)
self.status_code = status_code
self.media_type = self.media_type if media_type is None else media_type
self.background = background
self.init_headers(headers)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
async for chunk in self.body_iterator:
if not isinstance(chunk, bytes):
chunk = chunk.encode(self.charset)
await send({"type": "http.response.body", "body": chunk, "more_body": True})
await send({"type": "http.response.body", "body": b"", "more_body": False})
if self.background is not None:
await self.background()
class FileResponse(Response):
chunk_size = 4096
def __init__(
self,
path: str,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
filename: str = None,
stat_result: os.stat_result = None,
method: str = None,
) -> None:
assert aiofiles is not None, "'aiofiles' must be installed to use FileResponse"
self.path = path
self.status_code = status_code
self.filename = filename
self.send_header_only = method is not None and method.upper() == "HEAD"
if media_type is None:
media_type = guess_type(filename or path)[0] or "text/plain"
self.media_type = media_type
self.background = background
self.init_headers(headers)
if self.filename is not None:
content_disposition = 'attachment; filename="{}"'.format(self.filename)
self.headers.setdefault("content-disposition", content_disposition)
self.stat_result = stat_result
if stat_result is not None:
self.set_stat_headers(stat_result)
def set_stat_headers(self, stat_result: os.stat_result) -> None:
content_length = str(stat_result.st_size)
last_modified = formatdate(stat_result.st_mtime, usegmt=True)
etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
etag = hashlib.md5(etag_base.encode()).hexdigest()
self.headers.setdefault("content-length", content_length)
self.headers.setdefault("last-modified", last_modified)
self.headers.setdefault("etag", etag)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if self.stat_result is None:
try:
stat_result = await aio_stat(self.path)
self.set_stat_headers(stat_result)
except FileNotFoundError:
raise RuntimeError(f"File at path {self.path} does not exist.")
else:
mode = stat_result.st_mode
if not stat.S_ISREG(mode):
raise RuntimeError(f"File at path {self.path} is not a file.")
await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
if self.send_header_only:
await send({"type": "http.response.body"})
else:
async with aiofiles.open(self.path, mode="rb") as file:
more_body = True
while more_body:
chunk = await file.read(self.chunk_size)
more_body = len(chunk) == self.chunk_size
await send(
{
"type": "http.response.body",
"body": chunk,
"more_body": more_body,
}
)
if self.background is not None:
await self.background()
#-------------------------- Routing ________________________________
class NoMatchFound(Exception):
"""
Raised by `.url_for(name, **path_params)` and `.url_path_for(name, **path_params)`
if no matching route exists.
"""
class Match(Enum):
NONE = 0
PARTIAL = 1
FULL = 2
def request_response(func: typing.Callable) -> ASGIApp:
"""
Takes a function or coroutine `func(request) -> response`,
and returns an ASGI application.
"""
is_coroutine = asyncio.iscoroutinefunction(func)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive=receive, send=send)
if is_coroutine:
response = await func(request)
else:
response = await run_in_threadpool(func, request)
await response(scope, receive, send)
return app
def get_name(endpoint: typing.Callable) -> str:
if inspect.isfunction(endpoint) or inspect.isclass(endpoint):
return endpoint.__name__
return endpoint.__class__.__name__
def replace_params(
path: str,
param_convertors: typing.Dict[str, Convertor],
path_params: typing.Dict[str, str],
) -> typing.Tuple[str, dict]:
for key, value in list(path_params.items()):
if "{" + key + "}" in path:
convertor = param_convertors[key]
value = convertor.to_string(value)
path = path.replace("{" + key + "}", value)
path_params.pop(key)
return path, path_params
# Match parameters in URL paths, eg. '{param}', and '{param:int}'
PARAM_REGEX = re.compile("{([a-zA-Z_][a-zA-Z0-9_]*)(:[a-zA-Z_][a-zA-Z0-9_]*)?}")
def compile_path(
path: str,
) -> typing.Tuple[typing.Pattern, str, typing.Dict[str, Convertor]]:
"""
Given a path string, like: "/{username:str}", return a three-tuple
of (regex, format, {param_name:convertor}).
regex: "/(?P<username>[^/]+)"
format: "/{username}"
convertors: {"username": StringConvertor()}
"""
path_regex = "^"
path_format = ""
idx = 0
param_convertors = {}
for match in PARAM_REGEX.finditer(path):
param_name, convertor_type = match.groups("str")
convertor_type = convertor_type.lstrip(":")
assert (
convertor_type in CONVERTOR_TYPES
), f"Unknown path convertor '{convertor_type}'"
convertor = CONVERTOR_TYPES[convertor_type]
path_regex += path[idx : match.start()]
path_regex += f"(?P<{param_name}>{convertor.regex})"
path_format += path[idx : match.start()]
path_format += "{%s}" % param_name
param_convertors[param_name] = convertor
idx = match.end()
path_regex += path[idx:] + "$"
path_format += path[idx:]
return re.compile(path_regex), path_format, param_convertors
class BaseRoute:
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
raise NotImplementedError() # pragma: no cover
def url_path_for(self, name: str, **path_params: str) -> URLPath:
raise NotImplementedError() # pragma: no cover
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
raise NotImplementedError() # pragma: no cover
class Route(BaseRoute):
def __init__(
self,
path: str,
endpoint: typing.Callable,
*,
methods: typing.List[str] = None,
name: str = None,
include_in_schema: bool = True,
) -> None:
assert path.startswith("/"), "Routed paths must start with '/'"
self.path = path
self.endpoint = endpoint
self.name = get_name(endpoint) if name is None else name
self.include_in_schema = include_in_schema
if inspect.isfunction(endpoint) or inspect.ismethod(endpoint):
# Endpoint is function or method. Treat it as `func(request) -> response`.
self.app = request_response(endpoint)
if methods is None:
methods = ["GET"]
else:
# Endpoint is a class. Treat it as ASGI.
self.app = endpoint
if methods is None:
self.methods = None
else:
self.methods = set(method.upper() for method in methods)
if "GET" in self.methods:
self.methods.add("HEAD")
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] == "http":
match = self.path_regex.match(scope["path"])
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
child_scope = {"endpoint": self.endpoint, "path_params": path_params}
if self.methods and scope["method"] not in self.methods:
return Match.PARTIAL, child_scope
else:
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, **path_params: str) -> URLPath:
seen_params = set(path_params.keys())
expected_params = set(self.param_convertors.keys())
if name != self.name or seen_params != expected_params:
raise NoMatchFound()
path, remaining_params = replace_params(
self.path_format, self.param_convertors, path_params
)
assert not remaining_params
return URLPath(path=path, protocol="http")
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if self.methods and scope["method"] not in self.methods:
if "app" in scope:
raise HTTPException(status_code=405)
else:
response = PlainTextResponse("Method Not Allowed", status_code=405)
await response(scope, receive, send)
else:
await self.app(scope, receive, send)
def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, Route)
and self.path == other.path
and self.endpoint == other.endpoint
and self.methods == other.methods
)
class Mount(BaseRoute):
def __init__(
self,
path: str,
app: ASGIApp = None,
routes: typing.List[BaseRoute] = None,
name: str = None,
) -> None:
assert path == "" or path.startswith("/"), "Routed paths must start with '/'"
assert (
app is not None or routes is not None
), "Either 'app=...', or 'routes=' must be specified"
self.path = path.rstrip("/")
if app is not None:
self.app = app # type: ASGIApp
else:
self.app = Router(routes=routes)
self.name = name
self.path_regex, self.path_format, self.param_convertors = compile_path(
self.path + "/{path:path}"
)
@property
def routes(self) -> typing.List[BaseRoute]:
return getattr(self.app, "routes", None)
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] in ("http", "websocket"):
path = scope["path"]
match = self.path_regex.match(path)
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
remaining_path = "/" + matched_params.pop("path")
matched_path = path[: -len(remaining_path)]
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
root_path = scope.get("root_path", "")
child_scope = {
"path_params": path_params,
"app_root_path": scope.get("app_root_path", root_path),
"root_path": root_path + matched_path,
"path": remaining_path,
"endpoint": self.app,
}
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, **path_params: str) -> URLPath:
if self.name is not None and name == self.name and "path" in path_params:
# 'name' matches "<mount_name>".
path_params["path"] = path_params["path"].lstrip("/")
path, remaining_params = replace_params(
self.path_format, self.param_convertors, path_params
)
if not remaining_params:
return URLPath(path=path)
elif self.name is None or name.startswith(self.name + ":"):
if self.name is None:
# No mount name.
remaining_name = name
else:
# 'name' matches "<mount_name>:<child_name>".
remaining_name = name[len(self.name) + 1 :]
path_kwarg = path_params.get("path")
path_params["path"] = ""
path_prefix, remaining_params = replace_params(
self.path_format, self.param_convertors, path_params
)
if path_kwarg is not None:
remaining_params["path"] = path_kwarg
for route in self.routes or []:
try:
url = route.url_path_for(remaining_name, **remaining_params)
return URLPath(
path=path_prefix.rstrip("/") + str(url), protocol=url.protocol
)
except NoMatchFound:
pass
raise NoMatchFound()
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, Mount)
and self.path == other.path
and self.app == other.app
)
class Host(BaseRoute):
def __init__(self, host: str, app: ASGIApp, name: str = None) -> None:
self.host = host
self.app = app
self.name = name
self.host_regex, self.host_format, self.param_convertors = compile_path(host)
@property
def routes(self) -> typing.List[BaseRoute]:
return getattr(self.app, "routes", None)
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] in ("http", "websocket"):
headers = Headers(scope=scope)
host = headers.get("host", "").split(":")[0]
match = self.host_regex.match(host)
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
child_scope = {"path_params": path_params, "endpoint": self.app}
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, **path_params: str) -> URLPath:
if self.name is not None and name == self.name and "path" in path_params:
# 'name' matches "<mount_name>".
path = path_params.pop("path")
host, remaining_params = replace_params(
self.host_format, self.param_convertors, path_params
)
if not remaining_params:
return URLPath(path=path, host=host)
elif self.name is None or name.startswith(self.name + ":"):
if self.name is None:
# No mount name.
remaining_name = name
else:
# 'name' matches "<mount_name>:<child_name>".
remaining_name = name[len(self.name) + 1 :]
host, remaining_params = replace_params(
self.host_format, self.param_convertors, path_params
)
for route in self.routes or []:
try:
url = route.url_path_for(remaining_name, **remaining_params)
return URLPath(path=str(url), protocol=url.protocol, host=host)
except NoMatchFound:
pass
raise NoMatchFound()
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, Host)
and self.host == other.host
and self.app == other.app
)
class Lifespan(BaseRoute):
def __init__(
self,
on_startup: typing.Union[typing.Callable, typing.List[typing.Callable]] = None,
on_shutdown: typing.Union[typing.Callable, typing.List[typing.Callable]] = None,
):
self.startup_handlers = self.to_list(on_startup)
self.shutdown_handlers = self.to_list(on_shutdown)
def to_list(
self, item: typing.Union[typing.Callable, typing.List[typing.Callable]] = None
) -> typing.List[typing.Callable]:
if item is None:
return []
return list(item) if isinstance(item, (list, tuple)) else [item]
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] == "lifespan":
return Match.FULL, {}
return Match.NONE, {}
def add_event_handler(self, event_type: str, func: typing.Callable) -> None:
assert event_type in ("startup", "shutdown")
if event_type == "startup":
self.startup_handlers.append(func)
else:
assert event_type == "shutdown"
self.shutdown_handlers.append(func)
def on_event(self, event_type: str) -> typing.Callable:
def decorator(func: typing.Callable) -> typing.Callable:
self.add_event_handler(event_type, func)
return func
return decorator
async def startup(self) -> None:
for handler in self.startup_handlers:
if asyncio.iscoroutinefunction(handler):
await handler()
else:
handler()
async def shutdown(self) -> None:
for handler in self.shutdown_handlers:
if asyncio.iscoroutinefunction(handler):
await handler()
else:
handler()
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
message = await receive()
assert message["type"] == "lifespan.startup"
try:
await self.startup()
except BaseException:
msg = traceback.format_exc()
await send({"type": "lifespan.startup.failed", "message": msg})
raise
await send({"type": "lifespan.startup.complete"})
message = await receive()
assert message["type"] == "lifespan.shutdown"
await self.shutdown()
await send({"type": "lifespan.shutdown.complete"})
class Router:
def __init__(
self,
routes: typing.List[BaseRoute] = None,
redirect_slashes: bool = True,
default: ASGIApp = None,
on_startup: typing.List[typing.Callable] = None,
on_shutdown: typing.List[typing.Callable] = None,
) -> None:
self.routes = [] if routes is None else list(routes)
self.redirect_slashes = redirect_slashes
self.default = self.not_found if default is None else default
self.lifespan = Lifespan(on_startup=on_startup, on_shutdown=on_shutdown)
def mount(self, path: str, app: ASGIApp, name: str = None) -> None:
route = Mount(path, app=app, name=name)
self.routes.append(route)
def host(self, host: str, app: ASGIApp, name: str = None) -> None:
route = Host(host, app=app, name=name)
self.routes.append(route)
def add_route(
self,
path: str,
endpoint: typing.Callable,
methods: typing.List[str] = None,
name: str = None,
include_in_schema: bool = True,
) -> None:
route = Route(
path,
endpoint=endpoint,
methods=methods,
name=name,
include_in_schema=include_in_schema,
)
self.routes.append(route)
def add_websocket_route(
self, path: str, endpoint: typing.Callable, name: str = None
) -> None:
route = WebSocketRoute(path, endpoint=endpoint, name=name)
self.routes.append(route)
def route(
self,
path: str,
methods: typing.List[str] = None,
name: str = None,
include_in_schema: bool = True,
) -> typing.Callable:
def decorator(func: typing.Callable) -> typing.Callable:
self.add_route(
path,
func,
methods=methods,
name=name,
include_in_schema=include_in_schema,
)
return func
return decorator
def websocket_route(self, path: str, name: str = None) -> typing.Callable:
def decorator(func: typing.Callable) -> typing.Callable:
self.add_websocket_route(path, func, name=name)
return func
return decorator
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "websocket":
websocket_close = WebSocketClose()
await websocket_close(receive, send)
return
# If we're running inside a aspire.core application then raise an
# exception, so that the configurable exception handler can deal with
# returning the response. For plain ASGI apps, just return the response.
if "app" in scope:
raise HTTPException(status_code=404)
else:
response = PlainTextResponse("Not Found", status_code=404)
await response(scope, receive, send)
def url_path_for(self, name: str, **path_params: str) -> URLPath:
for route in self.routes:
try:
return route.url_path_for(name, **path_params)
except NoMatchFound:
pass
raise NoMatchFound()
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] in ("http", "websocket", "lifespan")
if "router" not in scope:
scope["router"] = self
partial = None
for route in self.routes:
match, child_scope = route.matches(scope)
if match == Match.FULL:
scope.update(child_scope)
await route(scope, receive, send)
return
elif match == Match.PARTIAL and partial is None:
partial = route
partial_scope = child_scope
if partial is not None:
scope.update(partial_scope)
await partial(scope, receive, send)
return
if scope["type"] == "http" and self.redirect_slashes:
if not scope["path"].endswith("/"):
redirect_scope = dict(scope)
redirect_scope["path"] += "/"
for route in self.routes:
match, child_scope = route.matches(redirect_scope)
if match != Match.NONE:
redirect_url = URL(scope=redirect_scope)
response = RedirectResponse(url=str(redirect_url))
await response(scope, receive, send)
return
if scope["type"] == "lifespan":
await self.lifespan(scope, receive, send)
else:
await self.default(scope, receive, send)
def __eq__(self, other: typing.Any) -> bool:
return isinstance(other, Router) and self.routes == other.routes
#----------------------------- endpoints ----------------------------------
class HTTPEndpoint:
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "http"
self.scope = scope
self.receive = receive
self.send = send
def __await__(self) -> typing.Generator:
return self.dispatch().__await__()
async def dispatch(self) -> None:
request = Request(self.scope, receive=self.receive)
handler_name = "get" if request.method == "HEAD" else request.method.lower()
handler = getattr(self, handler_name, self.method_not_allowed)
is_async = asyncio.iscoroutinefunction(handler)
if is_async:
response = await handler(request)
else:
response = await run_in_threadpool(handler, request)
await response(self.scope, self.receive, self.send)
async def method_not_allowed(self, request: Request) -> Response:
# If we're running inside a aspire.core application then raise an
# exception, so that the configurable exception handler can deal with
# returning the response. For plain ASGI apps, just return the response.
if "app" in self.scope:
raise HTTPException(status_code=405)
return PlainTextResponse("Method Not Allowed", status_code=405)
#-------------------------- Static Assets --------------------------
class NotModifiedResponse(Response):
NOT_MODIFIED_HEADERS = (
"cache-control",
"content-location",
"date",
"etag",
"expires",
"vary",
)
def __init__(self, headers: Headers):
super().__init__(
status_code=304,
headers={
name: value
for name, value in headers.items()
if name in self.NOT_MODIFIED_HEADERS
},
)
class StaticFiles:
def __init__(
self,
*,
directory: str = None,
packages: typing.List[str] = None,
html: bool = False,
check_dir: bool = True,
) -> None:
self.directory = directory
self.packages = packages
self.all_directories = self.get_directories(directory, packages)
self.html = html
self.config_checked = False
if check_dir and directory is not None and not os.path.isdir(directory):
raise RuntimeError(f"Directory '{directory}' does not exist")
def get_directories(
self, directory: str = None, packages: typing.List[str] = None
) -> typing.List[str]:
"""
Given `directory` and `packages` arguments, return a list of all the
directories that should be used for serving static files from.
"""
directories = []
if directory is not None:
directories.append(directory)
for package in packages or []:
spec = importlib.util.find_spec(package)
assert spec is not None, f"Package {package!r} could not be found."
assert (
spec.origin is not None
), f"Directory 'statics' in package {package!r} could not be found."
directory = os.path.normpath(os.path.join(spec.origin, "..", "statics"))
assert os.path.isdir(
directory
), f"Directory 'statics' in package {package!r} could not be found."
directories.append(directory)
return directories
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""
The ASGI entry point.
"""
assert scope["type"] == "http"
if not self.config_checked:
await self.check_config()
self.config_checked = True
path = self.get_path(scope)
response = await self.get_response(path, scope)
await response(scope, receive, send)
def get_path(self, scope: Scope) -> str:
"""
Given the ASGI scope, return the `path` string to serve up,
with OS specific path seperators, and any '..', '.' components removed.
"""
return os.path.normpath(os.path.join(*scope["path"].split("/")))
async def get_response(self, path: str, scope: Scope) -> Response:
"""
Returns an HTTP response, given the incoming path, method and request headers.
"""
if scope["method"] not in ("GET", "HEAD"):
return PlainTextResponse("Method Not Allowed", status_code=405)
if path.startswith(".."):
# Most clients will normalize the path, so we shouldn't normally
# get this, but don't allow misbehaving clients to break out of
# the static files directory.
return PlainTextResponse("Not Found", status_code=404)
full_path, stat_result = await self.lookup_path(path)
if stat_result and stat.S_ISREG(stat_result.st_mode):
# We have a static file to serve.
return self.file_response(full_path, stat_result, scope)
elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html:
# We're in HTML mode, and have got a directory URL.
# Check if we have 'index.html' file to serve.
index_path = os.path.join(path, "index.html")
full_path, stat_result = await self.lookup_path(index_path)
if stat_result is not None and stat.S_ISREG(stat_result.st_mode):
if not scope["path"].endswith("/"):
# Directory URLs should redirect to always end in "/".
url = URL(scope=scope)
url = url.replace(path=url.path + "/")
return RedirectResponse(url=url)
return self.file_response(full_path, stat_result, scope)
if self.html:
# Check for '404.html' if we're in HTML mode.
full_path, stat_result = await self.lookup_path("404.html")
if stat_result is not None and stat.S_ISREG(stat_result.st_mode):
return FileResponse(
full_path,
stat_result=stat_result,
method=scope["method"],
status_code=404
)
return PlainTextResponse("Not Found", status_code=404)
async def lookup_path(
self, path: str
) -> typing.Tuple[str, typing.Optional[os.stat_result]]:
for directory in self.all_directories:
full_path = os.path.join(directory, path)
if (
os.path.commonprefix([os.path.realpath(full_path), directory])
!= directory
):
full_path = os.path.realpath(os.path.join(directory, path))
directory = os.path.realpath(directory)
if os.path.commonprefix([full_path, directory]) != directory:
# Don't allow misbehaving clients to break out of the static files directory.
continue
try:
stat_result = await aio_stat(full_path)
return (full_path, stat_result)
except FileNotFoundError:
pass
return ("", None)
def file_response(
self,
full_path: str,
stat_result: os.stat_result,
scope: Scope,
status_code: int = 200,
) -> Response:
method = scope["method"]
request_headers = Headers(scope=scope)
response = FileResponse(
full_path, status_code=status_code, stat_result=stat_result, method=method
)
if self.is_not_modified(response.headers, request_headers):
return NotModifiedResponse(response.headers)
return response
async def check_config(self) -> None:
"""
Perform a one-off configuration check that StaticFiles is actually
pointed at a directory, so that we can raise loud errors rather than
just returning 404 responses.
"""
if self.directory is None:
return
try:
stat_result = await aio_stat(self.directory)
except FileNotFoundError:
raise RuntimeError(
f"StaticFiles directory '{self.directory}' does not exist."
)
if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)):
raise RuntimeError(
f"StaticFiles path '{self.directory}' is not a directory."
)
def is_not_modified(
self, response_headers: Headers, request_headers: Headers
) -> bool:
"""
Given the request and response headers, return `True` if an HTTP
"Not Modified" response could be returned instead.
"""
try:
if_none_match = request_headers["if-none-match"]
etag = response_headers["etag"]
if if_none_match == etag:
return True
except KeyError:
pass
try:
if_modified_since = parsedate(request_headers["if-modified-since"])
last_modified = parsedate(response_headers["last-modified"])
if (
if_modified_since is not None
and last_modified is not None
and if_modified_since >= last_modified
):
return True
except KeyError:
pass
return False
#-------------------------- Template Services ----------------------
class _TemplateResponse(Response):
media_type = "text/html"
def __init__(
self,
template: typing.Any,
context: dict,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
):
self.template = template
self.context = context
content = template.render(context)
super().__init__(content, status_code, headers, media_type, background)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
request = self.context.get("request", {})
extensions = request.get("extensions", {})
if "http.response.template" in extensions:
await send(
{
"type": "http.response.template",
"template": self.template,
"context": self.context,
}
)
await super().__call__(scope, receive, send)
class JinjaTemplates:
"""
templates = Templates("templates")
return templates.TemplateResponse("index.html", {"request": request})
"""
def __init__(self, directory: str) -> None:
assert jinja2 is not None, "jinja2 must be installed to use Templates"
self.env = self.get_env(directory)
def get_env(self, directory: str) -> "jinja2.Environment":
@jinja2.contextfunction
def url_for(context: dict, name: str, **path_params: typing.Any) -> str:
request = context["request"]
return request.url_for(name, **path_params)
loader = jinja2.FileSystemLoader(directory)
env = jinja2.Environment(loader=loader, autoescape=True)
env.globals["url_for"] = url_for
return env
def get_template(self, name: str) -> "jinja2.Template":
return self.env.get_template(name)
def TemplateResponse(
self,
name: str,
context: dict,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
) -> _TemplateResponse:
if "request" not in context:
raise ValueError('context must include a "request" key')
template = self.get_template(name)
return _TemplateResponse(
template,
context,
status_code=status_code,
headers=headers,
media_type=media_type,
background=background,
)
#-------------------------- Network Services -----------------------
def build_environ(scope: Scope, body: bytes) -> dict:
"""
Builds a scope and request body into a WSGI environ object.
"""
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": scope.get("root_path", ""),
"PATH_INFO": scope["path"],
"QUERY_STRING": scope["query_string"].decode("ascii"),
"SERVER_PROTOCOL": f"HTTP/{scope["http_version"]}",
"wsgi.version": (1, 0),
"wsgi.url_scheme": scope.get("scheme", "http"),
"wsgi.input": io.BytesIO(body),
"wsgi.errors": sys.stdout,
"wsgi.multithread": True,
"wsgi.multiprocess": True,
"wsgi.run_once": False,
}
# Get server name and port - required in WSGI, not in ASGI
server = scope.get("server") or ("localhost", 80)
environ["SERVER_NAME"] = server[0]
environ["SERVER_PORT"] = server[1]
# Get client IP address
if scope.get("client"):
environ["REMOTE_ADDR"] = scope["client"][0]
# Go through headers and make them into environ entries
for name, value in scope.get("headers", []):
name = name.decode("latin1")
if name == "content-length":
corrected_name = "CONTENT_LENGTH"
elif name == "content-type":
corrected_name = "CONTENT_TYPE"
else:
corrected_name = f"HTTP_{name}".upper().replace("-", "_")
# HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
value = value.decode("latin1")
if corrected_name in environ:
value = environ[corrected_name] + "," + value
environ[corrected_name] = value
return environ
###--------------------- Web Sockets -------------------------------
class WebSocketState(enum.Enum):
CONNECTING = 0
CONNECTED = 1
DISCONNECTED = 2
class WebSocketDisconnect(Exception):
def __init__(self, code: int = 1000) -> None:
self.code = code
class WebSocket(HTTPConnection):
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
super().__init__(scope)
assert scope["type"] == "websocket"
self._receive = receive
self._send = send
self.client_state = WebSocketState.CONNECTING
self.application_state = WebSocketState.CONNECTING
async def receive(self) -> Message:
"""
Receive ASGI websocket messages, ensuring valid state transitions.
"""
if self.client_state == WebSocketState.CONNECTING:
message = await self._receive()
message_type = message["type"]
assert message_type == "websocket.connect"
self.client_state = WebSocketState.CONNECTED
return message
elif self.client_state == WebSocketState.CONNECTED:
message = await self._receive()
message_type = message["type"]
assert message_type in {"websocket.receive", "websocket.disconnect"}
if message_type == "websocket.disconnect":
self.client_state = WebSocketState.DISCONNECTED
return message
else:
raise RuntimeError(
'Cannot call "receive" once a disconnect message has been received.'
)
async def send(self, message: Message) -> None:
"""
Send ASGI websocket messages, ensuring valid state transitions.
"""
if self.application_state == WebSocketState.CONNECTING:
message_type = message["type"]
assert message_type in {"websocket.accept", "websocket.close"}
if message_type == "websocket.close":
self.application_state = WebSocketState.DISCONNECTED
else:
self.application_state = WebSocketState.CONNECTED
await self._send(message)
elif self.application_state == WebSocketState.CONNECTED:
message_type = message["type"]
assert message_type in {"websocket.send", "websocket.close"}
if message_type == "websocket.close":
self.application_state = WebSocketState.DISCONNECTED
await self._send(message)
else:
raise RuntimeError('Cannot call "send" once a close message has been sent.')
async def accept(self, subprotocol: str = None) -> None:
if self.client_state == WebSocketState.CONNECTING:
# If we haven't yet seen the 'connect' message, then wait for it first.
await self.receive()
await self.send({"type": "websocket.accept", "subprotocol": subprotocol})
def _raise_on_disconnect(self, message: Message) -> None:
if message["type"] == "websocket.disconnect":
raise WebSocketDisconnect(message["code"])
async def receive_text(self) -> str:
assert self.application_state == WebSocketState.CONNECTED
message = await self.receive()
self._raise_on_disconnect(message)
return message["text"]
async def receive_bytes(self) -> bytes:
assert self.application_state == WebSocketState.CONNECTED
message = await self.receive()
self._raise_on_disconnect(message)
return message["bytes"]
async def receive_json(self, mode: str = "text") -> typing.Any:
assert mode in ["text", "binary"]
assert self.application_state == WebSocketState.CONNECTED
message = await self.receive()
self._raise_on_disconnect(message)
if mode == "text":
text = message["text"]
else:
text = message["bytes"].decode("utf-8")
return json.loads(text)
async def send_text(self, data: str) -> None:
await self.send({"type": "websocket.send", "text": data})
async def send_bytes(self, data: bytes) -> None:
await self.send({"type": "websocket.send", "bytes": data})
async def send_json(self, data: typing.Any, mode: str = "text") -> None:
assert mode in ["text", "binary"]
text = json.dumps(data)
if mode == "text":
await self.send({"type": "websocket.send", "text": text})
else:
await self.send({"type": "websocket.send", "bytes": text.encode("utf-8")})
async def close(self, code: int = 1000) -> None:
await self.send({"type": "websocket.close", "code": code})
class WebSocketClose:
def __init__(self, code: int = 1000) -> None:
self.code = code
async def __call__(self, receive: Receive, send: Send) -> None:
await send({"type": "websocket.close", "code": self.code})
class WebSocketEndpoint:
encoding = None # May be "text", "bytes", or "json".
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "websocket"
self.scope = scope
self.receive = receive
self.send = send
def __await__(self) -> typing.Generator:
return self.dispatch().__await__()
async def dispatch(self) -> None:
websocket = WebSocket(self.scope, receive=self.receive, send=self.send)
await self.on_connect(websocket)
close_code = status.WS_1000_NORMAL_CLOSURE
try:
while True:
message = await websocket.receive()
if message["type"] == "websocket.receive":
data = await self.decode(websocket, message)
await self.on_receive(websocket, data)
elif message["type"] == "websocket.disconnect":
close_code = int(message.get("code", status.WS_1000_NORMAL_CLOSURE))
break
except Exception as exc:
close_code = status.WS_1011_INTERNAL_ERROR
raise exc from None
finally:
await self.on_disconnect(websocket, close_code)
async def decode(self, websocket: WebSocket, message: Message) -> typing.Any:
if self.encoding == "text":
if "text" not in message:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Expected text websocket messages, but got bytes")
return message["text"]
elif self.encoding == "bytes":
if "bytes" not in message:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Expected bytes websocket messages, but got text")
return message["bytes"]
elif self.encoding == "json":
if message.get("text") is not None:
text = message["text"]
else:
text = message["bytes"].decode("utf-8")
try:
return json.loads(text)
except json.decoder.JSONDecodeError:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Malformed JSON data received.")
assert (
self.encoding is None
), f"Unsupported 'encoding' attribute {self.encoding}"
return message["text"] if message.get("text") else message["bytes"]
async def on_connect(self, websocket: WebSocket) -> None:
"""Override to handle an incoming websocket connection"""
await websocket.accept()
async def on_receive(self, websocket: WebSocket, data: typing.Any) -> None:
"""Override to handle an incoming websocket message"""
async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None:
"""Override to handle a disconnecting websocket"""
def websocket_session(func: typing.Callable) -> ASGIApp:
"""
Takes a coroutine `func(session)`, and returns an ASGI application.
"""
# assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async"
async def app(scope: Scope, receive: Receive, send: Send) -> None:
session = WebSocket(scope, receive=receive, send=send)
await func(session)
return app
class WebSocketRoute(BaseRoute):
def __init__(
self, path: str, endpoint: typing.Callable, *, name: str = None
) -> None:
assert path.startswith("/"), "Routed paths must start with '/'"
self.path = path
self.endpoint = endpoint
self.name = get_name(endpoint) if name is None else name
if inspect.isfunction(endpoint) or inspect.ismethod(endpoint):
# Endpoint is function or method. Treat it as `func(websocket)`.
self.app = websocket_session(endpoint)
else:
# Endpoint is a class. Treat it as ASGI.
self.app = endpoint
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] == "websocket":
match = self.path_regex.match(scope["path"])
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
child_scope = {"endpoint": self.endpoint, "path_params": path_params}
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, **path_params: str) -> URLPath:
seen_params = set(path_params.keys())
expected_params = set(self.param_convertors.keys())
if name != self.name or seen_params != expected_params:
raise NoMatchFound()
path, remaining_params = replace_params(
self.path_format, self.param_convertors, path_params
)
assert not remaining_params
return URLPath(path=path, protocol="websocket")
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, WebSocketRoute)
and self.path == other.path
and self.endpoint == other.endpoint
)
###--------------------- Web Server Gateway Interface (WSGI) -------------------
class WSGIResponder:
def __init__(self, app: typing.Callable, scope: Scope) -> None:
self.app = app
self.scope = scope
self.status = None
self.response_headers = None
self.send_event = asyncio.Event()
self.send_queue = [] # type: typing.List[typing.Optional[Message]]
self.loop = asyncio.get_event_loop()
self.response_started = False
self.exc_info = None # type: typing.Any
async def __call__(self, receive: Receive, send: Send) -> None:
body = b""
more_body = True
while more_body:
message = await receive()
body += message.get("body", b"")
more_body = message.get("more_body", False)
environ = build_environ(self.scope, body)
sender = None
try:
sender = self.loop.create_task(self.sender(send))
await run_in_threadpool(self.wsgi, environ, self.start_response)
self.send_queue.append(None)
self.send_event.set()
await asyncio.wait_for(sender, None)
if self.exc_info is not None:
raise self.exc_info[0].with_traceback(
self.exc_info[1], self.exc_info[2]
)
finally:
if sender and not sender.done():
sender.cancel() # pragma: no cover
async def sender(self, send: Send) -> None:
while True:
if self.send_queue:
message = self.send_queue.pop(0)
if message is None:
return
await send(message)
else:
await self.send_event.wait()
self.send_event.clear()
def start_response(
self,
status: str,
response_headers: typing.List[typing.Tuple[str, str]],
exc_info: typing.Any = None,
) -> None:
self.exc_info = exc_info
if not self.response_started:
self.response_started = True
status_code_string, _ = status.split(" ", 1)
status_code = int(status_code_string)
headers = [
(name.encode("ascii"), value.encode("ascii"))
for name, value in response_headers
]
self.send_queue.append(
{
"type": "http.response.start",
"status": status_code,
"headers": headers,
}
)
self.loop.call_soon_threadsafe(self.send_event.set)
def wsgi(self, environ: dict, start_response: typing.Callable) -> None:
for chunk in self.app(environ, start_response):
self.send_queue.append(
{"type": "http.response.body", "body": chunk, "more_body": True}
)
self.loop.call_soon_threadsafe(self.send_event.set)
self.send_queue.append({"type": "http.response.body", "body": b""})
self.loop.call_soon_threadsafe(self.send_event.set)
class WSGIMiddleware:
def __init__(self, app: typing.Callable, workers: int = 10) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "http"
responder = WSGIResponder(self.app, scope)
await responder(receive, send)
#------------------------------ base helper ------------------------------------
RequestResponseEndpoint = typing.Callable[[Request], typing.Awaitable[Response]]
DispatchFunction = typing.Callable[
[Request, RequestResponseEndpoint], typing.Awaitable[Response]
]
class ExceptionMiddleware:
def __init__(
self, app: ASGIApp, handlers: dict = None, debug: bool = False
) -> None:
self.app = app
self.debug = debug # TODO: We ought to handle 404 cases if debug is set.
self._status_handlers = {} # type: typing.Dict[int, typing.Callable]
self._exception_handlers = {
HTTPException: self.http_exception
} # type: typing.Dict[typing.Type[Exception], typing.Callable]
if handlers is not None:
for key, value in handlers.items():
self.add_exception_handler(key, value)
def add_exception_handler(
self,
exc_class_or_status_code: typing.Union[int, typing.Type[Exception]],
handler: typing.Callable,
) -> None:
if isinstance(exc_class_or_status_code, int):
self._status_handlers[exc_class_or_status_code] = handler
else:
assert issubclass(exc_class_or_status_code, Exception)
self._exception_handlers[exc_class_or_status_code] = handler
def _lookup_exception_handler(
self, exc: Exception
) -> typing.Optional[typing.Callable]:
for cls in type(exc).__mro__:
if cls in self._exception_handlers:
return self._exception_handlers[cls]
return None
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
response_started = False
async def sender(message: Message) -> None:
nonlocal response_started
if message["type"] == "http.response.start":
response_started = True
await send(message)
try:
await self.app(scope, receive, sender)
except Exception as exc:
handler = None
if isinstance(exc, HTTPException):
handler = self._status_handlers.get(exc.status_code)
if handler is None:
handler = self._lookup_exception_handler(exc)
if handler is None:
raise exc from None
if response_started:
msg = "Caught handled exception, but response already started."
raise RuntimeError(msg) from exc
request = Request(scope, receive=receive)
if asyncio.iscoroutinefunction(handler):
response = await handler(request, exc)
else:
response = await run_in_threadpool(handler, request, exc)
await response(scope, receive, sender)
def http_exception(self, request: Request, exc: HTTPException) -> Response:
if exc.status_code in {204, 304}:
return Response(b"", status_code=exc.status_code)
return PlainTextResponse(exc.detail, status_code=exc.status_code)
# Call Request, Response
class BaseHTTPMiddleware:
def __init__(self, app: ASGIApp, dispatch: DispatchFunction = None) -> None:
self.app = app
self.dispatch_func = self.dispatch if dispatch is None else dispatch
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
request = Request(scope, receive=receive)
response = await self.dispatch_func(request, self.call_next)
await response(scope, receive, send)
async def call_next(self, request: Request) -> Response:
loop = asyncio.get_event_loop()
queue = asyncio.Queue() # type: asyncio.Queue
scope = request.scope
receive = request.receive
send = queue.put
async def coro() -> None:
try:
await self.app(scope, receive, send)
finally:
await queue.put(None)
task = loop.create_task(coro())
message = await queue.get()
if message is None:
task.result()
raise RuntimeError("No response returned.")
assert message["type"] == "http.response.start"
async def body_stream() -> typing.AsyncGenerator[bytes, None]:
while True:
message = await queue.get()
if message is None:
break
assert message["type"] == "http.response.body"
yield message["body"]
task.result()
response = StreamingResponse(
status_code=message["status"], content=body_stream()
)
response.raw_headers = message["headers"]
return response
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
raise NotImplementedError() # pragma: no cover
#------------------------------ errors helpers ---------------------------------
STYLES = """
p {
color: #211c1c;
}
.traceback-container {
border: 1px solid #038BB8;
}
.traceback-title {
background-color: #038BB8;
color: lemonchiffon;
padding: 12px;
font-size: 20px;
margin-top: 0px;
}
.frame-line {
padding-left: 10px;
}
.center-line {
background-color: #038BB8;
color: #f9f6e1;
padding: 5px 0px 5px 5px;
}
.lineno {
margin-right: 5px;
}
.frame-filename {
font-weight: unset;
padding: 10px 10px 10px 0px;
background-color: #E4F4FD;
margin-right: 10px;
font: #394D54;
color: #191f21;
font-size: 17px;
border: 1px solid #c7dce8;
}
.collapse-btn {
float: right;
padding: 0px 5px 1px 5px;
border: solid 1px #96aebb;
cursor: pointer;
}
.collapsed {
display: none;
}
.source-code {
font-family: courier;
font-size: small;
padding-bottom: 10px;
}
"""
JS = """
<script type="text/javascript">
function collapse(element){
const frameId = element.getAttribute("data-frame-id");
const frame = document.getElementById(frameId);
if (frame.classList.contains("collapsed")){
element.innerHTML = "‒";
frame.classList.remove("collapsed");
} else {
element.innerHTML = "+";
frame.classList.add("collapsed");
}
}
</script>
"""
TEMPLATE = """
<html>
<head>
<style type='text/css'>
{styles}
</style>
<title>aspire.core Debugger</title>
</head>
<body>
<h1>500 Server Error</h1>
<h2>{error}</h2>
<div class="traceback-container">
<p class="traceback-title">Traceback</p>
<div>{exc_html}</div>
</div>
{js}
</body>
</html>
"""
FRAME_TEMPLATE = """
<div>
<p class="frame-filename"><span class="debug-filename frame-line">File {frame_filename}</span>,
line <i>{frame_lineno}</i>,
in <b>{frame_name}</b>
<span class="collapse-btn" data-frame-id="{frame_filename}-{frame_lineno}" onclick="collapse(this)">{collapse_button}</span>
</p>
<div id="{frame_filename}-{frame_lineno}" class="source-code {collapsed}">{code_context}</div>
</div>
"""
LINE = """
<p><span class="frame-line">
<span class="lineno">{lineno}.</span> {line}</span></p>
"""
CENTER_LINE = """
<p class="center-line"><span class="frame-line center-line">
<span class="lineno">{lineno}.</span> {line}</span></p>
"""
class ServerErrorMiddleware:
"""
Handles returning 500 responses when a server error occurs.
If 'debug' is set, then traceback responses will be returned,
otherwise the designated 'handler' will be called.
This middleware class should generally be used to wrap *everything*
else up, so that unhandled exceptions anywhere in the stack
always result in an appropriate 500 response.
"""
def __init__(
self, app: ASGIApp, handler: typing.Callable = None, debug: bool = False
) -> None:
self.app = app
self.handler = handler
self.debug = debug
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
response_started = False
async def _send(message: Message) -> None:
nonlocal response_started, send
if message["type"] == "http.response.start":
response_started = True
await send(message)
try:
await self.app(scope, receive, _send)
except Exception as exc:
if not response_started:
request = Request(scope)
if self.debug:
# In debug mode, return traceback responses.
response = self.debug_response(request, exc)
elif self.handler is None:
# Use our default 500 error handler.
response = self.error_response(request, exc)
else:
# Use an installed 500 error handler.
if asyncio.iscoroutinefunction(self.handler):
response = await self.handler(request, exc)
else:
response = await run_in_threadpool(self.handler, request, exc)
await response(scope, receive, send)
# We always continue to raise the exception.
# This allows servers to log the error, or allows test clients
# to optionally raise the error within the test case.
raise exc from None
def format_line(
self, position: int, line: str, frame_lineno: int, center_lineno: int
) -> str:
values = {
"line": line.replace(" ", " "),
"lineno": frame_lineno + (position - center_lineno),
}
if position != center_lineno:
return LINE.format(**values)
return CENTER_LINE.format(**values)
def generate_frame_html(
self, frame: inspect.FrameInfo, center_lineno: int, is_collapsed: bool
) -> str:
code_context = "".join(
self.format_line(context_position, line, frame.lineno, center_lineno)
for context_position, line in enumerate(frame.code_context or [])
)
values = {
"frame_filename": frame.filename,
"frame_lineno": frame.lineno,
"frame_name": frame.function,
"code_context": code_context,
"collapsed": "collapsed" if is_collapsed else "",
"collapse_button": "+" if is_collapsed else "‒",
}
return FRAME_TEMPLATE.format(**values)
def generate_html(self, exc: Exception, limit: int = 7) -> str:
traceback_obj = traceback.TracebackException.from_exception(
exc, capture_locals=True
)
#frames = inspect.getinnerframes(
# traceback_obj.exc_traceback, limit # type: ignore
#)
center_lineno = int((limit - 1) / 2)
exc_html = ""
is_collapsed = False
#for frame in reversed(frames):
# exc_html += self.generate_frame_html(frame, center_lineno, is_collapsed)
# is_collapsed = True
# Implemented Feb 27 2021
exc_traceback = exc.__traceback__
if exc_traceback is not None:
frames = inspect.getinnerframes(exc_traceback, limit)
for frame in reversed(frames):
exc_html += self.generate_frame_html(frame, center_lineno, is_collapsed)
is_collapsed = True
error = f"{traceback_obj.exc_type.__name__}: {html.escape(str(traceback_obj))}"
return TEMPLATE.format(styles=STYLES, js=JS, error=error, exc_html=exc_html)
def generate_plain_text(self, exc: Exception) -> str:
return "".join(traceback.format_tb(exc.__traceback__))
def debug_response(self, request: Request, exc: Exception) -> Response:
accept = request.headers.get("accept", "")
if "text/html" in accept:
content = self.generate_html(exc)
return HTMLResponse(content, status_code=500)
content = self.generate_plain_text(exc)
return PlainTextResponse(content, status_code=500)
def error_response(self, request: Request, exc: Exception) -> Response:
return PlainTextResponse("Internal Server Error", status_code=500)
#---------------------- Gzip Assistant ----------------------------------
class GZipMiddleware:
def __init__(self, app: ASGIApp, minimum_size: int = 500) -> None:
self.app = app
self.minimum_size = minimum_size
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "http":
headers = Headers(scope=scope)
if "gzip" in headers.get("Accept-Encoding", ""):
responder = GZipResponder(self.app, self.minimum_size)
await responder(scope, receive, send)
return
await self.app(scope, receive, send)
class GZipResponder:
def __init__(self, app: ASGIApp, minimum_size: int) -> None:
self.app = app
self.minimum_size = minimum_size
self.send = unattached_send # type: Send
self.initial_message = {} # type: Message
self.started = False
self.gzip_buffer = io.BytesIO()
self.gzip_file = gzip.GzipFile(mode="wb", fileobj=self.gzip_buffer)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
self.send = send
await self.app(scope, receive, self.send_with_gzip)
async def send_with_gzip(self, message: Message) -> None:
message_type = message["type"]
if message_type == "http.response.start":
# Don't send the initial message until we've determined how to
# modify the ougoging headers correctly.
self.initial_message = message
elif message_type == "http.response.body" and not self.started:
self.started = True
body = message.get("body", b"")
more_body = message.get("more_body", False)
if len(body) < self.minimum_size and not more_body:
# Don't apply GZip to small outgoing responses.
await self.send(self.initial_message)
await self.send(message)
elif not more_body:
# Standard GZip response.
self.gzip_file.write(body)
self.gzip_file.close()
body = self.gzip_buffer.getvalue()
headers = MutableHeaders(raw=self.initial_message["headers"])
headers["Content-Encoding"] = "gzip"
headers["Content-Length"] = str(len(body))
headers.add_vary_header("Accept-Encoding")
message["body"] = body
await self.send(self.initial_message)
await self.send(message)
else:
# Initial body in streaming GZip response.
headers = MutableHeaders(raw=self.initial_message["headers"])
headers["Content-Encoding"] = "gzip"
headers.add_vary_header("Accept-Encoding")
del headers["Content-Length"]
self.gzip_file.write(body)
message["body"] = self.gzip_buffer.getvalue()
self.gzip_buffer.seek(0)
self.gzip_buffer.truncate()
await self.send(self.initial_message)
await self.send(message)
elif message_type == "http.response.body":
# Remaining body in streaming GZip response.
body = message.get("body", b"")
more_body = message.get("more_body", False)
self.gzip_file.write(body)
if not more_body:
self.gzip_file.close()
message["body"] = self.gzip_buffer.getvalue()
self.gzip_buffer.seek(0)
self.gzip_buffer.truncate()
await self.send(message)
async def unattached_send(message: Message) -> None:
raise RuntimeError("send awaitable not set") # pragma: no cover
| import asyncio
import enum
import functools
import gzip
import hashlib
import html
import http
import http.cookies
import importlib.util
import inspect
import io
import json
import math
import os
import re
import stat
import sys
import tempfile
import traceback
import typing
from collections import namedtuple
from collections.abc import Sequence
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit, unquote_plus
from enum import Enum
from typing import Any, AsyncGenerator, Iterator
from email.utils import parsedate
from aiofiles.os import stat as aio_stat
from enum import Enum
from email.utils import formatdate
from mimetypes import guess_type
from urllib.parse import quote_plus
from collections.abc import Mapping
try:
import contextvars # Python 3.7+ only.
except ImportError: # pragma: no cover
contextvars = None # type: ignore
# Implemented Feb 27-2021 By Author
if sys.version_info >= (3, 7): # pragma: no cover
from asyncio import create_task
else: # pragma: no cover
from asyncio import ensure_future as create_task
try:
from multipart.multipart import parse_options_header
except ImportError: # pragma: nocover
parse_options_header = None # type: ignore
try:
import aiofiles
from aiofiles.os import stat as aio_stat
except ImportError: # pragma: nocover
aiofiles = None # type: ignore
aio_stat = None # type: ignore
try:
import ujson
except ImportError: # pragma: nocover
ujson = None
try:
import jinja2
except ImportError: # pragma: nocover
jinja2 = None # type: ignore
# type: ignore
#---------------------------------- Configuration --------------
SERVER_PUSH_HEADERS_TO_COPY = {
"accept",
"accept-encoding",
"accept-language",
"cache-control",
"user-agent",
}
#------------- Typing ----------------------------------
Scope = typing.MutableMapping[str, typing.Any]
Message = typing.MutableMapping[str, typing.Any]
Receive = typing.Callable[[], typing.Awaitable[Message]]
Send = typing.Callable[[Message], typing.Awaitable[None]]
ASGIApp = typing.Callable[[Scope, Receive, Send], typing.Awaitable[None]]
#----------------- Concurrency ------------------------------
T = typing.TypeVar("T")
# Implemented Feb 27-2021 By Author Update from starlette 1.3
async def run_until_first_complete(*args: typing.Tuple[typing.Callable, dict]) -> None:
tasks = [create_task(handler(**kwargs)) for handler, kwargs in args]
(done, pending) = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
[task.cancel() for task in pending]
[task.result() for task in done]
async def run_in_threadpool(
func: typing.Callable[..., T], *args: typing.Any, **kwargs: typing.Any
) -> T:
loop = asyncio.get_event_loop()
if contextvars is not None: # pragma: no cover
# Ensure we run in the same context
child = functools.partial(func, *args, **kwargs)
context = contextvars.copy_context()
func = context.run
args = (child,)
elif kwargs: # pragma: no cover
# loop.run_in_executor doesn't accept 'kwargs', so bind them in here
func = functools.partial(func, **kwargs)
return await loop.run_in_executor(None, func, *args)
class _StopIteration(Exception):
pass
def _next(iterator: Iterator) -> Any:
# We can't raise `StopIteration` from within the threadpool iterator
# and catch it outside that context, so we coerce them into a different
# exception type.
try:
return next(iterator)
except StopIteration:
raise _StopIteration
async def iterate_in_threadpool(iterator: Iterator) -> AsyncGenerator:
while True:
try:
yield await run_in_threadpool(_next, iterator)
except _StopIteration:
break
#----------------------------- exceptions ----------------------------------
class HTTPException(Exception):
def __init__(self, status_code: int, detail: str = None) -> None:
if detail is None:
detail = http.HTTPStatus(status_code).phrase
self.status_code = status_code
self.detail = detail
def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"
#---------------- Datastructures ----------------------------
Address = namedtuple("Address", ["host", "port"])
class URL:
def __init__(
self, url: str = "", scope: Scope = None, **components: typing.Any
) -> None:
if scope is not None:
assert not url, 'Cannot set both "url" and "scope".'
assert not components, 'Cannot set both "scope" and "**components".'
scheme = scope.get("scheme", "http")
server = scope.get("server", None)
path = scope.get("root_path", "") + scope["path"]
query_string = scope.get("query_string", b"")
host_header = None
for key, value in scope["headers"]:
if key == b"host":
host_header = value.decode("latin-1")
break
if host_header is not None:
url = f"{scheme}://{host_header}{path}"
elif server is None:
url = path
else:
host, port = server
default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme]
if port == default_port:
url = f"{scheme}://{host}{path}"
else:
url = f"{scheme}://{host}:{port}{path}"
if query_string:
url += "?" + query_string.decode()
elif components:
assert not url, 'Cannot set both "url" and "**components".'
url = URL("").replace(**components).components.geturl()
self._url = url
@property
def components(self) -> SplitResult:
if not hasattr(self, "_components"):
self._components = urlsplit(self._url)
return self._components
@property
def scheme(self) -> str:
return self.components.scheme
@property
def netloc(self) -> str:
return self.components.netloc
@property
def path(self) -> str:
return self.components.path
@property
def query(self) -> str:
return self.components.query
@property
def fragment(self) -> str:
return self.components.fragment
@property
def username(self) -> typing.Union[None, str]:
return self.components.username
@property
def password(self) -> typing.Union[None, str]:
return self.components.password
@property
def hostname(self) -> typing.Union[None, str]:
return self.components.hostname
@property
def port(self) -> typing.Optional[int]:
return self.components.port
@property
def is_secure(self) -> bool:
return self.scheme in ("https", "wss")
def replace(self, **kwargs: typing.Any) -> "URL":
if (
"username" in kwargs
or "password" in kwargs
or "hostname" in kwargs
or "port" in kwargs
):
hostname = kwargs.pop("hostname", self.hostname)
port = kwargs.pop("port", self.port)
username = kwargs.pop("username", self.username)
password = kwargs.pop("password", self.password)
netloc = hostname
if port is not None:
netloc += f":{port}"
if username is not None:
userpass = username
if password is not None:
userpass += f":{password}"
netloc = f"{userpass}@{netloc}"
kwargs["netloc"] = netloc
components = self.components._replace(**kwargs)
return self.__class__(components.geturl())
def include_query_params(self, **kwargs: typing.Any) -> "URL":
params = MultiDict(parse_qsl(self.query, keep_blank_values=True))
params.update({str(key): str(value) for key, value in kwargs.items()})
query = urlencode(params.multi_items())
return self.replace(query=query)
def replace_query_params(self, **kwargs: typing.Any) -> "URL":
query = urlencode([(str(key), str(value)) for key, value in kwargs.items()])
return self.replace(query=query)
def remove_query_params(
self, keys: typing.Union[str, typing.Sequence[str]]
) -> "URL":
if isinstance(keys, str):
keys = [keys]
params = MultiDict(parse_qsl(self.query, keep_blank_values=True))
for key in keys:
params.pop(key, None)
query = urlencode(params.multi_items())
return self.replace(query=query)
def __eq__(self, other: typing.Any) -> bool:
return str(self) == str(other)
def __str__(self) -> str:
return self._url
def __repr__(self) -> str:
url = str(self)
if self.password:
url = str(self.replace(password="********"))
return f"{self.__class__.__name__}({repr(url)})"
class URLPath(str):
"""
A URL path string that may also hold an associated protocol and/or host.
Used by the routing to return `url_path_for` matches.
"""
def __new__(cls, path: str, protocol: str = "", host: str = "") -> "URLPath":
assert protocol in ("http", "websocket", "")
return str.__new__(cls, path) # type: ignore
def __init__(self, path: str, protocol: str = "", host: str = "") -> None:
self.protocol = protocol
self.host = host
def make_absolute_url(self, base_url: typing.Union[str, URL]) -> str:
if isinstance(base_url, str):
base_url = URL(base_url)
if self.protocol:
scheme = {
"http": {True: "https", False: "http"},
"websocket": {True: "wss", False: "ws"},
}[self.protocol][base_url.is_secure]
else:
scheme = base_url.scheme
if self.host:
netloc = self.host
else:
netloc = base_url.netloc
path = base_url.path.rstrip("/") + str(self)
return str(URL(scheme=scheme, netloc=netloc, path=path))
class Secret:
"""
Holds a string value that should not be revealed in tracebacks etc.
You should cast the value to `str` at the point it is required.
"""
def __init__(self, value: str):
self._value = value
def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}('**********')"
def __str__(self) -> str:
return self._value
class CommaSeparatedStrings(Sequence):
def __init__(self, value: typing.Union[str, typing.Sequence[str]]):
if isinstance(value, str):
splitter = shlex(value, posix=True)
splitter.whitespace = ","
splitter.whitespace_split = True
self._items = [item.strip() for item in splitter]
else:
self._items = list(value)
def __len__(self) -> int:
return len(self._items)
def __getitem__(self, index: typing.Union[int, slice]) -> typing.Any:
return self._items[index]
def __iter__(self) -> typing.Iterator[str]:
return iter(self._items)
def __repr__(self) -> str:
class_name = self.__class__.__name__
items = [item for item in self]
return f"{class_name}({items!r})"
def __str__(self) -> str:
return ", ".join([repr(item) for item in self])
class ImmutableMultiDict(typing.Mapping):
def __init__(
self,
*args: typing.Union[
"ImmutableMultiDict",
typing.Mapping,
typing.List[typing.Tuple[typing.Any, typing.Any]],
],
**kwargs: typing.Any,
) -> None:
assert len(args) < 2, "Too many arguments."
if args:
value = args[0]
else:
value = []
if kwargs:
value = (
ImmutableMultiDict(value).multi_items()
+ ImmutableMultiDict(kwargs).multi_items()
)
if not value:
_items = [] # type: typing.List[typing.Tuple[typing.Any, typing.Any]]
elif hasattr(value, "multi_items"):
value = typing.cast(ImmutableMultiDict, value)
_items = list(value.multi_items())
elif hasattr(value, "items"):
value = typing.cast(typing.Mapping, value)
_items = list(value.items())
else:
value = typing.cast(
typing.List[typing.Tuple[typing.Any, typing.Any]], value
)
_items = list(value)
self._dict = {k: v for k, v in _items}
self._list = _items
def getlist(self, key: typing.Any) -> typing.List[str]:
return [item_value for item_key, item_value in self._list if item_key == key]
def keys(self) -> typing.KeysView:
return self._dict.keys()
def values(self) -> typing.ValuesView:
return self._dict.values()
def items(self) -> typing.ItemsView:
return self._dict.items()
def multi_items(self) -> typing.List[typing.Tuple[str, str]]:
return list(self._list)
def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:
if key in self._dict:
return self._dict[key]
return default
def __getitem__(self, key: typing.Any) -> str:
return self._dict[key]
def __contains__(self, key: typing.Any) -> bool:
return key in self._dict
def __iter__(self) -> typing.Iterator[typing.Any]:
return iter(self.keys())
def __len__(self) -> int:
return len(self._dict)
def __eq__(self, other: typing.Any) -> bool:
if not isinstance(other, self.__class__):
return False
return sorted(self._list) == sorted(other._list)
def __repr__(self) -> str:
class_name = self.__class__.__name__
items = self.multi_items()
return f"{class_name}({items!r})"
class MultiDict(ImmutableMultiDict):
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
self.setlist(key, [value])
def __delitem__(self, key: typing.Any) -> None:
self._list = [(k, v) for k, v in self._list if k != key]
del self._dict[key]
def pop(self, key: typing.Any, default: typing.Any = None) -> typing.Any:
self._list = [(k, v) for k, v in self._list if k != key]
return self._dict.pop(key, default)
def popitem(self) -> typing.Tuple:
key, value = self._dict.popitem()
self._list = [(k, v) for k, v in self._list if k != key]
return key, value
def poplist(self, key: typing.Any) -> typing.List:
values = [v for k, v in self._list if k == key]
self.pop(key)
return values
def clear(self) -> None:
self._dict.clear()
self._list.clear()
def setdefault(self, key: typing.Any, default: typing.Any = None) -> typing.Any:
if key not in self:
self._dict[key] = default
self._list.append((key, default))
return self[key]
def setlist(self, key: typing.Any, values: typing.List) -> None:
if not values:
self.pop(key, None)
else:
existing_items = [(k, v) for (k, v) in self._list if k != key]
self._list = existing_items + [(key, value) for value in values]
self._dict[key] = values[-1]
def append(self, key: typing.Any, value: typing.Any) -> None:
self._list.append((key, value))
self._dict[key] = value
def update(
self,
*args: typing.Union[
"MultiDict",
typing.Mapping,
typing.List[typing.Tuple[typing.Any, typing.Any]],
],
**kwargs: typing.Any,
) -> None:
value = MultiDict(*args, **kwargs)
existing_items = [(k, v) for (k, v) in self._list if k not in value.keys()]
self._list = existing_items + value.multi_items()
self._dict.update(value)
class QueryParams(ImmutableMultiDict):
"""
An immutable multidict.
"""
def __init__(
self,
*args: typing.Union[
"ImmutableMultiDict",
typing.Mapping,
typing.List[typing.Tuple[typing.Any, typing.Any]],
str,
bytes,
],
**kwargs: typing.Any,
) -> None:
assert len(args) < 2, "Too many arguments."
value = args[0] if args else []
if isinstance(value, str):
super().__init__(parse_qsl(value, keep_blank_values=True), **kwargs)
elif isinstance(value, bytes):
super().__init__(
parse_qsl(value.decode("latin-1"), keep_blank_values=True), **kwargs
)
else:
super().__init__(*args, **kwargs) # type: ignore
self._list = [(str(k), str(v)) for k, v in self._list]
self._dict = {str(k): str(v) for k, v in self._dict.items()}
def __str__(self) -> str:
return urlencode(self._list)
def __repr__(self) -> str:
class_name = self.__class__.__name__
query_string = str(self)
return f"{class_name}({query_string!r})"
class UploadFile:
"""
An uploaded file included as part of the request data.
"""
spool_max_size = 1024 * 1024
def __init__(
self, filename: str, file: typing.IO = None, content_type: str = ""
) -> None:
self.filename = filename
self.content_type = content_type
if file is None:
file = tempfile.SpooledTemporaryFile(max_size=self.spool_max_size)
self.file = file
async def write(self, data: typing.Union[bytes, str]) -> None:
await run_in_threadpool(self.file.write, data)
async def read(self, size: int = None) -> typing.Union[bytes, str]:
return await run_in_threadpool(self.file.read, size)
async def seek(self, offset: int) -> None:
await run_in_threadpool(self.file.seek, offset)
async def close(self) -> None:
await run_in_threadpool(self.file.close)
class FormData(ImmutableMultiDict):
"""
An immutable multidict, containing both file uploads and text input.
"""
def __init__(
self,
*args: typing.Union[
"FormData",
typing.Mapping[str, typing.Union[str, UploadFile]],
typing.List[typing.Tuple[str, typing.Union[str, UploadFile]]],
],
**kwargs: typing.Union[str, UploadFile],
) -> None:
super().__init__(*args, **kwargs) # type: ignore
async def close(self) -> None:
for key, value in self.multi_items():
if isinstance(value, UploadFile):
await value.close()
class Headers(typing.Mapping[str, str]):
"""
An immutable, case-insensitive multidict.
"""
def __init__(
self,
headers: typing.Mapping[str, str] = None,
raw: typing.List[typing.Tuple[bytes, bytes]] = None,
scope: Scope = None,
) -> None:
self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]
if headers is not None:
assert raw is None, 'Cannot set both "headers" and "raw".'
assert scope is None, 'Cannot set both "headers" and "scope".'
self._list = [
(key.lower().encode("latin-1"), value.encode("latin-1"))
for key, value in headers.items()
]
elif raw is not None:
assert scope is None, 'Cannot set both "raw" and "scope".'
self._list = raw
elif scope is not None:
self._list = scope["headers"]
@property
def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:
return list(self._list)
def keys(self) -> typing.List[str]: # type: ignore
return [key.decode("latin-1") for key, value in self._list]
def values(self) -> typing.List[str]: # type: ignore
return [value.decode("latin-1") for key, value in self._list]
def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore
return [
(key.decode("latin-1"), value.decode("latin-1"))
for key, value in self._list
]
def get(self, key: str, default: typing.Any = None) -> typing.Any:
try:
return self[key]
except KeyError:
return default
def getlist(self, key: str) -> typing.List[str]:
get_header_key = key.lower().encode("latin-1")
return [
item_value.decode("latin-1")
for item_key, item_value in self._list
if item_key == get_header_key
]
def mutablecopy(self) -> "MutableHeaders":
return MutableHeaders(raw=self._list[:])
def __getitem__(self, key: str) -> str:
get_header_key = key.lower().encode("latin-1")
for header_key, header_value in self._list:
if header_key == get_header_key:
return header_value.decode("latin-1")
raise KeyError(key)
def __contains__(self, key: typing.Any) -> bool:
get_header_key = key.lower().encode("latin-1")
for header_key, header_value in self._list:
if header_key == get_header_key:
return True
return False
def __iter__(self) -> typing.Iterator[typing.Any]:
return iter(self.keys())
def __len__(self) -> int:
return len(self._list)
def __eq__(self, other: typing.Any) -> bool:
if not isinstance(other, Headers):
return False
return sorted(self._list) == sorted(other._list)
def __repr__(self) -> str:
class_name = self.__class__.__name__
as_dict = dict(self.items())
if len(as_dict) == len(self):
return f"{class_name}({as_dict!r})"
return f"{class_name}(raw={self.raw!r})"
class MutableHeaders(Headers):
def __setitem__(self, key: str, value: str) -> None:
"""
Set the header `key` to `value`, removing any duplicate entries.
Retains insertion order.
"""
set_key = key.lower().encode("latin-1")
set_value = value.encode("latin-1")
found_indexes = []
for idx, (item_key, item_value) in enumerate(self._list):
if item_key == set_key:
found_indexes.append(idx)
for idx in reversed(found_indexes[1:]):
del self._list[idx]
if found_indexes:
idx = found_indexes[0]
self._list[idx] = (set_key, set_value)
else:
self._list.append((set_key, set_value))
def __delitem__(self, key: str) -> None:
"""
Remove the header `key`.
"""
del_key = key.lower().encode("latin-1")
pop_indexes = []
for idx, (item_key, item_value) in enumerate(self._list):
if item_key == del_key:
pop_indexes.append(idx)
for idx in reversed(pop_indexes):
del self._list[idx]
@property
def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:
return self._list
def setdefault(self, key: str, value: str) -> str:
"""
If the header `key` does not exist, then set it to `value`.
Returns the header value.
"""
set_key = key.lower().encode("latin-1")
set_value = value.encode("latin-1")
for idx, (item_key, item_value) in enumerate(self._list):
if item_key == set_key:
return item_value.decode("latin-1")
self._list.append((set_key, set_value))
return value
def update(self, other: dict) -> None:
for key, val in other.items():
self[key] = val
def append(self, key: str, value: str) -> None:
"""
Append a header, preserving any duplicate entries.
"""
append_key = key.lower().encode("latin-1")
append_value = value.encode("latin-1")
self._list.append((append_key, append_value))
def add_vary_header(self, vary: str) -> None:
existing = self.get("vary")
if existing is not None:
vary = ", ".join([existing, vary])
self["vary"] = vary
class State(object):
"""
An object that can be used to store arbitrary state.
Used for `request.state` and `app.state`.
"""
def __init__(self, state: typing.Dict = None):
if state is None:
state = {}
super(State, self).__setattr__("_state", state)
def __setattr__(self, key: typing.Any, value: typing.Any) -> None:
self._state[key] = value
def __getattr__(self, key: typing.Any) -> typing.Any:
return self._state.get(key, AttributeError( f"{self.__class__.__name__} Object missing attribute {key}" ))
def __delattr__(self, key: typing.Any) -> None:
try:
del self._state[key]
except KeyError:
return AttributeError( f"{self.__class__.__name__} Object missing attribute {key}" )
#------------------------- Form Parsers ---------------------------------------
try:
from multipart.multipart import parse_options_header
import multipart
except ImportError: # pragma: nocover
parse_options_header = None # type: ignore
multipart = None # type: ignore
class FormMessage(Enum):
FIELD_START = 1
FIELD_NAME = 2
FIELD_DATA = 3
FIELD_END = 4
END = 5
class MultiPartMessage(Enum):
PART_BEGIN = 1
PART_DATA = 2
PART_END = 3
HEADER_FIELD = 4
HEADER_VALUE = 5
HEADER_END = 6
HEADERS_FINISHED = 7
END = 8
def _user_safe_decode(src: bytes, codec: str) -> str:
try:
return src.decode(codec)
except (UnicodeDecodeError, LookupError):
return src.decode("latin-1")
class FormParser:
def __init__(
self, headers: Headers, stream: typing.AsyncGenerator[bytes, None]
) -> None:
assert (
multipart is not None
), "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
self.messages = [] # type: typing.List[typing.Tuple[FormMessage, bytes]]
def on_field_start(self) -> None:
message = (FormMessage.FIELD_START, b"")
self.messages.append(message)
def on_field_name(self, data: bytes, start: int, end: int) -> None:
message = (FormMessage.FIELD_NAME, data[start:end])
self.messages.append(message)
def on_field_data(self, data: bytes, start: int, end: int) -> None:
message = (FormMessage.FIELD_DATA, data[start:end])
self.messages.append(message)
def on_field_end(self) -> None:
message = (FormMessage.FIELD_END, b"")
self.messages.append(message)
def on_end(self) -> None:
message = (FormMessage.END, b"")
self.messages.append(message)
async def parse(self) -> FormData:
# Callbacks dictionary.
callbacks = {
"on_field_start": self.on_field_start,
"on_field_name": self.on_field_name,
"on_field_data": self.on_field_data,
"on_field_end": self.on_field_end,
"on_end": self.on_end,
}
# Create the parser.
parser = multipart.QuerystringParser(callbacks)
field_name = b""
field_value = b""
items = (
[]
) # type: typing.List[typing.Tuple[str, typing.Union[str, UploadFile]]]
# Feed the parser with data from the request.
async for chunk in self.stream:
if chunk:
parser.write(chunk)
else:
parser.finalize()
messages = list(self.messages)
self.messages.clear()
for message_type, message_bytes in messages:
if message_type == FormMessage.FIELD_START:
field_name = b""
field_value = b""
elif message_type == FormMessage.FIELD_NAME:
field_name += message_bytes
elif message_type == FormMessage.FIELD_DATA:
field_value += message_bytes
elif message_type == FormMessage.FIELD_END:
name = unquote_plus(field_name.decode("latin-1"))
value = unquote_plus(field_value.decode("latin-1"))
items.append((name, value))
elif message_type == FormMessage.END:
pass
return FormData(items)
class MultiPartParser:
def __init__(
self, headers: Headers, stream: typing.AsyncGenerator[bytes, None]
) -> None:
assert (
multipart is not None
), "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
self.messages = [] # type: typing.List[typing.Tuple[MultiPartMessage, bytes]]
def on_part_begin(self) -> None:
message = (MultiPartMessage.PART_BEGIN, b"")
self.messages.append(message)
def on_part_data(self, data: bytes, start: int, end: int) -> None:
message = (MultiPartMessage.PART_DATA, data[start:end])
self.messages.append(message)
def on_part_end(self) -> None:
message = (MultiPartMessage.PART_END, b"")
self.messages.append(message)
def on_header_field(self, data: bytes, start: int, end: int) -> None:
message = (MultiPartMessage.HEADER_FIELD, data[start:end])
self.messages.append(message)
def on_header_value(self, data: bytes, start: int, end: int) -> None:
message = (MultiPartMessage.HEADER_VALUE, data[start:end])
self.messages.append(message)
def on_header_end(self) -> None:
message = (MultiPartMessage.HEADER_END, b"")
self.messages.append(message)
def on_headers_finished(self) -> None:
message = (MultiPartMessage.HEADERS_FINISHED, b"")
self.messages.append(message)
def on_end(self) -> None:
message = (MultiPartMessage.END, b"")
self.messages.append(message)
async def parse(self) -> FormData:
# Parse the Content-Type header to get the multipart boundary.
content_type, params = parse_options_header(self.headers["Content-Type"])
charset = params.get(b"charset", "utf-8")
if type(charset) == bytes:
charset = charset.decode("latin-1")
boundary = params.get(b"boundary")
# Callbacks dictionary.
callbacks = {
"on_part_begin": self.on_part_begin,
"on_part_data": self.on_part_data,
"on_part_end": self.on_part_end,
"on_header_field": self.on_header_field,
"on_header_value": self.on_header_value,
"on_header_end": self.on_header_end,
"on_headers_finished": self.on_headers_finished,
"on_end": self.on_end,
}
# Create the parser.
parser = multipart.MultipartParser(boundary, callbacks)
header_field = b""
header_value = b""
content_disposition = None
content_type = b""
field_name = ""
data = b""
file = None # type: typing.Optional[UploadFile]
items = (
[]
) # type: typing.List[typing.Tuple[str, typing.Union[str, UploadFile]]]
# Feed the parser with data from the request.
async for chunk in self.stream:
parser.write(chunk)
messages = list(self.messages)
self.messages.clear()
for message_type, message_bytes in messages:
if message_type == MultiPartMessage.PART_BEGIN:
content_disposition = None
content_type = b""
data = b""
elif message_type == MultiPartMessage.HEADER_FIELD:
header_field += message_bytes
elif message_type == MultiPartMessage.HEADER_VALUE:
header_value += message_bytes
elif message_type == MultiPartMessage.HEADER_END:
field = header_field.lower()
if field == b"content-disposition":
content_disposition = header_value
elif field == b"content-type":
content_type = header_value
header_field = b""
header_value = b""
elif message_type == MultiPartMessage.HEADERS_FINISHED:
disposition, options = parse_options_header(content_disposition)
field_name = _user_safe_decode(options[b"name"], charset)
if b"filename" in options:
filename = _user_safe_decode(options[b"filename"], charset)
file = UploadFile(
filename=filename,
content_type=content_type.decode("latin-1"),
)
else:
file = None
elif message_type == MultiPartMessage.PART_DATA:
if file is None:
data += message_bytes
else:
await file.write(message_bytes)
elif message_type == MultiPartMessage.PART_END:
if file is None:
items.append((field_name, _user_safe_decode(data, charset)))
else:
await file.seek(0)
items.append((field_name, file))
elif message_type == MultiPartMessage.END:
pass
parser.finalize()
return FormData(items)
#------------------------------------ converters ----------------------------------
class Convertor:
regex = ""
def convert(self, value: str) -> typing.Any:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: typing.Any) -> str:
raise NotImplementedError() # pragma: no cover
class StringConvertor(Convertor):
regex = "[^/]+"
def convert(self, value: str) -> typing.Any:
return value
def to_string(self, value: typing.Any) -> str:
value = str(value)
assert "/" not in value, "May not contain path seperators"
assert value, "Must not be empty"
return value
class PathConvertor(Convertor):
regex = ".*"
def convert(self, value: str) -> typing.Any:
return str(value)
def to_string(self, value: typing.Any) -> str:
return str(value)
class IntegerConvertor(Convertor):
regex = "[0-9]+"
def convert(self, value: str) -> typing.Any:
return int(value)
def to_string(self, value: typing.Any) -> str:
value = int(value)
assert value >= 0, "Negative integers are not supported"
return str(value)
class FloatConvertor(Convertor):
regex = "[0-9]+(.[0-9]+)?"
def convert(self, value: str) -> typing.Any:
return float(value)
def to_string(self, value: typing.Any) -> str:
value = float(value)
assert value >= 0.0, "Negative floats are not supported"
assert not math.isnan(value), "NaN values are not supported"
assert not math.isinf(value), "Infinite values are not supported"
return ("%0.20f" % value).rstrip("0").rstrip(".")
CONVERTOR_TYPES = {
"str": StringConvertor(),
"path": PathConvertor(),
"int": IntegerConvertor(),
"float": FloatConvertor(),
}
class EndpointInfo(typing.NamedTuple):
path: str
http_method: str
func: typing.Callable
#-------------------------- Background Tasks ------------------------------
class BackgroundTask:
def __init__(
self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any
) -> None:
self.func = func
self.args = args
self.kwargs = kwargs
self.is_async = asyncio.iscoroutinefunction(func)
async def __call__(self) -> None:
if self.is_async:
await self.func(*self.args, **self.kwargs)
else:
await run_in_threadpool(self.func, *self.args, **self.kwargs)
class BackgroundTasks(BackgroundTask):
def __init__(self, tasks: typing.Sequence[BackgroundTask] = []):
self.tasks = list(tasks)
def add_task(
self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any
) -> None:
task = BackgroundTask(func, *args, **kwargs)
self.tasks.append(task)
async def __call__(self) -> None:
for task in self.tasks:
await task()
#---------------------------- Requests ------------------------------
class ClientDisconnect(Exception):
pass
class HTTPConnection(Mapping):
"""
A base class for incoming HTTP connections, that is used to provide
any functionality that is common to both `Request` and `WebSocket`.
"""
def __init__(self, scope: Scope, receive: Receive = None) -> None:
assert scope["type"] in ("http", "websocket")
self.scope = scope
def __getitem__(self, key: str) -> str:
return self.scope[key]
def __iter__(self) -> typing.Iterator[str]:
return iter(self.scope)
def __len__(self) -> int:
return len(self.scope)
@property
def app(self) -> typing.Any:
return self.scope["app"]
@property
def url(self) -> URL:
if not hasattr(self, "_url"):
self._url = URL(scope=self.scope)
return self._url
@property
def base_url(self) -> URL:
if not hasattr(self, "_base_url"):
base_url_scope = dict(self.scope)
base_url_scope["path"] = "/"
base_url_scope["query_string"] = b""
base_url_scope["root_path"] = base_url_scope.get(
"app_root_path", base_url_scope.get("root_path", "")
)
self._base_url = URL(scope=base_url_scope)
return self._base_url
@property
def headers(self) -> Headers:
if not hasattr(self, "_headers"):
self._headers = Headers(scope=self.scope)
return self._headers
@property
def query_params(self) -> QueryParams:
if not hasattr(self, "_query_params"):
self._query_params = QueryParams(self.scope["query_string"])
return self._query_params
@property
def path_params(self) -> dict:
return self.scope.get("path_params", {})
@property
def cookies(self) -> typing.Dict[str, str]:
if not hasattr(self, "_cookies"):
cookies = {}
cookie_header = self.headers.get("cookie")
if cookie_header:
cookie = http.cookies.SimpleCookie() # type: http.cookies.BaseCookie
cookie.load(cookie_header)
for key, morsel in cookie.items():
cookies[key] = morsel.value
self._cookies = cookies
return self._cookies
@property
def client(self) -> Address:
host, port = self.scope.get("client") or (None, None)
return Address(host=host, port=port)
@property
def session(self) -> dict:
assert (
"session" in self.scope
), "SessionMiddleware must be installed to access request.session"
return self.scope["session"]
@property
def auth(self) -> typing.Any:
assert (
"auth" in self.scope
), "AuthenticationMiddleware must be installed to access request.auth"
return self.scope["auth"]
@property
def user(self) -> typing.Any:
assert (
"user" in self.scope
), "AuthenticationMiddleware must be installed to access request.user"
return self.scope["user"]
@property
def state(self) -> State:
if not hasattr(self, "_state"):
# Ensure 'state' has an empty dict if it's not already populated.
self.scope.setdefault("state", {})
# Create a state instance with a reference to the dict in which it should store info
self._state = State(self.scope["state"])
return self._state
def url_for(self, name: str, **path_params: typing.Any) -> str:
router = self.scope["router"]
url_path = router.url_path_for(name, **path_params)
return url_path.make_absolute_url(base_url=self.base_url)
async def empty_receive() -> Message:
raise RuntimeError("Receive channel has not been made available")
async def empty_send(message: Message) -> None:
raise RuntimeError("Send channel has not been made available")
class Request(HTTPConnection):
def __init__(
self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send
):
super().__init__(scope)
assert scope["type"] == "http"
self._receive = receive
self._send = send
self._stream_consumed = False
self._is_disconnected = False
@property
def method(self) -> str:
return self.scope["method"]
@property
def receive(self) -> Receive:
return self._receive
async def stream(self) -> typing.AsyncGenerator[bytes, None]:
if hasattr(self, "_body"):
yield self._body
yield b""
return
if self._stream_consumed:
raise RuntimeError("Stream consumed")
self._stream_consumed = True
while True:
message = await self._receive()
if message["type"] == "http.request":
body = message.get("body", b"")
if body:
yield body
if not message.get("more_body", False):
break
elif message["type"] == "http.disconnect":
self._is_disconnected = True
raise ClientDisconnect()
yield b""
async def body(self) -> bytes:
if not hasattr(self, "_body"):
chunks = []
async for chunk in self.stream():
chunks.append(chunk)
self._body = b"".join(chunks)
return self._body
async def json(self) -> typing.Any:
if not hasattr(self, "_json"):
body = await self.body()
self._json = json.loads(body)
return self._json
async def form(self) -> FormData:
if not hasattr(self, "_form"):
assert (
parse_options_header is not None
), "The `python-multipart` library must be installed to use form parsing."
content_type_header = self.headers.get("Content-Type")
content_type, options = parse_options_header(content_type_header)
if content_type == b"multipart/form-data":
multipart_parser = MultiPartParser(self.headers, self.stream())
self._form = await multipart_parser.parse()
elif content_type == b"application/x-www-form-urlencoded":
form_parser = FormParser(self.headers, self.stream())
self._form = await form_parser.parse()
else:
self._form = FormData()
return self._form
async def close(self) -> None:
if hasattr(self, "_form"):
await self._form.close()
async def is_disconnected(self) -> bool:
if not self._is_disconnected:
try:
message = await asyncio.wait_for(self._receive(), timeout=0.0000001)
except asyncio.TimeoutError:
message = {}
if message.get("type") == "http.disconnect":
self._is_disconnected = True
return self._is_disconnected
async def send_push_promise(self, path: str) -> None:
if "http.response.push" in self.scope.get("extensions", {}):
raw_headers = []
for name in SERVER_PUSH_HEADERS_TO_COPY:
for value in self.headers.getlist(name):
raw_headers.append(
(name.encode("latin-1"), value.encode("latin-1"))
)
await self._send(
{"type": "http.response.push", "path": path, "headers": raw_headers}
)
#------------------------- Responses ------------------------------
class Response:
media_type = None
charset = "utf-8"
def __init__(
self,
content: typing.Any = None,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
) -> None:
self.body = self.render(content)
self.status_code = status_code
if media_type is not None:
self.media_type = media_type
self.background = background
self.init_headers(headers)
def render(self, content: typing.Any) -> bytes:
if content is None:
return b""
if isinstance(content, bytes):
return content
return content.encode(self.charset)
def init_headers(self, headers: typing.Mapping[str, str] = None) -> None:
if headers is None:
raw_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
populate_content_length = True
populate_content_type = True
else:
raw_headers = [
(k.lower().encode("latin-1"), v.encode("latin-1"))
for k, v in headers.items()
]
keys = [h[0] for h in raw_headers]
populate_content_length = b"content-length" not in keys
populate_content_type = b"content-type" not in keys
body = getattr(self, "body", b"")
if body and populate_content_length:
content_length = str(len(body))
raw_headers.append((b"content-length", content_length.encode("latin-1")))
content_type = self.media_type
if content_type is not None and populate_content_type:
if content_type.startswith("text/"):
content_type += "; charset=" + self.charset
raw_headers.append((b"content-type", content_type.encode("latin-1")))
self.raw_headers = raw_headers
@property
def headers(self) -> MutableHeaders:
if not hasattr(self, "_headers"):
self._headers = MutableHeaders(raw=self.raw_headers)
return self._headers
def set_cookie(
self,
key: str,
value: str = "",
max_age: int = None,
expires: int = None,
path: str = "/",
domain: str = None,
secure: bool = False,
httponly: bool = False,
) -> None:
cookie = http.cookies.SimpleCookie() # type: http.cookies.BaseCookie
cookie[key] = value
if max_age is not None:
cookie[key]["max-age"] = max_age # type: ignore
if expires is not None:
cookie[key]["expires"] = expires # type: ignore
if path is not None:
cookie[key]["path"] = path
if domain is not None:
cookie[key]["domain"] = domain
if secure:
cookie[key]["secure"] = True # type: ignore
if httponly:
cookie[key]["httponly"] = True # type: ignore
cookie_val = cookie.output(header="").strip()
self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
def delete_cookie(self, key: str, path: str = "/", domain: str = None) -> None:
self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
await send({"type": "http.response.body", "body": self.body})
if self.background is not None:
await self.background()
class HTMLResponse(Response):
media_type = "text/html"
class PlainTextResponse(Response):
media_type = "text/plain"
class JSONResponse(Response):
media_type = "application/json"
def render(self, content: typing.Any) -> bytes:
return json.dumps(
content,
ensure_ascii=False,
allow_nan=False,
indent=None,
separators=(",", ":"),
).encode("utf-8")
class UJSONResponse(JSONResponse):
media_type = "application/json"
def render(self, content: typing.Any) -> bytes:
return ujson.dumps(content, ensure_ascii=False).encode("utf-8")
class RedirectResponse(Response):
def __init__(
self, url: typing.Union[str, URL], status_code: int = 307, headers: dict = None
) -> None:
super().__init__(content=b"", status_code=status_code, headers=headers)
self.headers["location"] = quote_plus(str(url), safe=":/%#?&=@[]!$&'()*+,;")
class StreamingResponse(Response):
def __init__(
self,
content: typing.Any,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
) -> None:
if inspect.isasyncgen(content):
self.body_iterator = content
else:
self.body_iterator = iterate_in_threadpool(content)
self.status_code = status_code
self.media_type = self.media_type if media_type is None else media_type
self.background = background
self.init_headers(headers)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
async for chunk in self.body_iterator:
if not isinstance(chunk, bytes):
chunk = chunk.encode(self.charset)
await send({"type": "http.response.body", "body": chunk, "more_body": True})
await send({"type": "http.response.body", "body": b"", "more_body": False})
if self.background is not None:
await self.background()
class FileResponse(Response):
chunk_size = 4096
def __init__(
self,
path: str,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
filename: str = None,
stat_result: os.stat_result = None,
method: str = None,
) -> None:
assert aiofiles is not None, "'aiofiles' must be installed to use FileResponse"
self.path = path
self.status_code = status_code
self.filename = filename
self.send_header_only = method is not None and method.upper() == "HEAD"
if media_type is None:
media_type = guess_type(filename or path)[0] or "text/plain"
self.media_type = media_type
self.background = background
self.init_headers(headers)
if self.filename is not None:
content_disposition = 'attachment; filename="{}"'.format(self.filename)
self.headers.setdefault("content-disposition", content_disposition)
self.stat_result = stat_result
if stat_result is not None:
self.set_stat_headers(stat_result)
def set_stat_headers(self, stat_result: os.stat_result) -> None:
content_length = str(stat_result.st_size)
last_modified = formatdate(stat_result.st_mtime, usegmt=True)
etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
etag = hashlib.md5(etag_base.encode()).hexdigest()
self.headers.setdefault("content-length", content_length)
self.headers.setdefault("last-modified", last_modified)
self.headers.setdefault("etag", etag)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if self.stat_result is None:
try:
stat_result = await aio_stat(self.path)
self.set_stat_headers(stat_result)
except FileNotFoundError:
raise RuntimeError(f"File at path {self.path} does not exist.")
else:
mode = stat_result.st_mode
if not stat.S_ISREG(mode):
raise RuntimeError(f"File at path {self.path} is not a file.")
await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
if self.send_header_only:
await send({"type": "http.response.body"})
else:
async with aiofiles.open(self.path, mode="rb") as file:
more_body = True
while more_body:
chunk = await file.read(self.chunk_size)
more_body = len(chunk) == self.chunk_size
await send(
{
"type": "http.response.body",
"body": chunk,
"more_body": more_body,
}
)
if self.background is not None:
await self.background()
#-------------------------- Routing ________________________________
class NoMatchFound(Exception):
"""
Raised by `.url_for(name, **path_params)` and `.url_path_for(name, **path_params)`
if no matching route exists.
"""
class Match(Enum):
NONE = 0
PARTIAL = 1
FULL = 2
def request_response(func: typing.Callable) -> ASGIApp:
"""
Takes a function or coroutine `func(request) -> response`,
and returns an ASGI application.
"""
is_coroutine = asyncio.iscoroutinefunction(func)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive=receive, send=send)
if is_coroutine:
response = await func(request)
else:
response = await run_in_threadpool(func, request)
await response(scope, receive, send)
return app
def get_name(endpoint: typing.Callable) -> str:
if inspect.isfunction(endpoint) or inspect.isclass(endpoint):
return endpoint.__name__
return endpoint.__class__.__name__
def replace_params(
path: str,
param_convertors: typing.Dict[str, Convertor],
path_params: typing.Dict[str, str],
) -> typing.Tuple[str, dict]:
for key, value in list(path_params.items()):
if "{" + key + "}" in path:
convertor = param_convertors[key]
value = convertor.to_string(value)
path = path.replace("{" + key + "}", value)
path_params.pop(key)
return path, path_params
# Match parameters in URL paths, eg. '{param}', and '{param:int}'
PARAM_REGEX = re.compile("{([a-zA-Z_][a-zA-Z0-9_]*)(:[a-zA-Z_][a-zA-Z0-9_]*)?}")
def compile_path(
path: str,
) -> typing.Tuple[typing.Pattern, str, typing.Dict[str, Convertor]]:
"""
Given a path string, like: "/{username:str}", return a three-tuple
of (regex, format, {param_name:convertor}).
regex: "/(?P<username>[^/]+)"
format: "/{username}"
convertors: {"username": StringConvertor()}
"""
path_regex = "^"
path_format = ""
idx = 0
param_convertors = {}
for match in PARAM_REGEX.finditer(path):
param_name, convertor_type = match.groups("str")
convertor_type = convertor_type.lstrip(":")
assert (
convertor_type in CONVERTOR_TYPES
), f"Unknown path convertor '{convertor_type}'"
convertor = CONVERTOR_TYPES[convertor_type]
path_regex += path[idx : match.start()]
path_regex += f"(?P<{param_name}>{convertor.regex})"
path_format += path[idx : match.start()]
path_format += "{%s}" % param_name
param_convertors[param_name] = convertor
idx = match.end()
path_regex += path[idx:] + "$"
path_format += path[idx:]
return re.compile(path_regex), path_format, param_convertors
class BaseRoute:
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
raise NotImplementedError() # pragma: no cover
def url_path_for(self, name: str, **path_params: str) -> URLPath:
raise NotImplementedError() # pragma: no cover
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
raise NotImplementedError() # pragma: no cover
class Route(BaseRoute):
def __init__(
self,
path: str,
endpoint: typing.Callable,
*,
methods: typing.List[str] = None,
name: str = None,
include_in_schema: bool = True,
) -> None:
assert path.startswith("/"), "Routed paths must start with '/'"
self.path = path
self.endpoint = endpoint
self.name = get_name(endpoint) if name is None else name
self.include_in_schema = include_in_schema
if inspect.isfunction(endpoint) or inspect.ismethod(endpoint):
# Endpoint is function or method. Treat it as `func(request) -> response`.
self.app = request_response(endpoint)
if methods is None:
methods = ["GET"]
else:
# Endpoint is a class. Treat it as ASGI.
self.app = endpoint
if methods is None:
self.methods = None
else:
self.methods = set(method.upper() for method in methods)
if "GET" in self.methods:
self.methods.add("HEAD")
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] == "http":
match = self.path_regex.match(scope["path"])
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
child_scope = {"endpoint": self.endpoint, "path_params": path_params}
if self.methods and scope["method"] not in self.methods:
return Match.PARTIAL, child_scope
else:
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, **path_params: str) -> URLPath:
seen_params = set(path_params.keys())
expected_params = set(self.param_convertors.keys())
if name != self.name or seen_params != expected_params:
raise NoMatchFound()
path, remaining_params = replace_params(
self.path_format, self.param_convertors, path_params
)
assert not remaining_params
return URLPath(path=path, protocol="http")
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if self.methods and scope["method"] not in self.methods:
if "app" in scope:
raise HTTPException(status_code=405)
else:
response = PlainTextResponse("Method Not Allowed", status_code=405)
await response(scope, receive, send)
else:
await self.app(scope, receive, send)
def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, Route)
and self.path == other.path
and self.endpoint == other.endpoint
and self.methods == other.methods
)
class Mount(BaseRoute):
def __init__(
self,
path: str,
app: ASGIApp = None,
routes: typing.List[BaseRoute] = None,
name: str = None,
) -> None:
assert path == "" or path.startswith("/"), "Routed paths must start with '/'"
assert (
app is not None or routes is not None
), "Either 'app=...', or 'routes=' must be specified"
self.path = path.rstrip("/")
if app is not None:
self.app = app # type: ASGIApp
else:
self.app = Router(routes=routes)
self.name = name
self.path_regex, self.path_format, self.param_convertors = compile_path(
self.path + "/{path:path}"
)
@property
def routes(self) -> typing.List[BaseRoute]:
return getattr(self.app, "routes", None)
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] in ("http", "websocket"):
path = scope["path"]
match = self.path_regex.match(path)
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
remaining_path = "/" + matched_params.pop("path")
matched_path = path[: -len(remaining_path)]
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
root_path = scope.get("root_path", "")
child_scope = {
"path_params": path_params,
"app_root_path": scope.get("app_root_path", root_path),
"root_path": root_path + matched_path,
"path": remaining_path,
"endpoint": self.app,
}
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, **path_params: str) -> URLPath:
if self.name is not None and name == self.name and "path" in path_params:
# 'name' matches "<mount_name>".
path_params["path"] = path_params["path"].lstrip("/")
path, remaining_params = replace_params(
self.path_format, self.param_convertors, path_params
)
if not remaining_params:
return URLPath(path=path)
elif self.name is None or name.startswith(self.name + ":"):
if self.name is None:
# No mount name.
remaining_name = name
else:
# 'name' matches "<mount_name>:<child_name>".
remaining_name = name[len(self.name) + 1 :]
path_kwarg = path_params.get("path")
path_params["path"] = ""
path_prefix, remaining_params = replace_params(
self.path_format, self.param_convertors, path_params
)
if path_kwarg is not None:
remaining_params["path"] = path_kwarg
for route in self.routes or []:
try:
url = route.url_path_for(remaining_name, **remaining_params)
return URLPath(
path=path_prefix.rstrip("/") + str(url), protocol=url.protocol
)
except NoMatchFound:
pass
raise NoMatchFound()
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, Mount)
and self.path == other.path
and self.app == other.app
)
class Host(BaseRoute):
def __init__(self, host: str, app: ASGIApp, name: str = None) -> None:
self.host = host
self.app = app
self.name = name
self.host_regex, self.host_format, self.param_convertors = compile_path(host)
@property
def routes(self) -> typing.List[BaseRoute]:
return getattr(self.app, "routes", None)
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] in ("http", "websocket"):
headers = Headers(scope=scope)
host = headers.get("host", "").split(":")[0]
match = self.host_regex.match(host)
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
child_scope = {"path_params": path_params, "endpoint": self.app}
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, **path_params: str) -> URLPath:
if self.name is not None and name == self.name and "path" in path_params:
# 'name' matches "<mount_name>".
path = path_params.pop("path")
host, remaining_params = replace_params(
self.host_format, self.param_convertors, path_params
)
if not remaining_params:
return URLPath(path=path, host=host)
elif self.name is None or name.startswith(self.name + ":"):
if self.name is None:
# No mount name.
remaining_name = name
else:
# 'name' matches "<mount_name>:<child_name>".
remaining_name = name[len(self.name) + 1 :]
host, remaining_params = replace_params(
self.host_format, self.param_convertors, path_params
)
for route in self.routes or []:
try:
url = route.url_path_for(remaining_name, **remaining_params)
return URLPath(path=str(url), protocol=url.protocol, host=host)
except NoMatchFound:
pass
raise NoMatchFound()
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, Host)
and self.host == other.host
and self.app == other.app
)
class Lifespan(BaseRoute):
def __init__(
self,
on_startup: typing.Union[typing.Callable, typing.List[typing.Callable]] = None,
on_shutdown: typing.Union[typing.Callable, typing.List[typing.Callable]] = None,
):
self.startup_handlers = self.to_list(on_startup)
self.shutdown_handlers = self.to_list(on_shutdown)
def to_list(
self, item: typing.Union[typing.Callable, typing.List[typing.Callable]] = None
) -> typing.List[typing.Callable]:
if item is None:
return []
return list(item) if isinstance(item, (list, tuple)) else [item]
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] == "lifespan":
return Match.FULL, {}
return Match.NONE, {}
def add_event_handler(self, event_type: str, func: typing.Callable) -> None:
assert event_type in ("startup", "shutdown")
if event_type == "startup":
self.startup_handlers.append(func)
else:
assert event_type == "shutdown"
self.shutdown_handlers.append(func)
def on_event(self, event_type: str) -> typing.Callable:
def decorator(func: typing.Callable) -> typing.Callable:
self.add_event_handler(event_type, func)
return func
return decorator
async def startup(self) -> None:
for handler in self.startup_handlers:
if asyncio.iscoroutinefunction(handler):
await handler()
else:
handler()
async def shutdown(self) -> None:
for handler in self.shutdown_handlers:
if asyncio.iscoroutinefunction(handler):
await handler()
else:
handler()
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
message = await receive()
assert message["type"] == "lifespan.startup"
try:
await self.startup()
except BaseException:
msg = traceback.format_exc()
await send({"type": "lifespan.startup.failed", "message": msg})
raise
await send({"type": "lifespan.startup.complete"})
message = await receive()
assert message["type"] == "lifespan.shutdown"
await self.shutdown()
await send({"type": "lifespan.shutdown.complete"})
class Router:
def __init__(
self,
routes: typing.List[BaseRoute] = None,
redirect_slashes: bool = True,
default: ASGIApp = None,
on_startup: typing.List[typing.Callable] = None,
on_shutdown: typing.List[typing.Callable] = None,
) -> None:
self.routes = [] if routes is None else list(routes)
self.redirect_slashes = redirect_slashes
self.default = self.not_found if default is None else default
self.lifespan = Lifespan(on_startup=on_startup, on_shutdown=on_shutdown)
def mount(self, path: str, app: ASGIApp, name: str = None) -> None:
route = Mount(path, app=app, name=name)
self.routes.append(route)
def host(self, host: str, app: ASGIApp, name: str = None) -> None:
route = Host(host, app=app, name=name)
self.routes.append(route)
def add_route(
self,
path: str,
endpoint: typing.Callable,
methods: typing.List[str] = None,
name: str = None,
include_in_schema: bool = True,
) -> None:
route = Route(
path,
endpoint=endpoint,
methods=methods,
name=name,
include_in_schema=include_in_schema,
)
self.routes.append(route)
def add_websocket_route(
self, path: str, endpoint: typing.Callable, name: str = None
) -> None:
route = WebSocketRoute(path, endpoint=endpoint, name=name)
self.routes.append(route)
def route(
self,
path: str,
methods: typing.List[str] = None,
name: str = None,
include_in_schema: bool = True,
) -> typing.Callable:
def decorator(func: typing.Callable) -> typing.Callable:
self.add_route(
path,
func,
methods=methods,
name=name,
include_in_schema=include_in_schema,
)
return func
return decorator
def websocket_route(self, path: str, name: str = None) -> typing.Callable:
def decorator(func: typing.Callable) -> typing.Callable:
self.add_websocket_route(path, func, name=name)
return func
return decorator
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "websocket":
websocket_close = WebSocketClose()
await websocket_close(receive, send)
return
# If we're running inside a aspire.core application then raise an
# exception, so that the configurable exception handler can deal with
# returning the response. For plain ASGI apps, just return the response.
if "app" in scope:
raise HTTPException(status_code=404)
else:
response = PlainTextResponse("Not Found", status_code=404)
await response(scope, receive, send)
def url_path_for(self, name: str, **path_params: str) -> URLPath:
for route in self.routes:
try:
return route.url_path_for(name, **path_params)
except NoMatchFound:
pass
raise NoMatchFound()
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] in ("http", "websocket", "lifespan")
if "router" not in scope:
scope["router"] = self
partial = None
for route in self.routes:
match, child_scope = route.matches(scope)
if match == Match.FULL:
scope.update(child_scope)
await route(scope, receive, send)
return
elif match == Match.PARTIAL and partial is None:
partial = route
partial_scope = child_scope
if partial is not None:
scope.update(partial_scope)
await partial(scope, receive, send)
return
if scope["type"] == "http" and self.redirect_slashes:
if not scope["path"].endswith("/"):
redirect_scope = dict(scope)
redirect_scope["path"] += "/"
for route in self.routes:
match, child_scope = route.matches(redirect_scope)
if match != Match.NONE:
redirect_url = URL(scope=redirect_scope)
response = RedirectResponse(url=str(redirect_url))
await response(scope, receive, send)
return
if scope["type"] == "lifespan":
await self.lifespan(scope, receive, send)
else:
await self.default(scope, receive, send)
def __eq__(self, other: typing.Any) -> bool:
return isinstance(other, Router) and self.routes == other.routes
#----------------------------- endpoints ----------------------------------
class HTTPEndpoint:
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "http"
self.scope = scope
self.receive = receive
self.send = send
def __await__(self) -> typing.Generator:
return self.dispatch().__await__()
async def dispatch(self) -> None:
request = Request(self.scope, receive=self.receive)
handler_name = "get" if request.method == "HEAD" else request.method.lower()
handler = getattr(self, handler_name, self.method_not_allowed)
is_async = asyncio.iscoroutinefunction(handler)
if is_async:
response = await handler(request)
else:
response = await run_in_threadpool(handler, request)
await response(self.scope, self.receive, self.send)
async def method_not_allowed(self, request: Request) -> Response:
# If we're running inside a aspire.core application then raise an
# exception, so that the configurable exception handler can deal with
# returning the response. For plain ASGI apps, just return the response.
if "app" in self.scope:
raise HTTPException(status_code=405)
return PlainTextResponse("Method Not Allowed", status_code=405)
#-------------------------- Static Assets --------------------------
class NotModifiedResponse(Response):
NOT_MODIFIED_HEADERS = (
"cache-control",
"content-location",
"date",
"etag",
"expires",
"vary",
)
def __init__(self, headers: Headers):
super().__init__(
status_code=304,
headers={
name: value
for name, value in headers.items()
if name in self.NOT_MODIFIED_HEADERS
},
)
class StaticFiles:
def __init__(
self,
*,
directory: str = None,
packages: typing.List[str] = None,
html: bool = False,
check_dir: bool = True,
) -> None:
self.directory = directory
self.packages = packages
self.all_directories = self.get_directories(directory, packages)
self.html = html
self.config_checked = False
if check_dir and directory is not None and not os.path.isdir(directory):
raise RuntimeError(f"Directory '{directory}' does not exist")
def get_directories(
self, directory: str = None, packages: typing.List[str] = None
) -> typing.List[str]:
"""
Given `directory` and `packages` arguments, return a list of all the
directories that should be used for serving static files from.
"""
directories = []
if directory is not None:
directories.append(directory)
for package in packages or []:
spec = importlib.util.find_spec(package)
assert spec is not None, f"Package {package!r} could not be found."
assert (
spec.origin is not None
), f"Directory 'statics' in package {package!r} could not be found."
directory = os.path.normpath(os.path.join(spec.origin, "..", "statics"))
assert os.path.isdir(
directory
), f"Directory 'statics' in package {package!r} could not be found."
directories.append(directory)
return directories
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""
The ASGI entry point.
"""
assert scope["type"] == "http"
if not self.config_checked:
await self.check_config()
self.config_checked = True
path = self.get_path(scope)
response = await self.get_response(path, scope)
await response(scope, receive, send)
def get_path(self, scope: Scope) -> str:
"""
Given the ASGI scope, return the `path` string to serve up,
with OS specific path seperators, and any '..', '.' components removed.
"""
return os.path.normpath(os.path.join(*scope["path"].split("/")))
async def get_response(self, path: str, scope: Scope) -> Response:
"""
Returns an HTTP response, given the incoming path, method and request headers.
"""
if scope["method"] not in ("GET", "HEAD"):
return PlainTextResponse("Method Not Allowed", status_code=405)
if path.startswith(".."):
# Most clients will normalize the path, so we shouldn't normally
# get this, but don't allow misbehaving clients to break out of
# the static files directory.
return PlainTextResponse("Not Found", status_code=404)
full_path, stat_result = await self.lookup_path(path)
if stat_result and stat.S_ISREG(stat_result.st_mode):
# We have a static file to serve.
return self.file_response(full_path, stat_result, scope)
elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html:
# We're in HTML mode, and have got a directory URL.
# Check if we have 'index.html' file to serve.
index_path = os.path.join(path, "index.html")
full_path, stat_result = await self.lookup_path(index_path)
if stat_result is not None and stat.S_ISREG(stat_result.st_mode):
if not scope["path"].endswith("/"):
# Directory URLs should redirect to always end in "/".
url = URL(scope=scope)
url = url.replace(path=url.path + "/")
return RedirectResponse(url=url)
return self.file_response(full_path, stat_result, scope)
if self.html:
# Check for '404.html' if we're in HTML mode.
full_path, stat_result = await self.lookup_path("404.html")
if stat_result is not None and stat.S_ISREG(stat_result.st_mode):
return FileResponse(
full_path,
stat_result=stat_result,
method=scope["method"],
status_code=404
)
return PlainTextResponse("Not Found", status_code=404)
async def lookup_path(
self, path: str
) -> typing.Tuple[str, typing.Optional[os.stat_result]]:
for directory in self.all_directories:
full_path = os.path.join(directory, path)
if (
os.path.commonprefix([os.path.realpath(full_path), directory])
!= directory
):
full_path = os.path.realpath(os.path.join(directory, path))
directory = os.path.realpath(directory)
if os.path.commonprefix([full_path, directory]) != directory:
# Don't allow misbehaving clients to break out of the static files directory.
continue
try:
stat_result = await aio_stat(full_path)
return (full_path, stat_result)
except FileNotFoundError:
pass
return ("", None)
def file_response(
self,
full_path: str,
stat_result: os.stat_result,
scope: Scope,
status_code: int = 200,
) -> Response:
method = scope["method"]
request_headers = Headers(scope=scope)
response = FileResponse(
full_path, status_code=status_code, stat_result=stat_result, method=method
)
if self.is_not_modified(response.headers, request_headers):
return NotModifiedResponse(response.headers)
return response
async def check_config(self) -> None:
"""
Perform a one-off configuration check that StaticFiles is actually
pointed at a directory, so that we can raise loud errors rather than
just returning 404 responses.
"""
if self.directory is None:
return
try:
stat_result = await aio_stat(self.directory)
except FileNotFoundError:
raise RuntimeError(
f"StaticFiles directory '{self.directory}' does not exist."
)
if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)):
raise RuntimeError(
f"StaticFiles path '{self.directory}' is not a directory."
)
def is_not_modified(
self, response_headers: Headers, request_headers: Headers
) -> bool:
"""
Given the request and response headers, return `True` if an HTTP
"Not Modified" response could be returned instead.
"""
try:
if_none_match = request_headers["if-none-match"]
etag = response_headers["etag"]
if if_none_match == etag:
return True
except KeyError:
pass
try:
if_modified_since = parsedate(request_headers["if-modified-since"])
last_modified = parsedate(response_headers["last-modified"])
if (
if_modified_since is not None
and last_modified is not None
and if_modified_since >= last_modified
):
return True
except KeyError:
pass
return False
#-------------------------- Template Services ----------------------
class _TemplateResponse(Response):
media_type = "text/html"
def __init__(
self,
template: typing.Any,
context: dict,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
):
self.template = template
self.context = context
content = template.render(context)
super().__init__(content, status_code, headers, media_type, background)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
request = self.context.get("request", {})
extensions = request.get("extensions", {})
if "http.response.template" in extensions:
await send(
{
"type": "http.response.template",
"template": self.template,
"context": self.context,
}
)
await super().__call__(scope, receive, send)
class JinjaTemplates:
"""
templates = Templates("templates")
return templates.TemplateResponse("index.html", {"request": request})
"""
def __init__(self, directory: str) -> None:
assert jinja2 is not None, "jinja2 must be installed to use Templates"
self.env = self.get_env(directory)
def get_env(self, directory: str) -> "jinja2.Environment":
@jinja2.contextfunction
def url_for(context: dict, name: str, **path_params: typing.Any) -> str:
request = context["request"]
return request.url_for(name, **path_params)
loader = jinja2.FileSystemLoader(directory)
env = jinja2.Environment(loader=loader, autoescape=True)
env.globals["url_for"] = url_for
return env
def get_template(self, name: str) -> "jinja2.Template":
return self.env.get_template(name)
def TemplateResponse(
self,
name: str,
context: dict,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
) -> _TemplateResponse:
if "request" not in context:
raise ValueError('context must include a "request" key')
template = self.get_template(name)
return _TemplateResponse(
template,
context,
status_code=status_code,
headers=headers,
media_type=media_type,
background=background,
)
#-------------------------- Network Services -----------------------
def build_environ(scope: Scope, body: bytes) -> dict:
"""
Builds a scope and request body into a WSGI environ object.
"""
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": scope.get("root_path", ""),
"PATH_INFO": scope["path"],
"QUERY_STRING": scope["query_string"].decode("ascii"),
"SERVER_PROTOCOL": f"HTTP/{scope['http_version']}",
"wsgi.version": (1, 0),
"wsgi.url_scheme": scope.get("scheme", "http"),
"wsgi.input": io.BytesIO(body),
"wsgi.errors": sys.stdout,
"wsgi.multithread": True,
"wsgi.multiprocess": True,
"wsgi.run_once": False,
}
# Get server name and port - required in WSGI, not in ASGI
server = scope.get("server") or ("localhost", 80)
environ["SERVER_NAME"] = server[0]
environ["SERVER_PORT"] = server[1]
# Get client IP address
if scope.get("client"):
environ["REMOTE_ADDR"] = scope["client"][0]
# Go through headers and make them into environ entries
for name, value in scope.get("headers", []):
name = name.decode("latin1")
if name == "content-length":
corrected_name = "CONTENT_LENGTH"
elif name == "content-type":
corrected_name = "CONTENT_TYPE"
else:
corrected_name = f"HTTP_{name}".upper().replace("-", "_")
# HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
value = value.decode("latin1")
if corrected_name in environ:
value = environ[corrected_name] + "," + value
environ[corrected_name] = value
return environ
###--------------------- Web Sockets -------------------------------
class WebSocketState(enum.Enum):
CONNECTING = 0
CONNECTED = 1
DISCONNECTED = 2
class WebSocketDisconnect(Exception):
def __init__(self, code: int = 1000) -> None:
self.code = code
class WebSocket(HTTPConnection):
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
super().__init__(scope)
assert scope["type"] == "websocket"
self._receive = receive
self._send = send
self.client_state = WebSocketState.CONNECTING
self.application_state = WebSocketState.CONNECTING
async def receive(self) -> Message:
"""
Receive ASGI websocket messages, ensuring valid state transitions.
"""
if self.client_state == WebSocketState.CONNECTING:
message = await self._receive()
message_type = message["type"]
assert message_type == "websocket.connect"
self.client_state = WebSocketState.CONNECTED
return message
elif self.client_state == WebSocketState.CONNECTED:
message = await self._receive()
message_type = message["type"]
assert message_type in {"websocket.receive", "websocket.disconnect"}
if message_type == "websocket.disconnect":
self.client_state = WebSocketState.DISCONNECTED
return message
else:
raise RuntimeError(
'Cannot call "receive" once a disconnect message has been received.'
)
async def send(self, message: Message) -> None:
"""
Send ASGI websocket messages, ensuring valid state transitions.
"""
if self.application_state == WebSocketState.CONNECTING:
message_type = message["type"]
assert message_type in {"websocket.accept", "websocket.close"}
if message_type == "websocket.close":
self.application_state = WebSocketState.DISCONNECTED
else:
self.application_state = WebSocketState.CONNECTED
await self._send(message)
elif self.application_state == WebSocketState.CONNECTED:
message_type = message["type"]
assert message_type in {"websocket.send", "websocket.close"}
if message_type == "websocket.close":
self.application_state = WebSocketState.DISCONNECTED
await self._send(message)
else:
raise RuntimeError('Cannot call "send" once a close message has been sent.')
async def accept(self, subprotocol: str = None) -> None:
if self.client_state == WebSocketState.CONNECTING:
# If we haven't yet seen the 'connect' message, then wait for it first.
await self.receive()
await self.send({"type": "websocket.accept", "subprotocol": subprotocol})
def _raise_on_disconnect(self, message: Message) -> None:
if message["type"] == "websocket.disconnect":
raise WebSocketDisconnect(message["code"])
async def receive_text(self) -> str:
assert self.application_state == WebSocketState.CONNECTED
message = await self.receive()
self._raise_on_disconnect(message)
return message["text"]
async def receive_bytes(self) -> bytes:
assert self.application_state == WebSocketState.CONNECTED
message = await self.receive()
self._raise_on_disconnect(message)
return message["bytes"]
async def receive_json(self, mode: str = "text") -> typing.Any:
assert mode in ["text", "binary"]
assert self.application_state == WebSocketState.CONNECTED
message = await self.receive()
self._raise_on_disconnect(message)
if mode == "text":
text = message["text"]
else:
text = message["bytes"].decode("utf-8")
return json.loads(text)
async def send_text(self, data: str) -> None:
await self.send({"type": "websocket.send", "text": data})
async def send_bytes(self, data: bytes) -> None:
await self.send({"type": "websocket.send", "bytes": data})
async def send_json(self, data: typing.Any, mode: str = "text") -> None:
assert mode in ["text", "binary"]
text = json.dumps(data)
if mode == "text":
await self.send({"type": "websocket.send", "text": text})
else:
await self.send({"type": "websocket.send", "bytes": text.encode("utf-8")})
async def close(self, code: int = 1000) -> None:
await self.send({"type": "websocket.close", "code": code})
class WebSocketClose:
def __init__(self, code: int = 1000) -> None:
self.code = code
async def __call__(self, receive: Receive, send: Send) -> None:
await send({"type": "websocket.close", "code": self.code})
class WebSocketEndpoint:
encoding = None # May be "text", "bytes", or "json".
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "websocket"
self.scope = scope
self.receive = receive
self.send = send
def __await__(self) -> typing.Generator:
return self.dispatch().__await__()
async def dispatch(self) -> None:
websocket = WebSocket(self.scope, receive=self.receive, send=self.send)
await self.on_connect(websocket)
close_code = status.WS_1000_NORMAL_CLOSURE
try:
while True:
message = await websocket.receive()
if message["type"] == "websocket.receive":
data = await self.decode(websocket, message)
await self.on_receive(websocket, data)
elif message["type"] == "websocket.disconnect":
close_code = int(message.get("code", status.WS_1000_NORMAL_CLOSURE))
break
except Exception as exc:
close_code = status.WS_1011_INTERNAL_ERROR
raise exc from None
finally:
await self.on_disconnect(websocket, close_code)
async def decode(self, websocket: WebSocket, message: Message) -> typing.Any:
if self.encoding == "text":
if "text" not in message:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Expected text websocket messages, but got bytes")
return message["text"]
elif self.encoding == "bytes":
if "bytes" not in message:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Expected bytes websocket messages, but got text")
return message["bytes"]
elif self.encoding == "json":
if message.get("text") is not None:
text = message["text"]
else:
text = message["bytes"].decode("utf-8")
try:
return json.loads(text)
except json.decoder.JSONDecodeError:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Malformed JSON data received.")
assert (
self.encoding is None
), f"Unsupported 'encoding' attribute {self.encoding}"
return message["text"] if message.get("text") else message["bytes"]
async def on_connect(self, websocket: WebSocket) -> None:
"""Override to handle an incoming websocket connection"""
await websocket.accept()
async def on_receive(self, websocket: WebSocket, data: typing.Any) -> None:
"""Override to handle an incoming websocket message"""
async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None:
"""Override to handle a disconnecting websocket"""
def websocket_session(func: typing.Callable) -> ASGIApp:
"""
Takes a coroutine `func(session)`, and returns an ASGI application.
"""
# assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async"
async def app(scope: Scope, receive: Receive, send: Send) -> None:
session = WebSocket(scope, receive=receive, send=send)
await func(session)
return app
class WebSocketRoute(BaseRoute):
def __init__(
self, path: str, endpoint: typing.Callable, *, name: str = None
) -> None:
assert path.startswith("/"), "Routed paths must start with '/'"
self.path = path
self.endpoint = endpoint
self.name = get_name(endpoint) if name is None else name
if inspect.isfunction(endpoint) or inspect.ismethod(endpoint):
# Endpoint is function or method. Treat it as `func(websocket)`.
self.app = websocket_session(endpoint)
else:
# Endpoint is a class. Treat it as ASGI.
self.app = endpoint
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] == "websocket":
match = self.path_regex.match(scope["path"])
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
child_scope = {"endpoint": self.endpoint, "path_params": path_params}
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, **path_params: str) -> URLPath:
seen_params = set(path_params.keys())
expected_params = set(self.param_convertors.keys())
if name != self.name or seen_params != expected_params:
raise NoMatchFound()
path, remaining_params = replace_params(
self.path_format, self.param_convertors, path_params
)
assert not remaining_params
return URLPath(path=path, protocol="websocket")
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, WebSocketRoute)
and self.path == other.path
and self.endpoint == other.endpoint
)
###--------------------- Web Server Gateway Interface (WSGI) -------------------
class WSGIResponder:
def __init__(self, app: typing.Callable, scope: Scope) -> None:
self.app = app
self.scope = scope
self.status = None
self.response_headers = None
self.send_event = asyncio.Event()
self.send_queue = [] # type: typing.List[typing.Optional[Message]]
self.loop = asyncio.get_event_loop()
self.response_started = False
self.exc_info = None # type: typing.Any
async def __call__(self, receive: Receive, send: Send) -> None:
body = b""
more_body = True
while more_body:
message = await receive()
body += message.get("body", b"")
more_body = message.get("more_body", False)
environ = build_environ(self.scope, body)
sender = None
try:
sender = self.loop.create_task(self.sender(send))
await run_in_threadpool(self.wsgi, environ, self.start_response)
self.send_queue.append(None)
self.send_event.set()
await asyncio.wait_for(sender, None)
if self.exc_info is not None:
raise self.exc_info[0].with_traceback(
self.exc_info[1], self.exc_info[2]
)
finally:
if sender and not sender.done():
sender.cancel() # pragma: no cover
async def sender(self, send: Send) -> None:
while True:
if self.send_queue:
message = self.send_queue.pop(0)
if message is None:
return
await send(message)
else:
await self.send_event.wait()
self.send_event.clear()
def start_response(
self,
status: str,
response_headers: typing.List[typing.Tuple[str, str]],
exc_info: typing.Any = None,
) -> None:
self.exc_info = exc_info
if not self.response_started:
self.response_started = True
status_code_string, _ = status.split(" ", 1)
status_code = int(status_code_string)
headers = [
(name.encode("ascii"), value.encode("ascii"))
for name, value in response_headers
]
self.send_queue.append(
{
"type": "http.response.start",
"status": status_code,
"headers": headers,
}
)
self.loop.call_soon_threadsafe(self.send_event.set)
def wsgi(self, environ: dict, start_response: typing.Callable) -> None:
for chunk in self.app(environ, start_response):
self.send_queue.append(
{"type": "http.response.body", "body": chunk, "more_body": True}
)
self.loop.call_soon_threadsafe(self.send_event.set)
self.send_queue.append({"type": "http.response.body", "body": b""})
self.loop.call_soon_threadsafe(self.send_event.set)
class WSGIMiddleware:
def __init__(self, app: typing.Callable, workers: int = 10) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "http"
responder = WSGIResponder(self.app, scope)
await responder(receive, send)
#------------------------------ base helper ------------------------------------
RequestResponseEndpoint = typing.Callable[[Request], typing.Awaitable[Response]]
DispatchFunction = typing.Callable[
[Request, RequestResponseEndpoint], typing.Awaitable[Response]
]
class ExceptionMiddleware:
def __init__(
self, app: ASGIApp, handlers: dict = None, debug: bool = False
) -> None:
self.app = app
self.debug = debug # TODO: We ought to handle 404 cases if debug is set.
self._status_handlers = {} # type: typing.Dict[int, typing.Callable]
self._exception_handlers = {
HTTPException: self.http_exception
} # type: typing.Dict[typing.Type[Exception], typing.Callable]
if handlers is not None:
for key, value in handlers.items():
self.add_exception_handler(key, value)
def add_exception_handler(
self,
exc_class_or_status_code: typing.Union[int, typing.Type[Exception]],
handler: typing.Callable,
) -> None:
if isinstance(exc_class_or_status_code, int):
self._status_handlers[exc_class_or_status_code] = handler
else:
assert issubclass(exc_class_or_status_code, Exception)
self._exception_handlers[exc_class_or_status_code] = handler
def _lookup_exception_handler(
self, exc: Exception
) -> typing.Optional[typing.Callable]:
for cls in type(exc).__mro__:
if cls in self._exception_handlers:
return self._exception_handlers[cls]
return None
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
response_started = False
async def sender(message: Message) -> None:
nonlocal response_started
if message["type"] == "http.response.start":
response_started = True
await send(message)
try:
await self.app(scope, receive, sender)
except Exception as exc:
handler = None
if isinstance(exc, HTTPException):
handler = self._status_handlers.get(exc.status_code)
if handler is None:
handler = self._lookup_exception_handler(exc)
if handler is None:
raise exc from None
if response_started:
msg = "Caught handled exception, but response already started."
raise RuntimeError(msg) from exc
request = Request(scope, receive=receive)
if asyncio.iscoroutinefunction(handler):
response = await handler(request, exc)
else:
response = await run_in_threadpool(handler, request, exc)
await response(scope, receive, sender)
def http_exception(self, request: Request, exc: HTTPException) -> Response:
if exc.status_code in {204, 304}:
return Response(b"", status_code=exc.status_code)
return PlainTextResponse(exc.detail, status_code=exc.status_code)
# Call Request, Response
class BaseHTTPMiddleware:
def __init__(self, app: ASGIApp, dispatch: DispatchFunction = None) -> None:
self.app = app
self.dispatch_func = self.dispatch if dispatch is None else dispatch
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
request = Request(scope, receive=receive)
response = await self.dispatch_func(request, self.call_next)
await response(scope, receive, send)
async def call_next(self, request: Request) -> Response:
loop = asyncio.get_event_loop()
queue = asyncio.Queue() # type: asyncio.Queue
scope = request.scope
receive = request.receive
send = queue.put
async def coro() -> None:
try:
await self.app(scope, receive, send)
finally:
await queue.put(None)
task = loop.create_task(coro())
message = await queue.get()
if message is None:
task.result()
raise RuntimeError("No response returned.")
assert message["type"] == "http.response.start"
async def body_stream() -> typing.AsyncGenerator[bytes, None]:
while True:
message = await queue.get()
if message is None:
break
assert message["type"] == "http.response.body"
yield message["body"]
task.result()
response = StreamingResponse(
status_code=message["status"], content=body_stream()
)
response.raw_headers = message["headers"]
return response
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
raise NotImplementedError() # pragma: no cover
#------------------------------ errors helpers ---------------------------------
STYLES = """
p {
color: #211c1c;
}
.traceback-container {
border: 1px solid #038BB8;
}
.traceback-title {
background-color: #038BB8;
color: lemonchiffon;
padding: 12px;
font-size: 20px;
margin-top: 0px;
}
.frame-line {
padding-left: 10px;
}
.center-line {
background-color: #038BB8;
color: #f9f6e1;
padding: 5px 0px 5px 5px;
}
.lineno {
margin-right: 5px;
}
.frame-filename {
font-weight: unset;
padding: 10px 10px 10px 0px;
background-color: #E4F4FD;
margin-right: 10px;
font: #394D54;
color: #191f21;
font-size: 17px;
border: 1px solid #c7dce8;
}
.collapse-btn {
float: right;
padding: 0px 5px 1px 5px;
border: solid 1px #96aebb;
cursor: pointer;
}
.collapsed {
display: none;
}
.source-code {
font-family: courier;
font-size: small;
padding-bottom: 10px;
}
"""
JS = """
<script type="text/javascript">
function collapse(element){
const frameId = element.getAttribute("data-frame-id");
const frame = document.getElementById(frameId);
if (frame.classList.contains("collapsed")){
element.innerHTML = "‒";
frame.classList.remove("collapsed");
} else {
element.innerHTML = "+";
frame.classList.add("collapsed");
}
}
</script>
"""
TEMPLATE = """
<html>
<head>
<style type='text/css'>
{styles}
</style>
<title>aspire.core Debugger</title>
</head>
<body>
<h1>500 Server Error</h1>
<h2>{error}</h2>
<div class="traceback-container">
<p class="traceback-title">Traceback</p>
<div>{exc_html}</div>
</div>
{js}
</body>
</html>
"""
FRAME_TEMPLATE = """
<div>
<p class="frame-filename"><span class="debug-filename frame-line">File {frame_filename}</span>,
line <i>{frame_lineno}</i>,
in <b>{frame_name}</b>
<span class="collapse-btn" data-frame-id="{frame_filename}-{frame_lineno}" onclick="collapse(this)">{collapse_button}</span>
</p>
<div id="{frame_filename}-{frame_lineno}" class="source-code {collapsed}">{code_context}</div>
</div>
"""
LINE = """
<p><span class="frame-line">
<span class="lineno">{lineno}.</span> {line}</span></p>
"""
CENTER_LINE = """
<p class="center-line"><span class="frame-line center-line">
<span class="lineno">{lineno}.</span> {line}</span></p>
"""
class ServerErrorMiddleware:
"""
Handles returning 500 responses when a server error occurs.
If 'debug' is set, then traceback responses will be returned,
otherwise the designated 'handler' will be called.
This middleware class should generally be used to wrap *everything*
else up, so that unhandled exceptions anywhere in the stack
always result in an appropriate 500 response.
"""
def __init__(
self, app: ASGIApp, handler: typing.Callable = None, debug: bool = False
) -> None:
self.app = app
self.handler = handler
self.debug = debug
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
response_started = False
async def _send(message: Message) -> None:
nonlocal response_started, send
if message["type"] == "http.response.start":
response_started = True
await send(message)
try:
await self.app(scope, receive, _send)
except Exception as exc:
if not response_started:
request = Request(scope)
if self.debug:
# In debug mode, return traceback responses.
response = self.debug_response(request, exc)
elif self.handler is None:
# Use our default 500 error handler.
response = self.error_response(request, exc)
else:
# Use an installed 500 error handler.
if asyncio.iscoroutinefunction(self.handler):
response = await self.handler(request, exc)
else:
response = await run_in_threadpool(self.handler, request, exc)
await response(scope, receive, send)
# We always continue to raise the exception.
# This allows servers to log the error, or allows test clients
# to optionally raise the error within the test case.
raise exc from None
def format_line(
self, position: int, line: str, frame_lineno: int, center_lineno: int
) -> str:
values = {
"line": line.replace(" ", " "),
"lineno": frame_lineno + (position - center_lineno),
}
if position != center_lineno:
return LINE.format(**values)
return CENTER_LINE.format(**values)
def generate_frame_html(
self, frame: inspect.FrameInfo, center_lineno: int, is_collapsed: bool
) -> str:
code_context = "".join(
self.format_line(context_position, line, frame.lineno, center_lineno)
for context_position, line in enumerate(frame.code_context or [])
)
values = {
"frame_filename": frame.filename,
"frame_lineno": frame.lineno,
"frame_name": frame.function,
"code_context": code_context,
"collapsed": "collapsed" if is_collapsed else "",
"collapse_button": "+" if is_collapsed else "‒",
}
return FRAME_TEMPLATE.format(**values)
def generate_html(self, exc: Exception, limit: int = 7) -> str:
traceback_obj = traceback.TracebackException.from_exception(
exc, capture_locals=True
)
#frames = inspect.getinnerframes(
# traceback_obj.exc_traceback, limit # type: ignore
#)
center_lineno = int((limit - 1) / 2)
exc_html = ""
is_collapsed = False
#for frame in reversed(frames):
# exc_html += self.generate_frame_html(frame, center_lineno, is_collapsed)
# is_collapsed = True
# Implemented Feb 27 2021
exc_traceback = exc.__traceback__
if exc_traceback is not None:
frames = inspect.getinnerframes(exc_traceback, limit)
for frame in reversed(frames):
exc_html += self.generate_frame_html(frame, center_lineno, is_collapsed)
is_collapsed = True
error = f"{traceback_obj.exc_type.__name__}: {html.escape(str(traceback_obj))}"
return TEMPLATE.format(styles=STYLES, js=JS, error=error, exc_html=exc_html)
def generate_plain_text(self, exc: Exception) -> str:
return "".join(traceback.format_tb(exc.__traceback__))
def debug_response(self, request: Request, exc: Exception) -> Response:
accept = request.headers.get("accept", "")
if "text/html" in accept:
content = self.generate_html(exc)
return HTMLResponse(content, status_code=500)
content = self.generate_plain_text(exc)
return PlainTextResponse(content, status_code=500)
def error_response(self, request: Request, exc: Exception) -> Response:
return PlainTextResponse("Internal Server Error", status_code=500)
#---------------------- Gzip Assistant ----------------------------------
class GZipMiddleware:
def __init__(self, app: ASGIApp, minimum_size: int = 500) -> None:
self.app = app
self.minimum_size = minimum_size
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "http":
headers = Headers(scope=scope)
if "gzip" in headers.get("Accept-Encoding", ""):
responder = GZipResponder(self.app, self.minimum_size)
await responder(scope, receive, send)
return
await self.app(scope, receive, send)
class GZipResponder:
def __init__(self, app: ASGIApp, minimum_size: int) -> None:
self.app = app
self.minimum_size = minimum_size
self.send = unattached_send # type: Send
self.initial_message = {} # type: Message
self.started = False
self.gzip_buffer = io.BytesIO()
self.gzip_file = gzip.GzipFile(mode="wb", fileobj=self.gzip_buffer)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
self.send = send
await self.app(scope, receive, self.send_with_gzip)
async def send_with_gzip(self, message: Message) -> None:
message_type = message["type"]
if message_type == "http.response.start":
# Don't send the initial message until we've determined how to
# modify the ougoging headers correctly.
self.initial_message = message
elif message_type == "http.response.body" and not self.started:
self.started = True
body = message.get("body", b"")
more_body = message.get("more_body", False)
if len(body) < self.minimum_size and not more_body:
# Don't apply GZip to small outgoing responses.
await self.send(self.initial_message)
await self.send(message)
elif not more_body:
# Standard GZip response.
self.gzip_file.write(body)
self.gzip_file.close()
body = self.gzip_buffer.getvalue()
headers = MutableHeaders(raw=self.initial_message["headers"])
headers["Content-Encoding"] = "gzip"
headers["Content-Length"] = str(len(body))
headers.add_vary_header("Accept-Encoding")
message["body"] = body
await self.send(self.initial_message)
await self.send(message)
else:
# Initial body in streaming GZip response.
headers = MutableHeaders(raw=self.initial_message["headers"])
headers["Content-Encoding"] = "gzip"
headers.add_vary_header("Accept-Encoding")
del headers["Content-Length"]
self.gzip_file.write(body)
message["body"] = self.gzip_buffer.getvalue()
self.gzip_buffer.seek(0)
self.gzip_buffer.truncate()
await self.send(self.initial_message)
await self.send(message)
elif message_type == "http.response.body":
# Remaining body in streaming GZip response.
body = message.get("body", b"")
more_body = message.get("more_body", False)
self.gzip_file.write(body)
if not more_body:
self.gzip_file.close()
message["body"] = self.gzip_buffer.getvalue()
self.gzip_buffer.seek(0)
self.gzip_buffer.truncate()
await self.send(message)
async def unattached_send(message: Message) -> None:
raise RuntimeError("send awaitable not set") # pragma: no cover
|
#!/usr/bin/env python3
#
# Generates an HTML file for previewing all styles defined in a CSS file
#
# dependencies: cssutils
# USAGE:
# css_preview_generator.py style.css -o preview.html
import html
import io
import sys
import cssutils
image_placeholder = "data:image/svg+xml;charset=UTF-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='150' viewBox='0 0 300 150'%3E%3Crect fill='yellow' width='300' height='150'/%3E%3Ctext fill='rgba(0,0,0,0.5)' x='50%25' y='50%25' text-anchor='middle'%3E300×150%3C/text%3E%3C/svg%3E"
def render(s, out):
# if isinstance(out, io.StringIO):
# terminator = ''
# else:
# terminator = '\n'
print(s, end='', file=out)
def process_css_definitions(chunks, full_selector, out):
if len(chunks):
chunk = chunks.pop(0)
render_open_tag(chunk, out)
process_css_definitions(chunks, full_selector, out)
render_close_tag(chunk, out)
else:
render(full_selector, out)
prefix_map = {
'.': 'class',
'#': 'id'
}
def extract_class_id(defn, extracted_attrs=''):
try:
for prefix in prefix_map.keys():
if prefix in defn:
items = defn.split(prefix)
value = ' '.join(items[1:])
# return a tuple of (tagname, 'class="bla blu"') or (tagname, 'id="abc"')
tag = items[0]
if any(suffix in tag for suffix in prefix_map.keys()):
return extract_class_id(tag, f'{prefix_map[prefix]}="{value}"')
else:
return items[0], f'{extracted_attrs} {prefix_map[prefix]}="{value}"'
except Exception as e:
print(e, file=sys.stderr)
return defn, ''
def render_open_tag(definition, out):
if definition.startswith(('.', '#')):
_, class_or_id = extract_class_id(definition)
render(f'<div {class_or_id}>', out)
else:
if definition == 'a' or definition.startswith(('a.', 'a#')):
tag, class_or_id = extract_class_id(definition)
render(f'''<a {class_or_id} href="#">''', out)
elif definition == 'img' or definition.startswith(('img.','img#')):
render(f'<img src="{image_placeholder}" alt="[image]">', out)
else:
tag, class_or_id = extract_class_id(definition)
if tag.lower() == 'td':
render(f'<table><thead><tr><th>🔶🔷[th]🔷🔶</th></thead><tbody><tr><td {class_or_id}>🔹[td]🔹<br/>', out)
else:
render(f'<{tag} {class_or_id}>', out)
def render_close_tag(definition, out):
if definition.startswith(('.', '#')):
render('</div>', out)
else:
if definition == 'a' or definition.startswith(('a.', 'a#')):
render(f'⚓️ {definition}</a>', out)
else:
tag, _ = extract_class_id(definition)
if tag.lower() == 'td':
render('</td></tr></tbody></table>', out)
else:
render(f'</{tag}>', out)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='CSS Preview Generator')
parser.add_argument('css_file',
help='CSS stylesheet file name')
parser.add_argument('--verbose', '-v',
help='Verbose output',
default=False,
action='store_true')
parser.add_argument('--output-file', '-o',
metavar='output',
help='HTML preview filename')
parser.add_argument('--no-frames', '-nf',
default=False,
action='store_true',
help='Do NOT wrap fixed/absolute elements in iframe')
args = parser.parse_args(sys.argv[1:])
output_file = args.output_file and open(args.output_file, 'w') or sys.stdout
already_seen = []
sheet = cssutils.parseFile(args.css_file)
print('Generating HTML preview. Please wait...', file=sys.stderr)
print(f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS preview: {args.css_file}</title>
<link href="{args.css_file}" rel="stylesheet" type="text/css" />
</head>
<body>
''', file=output_file)
selectors_requiring_iframe = []
# build a list of absolute & fixed rules
if not args.no_frames:
for rule in sheet:
if isinstance(rule, cssutils.css.CSSStyleRule):
position = getattr(rule.style, 'position', None)
if position in ('fixed', 'absolute', 'sticky'):
for single_selector in rule.selectorList: # type: cssutils.css.Selector
selectors_requiring_iframe.append(single_selector.selectorText)
# deduplicate list
selectors_requiring_iframe = list(dict.fromkeys(selectors_requiring_iframe))
for rule in sheet:
if isinstance(rule, cssutils.css.CSSStyleRule):
selectors: cssutils.css.SelectorList = getattr(rule, 'selectorList', [])
full_selectors_text = rule.selectorText
if args.verbose:
print(f'CSS Rule: {full_selectors_text}', file=sys.stderr)
for single_selector in selectors: # type: cssutils.css.Selector
current_selector_text = single_selector.selectorText
if not single_selector or current_selector_text.startswith(('html', 'body')):
continue
# 1. convert '>' to space
# 2. '~' '*' '+' and '[]' (not supported, ignoring them, convert to space, breaks semantics FIXME)
for c in '>*~+':
if c in current_selector_text:
current_selector_text = current_selector_text.replace(c, ' ')
for c in ':[':
if c in current_selector_text:
current_selector_text = current_selector_text.split(c)[0]
if current_selector_text in already_seen:
continue
else:
already_seen.append(current_selector_text)
if ' ' in current_selector_text:
current_selector_text = current_selector_text.replace(' ', ' ')
position = getattr(rule.style, 'position', None)
need_iframe = False
if not args.no_frames:
# if current selector is a child of an absolute/fixed rule then also wrap it in an iframe
matching_abs_parents = [sel for sel in selectors_requiring_iframe if sel in current_selector_text]
need_iframe = position in ('fixed', 'absolute', 'sticky') or len(matching_abs_parents)
need_table = False
if need_iframe:
print(
f'''<iframe style="border:1px dotted #acad9e;" width="400" height="300" srcdoc="{html.escape(f'<html><head><link href='{args.css_file}' rel='stylesheet' type='text/css'/></head><body style='background:#f6f4ee'>')}''',
end='', file=output_file)
out = io.StringIO()
else:
out = output_file
if args.verbose:
print(f'\t{current_selector_text}', file=sys.stderr)
process_css_definitions(current_selector_text.split(), full_selectors_text, out)
if need_iframe:
print(html.escape(out.getvalue()), end='', file=output_file)
print('"></iframe><br/>', file=output_file)
print('''
</body>
</html>''', file=output_file)
if args.output_file:
print(f'Wrote HTML to {args.output_file}.', file=sys.stderr)
| #!/usr/bin/env python3
#
# Generates an HTML file for previewing all styles defined in a CSS file
#
# dependencies: cssutils
# USAGE:
# css_preview_generator.py style.css -o preview.html
import html
import io
import sys
import cssutils
image_placeholder = "data:image/svg+xml;charset=UTF-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='150' viewBox='0 0 300 150'%3E%3Crect fill='yellow' width='300' height='150'/%3E%3Ctext fill='rgba(0,0,0,0.5)' x='50%25' y='50%25' text-anchor='middle'%3E300×150%3C/text%3E%3C/svg%3E"
def render(s, out):
# if isinstance(out, io.StringIO):
# terminator = ''
# else:
# terminator = '\n'
print(s, end='', file=out)
def process_css_definitions(chunks, full_selector, out):
if len(chunks):
chunk = chunks.pop(0)
render_open_tag(chunk, out)
process_css_definitions(chunks, full_selector, out)
render_close_tag(chunk, out)
else:
render(full_selector, out)
prefix_map = {
'.': 'class',
'#': 'id'
}
def extract_class_id(defn, extracted_attrs=''):
try:
for prefix in prefix_map.keys():
if prefix in defn:
items = defn.split(prefix)
value = ' '.join(items[1:])
# return a tuple of (tagname, 'class="bla blu"') or (tagname, 'id="abc"')
tag = items[0]
if any(suffix in tag for suffix in prefix_map.keys()):
return extract_class_id(tag, f'{prefix_map[prefix]}="{value}"')
else:
return items[0], f'{extracted_attrs} {prefix_map[prefix]}="{value}"'
except Exception as e:
print(e, file=sys.stderr)
return defn, ''
def render_open_tag(definition, out):
if definition.startswith(('.', '#')):
_, class_or_id = extract_class_id(definition)
render(f'<div {class_or_id}>', out)
else:
if definition == 'a' or definition.startswith(('a.', 'a#')):
tag, class_or_id = extract_class_id(definition)
render(f'''<a {class_or_id} href="#">''', out)
elif definition == 'img' or definition.startswith(('img.','img#')):
render(f'<img src="{image_placeholder}" alt="[image]">', out)
else:
tag, class_or_id = extract_class_id(definition)
if tag.lower() == 'td':
render(f'<table><thead><tr><th>🔶🔷[th]🔷🔶</th></thead><tbody><tr><td {class_or_id}>🔹[td]🔹<br/>', out)
else:
render(f'<{tag} {class_or_id}>', out)
def render_close_tag(definition, out):
if definition.startswith(('.', '#')):
render('</div>', out)
else:
if definition == 'a' or definition.startswith(('a.', 'a#')):
render(f'⚓️ {definition}</a>', out)
else:
tag, _ = extract_class_id(definition)
if tag.lower() == 'td':
render('</td></tr></tbody></table>', out)
else:
render(f'</{tag}>', out)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='CSS Preview Generator')
parser.add_argument('css_file',
help='CSS stylesheet file name')
parser.add_argument('--verbose', '-v',
help='Verbose output',
default=False,
action='store_true')
parser.add_argument('--output-file', '-o',
metavar='output',
help='HTML preview filename')
parser.add_argument('--no-frames', '-nf',
default=False,
action='store_true',
help='Do NOT wrap fixed/absolute elements in iframe')
args = parser.parse_args(sys.argv[1:])
output_file = args.output_file and open(args.output_file, 'w') or sys.stdout
already_seen = []
sheet = cssutils.parseFile(args.css_file)
print('Generating HTML preview. Please wait...', file=sys.stderr)
print(f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS preview: {args.css_file}</title>
<link href="{args.css_file}" rel="stylesheet" type="text/css" />
</head>
<body>
''', file=output_file)
selectors_requiring_iframe = []
# build a list of absolute & fixed rules
if not args.no_frames:
for rule in sheet:
if isinstance(rule, cssutils.css.CSSStyleRule):
position = getattr(rule.style, 'position', None)
if position in ('fixed', 'absolute', 'sticky'):
for single_selector in rule.selectorList: # type: cssutils.css.Selector
selectors_requiring_iframe.append(single_selector.selectorText)
# deduplicate list
selectors_requiring_iframe = list(dict.fromkeys(selectors_requiring_iframe))
for rule in sheet:
if isinstance(rule, cssutils.css.CSSStyleRule):
selectors: cssutils.css.SelectorList = getattr(rule, 'selectorList', [])
full_selectors_text = rule.selectorText
if args.verbose:
print(f'CSS Rule: {full_selectors_text}', file=sys.stderr)
for single_selector in selectors: # type: cssutils.css.Selector
current_selector_text = single_selector.selectorText
if not single_selector or current_selector_text.startswith(('html', 'body')):
continue
# 1. convert '>' to space
# 2. '~' '*' '+' and '[]' (not supported, ignoring them, convert to space, breaks semantics FIXME)
for c in '>*~+':
if c in current_selector_text:
current_selector_text = current_selector_text.replace(c, ' ')
for c in ':[':
if c in current_selector_text:
current_selector_text = current_selector_text.split(c)[0]
if current_selector_text in already_seen:
continue
else:
already_seen.append(current_selector_text)
if ' ' in current_selector_text:
current_selector_text = current_selector_text.replace(' ', ' ')
position = getattr(rule.style, 'position', None)
need_iframe = False
if not args.no_frames:
# if current selector is a child of an absolute/fixed rule then also wrap it in an iframe
matching_abs_parents = [sel for sel in selectors_requiring_iframe if sel in current_selector_text]
need_iframe = position in ('fixed', 'absolute', 'sticky') or len(matching_abs_parents)
need_table = False
if need_iframe:
print(
f'''<iframe style="border:1px dotted #acad9e;" width="400" height="300" srcdoc="{html.escape(f'<html><head><link href="{args.css_file}" rel="stylesheet" type="text/css"/></head><body style="background:#f6f4ee">')}''',
end='', file=output_file)
out = io.StringIO()
else:
out = output_file
if args.verbose:
print(f'\t{current_selector_text}', file=sys.stderr)
process_css_definitions(current_selector_text.split(), full_selectors_text, out)
if need_iframe:
print(html.escape(out.getvalue()), end='', file=output_file)
print('"></iframe><br/>', file=output_file)
print('''
</body>
</html>''', file=output_file)
if args.output_file:
print(f'Wrote HTML to {args.output_file}.', file=sys.stderr)
|
# (C) Datadog, Inc. 2021-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from contextlib import contextmanager
from copy import deepcopy
from datadog_checks.avi_vantage import metrics
from datadog_checks.base import AgentCheck, OpenMetricsBaseCheckV2
from datadog_checks.base.errors import CheckException
from .config_models import ConfigMixin
RESOURCE_METRICS = {
'virtualservice': metrics.VIRTUAL_SERVICE_METRICS,
'pool': metrics.POOL_METRICS,
'controller': metrics.CONTROLLER_METRICS,
'serviceengine': metrics.SERVICE_ENGINE_METRICS,
}
LABELS_REMAPPER = {'type': 'avi_type', 'tenant': 'avi_tenant'}
class AviVantageCheck(OpenMetricsBaseCheckV2, ConfigMixin):
__NAMESPACE__ = "avi_vantage"
def __init__(self, name, init_config, instances):
super(AviVantageCheck, self).__init__(name, init_config, instances)
# Required for storing the auth cookie
self.instance['persist_connections'] = True
self._base_url = None
@property
def base_url(self):
if not self._base_url:
self._base_url = self.config.avi_controller_url.rstrip('/')
return self._base_url
def configure_scrapers(self):
scrapers = {}
for entity in self.config.entities:
if entity not in RESOURCE_METRICS:
raise CheckException(
f"Entity {entity} is not valid. Must be one of {", ".join(RESOURCE_METRICS.keys())}."
)
resource_metrics = RESOURCE_METRICS[entity]
instance_copy = deepcopy(self.instance)
endpoint = self.base_url + "/api/analytics/prometheus-metrics/" + entity
instance_copy['openmetrics_endpoint'] = endpoint
instance_copy['metrics'] = [resource_metrics]
instance_copy['rename_labels'] = LABELS_REMAPPER.copy()
instance_copy['rename_labels']['name'] = entity + "_name"
instance_copy['rename_labels'].update(self.config.rename_labels)
scrapers[endpoint] = self.create_scraper(instance_copy)
self.scrapers.clear()
self.scrapers.update(scrapers)
@contextmanager
def login(self):
self.http._session = None
login_url = self.base_url + "/login"
logout_url = self.base_url + "/logout"
try:
login_resp = self.http.post(
login_url, data={'username': self.config.username, 'password': self.config.password}
)
login_resp.raise_for_status()
except Exception:
self.service_check("can_connect", AgentCheck.CRITICAL, tags=self.config.tags)
raise
else:
self.service_check("can_connect", AgentCheck.OK, tags=self.config.tags)
yield
csrf_token = self.http.session.cookies.get('csrftoken')
if csrf_token:
logout_resp = self.http.post(
logout_url, extra_headers={'X-CSRFToken': csrf_token, 'Referer': self.base_url}
)
logout_resp.raise_for_status()
@AgentCheck.metadata_entrypoint
def collect_avi_version(self):
response = self.http.get(self.base_url + "/api/cluster/version")
response.raise_for_status()
version = response.json()['Version']
self.set_metadata('version', version)
def create_scraper(self, config):
scraper = super(AviVantageCheck, self).create_scraper(config)
scraper.http = self.http
return scraper
def check(self, _):
with self.login():
try:
self.collect_avi_version()
except Exception:
self.log.debug("Unable to fetch Avi version", exc_info=True)
super(AviVantageCheck, self).check(None)
| # (C) Datadog, Inc. 2021-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from contextlib import contextmanager
from copy import deepcopy
from datadog_checks.avi_vantage import metrics
from datadog_checks.base import AgentCheck, OpenMetricsBaseCheckV2
from datadog_checks.base.errors import CheckException
from .config_models import ConfigMixin
RESOURCE_METRICS = {
'virtualservice': metrics.VIRTUAL_SERVICE_METRICS,
'pool': metrics.POOL_METRICS,
'controller': metrics.CONTROLLER_METRICS,
'serviceengine': metrics.SERVICE_ENGINE_METRICS,
}
LABELS_REMAPPER = {'type': 'avi_type', 'tenant': 'avi_tenant'}
class AviVantageCheck(OpenMetricsBaseCheckV2, ConfigMixin):
__NAMESPACE__ = "avi_vantage"
def __init__(self, name, init_config, instances):
super(AviVantageCheck, self).__init__(name, init_config, instances)
# Required for storing the auth cookie
self.instance['persist_connections'] = True
self._base_url = None
@property
def base_url(self):
if not self._base_url:
self._base_url = self.config.avi_controller_url.rstrip('/')
return self._base_url
def configure_scrapers(self):
scrapers = {}
for entity in self.config.entities:
if entity not in RESOURCE_METRICS:
raise CheckException(
f"Entity {entity} is not valid. Must be one of {', '.join(RESOURCE_METRICS.keys())}."
)
resource_metrics = RESOURCE_METRICS[entity]
instance_copy = deepcopy(self.instance)
endpoint = self.base_url + "/api/analytics/prometheus-metrics/" + entity
instance_copy['openmetrics_endpoint'] = endpoint
instance_copy['metrics'] = [resource_metrics]
instance_copy['rename_labels'] = LABELS_REMAPPER.copy()
instance_copy['rename_labels']['name'] = entity + "_name"
instance_copy['rename_labels'].update(self.config.rename_labels)
scrapers[endpoint] = self.create_scraper(instance_copy)
self.scrapers.clear()
self.scrapers.update(scrapers)
@contextmanager
def login(self):
self.http._session = None
login_url = self.base_url + "/login"
logout_url = self.base_url + "/logout"
try:
login_resp = self.http.post(
login_url, data={'username': self.config.username, 'password': self.config.password}
)
login_resp.raise_for_status()
except Exception:
self.service_check("can_connect", AgentCheck.CRITICAL, tags=self.config.tags)
raise
else:
self.service_check("can_connect", AgentCheck.OK, tags=self.config.tags)
yield
csrf_token = self.http.session.cookies.get('csrftoken')
if csrf_token:
logout_resp = self.http.post(
logout_url, extra_headers={'X-CSRFToken': csrf_token, 'Referer': self.base_url}
)
logout_resp.raise_for_status()
@AgentCheck.metadata_entrypoint
def collect_avi_version(self):
response = self.http.get(self.base_url + "/api/cluster/version")
response.raise_for_status()
version = response.json()['Version']
self.set_metadata('version', version)
def create_scraper(self, config):
scraper = super(AviVantageCheck, self).create_scraper(config)
scraper.http = self.http
return scraper
def check(self, _):
with self.login():
try:
self.collect_avi_version()
except Exception:
self.log.debug("Unable to fetch Avi version", exc_info=True)
super(AviVantageCheck, self).check(None)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
: Project - Test speed of different models
: standalone segmentation using torch in-built models - fcn, deeplabv3, lr-aspp
: Author - Xi Mo
: Institute - University of Kansas
: Date - 5/13/2021 last updated 5/15/2021
: Model Reference:
https://pytorch.org/vision/stable/models.html#semantic-segmentation
: HowTo:
0) This script adopts functoins from RGANet codes, can be execuated independently.
Requirments: pytorch >= 1.0.0, python >= 3.6, numpy
create a folder "checkpoint" at the same level of folder "dataset", then download correct
checkpoint ot the created folder, then run this script.
1) To specify parameters, refer to CONFIG and parser for details.
2) You can copy and rename this script to run several different models at a time,
to do this, you must specify correct gpu using '-gpu' parameter (default: 0)
"""
import torch
import time
import argparse
import math
import numpy as np
import torch.nn.functional as ops
from pathlib import Path
from torchvision import transforms
from torchvision.utils import save_image
from torch.utils.data import TensorDataset
parser = argparse.ArgumentParser(description="Arguments for training, validation and testing")
parser.add_argument("-gpu", type = int, default = 0,
help = "Designate GPU # for trainig and testing")
# Accomodation to suction dataset
parser.add_argument("-i", "--image", type = Path,
default = r"dataset/suction-based-grasping-dataset/data/color-input",
help = "Directory to training images")
parser.add_argument("-l", "--label", type = Path,
default = r"dataset/suction-based-grasping-dataset/data/label",
help = "Directory to training annotations")
parser.add_argument("-c", "--checkpoint", type = Path, default = r"checkpoint",
help = "Checkpoint file path specified by users")
CONFIG = {
"MODEL": "lr-aspp", # choose between "fcn", "deeplab", "lr-aspp"
"BACKBONE": "resnet50", # backbone "resnet50", "resnet101" for fcn
# backbone "resnet50", "resnet101", "mobilenet" for "deeplab"
# backbone "mobilenet" for "lr-aspp" (this will ignore backbone
# setting)
"NUM_CLS": 3, # number of classes
"INT_CLS": (255, 0, 128), # raw label intensity levels to differentiate classes
# Testing
"TEST_BATCH": 20, # batchsize for testing
"TEST_TIME": 1, # show runtime stats done running certain number of testing batches
"TEST_WORKERS": 0, # set number of workers to run testing batches
"TEST_PIN": True, # set to True if memory is pinned for testing batches
"TEST_RUNTIME": True, # False to disable runtime test
}
class SuctionDataset(torch.utils.data.Dataset):
def __init__(self, imgDir, labelDir, splitDir=None, mode="test", applyTrans=False, sameTrans=True):
super(SuctionDataset).__init__()
assert len(CONFIG["INT_CLS"]) > 1, "Must be more than 1 class"
assert len(CONFIG["INT_CLS"]) == CONFIG["NUM_CLS"], "Number of class does not match intensity levels"
self.applyTran = applyTrans
self.sameTrans = sameTrans
self.mode = mode
if splitDir and labelDir:
self.img = self.read_split_images(imgDir, splitDir, ".png", 1)
self.imgLen = len(self.img)
assert self.imgLen, "Empty dataset, please check directory"
self.nameList = list(self.img.keys())
self.W, self.H = self.img[self.nameList[0]].size
self.label = self.read_split_images(labelDir, splitDir, ".png", 0)
else:
raise IOError("Must specify training split file and annotation directory")
# get one pair of samples
def __getitem__(self, idx):
imgName = self.nameList[idx]
img, label = self.img[imgName], self.label[imgName]
# necesary transformation
operate = transforms.Compose([transforms.ToTensor(), self._transform_pad_image()])
img = operate(img)
label = self._convert_img_to_uint8_tensor(label)
return img, label
# get length of total smaples
def __len__(self):
return self.imgLen
# read names/directories from text files
@classmethod
def read_image_id(cls, filePath: Path, postFix: str) -> [str]:
assert filePath.is_file(), f"Invalid file path:\n{filePath.absolute()}"
with open(filePath, 'r') as f:
imgNames = f.readlines()
return [] if not imgNames else [ _.strip()+postFix for _ in imgNames]
# read a bunch of images from a list of image paths
@classmethod
def read_image_data(cls, imgList: [Path], colorMode=1) -> {str: Image.Image}:
dump = {}
for imgPath in imgList:
assert imgPath.is_file(), f"Invalid image path: \n{imgPath.absolute()}"
img = Image.open(imgPath)
if not colorMode: img = img.convert('L')
dump[imgPath.stem] = img
return dump
# read images according to split lists
@classmethod
def read_split_images(cls, imgRootDir: Path, filePath: Path, postFix=".png", colorMode=1) -> {str: Path}:
imgList = cls.read_image_id(filePath, postFix)
imgList = [imgRootDir.joinpath(_) for _ in imgList]
return cls.read_image_data(imgList, colorMode)
# PIL label to resized tensor
def _convert_img_to_uint8_tensor(self, label: Image) -> torch.Tensor:
dummy = np.array(label, dtype = np.uint8)
assert dummy.ndim == 2, "Only for grayscale labelling images"
save = []
intLevels = CONFIG["INT_CLS"]
for idx, val in enumerate(intLevels):
save.append(np.where(dummy == val))
for idx, val in enumerate(save):
dummy[val] = idx
dummy = torch.tensor(dummy, dtype = torch.uint8)
dummy = self._transform_pad_image()(dummy)
return dummy
# Helper to select model
def model_paser():
if CONFIG["MODEL"] == "fcn":
if CONFIG["BACKBONE"] == "resnet50":
from torchvision.models.segmentation import fcn_resnet50
model = fcn_resnet50(pretrained=False, progress=True,
aux_loss=False, num_classes=CONFIG["NUM_CLS"])
elif CONFIG["BACKBONE"] == "resnet101":
from torchvision.models.segmentation import fcn_resnet101
model = fcn_resnet101(pretrained=False, progress=True,
aux_loss=False, num_classes=CONFIG["NUM_CLS"])
else:
raise NameError(f"Unsupported backbone \"{CONFIG["BACKBONE"]}\" for FCN.")
elif CONFIG["MODEL"] == "deeplab":
if CONFIG["BACKBONE"] == "resnet50":
from torchvision.models.segmentation import deeplabv3_resnet50
model = deeplabv3_resnet50(pretrained=False, progress=True,
aux_loss=False, num_classes=CONFIG["NUM_CLS"])
elif CONFIG["BACKBONE"] == "resnet101":
from torchvision.models.segmentation import deeplabv3_resnet101
model = deeplabv3_resnet101(pretrained=False, progress=True,
aux_loss=False, num_classes=CONFIG["NUM_CLS"])
elif CONFIG["BACKBONE"] == "mobilenet":
from torchvision.models.segmentation import deeplabv3_mobilenet_v3_large
model = deeplabv3_mobilenet_v3_large(pretrained=False,
progress=True,
aux_loss=False,
num_classes=CONFIG["NUM_CLS"])
else:
raise NameError(f"Unsupported backbone \"{CONFIG["BACKBONE"]}\" for DeepLabv3.")
elif CONFIG["MODEL"] == "lr-aspp":
from torchvision.models.segmentation import lraspp_mobilenet_v3_large
CONFIG["BACKBONE"] = "mobilenet"
model = lraspp_mobilenet_v3_large(pretrained=False, progress=True,
aux_loss=False, num_classes=CONFIG["NUM_CLS"])
else:
raise NameError(f"Unsupported network \"{CONFIG["MODEL"]}\" for now, I'd much appreciate "
f"if you customize more state-of-the-arts architectures.")
return model
if __name__ == '__main__':
args = parser.parse_args()
assert isinstance(args.gpu, int), "invalid numerical format to designate GPU"
if torch.cuda.is_available():
device = torch.device("cuda:" + str(args.gpu))
else:
device = torch.device("cpu")
torch.autograd.set_detect_anomaly(True)
''' Test Only'''
# checkpoint filepath check
if str(args.checkpoint) != "checkpoint":
if not args.checkpoint.is_file():
raise IOError(f"Designated checkpoint file does not exist:\n"
f"{args.checkpoint.resolve()}")
ckptPath = args.checkpoint.resolve()
else:
ckptDir = Path.cwd().joinpath(CONFIG["MODEL"], "checkpoint")
if not ckptDir.is_dir():
raise IOError(f"Default folder 'checkpoint' does not exist:\n{ckptDir.resolve()}")
fileList = sorted(ckptDir.glob("*.pt"), reverse=True,key=lambda item: item.stat().st_ctime)
if len(fileList) == 0:
raise IOError(f"Cannot find any checkpoint files in:\n{ckptDir.resolve()}\n")
else:
ckptPath = fileList[0]
testSplitPath = args.image.parent.joinpath("test-split.txt")
if not testSplitPath.is_file():
raise IOError(f"Test-split file does not exist, please download the dataset first:\n"
f"{trainSplitPath}")
testData = SuctionDataset(args.image, args.label, testSplitPath,
mode="test", applyTrans=False, sameTrans=False)
testSet = torch.utils.data.DataLoader(
dataset = testData,
batch_size = CONFIG["TEST_BATCH"],
shuffle = False,
num_workers = CONFIG["TEST_WORKERS"],
pin_memory = CONFIG["TEST_PIN"],
drop_last = False)
# test
model = model_paser()
checkpoint = torch.load(ckptPath)
model.load_state_dict(checkpoint['model_state_dict'])
model.eval()
model.to(device)
totalBatch = np.ceil(len(testData) / CONFIG["TEST_BATCH"])
# get runtime estimation
if CONFIG["TEST_RUNTIME"]:
with torch.no_grad():
gStartTime = time.time()
for idx, data in enumerate(testSet):
if idx == 0: bStartTime = time.time()
img = data[0].to(device)
labelOut = model(img)["out"][0]
_ = torch.softmax(labelOut, dim=1)
if (idx + 1) % CONFIG["TEST_TIME"] == 0:
bEndTime = time.time()
bRunTime = (bEndTime - bStartTime) * 1e3 / (CONFIG["TEST_TIME"] * CONFIG["TEST_BATCH"])
bStartTime = time.time()
print("batch: %4d/%d, average_runtime (%d batches): %6fms per image"
% (idx + 1, totalBatch, CONFIG["TEST_TIME"], bRunTime))
gEndTime = time.time()
gRunTime = (gEndTime - gStartTime) * 1e3 / (totalBatch * CONFIG["TEST_BATCH"])
print("\n======================= %s Test Done =======================" %(CONFIG["MODEL"]))
print("Average (%d images in total): %6fms\n" % (len(testData), gRunTime))
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
: Project - Test speed of different models
: standalone segmentation using torch in-built models - fcn, deeplabv3, lr-aspp
: Author - Xi Mo
: Institute - University of Kansas
: Date - 5/13/2021 last updated 5/15/2021
: Model Reference:
https://pytorch.org/vision/stable/models.html#semantic-segmentation
: HowTo:
0) This script adopts functoins from RGANet codes, can be execuated independently.
Requirments: pytorch >= 1.0.0, python >= 3.6, numpy
create a folder "checkpoint" at the same level of folder "dataset", then download correct
checkpoint ot the created folder, then run this script.
1) To specify parameters, refer to CONFIG and parser for details.
2) You can copy and rename this script to run several different models at a time,
to do this, you must specify correct gpu using '-gpu' parameter (default: 0)
"""
import torch
import time
import argparse
import math
import numpy as np
import torch.nn.functional as ops
from pathlib import Path
from torchvision import transforms
from torchvision.utils import save_image
from torch.utils.data import TensorDataset
parser = argparse.ArgumentParser(description="Arguments for training, validation and testing")
parser.add_argument("-gpu", type = int, default = 0,
help = "Designate GPU # for trainig and testing")
# Accomodation to suction dataset
parser.add_argument("-i", "--image", type = Path,
default = r"dataset/suction-based-grasping-dataset/data/color-input",
help = "Directory to training images")
parser.add_argument("-l", "--label", type = Path,
default = r"dataset/suction-based-grasping-dataset/data/label",
help = "Directory to training annotations")
parser.add_argument("-c", "--checkpoint", type = Path, default = r"checkpoint",
help = "Checkpoint file path specified by users")
CONFIG = {
"MODEL": "lr-aspp", # choose between "fcn", "deeplab", "lr-aspp"
"BACKBONE": "resnet50", # backbone "resnet50", "resnet101" for fcn
# backbone "resnet50", "resnet101", "mobilenet" for "deeplab"
# backbone "mobilenet" for "lr-aspp" (this will ignore backbone
# setting)
"NUM_CLS": 3, # number of classes
"INT_CLS": (255, 0, 128), # raw label intensity levels to differentiate classes
# Testing
"TEST_BATCH": 20, # batchsize for testing
"TEST_TIME": 1, # show runtime stats done running certain number of testing batches
"TEST_WORKERS": 0, # set number of workers to run testing batches
"TEST_PIN": True, # set to True if memory is pinned for testing batches
"TEST_RUNTIME": True, # False to disable runtime test
}
class SuctionDataset(torch.utils.data.Dataset):
def __init__(self, imgDir, labelDir, splitDir=None, mode="test", applyTrans=False, sameTrans=True):
super(SuctionDataset).__init__()
assert len(CONFIG["INT_CLS"]) > 1, "Must be more than 1 class"
assert len(CONFIG["INT_CLS"]) == CONFIG["NUM_CLS"], "Number of class does not match intensity levels"
self.applyTran = applyTrans
self.sameTrans = sameTrans
self.mode = mode
if splitDir and labelDir:
self.img = self.read_split_images(imgDir, splitDir, ".png", 1)
self.imgLen = len(self.img)
assert self.imgLen, "Empty dataset, please check directory"
self.nameList = list(self.img.keys())
self.W, self.H = self.img[self.nameList[0]].size
self.label = self.read_split_images(labelDir, splitDir, ".png", 0)
else:
raise IOError("Must specify training split file and annotation directory")
# get one pair of samples
def __getitem__(self, idx):
imgName = self.nameList[idx]
img, label = self.img[imgName], self.label[imgName]
# necesary transformation
operate = transforms.Compose([transforms.ToTensor(), self._transform_pad_image()])
img = operate(img)
label = self._convert_img_to_uint8_tensor(label)
return img, label
# get length of total smaples
def __len__(self):
return self.imgLen
# read names/directories from text files
@classmethod
def read_image_id(cls, filePath: Path, postFix: str) -> [str]:
assert filePath.is_file(), f"Invalid file path:\n{filePath.absolute()}"
with open(filePath, 'r') as f:
imgNames = f.readlines()
return [] if not imgNames else [ _.strip()+postFix for _ in imgNames]
# read a bunch of images from a list of image paths
@classmethod
def read_image_data(cls, imgList: [Path], colorMode=1) -> {str: Image.Image}:
dump = {}
for imgPath in imgList:
assert imgPath.is_file(), f"Invalid image path: \n{imgPath.absolute()}"
img = Image.open(imgPath)
if not colorMode: img = img.convert('L')
dump[imgPath.stem] = img
return dump
# read images according to split lists
@classmethod
def read_split_images(cls, imgRootDir: Path, filePath: Path, postFix=".png", colorMode=1) -> {str: Path}:
imgList = cls.read_image_id(filePath, postFix)
imgList = [imgRootDir.joinpath(_) for _ in imgList]
return cls.read_image_data(imgList, colorMode)
# PIL label to resized tensor
def _convert_img_to_uint8_tensor(self, label: Image) -> torch.Tensor:
dummy = np.array(label, dtype = np.uint8)
assert dummy.ndim == 2, "Only for grayscale labelling images"
save = []
intLevels = CONFIG["INT_CLS"]
for idx, val in enumerate(intLevels):
save.append(np.where(dummy == val))
for idx, val in enumerate(save):
dummy[val] = idx
dummy = torch.tensor(dummy, dtype = torch.uint8)
dummy = self._transform_pad_image()(dummy)
return dummy
# Helper to select model
def model_paser():
if CONFIG["MODEL"] == "fcn":
if CONFIG["BACKBONE"] == "resnet50":
from torchvision.models.segmentation import fcn_resnet50
model = fcn_resnet50(pretrained=False, progress=True,
aux_loss=False, num_classes=CONFIG["NUM_CLS"])
elif CONFIG["BACKBONE"] == "resnet101":
from torchvision.models.segmentation import fcn_resnet101
model = fcn_resnet101(pretrained=False, progress=True,
aux_loss=False, num_classes=CONFIG["NUM_CLS"])
else:
raise NameError(f"Unsupported backbone \"{CONFIG['BACKBONE']}\" for FCN.")
elif CONFIG["MODEL"] == "deeplab":
if CONFIG["BACKBONE"] == "resnet50":
from torchvision.models.segmentation import deeplabv3_resnet50
model = deeplabv3_resnet50(pretrained=False, progress=True,
aux_loss=False, num_classes=CONFIG["NUM_CLS"])
elif CONFIG["BACKBONE"] == "resnet101":
from torchvision.models.segmentation import deeplabv3_resnet101
model = deeplabv3_resnet101(pretrained=False, progress=True,
aux_loss=False, num_classes=CONFIG["NUM_CLS"])
elif CONFIG["BACKBONE"] == "mobilenet":
from torchvision.models.segmentation import deeplabv3_mobilenet_v3_large
model = deeplabv3_mobilenet_v3_large(pretrained=False,
progress=True,
aux_loss=False,
num_classes=CONFIG["NUM_CLS"])
else:
raise NameError(f"Unsupported backbone \"{CONFIG['BACKBONE']}\" for DeepLabv3.")
elif CONFIG["MODEL"] == "lr-aspp":
from torchvision.models.segmentation import lraspp_mobilenet_v3_large
CONFIG["BACKBONE"] = "mobilenet"
model = lraspp_mobilenet_v3_large(pretrained=False, progress=True,
aux_loss=False, num_classes=CONFIG["NUM_CLS"])
else:
raise NameError(f"Unsupported network \"{CONFIG['MODEL']}\" for now, I'd much appreciate "
f"if you customize more state-of-the-arts architectures.")
return model
if __name__ == '__main__':
args = parser.parse_args()
assert isinstance(args.gpu, int), "invalid numerical format to designate GPU"
if torch.cuda.is_available():
device = torch.device("cuda:" + str(args.gpu))
else:
device = torch.device("cpu")
torch.autograd.set_detect_anomaly(True)
''' Test Only'''
# checkpoint filepath check
if str(args.checkpoint) != "checkpoint":
if not args.checkpoint.is_file():
raise IOError(f"Designated checkpoint file does not exist:\n"
f"{args.checkpoint.resolve()}")
ckptPath = args.checkpoint.resolve()
else:
ckptDir = Path.cwd().joinpath(CONFIG["MODEL"], "checkpoint")
if not ckptDir.is_dir():
raise IOError(f"Default folder 'checkpoint' does not exist:\n{ckptDir.resolve()}")
fileList = sorted(ckptDir.glob("*.pt"), reverse=True,key=lambda item: item.stat().st_ctime)
if len(fileList) == 0:
raise IOError(f"Cannot find any checkpoint files in:\n{ckptDir.resolve()}\n")
else:
ckptPath = fileList[0]
testSplitPath = args.image.parent.joinpath("test-split.txt")
if not testSplitPath.is_file():
raise IOError(f"Test-split file does not exist, please download the dataset first:\n"
f"{trainSplitPath}")
testData = SuctionDataset(args.image, args.label, testSplitPath,
mode="test", applyTrans=False, sameTrans=False)
testSet = torch.utils.data.DataLoader(
dataset = testData,
batch_size = CONFIG["TEST_BATCH"],
shuffle = False,
num_workers = CONFIG["TEST_WORKERS"],
pin_memory = CONFIG["TEST_PIN"],
drop_last = False)
# test
model = model_paser()
checkpoint = torch.load(ckptPath)
model.load_state_dict(checkpoint['model_state_dict'])
model.eval()
model.to(device)
totalBatch = np.ceil(len(testData) / CONFIG["TEST_BATCH"])
# get runtime estimation
if CONFIG["TEST_RUNTIME"]:
with torch.no_grad():
gStartTime = time.time()
for idx, data in enumerate(testSet):
if idx == 0: bStartTime = time.time()
img = data[0].to(device)
labelOut = model(img)["out"][0]
_ = torch.softmax(labelOut, dim=1)
if (idx + 1) % CONFIG["TEST_TIME"] == 0:
bEndTime = time.time()
bRunTime = (bEndTime - bStartTime) * 1e3 / (CONFIG["TEST_TIME"] * CONFIG["TEST_BATCH"])
bStartTime = time.time()
print("batch: %4d/%d, average_runtime (%d batches): %6fms per image"
% (idx + 1, totalBatch, CONFIG["TEST_TIME"], bRunTime))
gEndTime = time.time()
gRunTime = (gEndTime - gStartTime) * 1e3 / (totalBatch * CONFIG["TEST_BATCH"])
print("\n======================= %s Test Done =======================" %(CONFIG["MODEL"]))
print("Average (%d images in total): %6fms\n" % (len(testData), gRunTime))
|
__author__ = "Fox Cunning"
import configparser
import os
import threading
import time
import tkinter
from typing import Optional, Tuple, List
import pyo
import appJar
import colour
from APU.APU import APU
from debug import log
from editor_settings import EditorSettings
from rom import ROM
# ----------------------------------------------------------------------------------------------------------------------
_NOISE_FREQ_TABLE = [4811.2, 2405.6, 1202.8, 601.4, 300.7, 200.5, 150.4, 120.3,
95.3, 75.8, 50.6, 37.9, 25.3, 18.9, 9.5, 4.7]
_VOLUME_TABLE = [0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75]
class SFXEditor:
# ------------------------------------------------------------------------------------------------------------------
def __init__(self, app: appJar.gui, settings: EditorSettings, rom: ROM, apu: APU, sound_server: pyo.Server):
self.app = app
self.rom = rom
self.settings = settings
# We need to access the Pyo server, and stop music playback before playing a SFX
self.sound_server = sound_server
self.sfx_names: List[str] = []
self._unsaved_changes: bool = False
self._sfx_id = -1
# Values from the four-byte sfx entries table
self._volume_only: bool = False
self._channel: int = 0
self._size: int = 0
self._address: int = 0
# First four bytes from sound data
self._setup_values: bytearray = bytearray()
# The rest of the data
self._sfx_data: bytearray = bytearray()
self.apu: APU = apu
self._play_thread: threading.Thread = threading.Thread()
self._playing: bool = True
# Playback: current position in the data array
self._sfx_pos: int = 0
# Canvas reference and item IDs
self._canvas_sfx: tkinter.Canvas = tkinter.Canvas()
self._volume_line: int = 0
self._timer_line: int = 0
# Detect and fix data size bug
if self.rom.read_word(0x9, 0xA007) == 0x76A8:
self.info("Fixing SFX data size bug.")
data = [0x29, 0x03, 0x0A, 0x0A, 0xAA, 0xB9, 0x6B, 0xA1, 0x9D, 0xA8, 0x76, 0xC8, 0xB9, 0x6B, 0xA1, 0x9D,
0x9B, 0x76, 0xC8, 0xB9, 0x6B, 0xA1, 0x9D, 0x98, 0x76, 0xC8, 0xB9, 0x6B, 0xA1, 0x9D, 0x99, 0x76,
0xC8, 0xBD, 0x98, 0x76, 0x85, 0xF0, 0xBD, 0x99, 0x76, 0x85, 0xF1, 0xA0, 0x00, 0xB1, 0xF0, 0x9D,
0x00, 0x40, 0xC8, 0xB1, 0xF0, 0x9D, 0x01, 0x40, 0xC8, 0xB1, 0xF0, 0x9D, 0x02, 0x40, 0xC8, 0xB1,
0xF0, 0x9D, 0x03, 0x40, 0xC8, 0x98, 0x9D, 0x9A, 0x76, 0x60]
self.rom.write_bytes(0x9, 0xA006, bytearray(data))
# ------------------------------------------------------------------------------------------------------------------
def error(self, message: str):
log(2, f"{self.__class__.__name__}", message)
# ------------------------------------------------------------------------------------------------------------------
def warning(self, message: str):
log(3, f"{self.__class__.__name__}", message)
# ------------------------------------------------------------------------------------------------------------------
def info(self, message: str):
log(4, f"{self.__class__.__name__}", message)
# ------------------------------------------------------------------------------------------------------------------
def close_window(self) -> bool:
self._unsaved_changes = False
self.app.emptySubWindow("SFX_Editor")
self._volume_line = 0
self._timer_line = 0
if self._play_thread.is_alive():
self._size = 0
self._play_thread.join(500)
if self._play_thread.is_alive():
self.warning("Could not stop audio playback thread!")
# self.app.destroySubWindow("SFX_Editor")
self.app.hideSubWindow("SFX_Editor", useStopFunction=False)
return True
# ------------------------------------------------------------------------------------------------------------------
def show_window(self, sfx_id: int) -> None:
"""
Parameters
----------
sfx_id: int
Index of the sound effect to edit
"""
self._sfx_id = sfx_id
# Check if window already exists
try:
self.app.openSubWindow("SFX_Editor")
self.close_window()
generator = self.app.subWindow("SFX_Editor")
except appJar.appjar.ItemLookupError:
self._volume_line = 0
self._timer_line = 0
generator = self.app.subWindow("SFX_Editor", size=[600, 460], padding=[2, 2], title="Sound Effect Editor",
resizable=False, modal=False, blocking=False,
bg=colour.DARK_ORANGE, fg=colour.WHITE, stopFunction=self.close_window)
with generator:
with self.app.frame("XE_Frame_Buttons", padding=[4, 2], sticky="NEW", row=0, column=0, colspan=2):
self.app.button("XE_Apply", self._sfx_input, image="res/floppy.gif", bg=colour.LIGHT_ORANGE,
row=0, column=1)
self.app.button("XE_Reload", self._sfx_input, image="res/reload.gif", bg=colour.LIGHT_ORANGE,
row=0, column=2)
self.app.button("XE_Close", self._sfx_input, image="res/close.gif", bg=colour.LIGHT_ORANGE,
row=0, column=3)
self.app.label("XE_Label_SFX_Name", "Name:", sticky="WE", row=0, column=4, font=11)
self.app.entry("XE_SFX_Name", f"{self.sfx_names[sfx_id]}", bg=colour.MEDIUM_ORANGE, fg=colour.WHITE,
row=0, column=5, width=20, font=12)
self.app.button("XE_Play_Stop", self._sfx_input, image="res/play.gif", bg=colour.LIGHT_ORANGE,
row=0, column=6)
with self.app.frame("XE_Frame_Setup", padding=[2, 2], sticky="NW", row=1, column=0):
self.app.label("XE_Label_Channel_0", "Channel", sticky="W",
row=0, column=0, font=11)
self.app.button("XE_Channel_0", self._sfx_input, image="res/square_0.gif", bg=colour.LIGHT_ORANGE,
row=0, column=1)
self.app.button("XE_Channel_1", self._sfx_input, image="res/square_1.gif", bg=colour.DARK_ORANGE,
row=0, column=2)
self.app.button("XE_Channel_2", self._sfx_input, image="res/triangle_wave.gif", bg=colour.DARK_ORANGE,
row=0, column=3)
self.app.button("XE_Channel_3", self._sfx_input, image="res/noise_wave.gif", bg=colour.DARK_ORANGE,
row=0, column=4)
self.app.label("XE_Label_Channel_1", "Setup values:", sticky="SEW", row=1, column=0, colspan=5, font=11)
with self.app.frameStack("XE_Stack_Channel", sticky="NW", row=2, column=0, colspan=5):
# Square channels setup panel ----------------------------------------------------------------------
with self.app.frame("XE_Frame_Square_Setup", padding=[2, 1],
bg=colour.DARK_ORANGE, fg=colour.WHITE):
self.app.label("XE_Label_S0", "Duty Cycle", sticky="E", row=0, column=0, font=10)
self.app.optionBox("XE_Duty_Cycle", ["12.5%", "25%", "50%", "75%"], width=12, sticky="W",
row=0, column=1, font=9, change=self._sfx_input)
self.app.label("XE_Pulse_Label_LC_Flag", "Length Ctr Halt", sticky="E",
row=1, column=0, font=10)
self.app.checkBox("XE_Pulse_LC_Flag", True, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=1, column=1)
self.app.label("XE_Pulse_Label_CV_Flag", "Constant Volume", sticky="E",
row=2, column=0, font=10)
self.app.checkBox("XE_Pulse_CV_Flag", True, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=2, column=1)
self.app.label("XE_Pulse_Label_0", "Volume: 00", sticky="SE", row=3, column=0, font=10)
self.app.scale("XE_Pulse_Volume", direction="horizontal", range=[0, 15], value=0, increment=1,
sticky="W", show=False, bg=colour.DARK_ORANGE,
row=3, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Pulse_Volume"))
self.app.label("XE_Label_Sweep_Enabled", "Enable Sweep", sticky="E",
row=4, column=0, font=10)
self.app.checkBox("XE_Sweep_Enable", False, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=4, column=1)
self.app.label("XE_Pulse_Label_1", "Sweep Period: 00", sticky="SE", row=5, column=0, font=10)
self.app.scale("XE_Sweep_Period", direction="horizontal", range=[0, 7], value=0, increment=1,
sticky="W", show=False, bg=colour.DARK_ORANGE,
row=5, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Sweep_Period"))
self.app.label("XE_Label_Sweep_Negate", "Negative Sweep", sticky="E",
row=6, column=0, font=10)
self.app.checkBox("XE_Sweep_Negate", False, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=6, column=1)
self.app.label("XE_Pulse_Label_2", "Shift Count: 00", sticky="SE", row=7, column=0, font=10)
self.app.scale("XE_Sweep_Shift", direction="horizontal", range=[0, 7], value=0, increment=1,
sticky="W", show=False, bg=colour.DARK_ORANGE,
row=7, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Sweep_Shift"))
self.app.label("XE_Pulse_Label_3", "Timer Value", sticky="E", row=8, column=0, font=10)
self.app.entry("XE_Pulse_Timer", 0, change=self._sfx_input, width=6, sticky="W",
kind="numeric", limit=5,
row=8, column=1, font=9, bg=colour.MEDIUM_ORANGE, fg=colour.WHITE)
self.app.label("XE_Pulse_Freq", "Frequency: 0.000 Hz", sticky="WE",
row=9, column=0, colspan=2, font=10, fg=colour.LIGHT_LIME)
self.app.label("XE_Pulse_Label_4", "Length Ctr Load: 00", sticky="SE",
row=10, column=0, font=10)
self.app.scale("XE_Pulse_Length_Load", direction="horizontal", range=[0, 31], value=0,
increment=1, sticky="W", show=False, bg=colour.DARK_ORANGE,
row=10, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Pulse_Length_Load"))
# Triangle channel setup panel ---------------------------------------------------------------------
with self.app.frame("XE_Frame_Triangle_Setup", padding=[2, 2],
bg=colour.DARK_ORANGE, fg=colour.WHITE):
self.app.label("XE_Triangle_Label_Control_Flag", "Control Flag", sticky="E",
row=0, column=0, font=10)
self.app.checkBox("XE_Triangle_Control_Flag", name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=0, column=1)
self.app.label("XE_Triangle_Label_0", "Linear Ctr Load", sticky="NE", row=1, column=0, font=10)
self.app.entry("XE_Linear_Load", 0, change=self._sfx_input, width=6, sticky="NW",
kind="numeric", limit=5,
row=1, column=1, font=9, bg=colour.MEDIUM_ORANGE, fg=colour.WHITE)
self.app.label("XE_Triangle_Label_1", "Timer Value", sticky="NE", row=2, column=0, font=10)
self.app.entry("XE_Triangle_Timer", 0, change=self._sfx_input, width=6, sticky="NW",
kind="numeric", limit=5,
row=2, column=1, font=9, bg=colour.MEDIUM_ORANGE, fg=colour.WHITE)
self.app.label("XE_Triangle_Freq", "Frequency: 0 Hz", sticky="NEW",
row=3, column=0, colspan=2, font=10, fg=colour.LIGHT_LIME)
self.app.label("XE_Triangle_Label_2", "Length Ctr Reload", sticky="NE",
row=4, column=0, font=10)
self.app.entry("XE_Triangle_Length_Load", 0, change=self._sfx_input, width=6, sticky="NW",
kind="numeric", limit=5,
row=4, column=1, font=9, bg=colour.MEDIUM_ORANGE, fg=colour.WHITE)
# Noise channel setup panel ------------------------------------------------------------------------
with self.app.frame("XE_Frame_Noise_Setup", padding=[2, 2],
bg=colour.DARK_ORANGE, fg=colour.WHITE):
self.app.label("XE_Noise_Label_LC_Flag", "LC Halt", sticky="E", row=0, column=0, font=10)
self.app.checkBox("XE_Noise_LC_Flag", False, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=0, column=1)
self.app.label("XE_Noise_Label_CV_Flag", "Constant Volume", sticky="E",
row=1, column=0, font=10)
self.app.checkBox("XE_Noise_CV_Flag", True, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=1, column=1)
self.app.label("XE_Noise_Label_0", "Volume: 00", sticky="NE", row=2, column=0, font=10)
self.app.scale("XE_Noise_Volume", direction="horizontal", range=[0, 15], value=0, increment=1,
sticky="NW", show=False, bg=colour.DARK_ORANGE,
row=2, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Noise_Volume"))
self.app.label("XE_Label_Noise_Loop", "Loop Noise", sticky="E", row=3, column=0, font=10)
self.app.checkBox("XE_Noise_Loop", True, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=3, column=1)
self.app.label("XE_Noise_Label_1", "Noise Period: 00", sticky="NE", row=4, column=0, font=10)
self.app.scale("XE_Noise_Period", direction="horizontal", range=[0, 15], value=0, increment=1,
sticky="NW", show=False, bg=colour.DARK_ORANGE,
row=4, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Noise_Period"))
self.app.label("XE_Noise_Freq", "Frequency: 0.00 Hz", sticky="WE",
row=5, column=0, colspan=2, font=10, fg=colour.LIGHT_LIME)
self.app.label("XE_Noise_Label_2", "Length Ctr Load: 00", sticky="NE",
row=6, column=0, font=10)
self.app.scale("XE_Noise_Load", direction="horizontal", range=[0, 31], value=0, increment=1,
sticky="NW", show=False, bg=colour.DARK_ORANGE,
row=6, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Noise_Load"))
# Data entry selection -------------------------------------------------------------------------------------
with self.app.frame("XE_Frame_Data", sticky="NW", padding=[2, 2], row=1, column=1):
with self.app.frame("XE_Frame_Data_Left", sticky="W", padding=[2, 2], row=0, column=0):
self.app.label("XE_Data_Label_0", "Data Size", sticky="W", row=0, column=0, font=10)
self.app.entry("XE_Data_Size", 1, kind="numeric", limit=4, width=4, sticky="W",
row=0, column=1, font=9, submit=self._sfx_input)
self.app.listBox("XE_Data_List", [], width=12, height=10, sticky="W", change=self._sfx_input,
bg=colour.MEDIUM_ORANGE, fg=colour.WHITE,
row=1, column=0, colspan=2, multi=False, group=True, font=9)
# Data controls ----------------------------------------------------------------------------------------
with self.app.frame("XE_Frame_Data_Right", sticky="WE", padding=[2, 2], row=0, column=1):
# --- Register 0
self.app.label("XE_Data_Label_1", "Duty", sticky="NEW", row=0, column=0, font=10)
self.app.optionBox("XE_Data_Duty", ["12.5%", "25%", "50%", "75%"], change=self._data_input,
row=0, column=1, width=8, sticky="NW", font=9)
self.app.checkBox("XE_Data_LC_Flag", True, name="Length Ctr Halt", sticky="NW",
selectcolor=colour.MEDIUM_ORANGE, change=self._data_input,
row=1, column=0, colspan=2, font=10)
self.app.checkBox("XE_Data_CV_Flag", True, name="Constant Volume", sticky="NW",
selectcolor=colour.MEDIUM_ORANGE, change=self._data_input,
row=2, column=0, colspan=2, font=10)
self.app.label("XE_Data_Label_2", "Volume: 00", sticky="NE", row=3, column=0, font=10)
self.app.scale("XE_Data_Reg_0", direction="horizontal", range=[0, 15], value=0, increment=1,
sticky="NW", show=False, bg=colour.DARK_ORANGE,
row=3, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._data_input("XE_Data_Reg_0"))
# --- Register 2
self.app.checkBox("XE_Data_Noise_Mode", False, text="Loop Noise", sticky="NW",
selectcolor=colour.MEDIUM_ORANGE, change=self._data_input,
row=4, column=0, colspan=2, font=10)
self.app.label("XE_Data_Label_3", "Period Value", sticky="NE", row=5, column=0, font=10)
self.app.entry("XE_Data_Reg_2", 0, change=self._data_input, width=6, sticky="NW",
kind="numeric", limit=5,
row=5, column=1, font=9, bg=colour.MEDIUM_ORANGE, fg=colour.WHITE)
self.app.label("XE_Data_Freq", "Frequency: 0 Hz", sticky="NEW",
row=6, column=0, colspan=2, font=10, fg=colour.LIGHT_LIME)
# Volume / Timer envelope Graph
with self.app.frame("XE_Frame_Data_Bottom", sticky="W", padding=[1, 1], row=1, column=0, colspan=2):
self.app.canvas("XE_Canvas_SFX", map=None, width=320, height=200, bg=colour.BLACK,
row=0, column=0)
self._canvas_sfx = self.app.getCanvasWidget("XE_Canvas_SFX")
self.read_sfx_data()
self._sfx_info()
# Draw graph
self._draw_sfx_graph()
self.app.showSubWindow("SFX_Editor")
# ------------------------------------------------------------------------------------------------------------------
def _get_selection_index(self, widget: str) -> int:
"""
Returns
-------
int:
The index of the currently selected option from an OptionBox widget
"""
value = "(nothing)"
try:
value = self.app.getOptionBox(widget)
box = self.app.getOptionBoxWidget(widget)
return box.options.index(value)
except ValueError as error:
self.error(f"ERROR: Getting selection index for '{value}' in '{widget}': {error}.")
return 0
# ------------------------------------------------------------------------------------------------------------------
def _data_input(self, widget: str) -> None:
# Get the selection index and calculate the position in the array depending on whether we use the first byte
# only or both bytes
selection = self.app.getListBoxPos("XE_Data_List")
if len(selection) < 1:
pos = 0
index = 0
else:
index = selection[0]
pos = selection[0] * (1 if self._volume_only else 2)
# Process event according to which widget has generated it
if widget == "XE_Data_Duty": # ------------------------------------------------------------------------------
value = self._get_selection_index(widget)
reg_value = self._sfx_data[pos] & 0x3F
self._sfx_data[pos] = reg_value | (value << 6)
self._unsaved_changes = True
self._update_data_list(index)
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Data_LC_Flag": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
# For the Triangle channel, this is the Control flag instead
if self._channel == 2:
reg_value = self._sfx_data[pos] & 0x7F
self._sfx_data[pos] = reg_value | (0x80 if flag else 0)
else:
reg_value = self._sfx_data[pos] & 0xDF
self._sfx_data[pos] = reg_value | (0x20 if flag else 0)
# There is no Length Counter Load control to enable/disable: the second byte only controls the period
self._unsaved_changes = True
self._update_data_list(index)
elif widget == "XE_Data_CV_Flag": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
reg_value = self._sfx_data[pos] & 0xEF
self._sfx_data[pos] = reg_value | (0x10 if flag else 0)
# Switch between volume and envelope labels
volume = self._sfx_data[pos] & 0x0F
if (self._sfx_data[pos] & 0x10) > 0:
# Constant Volume
self.app.setLabel("XE_Data_Label_2", f" Volume: {volume:02}")
else:
# Envelope Enabled
self.app.setLabel("XE_Data_Label_2", f"Envelope: {volume:02}")
self._unsaved_changes = True
self._update_data_list(index)
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Data_Reg_0": # --------------------------------------------------------------------------
value = self.app.getScale(widget)
reg_value = self._sfx_data[pos] & 0xF0
self._sfx_data[pos] = reg_value | value
if (self._sfx_data[pos] & 0x10) > 0:
# Constant Volume
self.app.setLabel("XE_Data_Label_2", f" Volume: {value:02}")
else:
# Envelope Enabled
self.app.setLabel("XE_Data_Label_2", f"Envelope: {value:02}")
self._unsaved_changes = True
self._update_data_list(index)
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Data_Noise_Mode": # ----------------------------------------------------------------------
pos += 1
flag = self.app.getCheckBox(widget)
reg_value = self._sfx_data[pos] & 0x7F
self._sfx_data[pos] = reg_value | (0x80 if flag else 0)
# Update frequency
period = self._sfx_data[pos] & 0x0F
freq = round(_NOISE_FREQ_TABLE[period] / (1 if flag else 93), 2)
self.app.setLabel("XE_Data_Freq", f"Frequency: {freq} Hz")
self._unsaved_changes = True
self._update_data_list(index)
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Data_Reg_2": # --------------------------------------------------------------------------
pos += 1
value = self.app.getEntry(widget)
if value is None:
return
# The Noise channel treats the period value differently
if self._channel == 3:
period = int(value) & 0x0F
# Mode flag
flag = (self._sfx_data[pos] & 0x80) > 0
reg_value = self._sfx_data[pos] & 0xF0
self._sfx_data[pos] = reg_value | period
# Update frequency display
freq = round(_NOISE_FREQ_TABLE[period] / (1 if flag else 93), 2)
# For all other channels, we need the whole timer value in order to display the correct frequency
else:
self._sfx_data[pos] = int(value) & 0xFF
timer = ((self._setup_values[3] & 0x07) << 8) | self._sfx_data[pos]
freq = round(1789773 / ((timer + 1) << (5 if self._channel == 2 else 4)), 2)
self.app.setLabel("XE_Data_Freq", f"Frequency: {freq} Hz")
self._unsaved_changes = True
self._update_data_list(index)
self._draw_sfx_graph(draw_volume=False)
else: # ------------------------------------------------------------------------------------------------------
self.info(f"Unimplemented input from setup widget: '{widget}'.")
# ------------------------------------------------------------------------------------------------------------------
def _sfx_input(self, widget: str) -> None:
if widget == "XE_Apply": # ----------------------------------------------------------------------------------
if self.save_sfx_data():
self.app.setStatusbar("Sound effects saved")
self._unsaved_changes = False
if self.settings.get("close sub-window after saving"):
self.app.hideSubWindow("SFX_Editor", useStopFunction=True)
elif widget == "XE_Close": # ----------------------------------------------------------------------------------
if self._unsaved_changes:
if not self.app.yesNoBox("SFX Editor", "Are you sure you want to close this window?\n" +
"Any unsaved changes will be lost.", "SFX_Editor"):
return
self._unsaved_changes = False
self.app.hideSubWindow("SFX_Editor", useStopFunction=True)
elif widget == "XE_Play_Stop": # ------------------------------------------------------------------------------
if self._play_thread.is_alive():
self.stop_playback()
else:
self.app.setButtonImage("XE_Play_Stop", "res/stop.gif")
self.app.setButtonTooltip("XE_Play_Stop", "Stop playback")
self._play_sfx()
elif widget[:11] == "XE_Channel_": # --------------------------------------------------------------------------
new_channel = int(widget[-1], 10)
if new_channel != self._channel:
self._channel = new_channel
self._sfx_info()
selection = self.app.getListBoxPos("XE_Data_List")
if len(selection) > 0:
self._event_info(selection[0])
self._draw_sfx_graph()
self._unsaved_changes = True
elif widget == "XE_Duty_Cycle": # --------------------------------------------------------------------------
value = self._get_selection_index(widget)
if value == self._setup_values[0] >> 6:
# No change
return
register_value = self._setup_values[0] & 0x3F
self._setup_values[0] = (value << 6) | register_value
self._draw_sfx_graph(draw_period=False)
self._unsaved_changes = True
elif widget == "XE_Pulse_LC_Flag": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
if flag == (self._setup_values[0] & 0x20) > 0:
# No change
return
register_value = self._setup_values[0] & 0xDF
self._setup_values[0] = register_value | (0x20 if flag else 0)
if flag:
self.app.disableScale("XE_Pulse_Length_Load")
else:
self.app.enableScale("XE_Pulse_Length_Load")
# This only affects the duration of the sound, so no need to redraw the graph
self._unsaved_changes = True
elif widget == "XE_Pulse_CV_Flag": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
if flag == ((self._setup_values[0] & 0x10) > 0):
# No change
return
register_value = self._setup_values[0] & 0xEF
self._setup_values[0] = register_value | (0x10 if flag else 0)
value = self._setup_values[0] & 0x0F
self.app.setLabel("XE_Pulse_Label_0", f"{"Volume" if flag else "Env. Period"}: {value:02}")
self._draw_sfx_graph(draw_period=False)
self._unsaved_changes = True
elif widget == "XE_Pulse_Volume": # --------------------------------------------------------------------------
value = self.app.getScale(widget) & 0x0F
register_value = self._setup_values[0] & 0xF0 # The other bits in the same register
flag = (self._setup_values[0] & 0x10) > 0
self.app.setLabel("XE_Pulse_Label_0", f"{"Volume" if flag else "Env. Period"}: {value:02}")
self._setup_values[0] = register_value | value
self._unsaved_changes = True
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Sweep_Enable": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
if flag == ((self._setup_values[1] & 0x80) > 0):
return
register_value = self._setup_values[1] & 0x7F
self._setup_values[1] = register_value | (0x80 if flag else 0)
if flag:
self.app.enableScale("XE_Sweep_Period")
self.app.enableScale("XE_Sweep_Shift")
else:
self.app.disableScale("XE_Sweep_Period")
self.app.disableScale("XE_Sweep_Shift")
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Sweep_Period": # --------------------------------------------------------------------------
value = self.app.getScale(widget)
if value == (self._setup_values[1] & 0x70) >> 4:
return
register_value = self._setup_values[1] & 0x8F
self._setup_values = register_value | (value << 4)
self.app.setLabel("XE_Pulse_Label_1", f"Sweep Period: {value:02}")
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Sweep_Negate": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
if flag == ((self._setup_values[1] & 0x1) > 0):
return
register_value = self._setup_values[1] & 0xF7
self._setup_values[1] = register_value | (0x08 if flag else 0)
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Sweep_Shift": # --------------------------------------------------------------------------
value = self.app.getScale(widget)
if value == self._setup_values[1] & 0x07:
return
register_value = self._setup_values[1] & 0xF8
self._setup_values[1] = register_value | value
self.app.setLabel("XE_Pulse_Label_2", f"Shift Count: {value:02}")
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Pulse_Timer": # --------------------------------------------------------------------------
try:
value = int(self.app.getEntry(widget)) & 0x7FF
self._setup_values[2] = value & 0x0FF
self._setup_values[3] = (self._setup_values[3] & 0xF8) | (value >> 8)
freq: float = 1789773 / ((value + 1) << 4)
self.app.setLabel("XE_Pulse_Freq", f"Frequency: {round(freq, 2)} Hz")
except TypeError:
return
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Pulse_Length_Load": # ----------------------------------------------------------------------
value = self.app.getScale(widget)
register_value = self._setup_values[3] & 0xF8
self.app.setLabel("XE_Pulse_Label_4", f"Length Ctr Load: {value:02}")
self._setup_values[3] = register_value | (value << 3)
self._unsaved_changes = True
elif widget == "XE_Triangle_Control_Flag": # ------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
if flag == ((self._setup_values[0] & 0x80) > 0):
return
register_value = self._setup_values[0] & 0x7F
self._setup_values[0] = register_value | (0x80 if flag else 0)
self._unsaved_changes = True
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Linear_Load": # --------------------------------------------------------------------------
value = self.app.getEntry(widget)
if value is None or int(value) == self._setup_values[0] & 0x7F:
return
register_value = self._setup_values[0] & 0x80
self._setup_values[0] = register_value | int(value)
self._unsaved_changes = True
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Triangle_Timer": # ----------------------------------------------------------------------
value = self.app.getEntry(widget)
if value is None:
return
timer_low = int(value) & 0x0FF
timer_high = int(value) >> 8
self._setup_values[2] = timer_low
self._setup_values[3] = (self._setup_values[3] & 0xF8) | timer_high
freq = 1789773 / (int(value + 1) << 5)
self.app.setLabel("XE_Triangle_Freq", f"Frequency: {round(freq, 2)} Hz")
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Noise_LC_Flag": # --------------------------------------------------------------------------
value = 0x20 if self.app.getCheckBox(widget) else 0x00
if value == 0:
self.app.enableScale("XE_Noise_Load")
else:
self.app.disableScale("XE_Noise_Load")
self._setup_values[0] = (self._setup_values[0] & 0x1F) | value
self._unsaved_changes = True
elif widget == "XE_Noise_CV_Flag": # --------------------------------------------------------------------------
value = 0x10 if self.app.getCheckBox(widget) else 0x00
volume = self._setup_values[0] & 0x0F
if value == 0:
# If the Constant Volume flag is clear, than this is the envelope period instead of volume
self.app.setLabel("XE_Noise_Label_0", f"Env. Period: {volume:02}")
else:
self.app.setLabel("XE_Noise_Label_0", f"Volume: {volume:02}")
self._setup_values[0] = (self._setup_values[0] & 0x2F) | value
self._unsaved_changes = True
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Noise_Volume": # --------------------------------------------------------------------------
value: int = self.app.getScale(widget)
# If the Constant Volume flag is clear, than this is the envelope period instead of volume
if (self._setup_values[0] & 0x10) > 0:
self.app.setLabel("XE_Noise_Label_0", f"Volume: {value:02}")
else:
self.app.setLabel("XE_Noise_Label_0", f"Env. Period: {value:02}")
self._setup_values[0] = (self._setup_values[0] & 0xF0) | (value & 0x0F)
self._unsaved_changes = True
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Noise_Loop":
value = 0x80 if self.app.getCheckBox(widget) else 0x00
self._setup_values[2] = (self._setup_values[2] & 0x0F) | value
self._unsaved_changes = True
elif widget == "XE_Noise_Period": # --------------------------------------------------------------------------
value: int = self.app.getScale(widget)
freq = _NOISE_FREQ_TABLE[value]
self.app.setLabel("XE_Noise_Label_1", f"Period: {value:02}")
self.app.setLabel("XE_Noise_Freq", f"Frequency: {freq} Hz")
self._setup_values[2] = (self._setup_values[0] & 0xF0) | value
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Noise_Load": # --------------------------------------------------------------------------
value = self.app.getScale(widget)
self.app.setLabel("XE_Noise_Label_2", f"Length Ctr Load: {value:02}")
self._setup_values[3] = value << 3
self._unsaved_changes = True
elif widget == "XE_Data_Size": # ------------------------------------------------------------------------------
value = self.app.getEntry(widget)
if value is None or int(value) == self._size or value < 1 or value > 64:
return
if value < self._size:
if not self.app.yesNoBox("SFX Editor", "Are you sure you want to reduce sound data size?\n" +
"The extra events will be permanently deleted.", "SFX_Editor"):
return
# Decrease size
byte_size = int(value) * (1 if self._volume_only else 2)
self._sfx_data = self._sfx_data[0:byte_size]
else:
# Increase size, create copy of last event to fill the rest
new_events = self._sfx_data[-1:] if self._volume_only else self._sfx_data[-2:]
diff = int(value) - self._size
self._sfx_data = self._sfx_data + (new_events * diff)
self._size = int(value)
self._update_data_list()
self._draw_sfx_graph()
elif widget == "XE_Data_List": # ------------------------------------------------------------------------------
selection = self.app.getListBoxPos(widget)
if len(selection) > 0:
self._event_info(selection[0])
else:
self.info(f"Unimplemented input from setup widget: '{widget}'.")
# ------------------------------------------------------------------------------------------------------------------
def get_sfx_info(self, sfx_id: int) -> Tuple[int, int, bool, int]:
"""
Returns
-------
Tuple[int, bool]
A tuple (channel, address, volume only flag, number of events).
"""
ptr = 0xA16B + (sfx_id << 2)
# Read sfx entry from table in ROM buffer
value = self.rom.read_byte(0x9, ptr)
volume_only = (value & 0x10) > 0
channel = value & 0x3
size = self.rom.read_byte(0x9, ptr + 1)
address = self.rom.read_word(0x9, ptr + 2)
return channel, address, volume_only, size
# ------------------------------------------------------------------------------------------------------------------
def read_sfx_names(self) -> List[str]:
# By default, everything is unnamed
self.sfx_names = []
for s in range(52):
self.sfx_names.append(f"(No Name)")
# If any definition filename matches the currently loaded ROM filename, then use that one
file_name = os.path.basename(self.rom.path).rsplit('.')[0] + "_audio.ini"
if os.path.exists(os.path.dirname(self.rom.path) + '/' + file_name):
file_name = os.path.dirname(self.rom.path) + '/' + file_name
elif os.path.exists("audio.ini"):
file_name = "audio.ini"
parser = configparser.ConfigParser()
parser.read(file_name)
if parser.has_section("SFX"):
section = parser["SFX"]
for s in range(52):
name = section.get(f"{s}", "")
if name != "":
self.sfx_names[s] = name
return self.sfx_names
# ------------------------------------------------------------------------------------------------------------------
def read_sfx_data(self, sfx_id: Optional[int] = None) -> Tuple[bool, int, int]:
"""
Reads an entry from the sfx table in bank 9.
Parameters
----------
sfx_id: Optional[int]
Index of the entry to read; re-reads currently loaded sfx if not specified.
Returns
-------
Tuple[bool, int, int]
A tuple (volume only flag, channel number, data address).
"""
if sfx_id is None:
sfx_id = self._sfx_id
if 52 < sfx_id < 0:
self.warning(f"Invalid Sound Effect Id requested: {sfx_id}.")
return False, 0, 0
address = 0xA16B + (sfx_id << 2)
# Read sfx entry from table in ROM buffer
value = self.rom.read_byte(0x9, address)
self._volume_only = (value & 0x10) > 0
self._channel = value & 0x3
self._size = self.rom.read_byte(0x9, address + 1)
self._address = self.rom.read_word(0x9, address + 2)
# Read sound data
address = self._address
# First four bytes are the "setup" values used to initialise the registers
self._setup_values = self.rom.read_bytes(0x9, address, 4)
self._sfx_data.clear()
address += 4
for _ in range(self._size):
self._sfx_data.append(self.rom.read_byte(0x9, address))
address += 1
if not self._volume_only:
self._sfx_data.append(self.rom.read_byte(0x9, address))
address += 1
return self._volume_only, self._channel, self._address
# ------------------------------------------------------------------------------------------------------------------
def save_sfx_data(self) -> bool:
"""
Returns
-------
bool
True if save successful, False otherwise (e.g. no room for event data)
"""
name = self.app.getEntry("XE_SFX_Name")
if name is None or len(name) < 1:
name = "(No Name)"
else:
# Save name in INI file
# If any definition filename matches the currently loaded ROM filename, then use that one
file_name = os.path.basename(self.rom.path).rsplit('.')[0] + "_audio.ini"
if os.path.exists(os.path.dirname(self.rom.path) + '/' + file_name):
file_name = os.path.dirname(self.rom.path) + '/' + file_name
elif os.path.exists("audio.ini"):
file_name = "audio.ini"
parser = configparser.ConfigParser()
parser.read(file_name)
if not parser.has_section("SFX"):
parser.add_section("SFX")
parser.set("SFX", f"{self._sfx_id}", name)
# Update SFX tab list
self.app.setOptionBox("ST_Option_SFX", self._sfx_id, value=f"0x{self._sfx_id:02X} {name}", callFunction=False)
# Map of valid ROM areas in Bank 9 where we can save our data
# Tuple: start address, size
memory = [(0xA23B, 2590), (0xA050, 176)]
# One buffer per memory area, we will only copy them to ROM if all data can be allocated successfully
buffers = [bytearray(), bytearray()]
# We will also recreate the table locally before copying it to ROM
table = bytearray()
# Go through all the sound effects and re-allocate them
for i in range(52):
if i == self._sfx_id:
# Save our new data
size = self._size
table.append(self._channel | (0x80 if self._volume_only else 0))
data = self._setup_values + self._sfx_data
else:
# Read data from ROM
ptr = 0xA16B + (i << 2)
size = self.rom.read_byte(0x9, ptr + 1)
channel = self.rom.read_byte(0x9, ptr)
table.append(channel)
old_address = self.rom.read_word(0x9, ptr + 2)
# 4 bytes of "setup values", then either 1 byte per event (volume only flag) or 2 bytes per event
data = self.rom.read_bytes(0x9, old_address, 4 + (size * (1 if (channel & 0x10) > 0 else 2)))
# Write number of events in the table
table.append(size)
# Get data size in bytes
data_size = len(data)
# See if it fits in the first area
if data_size <= memory[0][1]:
mem = 0
elif data_size <= memory[1][1]:
mem = 1
else:
self.app.errorBox("SFX Editor", f"Error saving sound effect #{i}: out of memory in ROM bank 9.",
"SFX_Editor")
return False
new_address = memory[mem][0]
table.append(new_address & 0x00FF) # Low byte
table.append(new_address >> 8) # High byte
# Advance the first available address and reduce size for the selected area
memory[mem] = new_address + data_size, memory[mem][1] - data_size
# Save data to our local buffer
buffers[mem] += data
# Memory successfully allocated, we can write both table and data to ROM
self.rom.write_bytes(0x9, 0xA16B, table)
self.rom.write_bytes(0x9, 0xA23B, buffers[0])
if len(buffers[1]) > 0:
self.rom.write_bytes(0x9, 0xA050, buffers[1])
return True
# ------------------------------------------------------------------------------------------------------------------
def _sfx_info(self) -> None:
if self._channel == 3: # Noise channel
self.app.selectFrame("XE_Stack_Channel", 2)
elif self._channel == 2: # Triangle channel
self.app.selectFrame("XE_Stack_Channel", 1)
else: # Pulse channels
self.app.selectFrame("XE_Stack_Channel", 0)
# Highlight current channel
for c in range(4):
self.app.setButtonBg(f"XE_Channel_{c}", colour.LIGHT_ORANGE if self._channel == c else colour.DARK_ORANGE)
# Set widgets according to sfx setup data
if self._channel == 3: # Noise
lc_flag = (self._setup_values[0] & 0x20) > 0
cv_flag = (self._setup_values[0] & 0x10) > 0
volume = self._setup_values[0] & 0x0F
loop = (self._setup_values[2] & 0x80) > 0
period = self._setup_values[2] & 0x0F
length_ctr_load = self._setup_values[3] >> 3
self.app.setCheckBox("XE_Noise_LC_Flag", lc_flag, callFunction=False)
self.app.setCheckBox("XE_Noise_CV_Flag", cv_flag, callFunction=False)
self.app.setScale("XE_Noise_Volume", volume, callFunction=False)
# If the Constant Volume flag is clear, than this is the envelope period instead of volume
if (self._setup_values[0] & 0x10) > 0:
self.app.setLabel("XE_Noise_Label_0", f"Volume: {volume:02}")
else:
self.app.setLabel("XE_Noise_Label_0", f"Env. Period: {volume:02}")
self.app.setCheckBox("XE_Noise_Loop", loop, callFunction=False)
self.app.setScale("XE_Noise_Period", period)
freq = _NOISE_FREQ_TABLE[period]
self.app.setLabel("XE_Noise_Label_1", f"Period: {period:02}")
self.app.setLabel("XE_Noise_Freq", f"Frequency: {freq} Hz")
self.app.setScale("XE_Noise_Load", length_ctr_load)
self.app.setLabel("XE_Noise_Label_2", f"Length Ctr Load: {length_ctr_load:02}")
if lc_flag:
self.app.disableScale("XE_Noise_Load")
else:
self.app.enableScale("XE_Noise_Load")
elif self._channel == 2: # Triangle
control_flag: bool = (self._setup_values[0] & 0x80) > 0
linear_ctr_reload: int = self._setup_values[0] & 0x7F
timer_value: int = self._setup_values[2] | ((self._setup_values[3] & 0x3) << 8)
frequency = 1789773 / ((timer_value + 1) << 5)
length_ctr_load: int = (self._setup_values[3] & 0xF8) >> 3
self.app.setCheckBox("XE_Triangle_Control_Flag", control_flag, callFunction=False)
self.app.clearEntry("XE_Linear_Load", callFunction=False, setFocus=False)
self.app.setEntry("XE_Linear_Load", linear_ctr_reload, callFunction=False)
self.app.clearEntry("XE_Triangle_Timer", callFunction=False, setFocus=False)
self.app.setEntry("XE_Triangle_Timer", timer_value, callFunction=False)
self.app.setLabel("XE_Triangle_Freq", f"Frequency: {round(frequency, 2)} Hz")
self.app.clearEntry("XE_Triangle_Length_Load", callFunction=False, setFocus=False)
self.app.setEntry("XE_Triangle_Length_Load", length_ctr_load, callFunction=False)
else: # Pulse
duty = (self._setup_values[0] >> 6)
lc_flag = (self._setup_values[0] & 0x20) > 0
cv_flag = (self._setup_values[0] & 0x10) > 0
volume = self._setup_values[0] & 0x0F
sweep_enable = (self._setup_values[1] & 0x80) > 0
sweep_period = (self._setup_values[1] & 0x70) >> 4
sweep_negate = (self._setup_values[1] & 0x08) > 0
sweep_shift = self._setup_values[1] & 0x3
timer = self._setup_values[2] | ((self._setup_values[3] & 0x03) << 8)
length_ctr_load = self._setup_values[3] >> 3
self.app.setOptionBox("XE_Duty_Cycle", duty, callFunction=False)
self.app.setCheckBox("XE_Pulse_LC_Flag", lc_flag, callFunction=False)
self.app.setCheckBox("XE_Pulse_CV_Flag", cv_flag, callFunction=False)
self.app.setScale("XE_Pulse_Volume", volume)
self.app.setLabel("XE_Pulse_Label_0", f"{"Volume" if cv_flag else "Env. Period"}: {volume:02}")
self.app.setCheckBox("XE_Sweep_Enable", sweep_enable, callFunction=False)
self.app.setLabel("XE_Pulse_Label_1", f"Sweep Period: {sweep_period:02}")
self.app.setScale("XE_Sweep_Period", sweep_period, callFunction=False)
self.app.setCheckBox("XE_Sweep_Negate", sweep_negate, callFunction=False)
self.app.setLabel("XE_Pulse_Label_2", f"Shift Count: {sweep_shift:02}")
self.app.setScale("XE_Sweep_Shift", sweep_shift, callFunction=False)
if sweep_enable:
self.app.enableScale("XE_Sweep_Period")
self.app.enableScale("XE_Sweep_Shift")
else:
self.app.disableScale("XE_Sweep_Period")
self.app.disableScale("XE_Sweep_Shift")
self.app.clearEntry("XE_Pulse_Timer", callFunction=False, setFocus=False)
self.app.setEntry("XE_Pulse_Timer", timer, callFunction=False)
freq: float = 1789773 / ((timer + 1) << 4)
self.app.setLabel("XE_Pulse_Freq", f"Frequency: {round(freq, 2)} Hz")
self.app.setScale("XE_Pulse_Length_Load", length_ctr_load)
self.app.setLabel("XE_Pulse_Label_4", f"Length Ctr Load: {length_ctr_load:02}")
if lc_flag:
self.app.disableScale("XE_Pulse_Length_Load")
else:
self.app.enableScale("XE_Pulse_Length_Load")
self._update_data_list()
# ------------------------------------------------------------------------------------------------------------------
def _update_data_list(self, event_index: Optional[int] = None) -> None:
# Only update one item if event_index is specified
if event_index is not None:
v = event_index * (1 if self._volume_only else 2)
text = f"#{event_index:02}: ${self._sfx_data[v]:02X}"
if not self._volume_only:
text += f", ${self._sfx_data[v + 1]:02X}"
self.app.setListItemAtPos("XE_Data_List", event_index, text)
self.app.selectListItemAtPos("XE_Data_List", event_index, callFunction=False)
return
# Otherwise list all data entries
self.app.clearEntry("XE_Data_Size", callFunction=False, setFocus=False)
self.app.setEntry("XE_Data_Size", self._size, callFunction=False)
self.app.clearListBox("XE_Data_List")
index = 0
v = 0
while index < self._size:
text = f"#{index:02}: ${self._sfx_data[v]:02X}"
v += 1
if not self._volume_only:
text += f", ${self._sfx_data[v]:02X}"
v += 1
self.app.addListItems("XE_Data_List", [text], False)
index += 1
# Select top entry
self.app.selectListItemAtPos("XE_Data_List", 0, callFunction=True)
# ------------------------------------------------------------------------------------------------------------------
def _event_info(self, event_id: int) -> None:
# --- Register 0
index = event_id * (1 if self._volume_only else 2)
# --- Reg 0, bits 7, 6
# Only Pulse channels have this
if self._channel < 2:
duty = self._sfx_data[index] >> 6
self.app.enableOptionBox("XE_Data_Duty")
self.app.setOptionBox("XE_Data_Duty", duty, callFunction=False)
else:
self.app.disableOptionBox("XE_Data_Duty")
# --- Reg 0, bits 5, 4
if self._channel != 2:
lc_flag = (self._sfx_data[index] & 0x20) > 0
self.app.setCheckBoxText("XE_Data_LC_Flag", "Length Ctr Halt")
self.app.setCheckBox("XE_Data_LC_Flag", lc_flag, callFunction=False)
cv_flag = (self._sfx_data[index] & 0x10) > 0
self.app.enableCheckBox("XE_Data_CV_Flag")
self.app.setCheckBox("XE_Data_CV_Flag", cv_flag, callFunction=False)
# --- Reg 0, bit 7
# For the Triangle channel, use the LC Flag widget for the Control Flag instead, then disable the CV widget
else:
control_flag = (self._sfx_data[index] & 0x80) > 0
self.app.setCheckBoxText("XE_Data_LC_Flag", "Control Flag")
self.app.setCheckBox("XE_Data_LC_Flag", control_flag, callFunction=False)
self.app.disableCheckBox("XE_Data_CV_Flag")
# --- Reg 0, bits 3-0
if self._channel != 2:
volume = self._sfx_data[index] & 0x0F
if (self._sfx_data[index] & 0x10) > 0:
# Constant Volume
self.app.setLabel("XE_Data_Label_2", f"Volume: {volume:02}")
else:
# Envelope Enabled
self.app.setLabel("XE_Data_Label_2", f"Env. Period: {volume:02}")
self.app.setScaleRange("XE_Data_Reg_0", 0, 15)
self.app.setScale("XE_Data_Reg_0", volume, callFunction=False)
# --- Reg 0, bit 7-0
# For the Triangle channel, this is the linear counter reload value
else:
linear_ctr_reload = self._sfx_data[index] & 0x7F
self.app.setLabel("XE_Data_Label_2", f"Linear Ctr: {linear_ctr_reload:02}")
self.app.setScaleRange("XE_Data_Reg_0", 0, 0x7F)
self.app.setScale("XE_Data_Reg_0", linear_ctr_reload, callFunction=False)
# --- Register 2
index += 1
self.app.clearEntry("XE_Data_Reg_2", callFunction=False, setFocus=False)
# --- Reg 2, bit 7 and 3-0
# The Noise channel uses the period value differently
if self._channel == 3:
noise_mode = (self._sfx_data[index] & 0x80) > 0
self.app.enableCheckBox("XE_Data_Noise_Mode")
self.app.setCheckBox("XE_Data_Noise_Mode", noise_mode, callFunction=False)
period = self._sfx_data[index] & 0x0F
freq = round(_NOISE_FREQ_TABLE[period] / (1 if noise_mode else 93), 2)
# --- Reg 2, bits 7-0
else:
period = self._sfx_data[index]
timer_high = self._setup_values[3] & 0x03
timer = (timer_high << 8) | period
freq = round(1789773 / ((timer + 1) << (5 if self._channel == 2 else 4)), 2)
self.app.disableCheckBox("XE_Data_Noise_Mode")
self.app.setEntry("XE_Data_Reg_2", period, callFunction=False)
self.app.setLabel("XE_Data_Freq", f"Frequency: {freq} Hz")
# ------------------------------------------------------------------------------------------------------------------
def _play_sfx(self) -> None:
if not self.sound_server.getIsBooted():
self.sound_server.boot()
if not self.sound_server.getIsStarted():
self.sound_server.start()
# Mute channels
self.apu.reset()
self.apu.play()
# Set initial values
if self._channel == 0:
apu_channel = self.apu.pulse_0
elif self._channel == 1:
apu_channel = self.apu.pulse_1
elif self._channel == 2:
apu_channel = self.apu.triangle
else:
apu_channel = self.apu.noise
apu_channel.write_reg0(self._setup_values[0])
apu_channel.write_reg1(self._setup_values[1])
apu_channel.write_reg2(self._setup_values[2])
apu_channel.write_reg3(self._setup_values[3])
self._sfx_pos = 0
# self.info(f"Playing {self._size} events ({len(self._sfx_data)} bytes)")
self._play_thread = threading.Thread(target=self._data_step, args=(apu_channel,))
self._play_thread.start()
# ------------------------------------------------------------------------------------------------------------------
def _data_step(self, apu_channel) -> None:
frame_interval = .0166
size = len(self._sfx_data)
while self._sfx_pos < size:
start_time = time.time()
# print(f"Step: {self._sfx_pos}")
# self.info(f"REG0:${self._sfx_data[self._sfx_pos]}")
apu_channel.write_reg0(self._sfx_data[self._sfx_pos])
self._sfx_pos += 1
if not self._volume_only:
# self.info(f"REG2:${self._sfx_data[self._sfx_pos]}")
apu_channel.write_reg2(self._sfx_data[self._sfx_pos])
self._sfx_pos += 1
interval = frame_interval - (time.time() - start_time)
if interval > 0:
time.sleep(interval)
# print("Stopping playback...")
self.stop_playback()
# ------------------------------------------------------------------------------------------------------------------
def stop_playback(self) -> None:
self.apu.stop()
try:
self.app.setButtonImage("XE_Play_Stop", "res/play.gif")
self.app.setButtonTooltip("XE_Play_Stop", "Start playback")
except appJar.appjar.ItemLookupError:
return
# ------------------------------------------------------------------------------------------------------------------
def _draw_sfx_graph(self, draw_volume: bool = True, draw_period: bool = True) -> None:
# This will be similar to the code used in the Instrument Editor
width = self._canvas_sfx.winfo_reqwidth()
base_height = self._canvas_sfx.winfo_reqheight() - 10
vertical_step = base_height >> 5
line_width = 1
# Calculate the width of each segment in our line
length = width // (self._size + 1)
if length < 8:
length = 8
line_width = 1 # Make the line thinner if it gets too crowded
trail = length >> 2
# One for each duty value, we consider 25% and 75% to be the same, for simplicity
hat = [trail >> 1, trail, length >> 1, trail]
"""
hat
___
| |
_____| |_____
trail tail tail = trail
_______________
length
"""
volume_points = []
timer_points = []
timer = 0
x = 0 # Start from the left of the canvas
# TODO Use envelope values instead of volume if enabled
# TODO Sweep unit values for timer if enabled
# Setup values first
if draw_volume:
if self._channel < 2:
duty = self._setup_values[0] >> 6
else:
duty = 3
volume = self._setup_values[0] & 0x0F
# Starting points
volume_points.append((x, base_height))
# Move right a bit
volume_points.append((x + trail, base_height))
# Go up, depending on volume
y = base_height - (volume * vertical_step)
volume_points.append((x + trail, y))
# Draw the "hat", depending on duty
volume_points.append((x + trail + hat[duty], y))
# Go back down
volume_points.append((x + trail + hat[duty], base_height))
# Move to the end of this line
volume_points.append((x + length, base_height))
if draw_period:
if self._channel == 3:
timer = self._setup_values[2] & 0x0F
y = (timer << 3) + 10
else:
timer = self._setup_values[2]
y = ((timer + 1) >> 2) + 10
timer_points.append((x, y))
# Next line will start here
x = x + length
# Now for the entries...
d = 0 # Position in the array, since entries can be either one- or two-byte long
for i in range(self._size):
if draw_volume:
duty = 3 if self._channel > 1 else self._sfx_data[d] >> 6
volume = self._sfx_data[d] & 0x0F
volume_points.append((x, base_height))
volume_points.append((x + trail, base_height))
y = base_height - (volume * vertical_step)
volume_points.append((x + trail, y))
volume_points.append((x + trail + hat[duty], y))
volume_points.append((x + trail + hat[duty], base_height))
volume_points.append((x + length, base_height))
d += 1
x = x + length
if self._volume_only:
# Use sweep unit value, if enabled
# ...otherwise, use the previous timer value
if draw_period:
if self._channel == 3: # The noise channel has a different use of its period value
y = (timer << 2) + 10
else:
y = ((timer + 1) >> 2) + 10
timer_points.append((x, y))
else:
if draw_period:
if self._channel == 3:
timer = self._sfx_data[d] & 0x0F
y = (timer << 3) + 10
else:
timer = self._sfx_data[d]
y = ((timer + 1) >> 2) + 10
timer_points.append((x, y))
# If only updating volume, this value is simply ignored
d += 1
# Make sure we cover the whole graph area horizontally
if draw_volume:
last = volume_points[-1]
volume_points[-1] = (320, last[1])
flat = [a for x in volume_points for a in x]
if self._volume_line > 0:
self._canvas_sfx.coords(self._volume_line, *flat)
self._canvas_sfx.itemconfigure(self._volume_line, width=line_width)
else:
self._volume_line = self._canvas_sfx.create_line(*flat, width=line_width, fill=colour.LIGHT_ORANGE)
if draw_period:
last = timer_points[-1]
timer_points[-1] = (320, last[1])
flat = [a for x in timer_points for a in x]
if self._timer_line > 0:
self._canvas_sfx.coords(self._timer_line, *flat)
self._canvas_sfx.itemconfigure(self._timer_line, width=line_width)
else:
self._timer_line = self._canvas_sfx.create_line(*flat, width=line_width, fill=colour.LIGHT_GREEN)
# Make sure the timer line is always drawn on top of the volume/duty bars
if not draw_period and self._timer_line > 0:
self._canvas_sfx.tag_raise(self._timer_line)
| __author__ = "Fox Cunning"
import configparser
import os
import threading
import time
import tkinter
from typing import Optional, Tuple, List
import pyo
import appJar
import colour
from APU.APU import APU
from debug import log
from editor_settings import EditorSettings
from rom import ROM
# ----------------------------------------------------------------------------------------------------------------------
_NOISE_FREQ_TABLE = [4811.2, 2405.6, 1202.8, 601.4, 300.7, 200.5, 150.4, 120.3,
95.3, 75.8, 50.6, 37.9, 25.3, 18.9, 9.5, 4.7]
_VOLUME_TABLE = [0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75]
class SFXEditor:
# ------------------------------------------------------------------------------------------------------------------
def __init__(self, app: appJar.gui, settings: EditorSettings, rom: ROM, apu: APU, sound_server: pyo.Server):
self.app = app
self.rom = rom
self.settings = settings
# We need to access the Pyo server, and stop music playback before playing a SFX
self.sound_server = sound_server
self.sfx_names: List[str] = []
self._unsaved_changes: bool = False
self._sfx_id = -1
# Values from the four-byte sfx entries table
self._volume_only: bool = False
self._channel: int = 0
self._size: int = 0
self._address: int = 0
# First four bytes from sound data
self._setup_values: bytearray = bytearray()
# The rest of the data
self._sfx_data: bytearray = bytearray()
self.apu: APU = apu
self._play_thread: threading.Thread = threading.Thread()
self._playing: bool = True
# Playback: current position in the data array
self._sfx_pos: int = 0
# Canvas reference and item IDs
self._canvas_sfx: tkinter.Canvas = tkinter.Canvas()
self._volume_line: int = 0
self._timer_line: int = 0
# Detect and fix data size bug
if self.rom.read_word(0x9, 0xA007) == 0x76A8:
self.info("Fixing SFX data size bug.")
data = [0x29, 0x03, 0x0A, 0x0A, 0xAA, 0xB9, 0x6B, 0xA1, 0x9D, 0xA8, 0x76, 0xC8, 0xB9, 0x6B, 0xA1, 0x9D,
0x9B, 0x76, 0xC8, 0xB9, 0x6B, 0xA1, 0x9D, 0x98, 0x76, 0xC8, 0xB9, 0x6B, 0xA1, 0x9D, 0x99, 0x76,
0xC8, 0xBD, 0x98, 0x76, 0x85, 0xF0, 0xBD, 0x99, 0x76, 0x85, 0xF1, 0xA0, 0x00, 0xB1, 0xF0, 0x9D,
0x00, 0x40, 0xC8, 0xB1, 0xF0, 0x9D, 0x01, 0x40, 0xC8, 0xB1, 0xF0, 0x9D, 0x02, 0x40, 0xC8, 0xB1,
0xF0, 0x9D, 0x03, 0x40, 0xC8, 0x98, 0x9D, 0x9A, 0x76, 0x60]
self.rom.write_bytes(0x9, 0xA006, bytearray(data))
# ------------------------------------------------------------------------------------------------------------------
def error(self, message: str):
log(2, f"{self.__class__.__name__}", message)
# ------------------------------------------------------------------------------------------------------------------
def warning(self, message: str):
log(3, f"{self.__class__.__name__}", message)
# ------------------------------------------------------------------------------------------------------------------
def info(self, message: str):
log(4, f"{self.__class__.__name__}", message)
# ------------------------------------------------------------------------------------------------------------------
def close_window(self) -> bool:
self._unsaved_changes = False
self.app.emptySubWindow("SFX_Editor")
self._volume_line = 0
self._timer_line = 0
if self._play_thread.is_alive():
self._size = 0
self._play_thread.join(500)
if self._play_thread.is_alive():
self.warning("Could not stop audio playback thread!")
# self.app.destroySubWindow("SFX_Editor")
self.app.hideSubWindow("SFX_Editor", useStopFunction=False)
return True
# ------------------------------------------------------------------------------------------------------------------
def show_window(self, sfx_id: int) -> None:
"""
Parameters
----------
sfx_id: int
Index of the sound effect to edit
"""
self._sfx_id = sfx_id
# Check if window already exists
try:
self.app.openSubWindow("SFX_Editor")
self.close_window()
generator = self.app.subWindow("SFX_Editor")
except appJar.appjar.ItemLookupError:
self._volume_line = 0
self._timer_line = 0
generator = self.app.subWindow("SFX_Editor", size=[600, 460], padding=[2, 2], title="Sound Effect Editor",
resizable=False, modal=False, blocking=False,
bg=colour.DARK_ORANGE, fg=colour.WHITE, stopFunction=self.close_window)
with generator:
with self.app.frame("XE_Frame_Buttons", padding=[4, 2], sticky="NEW", row=0, column=0, colspan=2):
self.app.button("XE_Apply", self._sfx_input, image="res/floppy.gif", bg=colour.LIGHT_ORANGE,
row=0, column=1)
self.app.button("XE_Reload", self._sfx_input, image="res/reload.gif", bg=colour.LIGHT_ORANGE,
row=0, column=2)
self.app.button("XE_Close", self._sfx_input, image="res/close.gif", bg=colour.LIGHT_ORANGE,
row=0, column=3)
self.app.label("XE_Label_SFX_Name", "Name:", sticky="WE", row=0, column=4, font=11)
self.app.entry("XE_SFX_Name", f"{self.sfx_names[sfx_id]}", bg=colour.MEDIUM_ORANGE, fg=colour.WHITE,
row=0, column=5, width=20, font=12)
self.app.button("XE_Play_Stop", self._sfx_input, image="res/play.gif", bg=colour.LIGHT_ORANGE,
row=0, column=6)
with self.app.frame("XE_Frame_Setup", padding=[2, 2], sticky="NW", row=1, column=0):
self.app.label("XE_Label_Channel_0", "Channel", sticky="W",
row=0, column=0, font=11)
self.app.button("XE_Channel_0", self._sfx_input, image="res/square_0.gif", bg=colour.LIGHT_ORANGE,
row=0, column=1)
self.app.button("XE_Channel_1", self._sfx_input, image="res/square_1.gif", bg=colour.DARK_ORANGE,
row=0, column=2)
self.app.button("XE_Channel_2", self._sfx_input, image="res/triangle_wave.gif", bg=colour.DARK_ORANGE,
row=0, column=3)
self.app.button("XE_Channel_3", self._sfx_input, image="res/noise_wave.gif", bg=colour.DARK_ORANGE,
row=0, column=4)
self.app.label("XE_Label_Channel_1", "Setup values:", sticky="SEW", row=1, column=0, colspan=5, font=11)
with self.app.frameStack("XE_Stack_Channel", sticky="NW", row=2, column=0, colspan=5):
# Square channels setup panel ----------------------------------------------------------------------
with self.app.frame("XE_Frame_Square_Setup", padding=[2, 1],
bg=colour.DARK_ORANGE, fg=colour.WHITE):
self.app.label("XE_Label_S0", "Duty Cycle", sticky="E", row=0, column=0, font=10)
self.app.optionBox("XE_Duty_Cycle", ["12.5%", "25%", "50%", "75%"], width=12, sticky="W",
row=0, column=1, font=9, change=self._sfx_input)
self.app.label("XE_Pulse_Label_LC_Flag", "Length Ctr Halt", sticky="E",
row=1, column=0, font=10)
self.app.checkBox("XE_Pulse_LC_Flag", True, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=1, column=1)
self.app.label("XE_Pulse_Label_CV_Flag", "Constant Volume", sticky="E",
row=2, column=0, font=10)
self.app.checkBox("XE_Pulse_CV_Flag", True, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=2, column=1)
self.app.label("XE_Pulse_Label_0", "Volume: 00", sticky="SE", row=3, column=0, font=10)
self.app.scale("XE_Pulse_Volume", direction="horizontal", range=[0, 15], value=0, increment=1,
sticky="W", show=False, bg=colour.DARK_ORANGE,
row=3, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Pulse_Volume"))
self.app.label("XE_Label_Sweep_Enabled", "Enable Sweep", sticky="E",
row=4, column=0, font=10)
self.app.checkBox("XE_Sweep_Enable", False, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=4, column=1)
self.app.label("XE_Pulse_Label_1", "Sweep Period: 00", sticky="SE", row=5, column=0, font=10)
self.app.scale("XE_Sweep_Period", direction="horizontal", range=[0, 7], value=0, increment=1,
sticky="W", show=False, bg=colour.DARK_ORANGE,
row=5, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Sweep_Period"))
self.app.label("XE_Label_Sweep_Negate", "Negative Sweep", sticky="E",
row=6, column=0, font=10)
self.app.checkBox("XE_Sweep_Negate", False, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=6, column=1)
self.app.label("XE_Pulse_Label_2", "Shift Count: 00", sticky="SE", row=7, column=0, font=10)
self.app.scale("XE_Sweep_Shift", direction="horizontal", range=[0, 7], value=0, increment=1,
sticky="W", show=False, bg=colour.DARK_ORANGE,
row=7, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Sweep_Shift"))
self.app.label("XE_Pulse_Label_3", "Timer Value", sticky="E", row=8, column=0, font=10)
self.app.entry("XE_Pulse_Timer", 0, change=self._sfx_input, width=6, sticky="W",
kind="numeric", limit=5,
row=8, column=1, font=9, bg=colour.MEDIUM_ORANGE, fg=colour.WHITE)
self.app.label("XE_Pulse_Freq", "Frequency: 0.000 Hz", sticky="WE",
row=9, column=0, colspan=2, font=10, fg=colour.LIGHT_LIME)
self.app.label("XE_Pulse_Label_4", "Length Ctr Load: 00", sticky="SE",
row=10, column=0, font=10)
self.app.scale("XE_Pulse_Length_Load", direction="horizontal", range=[0, 31], value=0,
increment=1, sticky="W", show=False, bg=colour.DARK_ORANGE,
row=10, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Pulse_Length_Load"))
# Triangle channel setup panel ---------------------------------------------------------------------
with self.app.frame("XE_Frame_Triangle_Setup", padding=[2, 2],
bg=colour.DARK_ORANGE, fg=colour.WHITE):
self.app.label("XE_Triangle_Label_Control_Flag", "Control Flag", sticky="E",
row=0, column=0, font=10)
self.app.checkBox("XE_Triangle_Control_Flag", name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=0, column=1)
self.app.label("XE_Triangle_Label_0", "Linear Ctr Load", sticky="NE", row=1, column=0, font=10)
self.app.entry("XE_Linear_Load", 0, change=self._sfx_input, width=6, sticky="NW",
kind="numeric", limit=5,
row=1, column=1, font=9, bg=colour.MEDIUM_ORANGE, fg=colour.WHITE)
self.app.label("XE_Triangle_Label_1", "Timer Value", sticky="NE", row=2, column=0, font=10)
self.app.entry("XE_Triangle_Timer", 0, change=self._sfx_input, width=6, sticky="NW",
kind="numeric", limit=5,
row=2, column=1, font=9, bg=colour.MEDIUM_ORANGE, fg=colour.WHITE)
self.app.label("XE_Triangle_Freq", "Frequency: 0 Hz", sticky="NEW",
row=3, column=0, colspan=2, font=10, fg=colour.LIGHT_LIME)
self.app.label("XE_Triangle_Label_2", "Length Ctr Reload", sticky="NE",
row=4, column=0, font=10)
self.app.entry("XE_Triangle_Length_Load", 0, change=self._sfx_input, width=6, sticky="NW",
kind="numeric", limit=5,
row=4, column=1, font=9, bg=colour.MEDIUM_ORANGE, fg=colour.WHITE)
# Noise channel setup panel ------------------------------------------------------------------------
with self.app.frame("XE_Frame_Noise_Setup", padding=[2, 2],
bg=colour.DARK_ORANGE, fg=colour.WHITE):
self.app.label("XE_Noise_Label_LC_Flag", "LC Halt", sticky="E", row=0, column=0, font=10)
self.app.checkBox("XE_Noise_LC_Flag", False, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=0, column=1)
self.app.label("XE_Noise_Label_CV_Flag", "Constant Volume", sticky="E",
row=1, column=0, font=10)
self.app.checkBox("XE_Noise_CV_Flag", True, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=1, column=1)
self.app.label("XE_Noise_Label_0", "Volume: 00", sticky="NE", row=2, column=0, font=10)
self.app.scale("XE_Noise_Volume", direction="horizontal", range=[0, 15], value=0, increment=1,
sticky="NW", show=False, bg=colour.DARK_ORANGE,
row=2, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Noise_Volume"))
self.app.label("XE_Label_Noise_Loop", "Loop Noise", sticky="E", row=3, column=0, font=10)
self.app.checkBox("XE_Noise_Loop", True, name="", sticky="W",
selectcolor=colour.MEDIUM_ORANGE, change=self._sfx_input,
row=3, column=1)
self.app.label("XE_Noise_Label_1", "Noise Period: 00", sticky="NE", row=4, column=0, font=10)
self.app.scale("XE_Noise_Period", direction="horizontal", range=[0, 15], value=0, increment=1,
sticky="NW", show=False, bg=colour.DARK_ORANGE,
row=4, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Noise_Period"))
self.app.label("XE_Noise_Freq", "Frequency: 0.00 Hz", sticky="WE",
row=5, column=0, colspan=2, font=10, fg=colour.LIGHT_LIME)
self.app.label("XE_Noise_Label_2", "Length Ctr Load: 00", sticky="NE",
row=6, column=0, font=10)
self.app.scale("XE_Noise_Load", direction="horizontal", range=[0, 31], value=0, increment=1,
sticky="NW", show=False, bg=colour.DARK_ORANGE,
row=6, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._sfx_input("XE_Noise_Load"))
# Data entry selection -------------------------------------------------------------------------------------
with self.app.frame("XE_Frame_Data", sticky="NW", padding=[2, 2], row=1, column=1):
with self.app.frame("XE_Frame_Data_Left", sticky="W", padding=[2, 2], row=0, column=0):
self.app.label("XE_Data_Label_0", "Data Size", sticky="W", row=0, column=0, font=10)
self.app.entry("XE_Data_Size", 1, kind="numeric", limit=4, width=4, sticky="W",
row=0, column=1, font=9, submit=self._sfx_input)
self.app.listBox("XE_Data_List", [], width=12, height=10, sticky="W", change=self._sfx_input,
bg=colour.MEDIUM_ORANGE, fg=colour.WHITE,
row=1, column=0, colspan=2, multi=False, group=True, font=9)
# Data controls ----------------------------------------------------------------------------------------
with self.app.frame("XE_Frame_Data_Right", sticky="WE", padding=[2, 2], row=0, column=1):
# --- Register 0
self.app.label("XE_Data_Label_1", "Duty", sticky="NEW", row=0, column=0, font=10)
self.app.optionBox("XE_Data_Duty", ["12.5%", "25%", "50%", "75%"], change=self._data_input,
row=0, column=1, width=8, sticky="NW", font=9)
self.app.checkBox("XE_Data_LC_Flag", True, name="Length Ctr Halt", sticky="NW",
selectcolor=colour.MEDIUM_ORANGE, change=self._data_input,
row=1, column=0, colspan=2, font=10)
self.app.checkBox("XE_Data_CV_Flag", True, name="Constant Volume", sticky="NW",
selectcolor=colour.MEDIUM_ORANGE, change=self._data_input,
row=2, column=0, colspan=2, font=10)
self.app.label("XE_Data_Label_2", "Volume: 00", sticky="NE", row=3, column=0, font=10)
self.app.scale("XE_Data_Reg_0", direction="horizontal", range=[0, 15], value=0, increment=1,
sticky="NW", show=False, bg=colour.DARK_ORANGE,
row=3, column=1, font=9).bind("<ButtonRelease-1>", lambda _e:
self._data_input("XE_Data_Reg_0"))
# --- Register 2
self.app.checkBox("XE_Data_Noise_Mode", False, text="Loop Noise", sticky="NW",
selectcolor=colour.MEDIUM_ORANGE, change=self._data_input,
row=4, column=0, colspan=2, font=10)
self.app.label("XE_Data_Label_3", "Period Value", sticky="NE", row=5, column=0, font=10)
self.app.entry("XE_Data_Reg_2", 0, change=self._data_input, width=6, sticky="NW",
kind="numeric", limit=5,
row=5, column=1, font=9, bg=colour.MEDIUM_ORANGE, fg=colour.WHITE)
self.app.label("XE_Data_Freq", "Frequency: 0 Hz", sticky="NEW",
row=6, column=0, colspan=2, font=10, fg=colour.LIGHT_LIME)
# Volume / Timer envelope Graph
with self.app.frame("XE_Frame_Data_Bottom", sticky="W", padding=[1, 1], row=1, column=0, colspan=2):
self.app.canvas("XE_Canvas_SFX", map=None, width=320, height=200, bg=colour.BLACK,
row=0, column=0)
self._canvas_sfx = self.app.getCanvasWidget("XE_Canvas_SFX")
self.read_sfx_data()
self._sfx_info()
# Draw graph
self._draw_sfx_graph()
self.app.showSubWindow("SFX_Editor")
# ------------------------------------------------------------------------------------------------------------------
def _get_selection_index(self, widget: str) -> int:
"""
Returns
-------
int:
The index of the currently selected option from an OptionBox widget
"""
value = "(nothing)"
try:
value = self.app.getOptionBox(widget)
box = self.app.getOptionBoxWidget(widget)
return box.options.index(value)
except ValueError as error:
self.error(f"ERROR: Getting selection index for '{value}' in '{widget}': {error}.")
return 0
# ------------------------------------------------------------------------------------------------------------------
def _data_input(self, widget: str) -> None:
# Get the selection index and calculate the position in the array depending on whether we use the first byte
# only or both bytes
selection = self.app.getListBoxPos("XE_Data_List")
if len(selection) < 1:
pos = 0
index = 0
else:
index = selection[0]
pos = selection[0] * (1 if self._volume_only else 2)
# Process event according to which widget has generated it
if widget == "XE_Data_Duty": # ------------------------------------------------------------------------------
value = self._get_selection_index(widget)
reg_value = self._sfx_data[pos] & 0x3F
self._sfx_data[pos] = reg_value | (value << 6)
self._unsaved_changes = True
self._update_data_list(index)
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Data_LC_Flag": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
# For the Triangle channel, this is the Control flag instead
if self._channel == 2:
reg_value = self._sfx_data[pos] & 0x7F
self._sfx_data[pos] = reg_value | (0x80 if flag else 0)
else:
reg_value = self._sfx_data[pos] & 0xDF
self._sfx_data[pos] = reg_value | (0x20 if flag else 0)
# There is no Length Counter Load control to enable/disable: the second byte only controls the period
self._unsaved_changes = True
self._update_data_list(index)
elif widget == "XE_Data_CV_Flag": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
reg_value = self._sfx_data[pos] & 0xEF
self._sfx_data[pos] = reg_value | (0x10 if flag else 0)
# Switch between volume and envelope labels
volume = self._sfx_data[pos] & 0x0F
if (self._sfx_data[pos] & 0x10) > 0:
# Constant Volume
self.app.setLabel("XE_Data_Label_2", f" Volume: {volume:02}")
else:
# Envelope Enabled
self.app.setLabel("XE_Data_Label_2", f"Envelope: {volume:02}")
self._unsaved_changes = True
self._update_data_list(index)
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Data_Reg_0": # --------------------------------------------------------------------------
value = self.app.getScale(widget)
reg_value = self._sfx_data[pos] & 0xF0
self._sfx_data[pos] = reg_value | value
if (self._sfx_data[pos] & 0x10) > 0:
# Constant Volume
self.app.setLabel("XE_Data_Label_2", f" Volume: {value:02}")
else:
# Envelope Enabled
self.app.setLabel("XE_Data_Label_2", f"Envelope: {value:02}")
self._unsaved_changes = True
self._update_data_list(index)
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Data_Noise_Mode": # ----------------------------------------------------------------------
pos += 1
flag = self.app.getCheckBox(widget)
reg_value = self._sfx_data[pos] & 0x7F
self._sfx_data[pos] = reg_value | (0x80 if flag else 0)
# Update frequency
period = self._sfx_data[pos] & 0x0F
freq = round(_NOISE_FREQ_TABLE[period] / (1 if flag else 93), 2)
self.app.setLabel("XE_Data_Freq", f"Frequency: {freq} Hz")
self._unsaved_changes = True
self._update_data_list(index)
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Data_Reg_2": # --------------------------------------------------------------------------
pos += 1
value = self.app.getEntry(widget)
if value is None:
return
# The Noise channel treats the period value differently
if self._channel == 3:
period = int(value) & 0x0F
# Mode flag
flag = (self._sfx_data[pos] & 0x80) > 0
reg_value = self._sfx_data[pos] & 0xF0
self._sfx_data[pos] = reg_value | period
# Update frequency display
freq = round(_NOISE_FREQ_TABLE[period] / (1 if flag else 93), 2)
# For all other channels, we need the whole timer value in order to display the correct frequency
else:
self._sfx_data[pos] = int(value) & 0xFF
timer = ((self._setup_values[3] & 0x07) << 8) | self._sfx_data[pos]
freq = round(1789773 / ((timer + 1) << (5 if self._channel == 2 else 4)), 2)
self.app.setLabel("XE_Data_Freq", f"Frequency: {freq} Hz")
self._unsaved_changes = True
self._update_data_list(index)
self._draw_sfx_graph(draw_volume=False)
else: # ------------------------------------------------------------------------------------------------------
self.info(f"Unimplemented input from setup widget: '{widget}'.")
# ------------------------------------------------------------------------------------------------------------------
def _sfx_input(self, widget: str) -> None:
if widget == "XE_Apply": # ----------------------------------------------------------------------------------
if self.save_sfx_data():
self.app.setStatusbar("Sound effects saved")
self._unsaved_changes = False
if self.settings.get("close sub-window after saving"):
self.app.hideSubWindow("SFX_Editor", useStopFunction=True)
elif widget == "XE_Close": # ----------------------------------------------------------------------------------
if self._unsaved_changes:
if not self.app.yesNoBox("SFX Editor", "Are you sure you want to close this window?\n" +
"Any unsaved changes will be lost.", "SFX_Editor"):
return
self._unsaved_changes = False
self.app.hideSubWindow("SFX_Editor", useStopFunction=True)
elif widget == "XE_Play_Stop": # ------------------------------------------------------------------------------
if self._play_thread.is_alive():
self.stop_playback()
else:
self.app.setButtonImage("XE_Play_Stop", "res/stop.gif")
self.app.setButtonTooltip("XE_Play_Stop", "Stop playback")
self._play_sfx()
elif widget[:11] == "XE_Channel_": # --------------------------------------------------------------------------
new_channel = int(widget[-1], 10)
if new_channel != self._channel:
self._channel = new_channel
self._sfx_info()
selection = self.app.getListBoxPos("XE_Data_List")
if len(selection) > 0:
self._event_info(selection[0])
self._draw_sfx_graph()
self._unsaved_changes = True
elif widget == "XE_Duty_Cycle": # --------------------------------------------------------------------------
value = self._get_selection_index(widget)
if value == self._setup_values[0] >> 6:
# No change
return
register_value = self._setup_values[0] & 0x3F
self._setup_values[0] = (value << 6) | register_value
self._draw_sfx_graph(draw_period=False)
self._unsaved_changes = True
elif widget == "XE_Pulse_LC_Flag": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
if flag == (self._setup_values[0] & 0x20) > 0:
# No change
return
register_value = self._setup_values[0] & 0xDF
self._setup_values[0] = register_value | (0x20 if flag else 0)
if flag:
self.app.disableScale("XE_Pulse_Length_Load")
else:
self.app.enableScale("XE_Pulse_Length_Load")
# This only affects the duration of the sound, so no need to redraw the graph
self._unsaved_changes = True
elif widget == "XE_Pulse_CV_Flag": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
if flag == ((self._setup_values[0] & 0x10) > 0):
# No change
return
register_value = self._setup_values[0] & 0xEF
self._setup_values[0] = register_value | (0x10 if flag else 0)
value = self._setup_values[0] & 0x0F
self.app.setLabel("XE_Pulse_Label_0", f"{'Volume' if flag else 'Env. Period'}: {value:02}")
self._draw_sfx_graph(draw_period=False)
self._unsaved_changes = True
elif widget == "XE_Pulse_Volume": # --------------------------------------------------------------------------
value = self.app.getScale(widget) & 0x0F
register_value = self._setup_values[0] & 0xF0 # The other bits in the same register
flag = (self._setup_values[0] & 0x10) > 0
self.app.setLabel("XE_Pulse_Label_0", f"{'Volume' if flag else 'Env. Period'}: {value:02}")
self._setup_values[0] = register_value | value
self._unsaved_changes = True
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Sweep_Enable": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
if flag == ((self._setup_values[1] & 0x80) > 0):
return
register_value = self._setup_values[1] & 0x7F
self._setup_values[1] = register_value | (0x80 if flag else 0)
if flag:
self.app.enableScale("XE_Sweep_Period")
self.app.enableScale("XE_Sweep_Shift")
else:
self.app.disableScale("XE_Sweep_Period")
self.app.disableScale("XE_Sweep_Shift")
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Sweep_Period": # --------------------------------------------------------------------------
value = self.app.getScale(widget)
if value == (self._setup_values[1] & 0x70) >> 4:
return
register_value = self._setup_values[1] & 0x8F
self._setup_values = register_value | (value << 4)
self.app.setLabel("XE_Pulse_Label_1", f"Sweep Period: {value:02}")
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Sweep_Negate": # --------------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
if flag == ((self._setup_values[1] & 0x1) > 0):
return
register_value = self._setup_values[1] & 0xF7
self._setup_values[1] = register_value | (0x08 if flag else 0)
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Sweep_Shift": # --------------------------------------------------------------------------
value = self.app.getScale(widget)
if value == self._setup_values[1] & 0x07:
return
register_value = self._setup_values[1] & 0xF8
self._setup_values[1] = register_value | value
self.app.setLabel("XE_Pulse_Label_2", f"Shift Count: {value:02}")
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Pulse_Timer": # --------------------------------------------------------------------------
try:
value = int(self.app.getEntry(widget)) & 0x7FF
self._setup_values[2] = value & 0x0FF
self._setup_values[3] = (self._setup_values[3] & 0xF8) | (value >> 8)
freq: float = 1789773 / ((value + 1) << 4)
self.app.setLabel("XE_Pulse_Freq", f"Frequency: {round(freq, 2)} Hz")
except TypeError:
return
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Pulse_Length_Load": # ----------------------------------------------------------------------
value = self.app.getScale(widget)
register_value = self._setup_values[3] & 0xF8
self.app.setLabel("XE_Pulse_Label_4", f"Length Ctr Load: {value:02}")
self._setup_values[3] = register_value | (value << 3)
self._unsaved_changes = True
elif widget == "XE_Triangle_Control_Flag": # ------------------------------------------------------------------
flag = self.app.getCheckBox(widget)
if flag == ((self._setup_values[0] & 0x80) > 0):
return
register_value = self._setup_values[0] & 0x7F
self._setup_values[0] = register_value | (0x80 if flag else 0)
self._unsaved_changes = True
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Linear_Load": # --------------------------------------------------------------------------
value = self.app.getEntry(widget)
if value is None or int(value) == self._setup_values[0] & 0x7F:
return
register_value = self._setup_values[0] & 0x80
self._setup_values[0] = register_value | int(value)
self._unsaved_changes = True
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Triangle_Timer": # ----------------------------------------------------------------------
value = self.app.getEntry(widget)
if value is None:
return
timer_low = int(value) & 0x0FF
timer_high = int(value) >> 8
self._setup_values[2] = timer_low
self._setup_values[3] = (self._setup_values[3] & 0xF8) | timer_high
freq = 1789773 / (int(value + 1) << 5)
self.app.setLabel("XE_Triangle_Freq", f"Frequency: {round(freq, 2)} Hz")
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Noise_LC_Flag": # --------------------------------------------------------------------------
value = 0x20 if self.app.getCheckBox(widget) else 0x00
if value == 0:
self.app.enableScale("XE_Noise_Load")
else:
self.app.disableScale("XE_Noise_Load")
self._setup_values[0] = (self._setup_values[0] & 0x1F) | value
self._unsaved_changes = True
elif widget == "XE_Noise_CV_Flag": # --------------------------------------------------------------------------
value = 0x10 if self.app.getCheckBox(widget) else 0x00
volume = self._setup_values[0] & 0x0F
if value == 0:
# If the Constant Volume flag is clear, than this is the envelope period instead of volume
self.app.setLabel("XE_Noise_Label_0", f"Env. Period: {volume:02}")
else:
self.app.setLabel("XE_Noise_Label_0", f"Volume: {volume:02}")
self._setup_values[0] = (self._setup_values[0] & 0x2F) | value
self._unsaved_changes = True
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Noise_Volume": # --------------------------------------------------------------------------
value: int = self.app.getScale(widget)
# If the Constant Volume flag is clear, than this is the envelope period instead of volume
if (self._setup_values[0] & 0x10) > 0:
self.app.setLabel("XE_Noise_Label_0", f"Volume: {value:02}")
else:
self.app.setLabel("XE_Noise_Label_0", f"Env. Period: {value:02}")
self._setup_values[0] = (self._setup_values[0] & 0xF0) | (value & 0x0F)
self._unsaved_changes = True
self._draw_sfx_graph(draw_period=False)
elif widget == "XE_Noise_Loop":
value = 0x80 if self.app.getCheckBox(widget) else 0x00
self._setup_values[2] = (self._setup_values[2] & 0x0F) | value
self._unsaved_changes = True
elif widget == "XE_Noise_Period": # --------------------------------------------------------------------------
value: int = self.app.getScale(widget)
freq = _NOISE_FREQ_TABLE[value]
self.app.setLabel("XE_Noise_Label_1", f"Period: {value:02}")
self.app.setLabel("XE_Noise_Freq", f"Frequency: {freq} Hz")
self._setup_values[2] = (self._setup_values[0] & 0xF0) | value
self._unsaved_changes = True
self._draw_sfx_graph(draw_volume=False)
elif widget == "XE_Noise_Load": # --------------------------------------------------------------------------
value = self.app.getScale(widget)
self.app.setLabel("XE_Noise_Label_2", f"Length Ctr Load: {value:02}")
self._setup_values[3] = value << 3
self._unsaved_changes = True
elif widget == "XE_Data_Size": # ------------------------------------------------------------------------------
value = self.app.getEntry(widget)
if value is None or int(value) == self._size or value < 1 or value > 64:
return
if value < self._size:
if not self.app.yesNoBox("SFX Editor", "Are you sure you want to reduce sound data size?\n" +
"The extra events will be permanently deleted.", "SFX_Editor"):
return
# Decrease size
byte_size = int(value) * (1 if self._volume_only else 2)
self._sfx_data = self._sfx_data[0:byte_size]
else:
# Increase size, create copy of last event to fill the rest
new_events = self._sfx_data[-1:] if self._volume_only else self._sfx_data[-2:]
diff = int(value) - self._size
self._sfx_data = self._sfx_data + (new_events * diff)
self._size = int(value)
self._update_data_list()
self._draw_sfx_graph()
elif widget == "XE_Data_List": # ------------------------------------------------------------------------------
selection = self.app.getListBoxPos(widget)
if len(selection) > 0:
self._event_info(selection[0])
else:
self.info(f"Unimplemented input from setup widget: '{widget}'.")
# ------------------------------------------------------------------------------------------------------------------
def get_sfx_info(self, sfx_id: int) -> Tuple[int, int, bool, int]:
"""
Returns
-------
Tuple[int, bool]
A tuple (channel, address, volume only flag, number of events).
"""
ptr = 0xA16B + (sfx_id << 2)
# Read sfx entry from table in ROM buffer
value = self.rom.read_byte(0x9, ptr)
volume_only = (value & 0x10) > 0
channel = value & 0x3
size = self.rom.read_byte(0x9, ptr + 1)
address = self.rom.read_word(0x9, ptr + 2)
return channel, address, volume_only, size
# ------------------------------------------------------------------------------------------------------------------
def read_sfx_names(self) -> List[str]:
# By default, everything is unnamed
self.sfx_names = []
for s in range(52):
self.sfx_names.append(f"(No Name)")
# If any definition filename matches the currently loaded ROM filename, then use that one
file_name = os.path.basename(self.rom.path).rsplit('.')[0] + "_audio.ini"
if os.path.exists(os.path.dirname(self.rom.path) + '/' + file_name):
file_name = os.path.dirname(self.rom.path) + '/' + file_name
elif os.path.exists("audio.ini"):
file_name = "audio.ini"
parser = configparser.ConfigParser()
parser.read(file_name)
if parser.has_section("SFX"):
section = parser["SFX"]
for s in range(52):
name = section.get(f"{s}", "")
if name != "":
self.sfx_names[s] = name
return self.sfx_names
# ------------------------------------------------------------------------------------------------------------------
def read_sfx_data(self, sfx_id: Optional[int] = None) -> Tuple[bool, int, int]:
"""
Reads an entry from the sfx table in bank 9.
Parameters
----------
sfx_id: Optional[int]
Index of the entry to read; re-reads currently loaded sfx if not specified.
Returns
-------
Tuple[bool, int, int]
A tuple (volume only flag, channel number, data address).
"""
if sfx_id is None:
sfx_id = self._sfx_id
if 52 < sfx_id < 0:
self.warning(f"Invalid Sound Effect Id requested: {sfx_id}.")
return False, 0, 0
address = 0xA16B + (sfx_id << 2)
# Read sfx entry from table in ROM buffer
value = self.rom.read_byte(0x9, address)
self._volume_only = (value & 0x10) > 0
self._channel = value & 0x3
self._size = self.rom.read_byte(0x9, address + 1)
self._address = self.rom.read_word(0x9, address + 2)
# Read sound data
address = self._address
# First four bytes are the "setup" values used to initialise the registers
self._setup_values = self.rom.read_bytes(0x9, address, 4)
self._sfx_data.clear()
address += 4
for _ in range(self._size):
self._sfx_data.append(self.rom.read_byte(0x9, address))
address += 1
if not self._volume_only:
self._sfx_data.append(self.rom.read_byte(0x9, address))
address += 1
return self._volume_only, self._channel, self._address
# ------------------------------------------------------------------------------------------------------------------
def save_sfx_data(self) -> bool:
"""
Returns
-------
bool
True if save successful, False otherwise (e.g. no room for event data)
"""
name = self.app.getEntry("XE_SFX_Name")
if name is None or len(name) < 1:
name = "(No Name)"
else:
# Save name in INI file
# If any definition filename matches the currently loaded ROM filename, then use that one
file_name = os.path.basename(self.rom.path).rsplit('.')[0] + "_audio.ini"
if os.path.exists(os.path.dirname(self.rom.path) + '/' + file_name):
file_name = os.path.dirname(self.rom.path) + '/' + file_name
elif os.path.exists("audio.ini"):
file_name = "audio.ini"
parser = configparser.ConfigParser()
parser.read(file_name)
if not parser.has_section("SFX"):
parser.add_section("SFX")
parser.set("SFX", f"{self._sfx_id}", name)
# Update SFX tab list
self.app.setOptionBox("ST_Option_SFX", self._sfx_id, value=f"0x{self._sfx_id:02X} {name}", callFunction=False)
# Map of valid ROM areas in Bank 9 where we can save our data
# Tuple: start address, size
memory = [(0xA23B, 2590), (0xA050, 176)]
# One buffer per memory area, we will only copy them to ROM if all data can be allocated successfully
buffers = [bytearray(), bytearray()]
# We will also recreate the table locally before copying it to ROM
table = bytearray()
# Go through all the sound effects and re-allocate them
for i in range(52):
if i == self._sfx_id:
# Save our new data
size = self._size
table.append(self._channel | (0x80 if self._volume_only else 0))
data = self._setup_values + self._sfx_data
else:
# Read data from ROM
ptr = 0xA16B + (i << 2)
size = self.rom.read_byte(0x9, ptr + 1)
channel = self.rom.read_byte(0x9, ptr)
table.append(channel)
old_address = self.rom.read_word(0x9, ptr + 2)
# 4 bytes of "setup values", then either 1 byte per event (volume only flag) or 2 bytes per event
data = self.rom.read_bytes(0x9, old_address, 4 + (size * (1 if (channel & 0x10) > 0 else 2)))
# Write number of events in the table
table.append(size)
# Get data size in bytes
data_size = len(data)
# See if it fits in the first area
if data_size <= memory[0][1]:
mem = 0
elif data_size <= memory[1][1]:
mem = 1
else:
self.app.errorBox("SFX Editor", f"Error saving sound effect #{i}: out of memory in ROM bank 9.",
"SFX_Editor")
return False
new_address = memory[mem][0]
table.append(new_address & 0x00FF) # Low byte
table.append(new_address >> 8) # High byte
# Advance the first available address and reduce size for the selected area
memory[mem] = new_address + data_size, memory[mem][1] - data_size
# Save data to our local buffer
buffers[mem] += data
# Memory successfully allocated, we can write both table and data to ROM
self.rom.write_bytes(0x9, 0xA16B, table)
self.rom.write_bytes(0x9, 0xA23B, buffers[0])
if len(buffers[1]) > 0:
self.rom.write_bytes(0x9, 0xA050, buffers[1])
return True
# ------------------------------------------------------------------------------------------------------------------
def _sfx_info(self) -> None:
if self._channel == 3: # Noise channel
self.app.selectFrame("XE_Stack_Channel", 2)
elif self._channel == 2: # Triangle channel
self.app.selectFrame("XE_Stack_Channel", 1)
else: # Pulse channels
self.app.selectFrame("XE_Stack_Channel", 0)
# Highlight current channel
for c in range(4):
self.app.setButtonBg(f"XE_Channel_{c}", colour.LIGHT_ORANGE if self._channel == c else colour.DARK_ORANGE)
# Set widgets according to sfx setup data
if self._channel == 3: # Noise
lc_flag = (self._setup_values[0] & 0x20) > 0
cv_flag = (self._setup_values[0] & 0x10) > 0
volume = self._setup_values[0] & 0x0F
loop = (self._setup_values[2] & 0x80) > 0
period = self._setup_values[2] & 0x0F
length_ctr_load = self._setup_values[3] >> 3
self.app.setCheckBox("XE_Noise_LC_Flag", lc_flag, callFunction=False)
self.app.setCheckBox("XE_Noise_CV_Flag", cv_flag, callFunction=False)
self.app.setScale("XE_Noise_Volume", volume, callFunction=False)
# If the Constant Volume flag is clear, than this is the envelope period instead of volume
if (self._setup_values[0] & 0x10) > 0:
self.app.setLabel("XE_Noise_Label_0", f"Volume: {volume:02}")
else:
self.app.setLabel("XE_Noise_Label_0", f"Env. Period: {volume:02}")
self.app.setCheckBox("XE_Noise_Loop", loop, callFunction=False)
self.app.setScale("XE_Noise_Period", period)
freq = _NOISE_FREQ_TABLE[period]
self.app.setLabel("XE_Noise_Label_1", f"Period: {period:02}")
self.app.setLabel("XE_Noise_Freq", f"Frequency: {freq} Hz")
self.app.setScale("XE_Noise_Load", length_ctr_load)
self.app.setLabel("XE_Noise_Label_2", f"Length Ctr Load: {length_ctr_load:02}")
if lc_flag:
self.app.disableScale("XE_Noise_Load")
else:
self.app.enableScale("XE_Noise_Load")
elif self._channel == 2: # Triangle
control_flag: bool = (self._setup_values[0] & 0x80) > 0
linear_ctr_reload: int = self._setup_values[0] & 0x7F
timer_value: int = self._setup_values[2] | ((self._setup_values[3] & 0x3) << 8)
frequency = 1789773 / ((timer_value + 1) << 5)
length_ctr_load: int = (self._setup_values[3] & 0xF8) >> 3
self.app.setCheckBox("XE_Triangle_Control_Flag", control_flag, callFunction=False)
self.app.clearEntry("XE_Linear_Load", callFunction=False, setFocus=False)
self.app.setEntry("XE_Linear_Load", linear_ctr_reload, callFunction=False)
self.app.clearEntry("XE_Triangle_Timer", callFunction=False, setFocus=False)
self.app.setEntry("XE_Triangle_Timer", timer_value, callFunction=False)
self.app.setLabel("XE_Triangle_Freq", f"Frequency: {round(frequency, 2)} Hz")
self.app.clearEntry("XE_Triangle_Length_Load", callFunction=False, setFocus=False)
self.app.setEntry("XE_Triangle_Length_Load", length_ctr_load, callFunction=False)
else: # Pulse
duty = (self._setup_values[0] >> 6)
lc_flag = (self._setup_values[0] & 0x20) > 0
cv_flag = (self._setup_values[0] & 0x10) > 0
volume = self._setup_values[0] & 0x0F
sweep_enable = (self._setup_values[1] & 0x80) > 0
sweep_period = (self._setup_values[1] & 0x70) >> 4
sweep_negate = (self._setup_values[1] & 0x08) > 0
sweep_shift = self._setup_values[1] & 0x3
timer = self._setup_values[2] | ((self._setup_values[3] & 0x03) << 8)
length_ctr_load = self._setup_values[3] >> 3
self.app.setOptionBox("XE_Duty_Cycle", duty, callFunction=False)
self.app.setCheckBox("XE_Pulse_LC_Flag", lc_flag, callFunction=False)
self.app.setCheckBox("XE_Pulse_CV_Flag", cv_flag, callFunction=False)
self.app.setScale("XE_Pulse_Volume", volume)
self.app.setLabel("XE_Pulse_Label_0", f"{'Volume' if cv_flag else 'Env. Period'}: {volume:02}")
self.app.setCheckBox("XE_Sweep_Enable", sweep_enable, callFunction=False)
self.app.setLabel("XE_Pulse_Label_1", f"Sweep Period: {sweep_period:02}")
self.app.setScale("XE_Sweep_Period", sweep_period, callFunction=False)
self.app.setCheckBox("XE_Sweep_Negate", sweep_negate, callFunction=False)
self.app.setLabel("XE_Pulse_Label_2", f"Shift Count: {sweep_shift:02}")
self.app.setScale("XE_Sweep_Shift", sweep_shift, callFunction=False)
if sweep_enable:
self.app.enableScale("XE_Sweep_Period")
self.app.enableScale("XE_Sweep_Shift")
else:
self.app.disableScale("XE_Sweep_Period")
self.app.disableScale("XE_Sweep_Shift")
self.app.clearEntry("XE_Pulse_Timer", callFunction=False, setFocus=False)
self.app.setEntry("XE_Pulse_Timer", timer, callFunction=False)
freq: float = 1789773 / ((timer + 1) << 4)
self.app.setLabel("XE_Pulse_Freq", f"Frequency: {round(freq, 2)} Hz")
self.app.setScale("XE_Pulse_Length_Load", length_ctr_load)
self.app.setLabel("XE_Pulse_Label_4", f"Length Ctr Load: {length_ctr_load:02}")
if lc_flag:
self.app.disableScale("XE_Pulse_Length_Load")
else:
self.app.enableScale("XE_Pulse_Length_Load")
self._update_data_list()
# ------------------------------------------------------------------------------------------------------------------
def _update_data_list(self, event_index: Optional[int] = None) -> None:
# Only update one item if event_index is specified
if event_index is not None:
v = event_index * (1 if self._volume_only else 2)
text = f"#{event_index:02}: ${self._sfx_data[v]:02X}"
if not self._volume_only:
text += f", ${self._sfx_data[v + 1]:02X}"
self.app.setListItemAtPos("XE_Data_List", event_index, text)
self.app.selectListItemAtPos("XE_Data_List", event_index, callFunction=False)
return
# Otherwise list all data entries
self.app.clearEntry("XE_Data_Size", callFunction=False, setFocus=False)
self.app.setEntry("XE_Data_Size", self._size, callFunction=False)
self.app.clearListBox("XE_Data_List")
index = 0
v = 0
while index < self._size:
text = f"#{index:02}: ${self._sfx_data[v]:02X}"
v += 1
if not self._volume_only:
text += f", ${self._sfx_data[v]:02X}"
v += 1
self.app.addListItems("XE_Data_List", [text], False)
index += 1
# Select top entry
self.app.selectListItemAtPos("XE_Data_List", 0, callFunction=True)
# ------------------------------------------------------------------------------------------------------------------
def _event_info(self, event_id: int) -> None:
# --- Register 0
index = event_id * (1 if self._volume_only else 2)
# --- Reg 0, bits 7, 6
# Only Pulse channels have this
if self._channel < 2:
duty = self._sfx_data[index] >> 6
self.app.enableOptionBox("XE_Data_Duty")
self.app.setOptionBox("XE_Data_Duty", duty, callFunction=False)
else:
self.app.disableOptionBox("XE_Data_Duty")
# --- Reg 0, bits 5, 4
if self._channel != 2:
lc_flag = (self._sfx_data[index] & 0x20) > 0
self.app.setCheckBoxText("XE_Data_LC_Flag", "Length Ctr Halt")
self.app.setCheckBox("XE_Data_LC_Flag", lc_flag, callFunction=False)
cv_flag = (self._sfx_data[index] & 0x10) > 0
self.app.enableCheckBox("XE_Data_CV_Flag")
self.app.setCheckBox("XE_Data_CV_Flag", cv_flag, callFunction=False)
# --- Reg 0, bit 7
# For the Triangle channel, use the LC Flag widget for the Control Flag instead, then disable the CV widget
else:
control_flag = (self._sfx_data[index] & 0x80) > 0
self.app.setCheckBoxText("XE_Data_LC_Flag", "Control Flag")
self.app.setCheckBox("XE_Data_LC_Flag", control_flag, callFunction=False)
self.app.disableCheckBox("XE_Data_CV_Flag")
# --- Reg 0, bits 3-0
if self._channel != 2:
volume = self._sfx_data[index] & 0x0F
if (self._sfx_data[index] & 0x10) > 0:
# Constant Volume
self.app.setLabel("XE_Data_Label_2", f"Volume: {volume:02}")
else:
# Envelope Enabled
self.app.setLabel("XE_Data_Label_2", f"Env. Period: {volume:02}")
self.app.setScaleRange("XE_Data_Reg_0", 0, 15)
self.app.setScale("XE_Data_Reg_0", volume, callFunction=False)
# --- Reg 0, bit 7-0
# For the Triangle channel, this is the linear counter reload value
else:
linear_ctr_reload = self._sfx_data[index] & 0x7F
self.app.setLabel("XE_Data_Label_2", f"Linear Ctr: {linear_ctr_reload:02}")
self.app.setScaleRange("XE_Data_Reg_0", 0, 0x7F)
self.app.setScale("XE_Data_Reg_0", linear_ctr_reload, callFunction=False)
# --- Register 2
index += 1
self.app.clearEntry("XE_Data_Reg_2", callFunction=False, setFocus=False)
# --- Reg 2, bit 7 and 3-0
# The Noise channel uses the period value differently
if self._channel == 3:
noise_mode = (self._sfx_data[index] & 0x80) > 0
self.app.enableCheckBox("XE_Data_Noise_Mode")
self.app.setCheckBox("XE_Data_Noise_Mode", noise_mode, callFunction=False)
period = self._sfx_data[index] & 0x0F
freq = round(_NOISE_FREQ_TABLE[period] / (1 if noise_mode else 93), 2)
# --- Reg 2, bits 7-0
else:
period = self._sfx_data[index]
timer_high = self._setup_values[3] & 0x03
timer = (timer_high << 8) | period
freq = round(1789773 / ((timer + 1) << (5 if self._channel == 2 else 4)), 2)
self.app.disableCheckBox("XE_Data_Noise_Mode")
self.app.setEntry("XE_Data_Reg_2", period, callFunction=False)
self.app.setLabel("XE_Data_Freq", f"Frequency: {freq} Hz")
# ------------------------------------------------------------------------------------------------------------------
def _play_sfx(self) -> None:
if not self.sound_server.getIsBooted():
self.sound_server.boot()
if not self.sound_server.getIsStarted():
self.sound_server.start()
# Mute channels
self.apu.reset()
self.apu.play()
# Set initial values
if self._channel == 0:
apu_channel = self.apu.pulse_0
elif self._channel == 1:
apu_channel = self.apu.pulse_1
elif self._channel == 2:
apu_channel = self.apu.triangle
else:
apu_channel = self.apu.noise
apu_channel.write_reg0(self._setup_values[0])
apu_channel.write_reg1(self._setup_values[1])
apu_channel.write_reg2(self._setup_values[2])
apu_channel.write_reg3(self._setup_values[3])
self._sfx_pos = 0
# self.info(f"Playing {self._size} events ({len(self._sfx_data)} bytes)")
self._play_thread = threading.Thread(target=self._data_step, args=(apu_channel,))
self._play_thread.start()
# ------------------------------------------------------------------------------------------------------------------
def _data_step(self, apu_channel) -> None:
frame_interval = .0166
size = len(self._sfx_data)
while self._sfx_pos < size:
start_time = time.time()
# print(f"Step: {self._sfx_pos}")
# self.info(f"REG0:${self._sfx_data[self._sfx_pos]}")
apu_channel.write_reg0(self._sfx_data[self._sfx_pos])
self._sfx_pos += 1
if not self._volume_only:
# self.info(f"REG2:${self._sfx_data[self._sfx_pos]}")
apu_channel.write_reg2(self._sfx_data[self._sfx_pos])
self._sfx_pos += 1
interval = frame_interval - (time.time() - start_time)
if interval > 0:
time.sleep(interval)
# print("Stopping playback...")
self.stop_playback()
# ------------------------------------------------------------------------------------------------------------------
def stop_playback(self) -> None:
self.apu.stop()
try:
self.app.setButtonImage("XE_Play_Stop", "res/play.gif")
self.app.setButtonTooltip("XE_Play_Stop", "Start playback")
except appJar.appjar.ItemLookupError:
return
# ------------------------------------------------------------------------------------------------------------------
def _draw_sfx_graph(self, draw_volume: bool = True, draw_period: bool = True) -> None:
# This will be similar to the code used in the Instrument Editor
width = self._canvas_sfx.winfo_reqwidth()
base_height = self._canvas_sfx.winfo_reqheight() - 10
vertical_step = base_height >> 5
line_width = 1
# Calculate the width of each segment in our line
length = width // (self._size + 1)
if length < 8:
length = 8
line_width = 1 # Make the line thinner if it gets too crowded
trail = length >> 2
# One for each duty value, we consider 25% and 75% to be the same, for simplicity
hat = [trail >> 1, trail, length >> 1, trail]
"""
hat
___
| |
_____| |_____
trail tail tail = trail
_______________
length
"""
volume_points = []
timer_points = []
timer = 0
x = 0 # Start from the left of the canvas
# TODO Use envelope values instead of volume if enabled
# TODO Sweep unit values for timer if enabled
# Setup values first
if draw_volume:
if self._channel < 2:
duty = self._setup_values[0] >> 6
else:
duty = 3
volume = self._setup_values[0] & 0x0F
# Starting points
volume_points.append((x, base_height))
# Move right a bit
volume_points.append((x + trail, base_height))
# Go up, depending on volume
y = base_height - (volume * vertical_step)
volume_points.append((x + trail, y))
# Draw the "hat", depending on duty
volume_points.append((x + trail + hat[duty], y))
# Go back down
volume_points.append((x + trail + hat[duty], base_height))
# Move to the end of this line
volume_points.append((x + length, base_height))
if draw_period:
if self._channel == 3:
timer = self._setup_values[2] & 0x0F
y = (timer << 3) + 10
else:
timer = self._setup_values[2]
y = ((timer + 1) >> 2) + 10
timer_points.append((x, y))
# Next line will start here
x = x + length
# Now for the entries...
d = 0 # Position in the array, since entries can be either one- or two-byte long
for i in range(self._size):
if draw_volume:
duty = 3 if self._channel > 1 else self._sfx_data[d] >> 6
volume = self._sfx_data[d] & 0x0F
volume_points.append((x, base_height))
volume_points.append((x + trail, base_height))
y = base_height - (volume * vertical_step)
volume_points.append((x + trail, y))
volume_points.append((x + trail + hat[duty], y))
volume_points.append((x + trail + hat[duty], base_height))
volume_points.append((x + length, base_height))
d += 1
x = x + length
if self._volume_only:
# Use sweep unit value, if enabled
# ...otherwise, use the previous timer value
if draw_period:
if self._channel == 3: # The noise channel has a different use of its period value
y = (timer << 2) + 10
else:
y = ((timer + 1) >> 2) + 10
timer_points.append((x, y))
else:
if draw_period:
if self._channel == 3:
timer = self._sfx_data[d] & 0x0F
y = (timer << 3) + 10
else:
timer = self._sfx_data[d]
y = ((timer + 1) >> 2) + 10
timer_points.append((x, y))
# If only updating volume, this value is simply ignored
d += 1
# Make sure we cover the whole graph area horizontally
if draw_volume:
last = volume_points[-1]
volume_points[-1] = (320, last[1])
flat = [a for x in volume_points for a in x]
if self._volume_line > 0:
self._canvas_sfx.coords(self._volume_line, *flat)
self._canvas_sfx.itemconfigure(self._volume_line, width=line_width)
else:
self._volume_line = self._canvas_sfx.create_line(*flat, width=line_width, fill=colour.LIGHT_ORANGE)
if draw_period:
last = timer_points[-1]
timer_points[-1] = (320, last[1])
flat = [a for x in timer_points for a in x]
if self._timer_line > 0:
self._canvas_sfx.coords(self._timer_line, *flat)
self._canvas_sfx.itemconfigure(self._timer_line, width=line_width)
else:
self._timer_line = self._canvas_sfx.create_line(*flat, width=line_width, fill=colour.LIGHT_GREEN)
# Make sure the timer line is always drawn on top of the volume/duty bars
if not draw_period and self._timer_line > 0:
self._canvas_sfx.tag_raise(self._timer_line)
|
from typing import Optional
from pydantic import AnyUrl, BaseSettings, validator
class Settings(BaseSettings):
SERVER_NAME: str = ""
APPLICATION_NAME: str = "TLS Reporting"
APPLICATION_DESCRIPTION: str = """A number of protocols exist for establishing encrypted channels between SMTP
Mail Transfer Agents (MTAs), including STARTTLS, DNS-Based Authentication of Named Entities (DANE) TLSA, and MTA
Strict Transport Security (MTA-STS). These protocols can fail due to misconfiguration or active attack, leading to
undelivered messages or delivery over unencrypted or unauthenticated channels.
The STARTTLS extension to SMTP [RFC3207] allows SMTP clients and hosts to establish secure SMTP sessions over TLS.
The protocol design uses an approach that has come to be known as "Opportunistic Security" (OS) [RFC7435]. This
method maintains interoperability with clients that do not support STARTTLS, but it means that any attacker could
potentially eavesdrop on a session. An attacker could perform a downgrade or interception attack by deleting parts
of the SMTP session (such as the "250 STARTTLS" response) or redirect the entire SMTP session (perhaps by
overwriting the resolved MX record of the delivery domain).
Because such "downgrade attacks" are not necessarily apparent to the receiving MTA, this document defines a
mechanism for sending domains to report on failures at multiple stages of the MTA-to-MTA conversation.
Recipient domains may also use the mechanisms defined by MTA-STS [RFC8461] or DANE [RFC6698] to publish additional
encryption and authentication requirements; this document defines a mechanism for sending domains that are
compatible with MTA-STS or DANE to share success and failure statistics with recipient domains.
Specifically, this document defines a reporting schema that covers failures in routing, DNS resolution, and STARTTLS
negotiation; policy validation errors for both DANE [RFC6698] and MTA-STS [RFC8461]; and a standard TXT record that
recipient domains can use to indicate where reports in this format should be sent. The report can also serve as a
heartbeat to indicate that systems are successfully negotiating TLS during sessions as expected.
Text from https://datatracker.ietf.org/doc/html/rfc8460
"""
# POSTGRES_SERVER: str
# POSTGRES_USER: str
# POSTGRES_PASSWORD: str
# POSTGRES_DB: str
SQLALCHEMY_DATABASE_URI: Optional[str] = "sqlite:///../../../sql_app.db"
#
# @classmethod
# @validator("SQLALCHEMY_DATABASE_URI", pre=True)
# def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
# if isinstance(v, str):
# return v
# return PostgresDsn.build(
# scheme="postgresql",
# user=values.get("POSTGRES_USER"),
# password=values.get("POSTGRES_PASSWORD"),
# host=values.get("POSTGRES_SERVER"),
# path=f"/{values.get("POSTGRES_DB") or ""}",
# )
class Config:
case_sensitive = True
env_file = ".env"
settings = Settings()
| from typing import Optional
from pydantic import AnyUrl, BaseSettings, validator
class Settings(BaseSettings):
SERVER_NAME: str = ""
APPLICATION_NAME: str = "TLS Reporting"
APPLICATION_DESCRIPTION: str = """A number of protocols exist for establishing encrypted channels between SMTP
Mail Transfer Agents (MTAs), including STARTTLS, DNS-Based Authentication of Named Entities (DANE) TLSA, and MTA
Strict Transport Security (MTA-STS). These protocols can fail due to misconfiguration or active attack, leading to
undelivered messages or delivery over unencrypted or unauthenticated channels.
The STARTTLS extension to SMTP [RFC3207] allows SMTP clients and hosts to establish secure SMTP sessions over TLS.
The protocol design uses an approach that has come to be known as "Opportunistic Security" (OS) [RFC7435]. This
method maintains interoperability with clients that do not support STARTTLS, but it means that any attacker could
potentially eavesdrop on a session. An attacker could perform a downgrade or interception attack by deleting parts
of the SMTP session (such as the "250 STARTTLS" response) or redirect the entire SMTP session (perhaps by
overwriting the resolved MX record of the delivery domain).
Because such "downgrade attacks" are not necessarily apparent to the receiving MTA, this document defines a
mechanism for sending domains to report on failures at multiple stages of the MTA-to-MTA conversation.
Recipient domains may also use the mechanisms defined by MTA-STS [RFC8461] or DANE [RFC6698] to publish additional
encryption and authentication requirements; this document defines a mechanism for sending domains that are
compatible with MTA-STS or DANE to share success and failure statistics with recipient domains.
Specifically, this document defines a reporting schema that covers failures in routing, DNS resolution, and STARTTLS
negotiation; policy validation errors for both DANE [RFC6698] and MTA-STS [RFC8461]; and a standard TXT record that
recipient domains can use to indicate where reports in this format should be sent. The report can also serve as a
heartbeat to indicate that systems are successfully negotiating TLS during sessions as expected.
Text from https://datatracker.ietf.org/doc/html/rfc8460
"""
# POSTGRES_SERVER: str
# POSTGRES_USER: str
# POSTGRES_PASSWORD: str
# POSTGRES_DB: str
SQLALCHEMY_DATABASE_URI: Optional[str] = "sqlite:///../../../sql_app.db"
#
# @classmethod
# @validator("SQLALCHEMY_DATABASE_URI", pre=True)
# def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
# if isinstance(v, str):
# return v
# return PostgresDsn.build(
# scheme="postgresql",
# user=values.get("POSTGRES_USER"),
# password=values.get("POSTGRES_PASSWORD"),
# host=values.get("POSTGRES_SERVER"),
# path=f"/{values.get('POSTGRES_DB') or ''}",
# )
class Config:
case_sensitive = True
env_file = ".env"
settings = Settings()
|
import shlex
from distutils.version import LooseVersion
from functools import partial
from itertools import product
from shipyard import Action, CIPrettyLogAction, IsolatedAction, ctx
#####################################
# Travis: Wait and pull/push images #
#####################################
def wait_and_pull_cmd(image_name):
return f"until docker pull {image_name}; do sleep 5; done"
def wait_and_push_cmd(image_name):
return f"until docker push {image_name}; do sleep 5; done"
def create_image_with_context(build_ctx, image, dockerfile, rpc_version=None):
if rpc_version is None:
rpc_version = ""
else:
rpc_version = f"--build-arg RPC_VERSION={rpc_version}"
namespace = build_ctx["namespace"]
sha_tag = build_ctx["sha_tag"]
docker_build_str = f"docker build --build-arg CODE_VERSION={sha_tag} \
--build-arg REGISTRY={namespace} {rpc_version} \
-t {namespace}/{image}:{sha_tag} \
-f dockerfiles/{dockerfile} {build_ctx['clipper_root']} "
return CIPrettyLogAction(image, docker_build_str, tags=["build"])
def push_image_with_context(build_ctx, image, push_sha=True, push_version=False):
namespace = build_ctx["namespace"]
sha_tag = build_ctx["sha_tag"]
version_tag = build_ctx["version_tag"]
image_name_sha = f"{namespace}/{image}:{sha_tag}"
image_name_version = f"{namespace}/{image}:{version_tag}"
docker_tag = f"docker tag {image_name_sha} {image_name_version}"
docker_push_sha = wait_and_push_cmd(image_name_sha)
docker_push_version = wait_and_push_cmd(image_name_version)
commands = [docker_tag]
if push_sha:
commands.append(docker_push_sha)
if push_version and ctx["push"]:
commands.append(docker_push_version)
version = LooseVersion(version_tag).version
if len(version) >= 3:
minor_version = ".".join(version[:2])
image_name_minor_version = f"{namespace}/{image}:{minor_version}"
tag_minor_ver = f"docker tag {image_name_sha} {image_name_minor_version}"
push_minor_ver = wait_and_push_cmd(image_name_minor_version)
commands.extend([tag_minor_ver, push_minor_ver])
return CIPrettyLogAction(f"publish_{image}", "\n".join(commands), tags=["push"])
def create_and_push_with_ctx(
ctx, name, dockerfile, push_version=False, rpc_version=None
):
create_image = partial(create_image_with_context, ctx)
push_image = partial(push_image_with_context, ctx)
created = create_image(name, dockerfile, rpc_version)
pushed = push_image(name, push_sha=True, push_version=push_version)
# Prepull will let docker re-use cached images
prepull = CIPrettyLogAction(
f"prepull_{name}", f"docker pull clipper/{name}:develop || true", ["prepull"]
)
prepull > created
created > pushed
return created
######################
# Lib Base Build DAG #
######################
lib_base = create_and_push_with_ctx(
ctx, "lib_base", "ClipperLibBaseDockerfile", push_version=False
)
query_frontend = create_and_push_with_ctx(
ctx, "query_frontend", "QueryFrontendDockerfile", push_version=True
)
management_frontend = create_and_push_with_ctx(
ctx, "management_frontend", "ManagementFrontendDockerfile", push_version=True
)
dev = create_and_push_with_ctx(ctx, "dev", "ClipperDevDockerfile ", push_version=True)
py35_dev = create_and_push_with_ctx(
ctx, "py35-dev", "ClipperPy35DevDockerfile ", push_version=True
)
unittests = create_and_push_with_ctx(
ctx, "unittests", "ClipperTestsDockerfile ", push_version=False
)
py35tests = create_and_push_with_ctx(
ctx, "py35tests", "ClipperPy35TestsDockerfile ", push_version=False
)
lib_base > query_frontend
lib_base > management_frontend
lib_base > dev
lib_base > py35_dev
dev > unittests
py35_dev > py35tests
######################
# Misc Container DAG #
######################
# Deprecate JVM Container!
# create_and_push_with_ctx(
# ctx, "spark-scala-container", "SparkScalaContainerDockerfile", push_version=True
# )
# create_and_push_with_ctx(
# ctx, "r-container-base", "RContainerDockerfile", push_version=True
# )
frontend_exporter = create_and_push_with_ctx(
ctx, "frontend-exporter", "FrontendExporterDockerfile", push_version=True
)
##################
# RPC Containers #
##################
py_rpc = create_and_push_with_ctx(
ctx, "py-rpc", "Py2RPCDockerfile", rpc_version="py", push_version=True
)
py35_rpc = create_and_push_with_ctx(
ctx, "py35-rpc", "Py35RPCDockerfile", rpc_version="py35", push_version=True
)
py36_rpc = create_and_push_with_ctx(
ctx, "py36-rpc", "Py36RPCDockerfile", rpc_version="py36", push_version=True
)
# Will be used for model containers building
rpc_containers = {"py": py_rpc, "py35": py35_rpc, "py36": py36_rpc}
py_rpc > create_and_push_with_ctx(
ctx, "sum-container", "SumDockerfile ", push_version=False
)
py_rpc > create_and_push_with_ctx(
ctx, "noop-container", "NoopDockerfile", push_version=True
)
####################
# Model Containers #
####################
models = [
("mxnet{version}", "MXNetContainer"),
("pytorch{version}", "PyTorchContainer"),
("tf{version}", "TensorFlow"),
("pyspark{version}", "PySparkContainer"),
("python{version}-closure", "PyClosureContainer"),
]
py_version = [("", "py"), ("35", "py35"), ("36", "py36")]
for (model_name, docker_file), (py_version_name, rpc_version) in product(
models, py_version
):
container = create_and_push_with_ctx(
ctx,
name=f"{model_name.format(version=py_version_name)}-container",
dockerfile=f"{docker_file}Dockerfile",
rpc_version=rpc_version,
push_version=True,
)
# link dependency
rpc_containers[rpc_version] > container
##############################
# Kubernetes Test Dependency #
##############################
kubernetes_test_target = IsolatedAction("kubernetes_test_containers")
kubernetes_containers = [
query_frontend.name,
management_frontend.name,
frontend_exporter.name,
"noop-container",
"python-closure-container", # travis has py2.7
]
for container in kubernetes_containers:
Action.get_action(container) > kubernetes_test_target
Action.get_action(f"publish_{container}") > kubernetes_test_target
for container in kubernetes_containers:
wait = IsolatedAction(
f"wait_{container}",
wait_and_pull_cmd(f'{ctx['namespace']}/{container}:{ctx['sha_tag']}'),
tags="wait_for_kubernetes_test_containers",
)
tag = IsolatedAction(
f"travis_re_tag_{container}",
f'docker tag {ctx['namespace']}/{container}:{ctx['sha_tag']} localhost:5000/{container}:{ctx['sha_tag']}',
tags="retag_kubernetes_test_containers",
)
wait > tag
push = IsolatedAction(
f"travis_re_push_{container}",
f'docker push localhost:5000/{container}:{ctx['sha_tag']}',
tags="repush_kubernetes_test_containers",
)
tag > push
| import shlex
from distutils.version import LooseVersion
from functools import partial
from itertools import product
from shipyard import Action, CIPrettyLogAction, IsolatedAction, ctx
#####################################
# Travis: Wait and pull/push images #
#####################################
def wait_and_pull_cmd(image_name):
return f"until docker pull {image_name}; do sleep 5; done"
def wait_and_push_cmd(image_name):
return f"until docker push {image_name}; do sleep 5; done"
def create_image_with_context(build_ctx, image, dockerfile, rpc_version=None):
if rpc_version is None:
rpc_version = ""
else:
rpc_version = f"--build-arg RPC_VERSION={rpc_version}"
namespace = build_ctx["namespace"]
sha_tag = build_ctx["sha_tag"]
docker_build_str = f"docker build --build-arg CODE_VERSION={sha_tag} \
--build-arg REGISTRY={namespace} {rpc_version} \
-t {namespace}/{image}:{sha_tag} \
-f dockerfiles/{dockerfile} {build_ctx['clipper_root']} "
return CIPrettyLogAction(image, docker_build_str, tags=["build"])
def push_image_with_context(build_ctx, image, push_sha=True, push_version=False):
namespace = build_ctx["namespace"]
sha_tag = build_ctx["sha_tag"]
version_tag = build_ctx["version_tag"]
image_name_sha = f"{namespace}/{image}:{sha_tag}"
image_name_version = f"{namespace}/{image}:{version_tag}"
docker_tag = f"docker tag {image_name_sha} {image_name_version}"
docker_push_sha = wait_and_push_cmd(image_name_sha)
docker_push_version = wait_and_push_cmd(image_name_version)
commands = [docker_tag]
if push_sha:
commands.append(docker_push_sha)
if push_version and ctx["push"]:
commands.append(docker_push_version)
version = LooseVersion(version_tag).version
if len(version) >= 3:
minor_version = ".".join(version[:2])
image_name_minor_version = f"{namespace}/{image}:{minor_version}"
tag_minor_ver = f"docker tag {image_name_sha} {image_name_minor_version}"
push_minor_ver = wait_and_push_cmd(image_name_minor_version)
commands.extend([tag_minor_ver, push_minor_ver])
return CIPrettyLogAction(f"publish_{image}", "\n".join(commands), tags=["push"])
def create_and_push_with_ctx(
ctx, name, dockerfile, push_version=False, rpc_version=None
):
create_image = partial(create_image_with_context, ctx)
push_image = partial(push_image_with_context, ctx)
created = create_image(name, dockerfile, rpc_version)
pushed = push_image(name, push_sha=True, push_version=push_version)
# Prepull will let docker re-use cached images
prepull = CIPrettyLogAction(
f"prepull_{name}", f"docker pull clipper/{name}:develop || true", ["prepull"]
)
prepull > created
created > pushed
return created
######################
# Lib Base Build DAG #
######################
lib_base = create_and_push_with_ctx(
ctx, "lib_base", "ClipperLibBaseDockerfile", push_version=False
)
query_frontend = create_and_push_with_ctx(
ctx, "query_frontend", "QueryFrontendDockerfile", push_version=True
)
management_frontend = create_and_push_with_ctx(
ctx, "management_frontend", "ManagementFrontendDockerfile", push_version=True
)
dev = create_and_push_with_ctx(ctx, "dev", "ClipperDevDockerfile ", push_version=True)
py35_dev = create_and_push_with_ctx(
ctx, "py35-dev", "ClipperPy35DevDockerfile ", push_version=True
)
unittests = create_and_push_with_ctx(
ctx, "unittests", "ClipperTestsDockerfile ", push_version=False
)
py35tests = create_and_push_with_ctx(
ctx, "py35tests", "ClipperPy35TestsDockerfile ", push_version=False
)
lib_base > query_frontend
lib_base > management_frontend
lib_base > dev
lib_base > py35_dev
dev > unittests
py35_dev > py35tests
######################
# Misc Container DAG #
######################
# Deprecate JVM Container!
# create_and_push_with_ctx(
# ctx, "spark-scala-container", "SparkScalaContainerDockerfile", push_version=True
# )
# create_and_push_with_ctx(
# ctx, "r-container-base", "RContainerDockerfile", push_version=True
# )
frontend_exporter = create_and_push_with_ctx(
ctx, "frontend-exporter", "FrontendExporterDockerfile", push_version=True
)
##################
# RPC Containers #
##################
py_rpc = create_and_push_with_ctx(
ctx, "py-rpc", "Py2RPCDockerfile", rpc_version="py", push_version=True
)
py35_rpc = create_and_push_with_ctx(
ctx, "py35-rpc", "Py35RPCDockerfile", rpc_version="py35", push_version=True
)
py36_rpc = create_and_push_with_ctx(
ctx, "py36-rpc", "Py36RPCDockerfile", rpc_version="py36", push_version=True
)
# Will be used for model containers building
rpc_containers = {"py": py_rpc, "py35": py35_rpc, "py36": py36_rpc}
py_rpc > create_and_push_with_ctx(
ctx, "sum-container", "SumDockerfile ", push_version=False
)
py_rpc > create_and_push_with_ctx(
ctx, "noop-container", "NoopDockerfile", push_version=True
)
####################
# Model Containers #
####################
models = [
("mxnet{version}", "MXNetContainer"),
("pytorch{version}", "PyTorchContainer"),
("tf{version}", "TensorFlow"),
("pyspark{version}", "PySparkContainer"),
("python{version}-closure", "PyClosureContainer"),
]
py_version = [("", "py"), ("35", "py35"), ("36", "py36")]
for (model_name, docker_file), (py_version_name, rpc_version) in product(
models, py_version
):
container = create_and_push_with_ctx(
ctx,
name=f"{model_name.format(version=py_version_name)}-container",
dockerfile=f"{docker_file}Dockerfile",
rpc_version=rpc_version,
push_version=True,
)
# link dependency
rpc_containers[rpc_version] > container
##############################
# Kubernetes Test Dependency #
##############################
kubernetes_test_target = IsolatedAction("kubernetes_test_containers")
kubernetes_containers = [
query_frontend.name,
management_frontend.name,
frontend_exporter.name,
"noop-container",
"python-closure-container", # travis has py2.7
]
for container in kubernetes_containers:
Action.get_action(container) > kubernetes_test_target
Action.get_action(f"publish_{container}") > kubernetes_test_target
for container in kubernetes_containers:
wait = IsolatedAction(
f"wait_{container}",
wait_and_pull_cmd(f'{ctx["namespace"]}/{container}:{ctx["sha_tag"]}'),
tags="wait_for_kubernetes_test_containers",
)
tag = IsolatedAction(
f"travis_re_tag_{container}",
f'docker tag {ctx["namespace"]}/{container}:{ctx["sha_tag"]} localhost:5000/{container}:{ctx["sha_tag"]}',
tags="retag_kubernetes_test_containers",
)
wait > tag
push = IsolatedAction(
f"travis_re_push_{container}",
f'docker push localhost:5000/{container}:{ctx["sha_tag"]}',
tags="repush_kubernetes_test_containers",
)
tag > push
|
import os
import sys
import uuid
import tempfile
import time
from io import StringIO
import re
import numpy as np
import trimesh
from pyobb.obb import OBB
from scipy.spatial import ConvexHull
from .meshing.surface_mesh_parameters import default_surface_mesh_parameter
from .face import Face
from .tools import export_objects, add_radius_to_edges, vector_to_np_array, perpendicular_vector, extrude, create_pipe, create_pipe_wire, add_radius_to_edges
from .logger import logger
import FreeCAD
import Part as FCPart
import BOPTools.SplitAPI
from FreeCAD import Base
from Draft import make_fillet
from Arch import makePipe
import Arch
App = FreeCAD
class Solid(object):
def __init__(self, *args, **kwargs):
self.id = kwargs.get('id', uuid.uuid4())
self.type = kwargs.get('type', None)
# logger.debug(f'initializing solid {self.id}')
self.name = kwargs.get('name', None)
self.normal = kwargs.get('normal', None)
self._fc_solid = kwargs.get('fc_solid', None)
self._faces = kwargs.get('faces', kwargs.get('_faces', None))
self.interfaces = kwargs.get('interfaces', [])
self.features = kwargs.get('features', {})
self.surface_mesh_setup = kwargs.get('_surface_mesh_setup',
kwargs.get('surface_mesh_setup', default_surface_mesh_parameter))
self.layer = kwargs.get('layer', None)
self.state = kwargs.get('state', 'solid')
self._obb = kwargs.get('obb', None)
@property
def obb(self):
if self._obb is None:
self.calc_obb()
return self._obb
@property
def txt_id(self):
return re.sub('\W+','', 'a' + str(self.id))
@property
def faces(self):
if self._faces is None:
if self._fc_solid is not None:
self._faces = [Face(fc_face=x) for x in self._fc_solid.Shape.Faces]
else:
self._faces = []
return self._faces
@faces.setter
def faces(self, value):
self._faces = value
self.generate_solid_from_faces()
@property
def fc_solid(self):
if self._fc_solid is None:
self.generate_solid_from_faces()
return self._fc_solid
@fc_solid.setter
def fc_solid(self, value):
self._fc_solid = value
@property
def Volume(self):
return self.fc_solid.Shape.Volume
@property
def stl(self):
return ''.join([x.stl for x in self.faces])
@property
def face_names(self):
return [str(x.id) for x in self.faces]
def update_face(self, face, new_face):
face.fc_face = new_face.fc_face
face.normal = None
# if new_face.name is None:
# new_face.name = face.name
#
# if face in self.faces:
# offset = self.faces.index(face, 0)
# self.faces[offset] = new_face
#
# if face in self.interfaces:
# offset = self.interfaces.index(face, 0)
# self.interfaces[offset] = new_face
#
# for key in self.features.keys():
# feature_faces = self.features[key]
# if face in feature_faces:
# offset = feature_faces.index(face, 0)
# feature_faces[offset] = new_face
def export_stl(self, filename):
try:
logger.debug(f'exporting .stl for solid {self.id}')
new_file = open(filename, 'w')
new_file.writelines(self.stl)
new_file.close()
logger.debug(f' finished exporting .stl for solid {self.id}')
except Exception as e:
logger.error(f'error while exporting .stl for solid {self.id}: {e}')
def export_step(self, filename):
logger.debug(f'exporting .stp for solid {self.id}')
path = os.path.dirname(filename)
os.makedirs(path, exist_ok=True)
try:
from .tools import name_step_faces
__objs__ = [self.fc_solid]
fd, tmp_file = tempfile.mkstemp(suffix='.stp')
os.close(fd)
FCPart.export(__objs__, tmp_file)
names = self.face_names
names_dict = {k: v for k, v in zip(range(names.__len__()), names)}
name_step_faces(fname=tmp_file, name=names_dict, new_fname=filename)
except Exception as e:
logger.error(f'error while exporting .stp for solid {self.id}:\n{e}')
finally:
try:
os.remove(tmp_file)
except FileNotFoundError as e:
pass
logger.debug(f' finished exporting .stp for solid {self.id}')
def generate_solid_from_faces(self):
# logger.debug(f'generating solid from faces: {self.id}')
start_time = time.time()
faces = []
[faces.extend(x.fc_face.Faces) for x in self.faces]
shell = FCPart.makeShell(faces)
shell.sewShape()
shell.fix(1e-7, 1e-7, 1e-7)
solid = FCPart.Solid(shell)
if not solid.isClosed():
logger.error(f'Solid {self.id}: solid is not closed')
# doc_start_time = time.time()
doc = App.newDocument()
__o__ = doc.addObject("Part::Feature", f'{str(self.id)}')
__o__.Label = f'{str(self.id)}'
__o__.Shape = solid
# logger.debug(f' doc time: {time.time() - doc_start_time} s')
self.fc_solid = __o__
# logger.debug(f' finished generation of solid from faces: {self.id} in {time.time() - start_time} s')
return self.fc_solid
def generate_faces_from_solid(self, solid):
pass
def write_of_geo(self, directory):
stl_str = ''.join([x.create_stl_str(of=True) for x in set(self.faces) - set(self.interfaces)])
new_file = open(os.path.join(directory, str(self.txt_id) + '.stl'), 'w')
new_file.writelines(stl_str)
new_file.close()
for interface in self.interfaces:
interface_path = os.path.join(directory, str(interface.txt_id) + '.stl')
if not os.path.exists(interface_path):
new_file = open(interface_path, 'w')
new_file.writelines(interface.create_stl_str(of=True))
new_file.close()
@property
def shm_geo_entry(self, offset=0):
local_offset = 4
offset = offset + local_offset
solid_faces = set(self.faces) - set(self.interfaces)
buf = StringIO()
buf.write(f"{" " * offset}{str(self.txt_id)}\n")
buf.write(f"{" " * offset}{"{"}\n")
buf.write(f"{" " * (offset + 4)}type triSurfaceMesh;\n")
buf.write(f"{" " * (offset + 4)}file \"{str(self.txt_id)}.stl\";\n")
buf.write(f"{" " * (offset + 4)}regions\n")
buf.write(f"{" " * (offset + 4)}{"{"}\n")
for face in solid_faces:
buf.write(f"{" " * (offset + 8)}{str(face.txt_id)}\t{"{"} name {str(face.txt_id)};\t{"}"}\n")
buf.write(f"{" " * (offset + 4)}{"}"}\n")
buf.write(f"{" " * offset}{"}"}\n")
return buf.getvalue()
@property
def shm_refinement_entry(self, offset=0):
local_offset = 4
offset = offset + local_offset
hull_faces = set(self.faces) - set(self.interfaces)
buf = StringIO()
buf.write(f"{" " * offset}{str(self.txt_id)}\n")
buf.write(f"{" " * offset}{"{"}\n")
buf.write(f"{" " * (offset + 4)}level ({self.surface_mesh_setup.min_refinement_level} {self.surface_mesh_setup.max_refinement_level});\n")
buf.write(f"{" " * (offset + 4)}regions\n")
buf.write(f"{" " * (offset + 4)}{"{"}\n")
for face in hull_faces:
face_level = f"({face.surface_mesh_setup.min_refinement_level} {face.surface_mesh_setup.max_refinement_level})"
buf.write(f"{" " * (offset + 8)}{str(face.txt_id)} {"{"} level {face_level}; patchInfo {"{"} type patch; {"}"} {"}"}\n")
buf.write(f"{" " * (offset + 4)}{"}"}\n")
buf.write(f"{" " * offset}{"}"}\n")
return buf.getvalue()
@property
def point_in_mesh(self):
if self.fc_solid is None:
return None
solid = self.fc_solid.Shape
b_box = self.fc_solid.Shape.BoundBox
location_in_mesh = np.array([b_box.Center.x + np.random.uniform(-0.1 + 0.1),
b_box.Center.y + np.random.uniform(-0.1 + 0.1),
b_box.Center.z + np.random.uniform(-0.1 + 0.1)])
if solid.isInside(Base.Vector(location_in_mesh), 0, True):
return location_in_mesh
else:
while not solid.isInside(Base.Vector(location_in_mesh), 0, True):
location_in_mesh = np.array([np.random.uniform(b_box.XMin, b_box.XMax),
np.random.uniform(b_box.YMin, b_box.YMax),
np.random.uniform(b_box.ZMin, b_box.ZMax)])
return location_in_mesh
def calc_obb(self):
pts = np.stack([np.array([x.X, x.Y, x.Z]) for x in self.fc_solid.Shape.Vertexes], axis=0)
hull = ConvexHull(pts)
hullpts = [pts[i] for i in hull.vertices]
obb = OBB.build_from_points(hullpts)
obbvec = [FreeCAD.Vector(p)for p in obb.points]
faces = []
idx = [[0, 1, 2, 3, 0],
[4, 5, 6, 7, 4],
[0, 1, 4, 5, 0],
[2, 3, 6, 7, 2],
[1, 2, 7, 4, 1],
[0, 5, 6, 3, 0]]
for ix in idx:
wire = FCPart.makePolygon([obbvec[i] for i in ix])
faces.append(FCPart.Face(wire))
shell = FCPart.makeShell(faces)
FCPart.show(shell)
p = trimesh.points.PointCloud(pts)
self._obb = p.bounding_box_oriented
return self._obb
def save_fcstd(self, filename, shape_type='solid'):
"""
save as freecad document
:param filename: full filename; example: '/tmp/test.FCStd'
:param shape_type: 'solid', 'faces'
"""
doc = App.newDocument(f"Solid {self.name}")
if shape_type == 'solid':
__o__ = doc.addObject("Part::Feature", f'Solid {self.name} {self.id}')
__o__.Shape = self.fc_solid.Shape
elif shape_type == 'face':
for face in self.faces:
__o__ = doc.addObject("Part::Face", f'Face {face.name} {face.id}')
__o__.Shape = face.fc_solid.Shape
doc.recompute()
doc.saveCopy(filename)
def is_inside(self, vec: Base.Vector):
return self.fc_solid.Shape.isInside(vec, 0, True)
def __repr__(self):
rep = f'Solid {self.name} {self.id} {self.Volume}'
return rep
class PipeSolid(Solid):
def __init__(self, *args, **kwargs):
self.id = kwargs.get('id', uuid.uuid4())
self.name = kwargs.get('name', None)
self.reference_face = kwargs.get('reference_face', None)
self.reference_edge_id = kwargs.get('reference_edge_id', 0)
self.tube_diameter = kwargs.get('tube_diameter', 0.02)
self.tube_inner_diameter = kwargs.get('tube_inner_diameter', 0.016)
self.tube_distance = kwargs.get('tube_distance', 0.50)
self.tube_side_1_offset = kwargs.get('tube_side_1_offset', 0.085)
self.tube_edge_distance = kwargs.get('tube_edge_distance', 0.50)
self.bending_radius = kwargs.get('bending_radius', 0.05)
self.reference_edge = None
self._initial_pipe_wire = None # pipe wire without radius
self._pipe_wire = None # pipe wire with radius
self._horizontal_lines = None
try:
pipe = self.generate_solid()
kwargs['fc_solid'] = pipe.fc_solid
kwargs['faces'] = pipe.faces
kwargs['interfaces'] = pipe.interfaces
kwargs['features'] = pipe.features
kwargs['type'] = 'pipe'
except Exception as e:
logger.error(f'Error generating pipe solid for {self.name} {self.id}')
Solid.__init__(self, *args, **kwargs)
@property
def initial_pipe_wire(self):
if self._initial_pipe_wire is None:
self._initial_pipe_wire, _ = self.generate_initial_pipe_wire()
return self._initial_pipe_wire
@property
def pipe_wire(self):
if self._pipe_wire is None:
self.pipe_wire = self.generate_pipe_wire()
return self._pipe_wire
@pipe_wire.setter
def pipe_wire(self, value):
self._pipe_wire = value
@property
def pipe_length(self):
return self.pipe_wire.Length
def generate_initial_pipe_wire(self):
pipe_wire, self._horizontal_lines = create_pipe_wire(self.reference_face.reference_face,
self.reference_edge_id,
self.tube_distance,
self.tube_edge_distance,
self.bending_radius,
self.tube_diameter
)
reference_face = self.reference_face.reference_face
self.reference_edge = reference_face.Edges[self.reference_edge_id]
normal = self.reference_face.get_normal(Base.Vector(self.reference_edge.Vertexes[0].X,
self.reference_edge.Vertexes[0].Y,
self.reference_edge.Vertexes[0].Z))
pipe_wire.Placement.move(self.reference_face.layer_dir * normal *
(- self.reference_face.component_construction.side_1_offset +
self.reference_face.tube_side_1_offset))
return pipe_wire, self._horizontal_lines
def generate_pipe_wire(self):
return add_radius_to_edges(self.initial_pipe_wire, self.bending_radius)
# from .tools import project_point_on_line
#
# reference_face = self.reference_face.reference_face
#
# self.reference_edge = reference_face.Edges[self.reference_edge_id]
# normal = self.reference_face.get_normal(Base.Vector(self.reference_edge.Vertexes[0].X,
# self.reference_edge.Vertexes[0].Y,
# self.reference_edge.Vertexes[0].Z))
# tube_main_dir = self.reference_edge.Curve.Direction.cross(normal)
#
# offset = -self.tube_edge_distance
# wires = []
# offset_possible = True
#
# while offset_possible:
# try:
# wire = reference_face.OuterWire.makeOffset2D(offset, join=1, openResult=False, intersection=False)
#
# # check if another is possible (return wire)
# try:
# reference_face.OuterWire.makeOffset2D(offset - self.tube_distance, join=1, openResult=False,
# intersection=False)
# wires.append(wire)
# offset = offset - 2 * self.tube_distance
# except Exception as e:
# logger.debug(f'no further wire generation possible{e}')
# offset_possible = False
# except Exception as e:
# logger.debug(f'no further wire generation possible{e}')
# offset_possible = False
#
# # check if last circle is possible:
# # try:
# # last_wire = reference_face.OuterWire.makeOffset2D(offset, join=1, openResult=False, intersection=False)
# # except Exception as e:
# # last_wire = None
# # logger.debug(f'no further wire generation possible{e}')
#
# last_wire = None
#
# # export_objects([*wires, last_wire], '/tmp/initial_wires2.FCStd')
#
# pipe_edges = []
#
# if (reference_face.Edges.__len__() - 1) >= (self.reference_edge_id + 1):
# start_edge_id = self.reference_edge_id + 1
# else:
# start_edge_id = 0
#
# # create inflow
# V1 = wires[0].Edges[start_edge_id].Vertex1.Point + tube_main_dir * 2 * self.tube_edge_distance
# V2 = wires[0].Edges[start_edge_id].Vertex1.Point + tube_main_dir * 1 * self.tube_edge_distance
# pipe_edges.append(FCPart.LineSegment(V1, V2).toShape())
#
# V1 = wires[0].Edges[start_edge_id].Vertex1.Point + tube_main_dir * 1 * self.tube_edge_distance
# V2 = wires[0].Edges[start_edge_id].Vertex1.Point
# pipe_edges.append(FCPart.LineSegment(V1, V2).toShape())
#
# # add edges except the start_edge
# pipe_edges.extend(wires[0].Edges[self.reference_edge_id + 1:])
# pipe_edges.extend(wires[0].Edges[0:self.reference_edge_id:])
#
# # modify reference_edge_id edge
# p1 = wires[0].Edges[self.reference_edge_id].Vertex1.Point
# p2 = wires[0].Edges[self.reference_edge_id].Vertex2.Point
# v1 = p1
# v2 = p2 - 2 * (p2 - p1).normalize() * self.tube_distance
# pipe_edges.append(FCPart.LineSegment(v1, v2).toShape())
#
# # export_objects(pipe_edges, '/tmp/pipe_edges7.FCStd')
# # export_wire([self.reference_face.OuterWire, *pipe_edges])
# # export_objects(wires, '/tmp/wires.FCStd')
#
# i = 1
# while i <= (wires.__len__() - 1):
# # create connection from previous wire to current wire:
# dir1 = (wires[i].Edges[start_edge_id].Vertex1.Point - pipe_edges[-1].Vertex2.Point).normalize()
# dir2 = (wires[i].Edges[start_edge_id].Vertexes[1].Point - pipe_edges[-1].Vertex2.Point).normalize()
#
# if sum(abs(abs(dir1) - abs(dir2))) < 1e-10:
# # export_objects([wires[i].Edges[start_edge_id]], '/tmp/pipe_edges6.FCStd')
# pipe_edges.append(FCPart.LineSegment(pipe_edges[-1].Vertex2.Point,
# wires[i].Edges[start_edge_id].Vertexes[0].Point).toShape())
# pipe_edges.append(wires[i].Edges[start_edge_id])
# # pipe_edges.append(FCPart.LineSegment(pipe_edges[-1].Vertex2.Point,
# # wires[i].Edges[start_edge_id].Vertexes[1].Point).toShape())
# else:
# projected_point = FreeCAD.Base.Vector(
# project_point_on_line(point=wires[i].Edges[start_edge_id].Vertex1.Point, line=pipe_edges[-1]))
#
# # change_previous end edge:
# pipe_edges[-1] = FCPart.LineSegment(pipe_edges[-1].Vertex1.Point, projected_point).toShape()
#
# pipe_edges.append(FCPart.LineSegment(wires[i].Edges[start_edge_id].Vertex1.Point,
# projected_point).toShape())
# pipe_edges.append(wires[i].Edges[start_edge_id])
#
# # #pipe_edges.append(FCPart.LineSegment(v1, v2).toShape())
# #
# # pipe_edges.append(FCPart.LineSegment(pipe_edges[-1].Vertex2.Point,
# # wires[i].Edges[start_edge_id].Vertexes[1].Point).toShape())
#
# # add other edges except start_edge
# pipe_edges.extend(wires[i].Edges[self.reference_edge_id + 2:])
# pipe_edges.extend(wires[i].Edges[0:self.reference_edge_id:])
#
# # modify reference_edge_id edge
# p1 = wires[i].Edges[self.reference_edge_id].Vertex1.Point
# p2 = wires[i].Edges[self.reference_edge_id].Vertex2.Point
# v1 = p1
# v2 = p2 - 2 * (p2 - p1).normalize() * self.tube_distance
# pipe_edges.append(FCPart.LineSegment(v1, v2).toShape())
#
# i = i + 1
#
# # export_objects(pipe_edges, '/tmp/all_edges_io4.FCStd')
# # export_objects(wire_out_edges, '/tmp/all_edges_io2.FCStd')
# # export_objects([wire_in], '/tmp/wire_in.FCStd')
# # export_objects([wire_out], '/tmp/wire_out9.FCStd')
# # export_objects([last_wire], '/tmp/last_wire.FCStd')
# # export_objects([wire_in, wire_out], '/tmp/wires.FCStd')
#
# # create
# succeeded = False
# while not succeeded:
# wire_in = FCPart.Wire(pipe_edges)
# wire_out = wire_in.makeOffset2D(-self.tube_distance,
# join=0,
# openResult=True,
# intersection=True,
# fill=False)
# # wire_in.distToShape(wire_out)
#
# if last_wire is not None:
# wire_in_edges = pipe_edges
#
# dir1 = (last_wire.Edges[start_edge_id].Vertex1.Point - pipe_edges[-1].Vertex2.Point).normalize()
# dir2 = (last_wire.Edges[start_edge_id].Vertexes[1].Point - pipe_edges[-1].Vertex2.Point).normalize()
#
# if sum(abs(abs(dir1) - abs(dir2))) < 1e-10:
# wire_in_edges.append(FCPart.LineSegment(wire_in_edges[-1].Vertex2.Point,
# last_wire.Edges[start_edge_id].Vertexes[1].Point).toShape())
# else:
# projected_point = FreeCAD.Base.Vector(
# project_point_on_line(point=last_wire.Edges[start_edge_id].Vertex1.Point, line=wire_in_edges[-1]))
#
# # change_previous end edge:
# wire_in_edges[-1] = FCPart.LineSegment(wire_in_edges[-1].Vertex1.Point, projected_point).toShape()
#
# wire_in_edges.append(FCPart.LineSegment(last_wire.Edges[start_edge_id].Vertex1.Point,
# projected_point).toShape())
# wire_in_edges.append(wires[i].Edges[start_edge_id])
#
# last_wire_edges = last_wire.Edges
# start_edge = last_wire.Edges[start_edge_id - 1]
# # del last_wire_edges[start_edge_id - 1]
# # del last_wire_edges[start_edge_id - 1]
# last_wire_edges.append(start_edge.split(start_edge.LastParameter - self.tube_distance).SubShapes[0])
# # wire_in_edges.extend(last_wire_edges)
# wire_in_edges.extend(last_wire_edges[self.reference_edge_id + 1:])
# wire_in_edges.extend(last_wire_edges[0:self.reference_edge_id:])
# wire_in = FCPart.Wire(wire_in_edges)
#
# # cut last wire out edge:
# wire_out_edges = wire_out.Edges
# wire_out_edges[-1] = wire_out_edges[-1].split(wire_out_edges[-1].LastParameter -
# self.tube_distance).SubShapes[0]
#
# wire_out = FCPart.Wire(wire_out_edges)
#
# # create connection between wire_in and wire_out:
# v1 = wire_in.Edges[-1].Vertex2.Point
# v2 = wire_out.Edges[-1].Vertex2.Point
# connection_edge = FCPart.LineSegment(v1, v2).toShape()
#
# edges_out = wire_out.Edges
# edges_out.reverse()
#
# all_edges = [*wire_in.Edges, connection_edge, *edges_out]
#
# try:
# FCPart.Wire(all_edges, intersection=False)
# succeeded = True
# except Exception as e:
# succeeded = False
# del pipe_edges[-1]
#
# if self.bending_radius is not None:
# all_edges = add_radius_to_edges(FCPart.Wire(all_edges).OrderedEdges, self.bending_radius)
#
# pipe_wire = FCPart.Wire(all_edges)
#
# pipe_wire.Placement.move(
# self.reference_face.layer_dir * normal * (- self.reference_face.component_construction.side_1_offset + self.reference_face.tube_side_1_offset))
#
# pipe_wire.Edges[0].reverse()
#
# return FCPart.Wire(pipe_wire.OrderedEdges)
def generate_solid(self):
logger.info(f'Creating solid for pipe {self.name} {self.id}')
hull = self.reference_face.plain_reference_face_solid.assembly.hull
pipe_shape = create_pipe(self.pipe_wire.Edges, self.tube_inner_diameter, self.reference_face.normal)
initial_tube_wall = create_pipe(self.pipe_wire.Edges, self.tube_diameter, self.reference_face.normal)
tube_wall = initial_tube_wall.cut(pipe_shape).common(hull.fc_solid.Shape)
# export_objects([tube_wall, pipe_shape], '/tmp/tube_wall.FCStd')
inlet_outlet = hull.fc_solid.Shape.Shells[0].common(pipe_shape)
if inlet_outlet.SubShapes.__len__() == 2:
inlet = Face(fc_face=inlet_outlet.SubShapes[0].removeSplitter(),
name='Pipe_Inlet')
outlet = Face(fc_face=inlet_outlet.SubShapes[1].removeSplitter(),
name='Pipe_Outlet')
else:
raise Exception('can not identify inlet and outlet')
pipe_faces = BOPTools.SplitAPI.slice(pipe_shape.Shells[0], hull.fc_solid.Shape.Shells, "Split",
1e-3)
faces = [*inlet.fc_face.Faces, *outlet.fc_face.Faces, *pipe_faces.Faces]
shell = FCPart.makeShell(faces)
shell.sewShape()
shell.fix(1e-3, 1e-3, 1e-3)
pipe = FCPart.Solid(shell)
layer_pipe_interfaces = []
logger.info(f'Updating layer solids reference face {self.reference_face.name} {self.reference_face.id}')
for i, solid in enumerate(self.reference_face.assembly.solids):
logger.info(f'Updating layer solid {i+1} of {self.reference_face.assembly.solids.__len__()}: '
f'{solid.name} {solid.id}')
common = solid.fc_solid.Shape.common(initial_tube_wall)
if common.Faces:
new_faces = []
for face in solid.faces:
new_face = Face(fc_face=face.fc_face.cut(initial_tube_wall))
new_faces.append(new_face)
solid.update_face(face, new_face)
solid.generate_solid_from_faces()
# export_objects([solid.fc_solid.Shape], '/tmp/solid.FCStd')
# export_objects([common], '/tmp/common.FCStd')
pipe_interface = Face(fc_face=solid.fc_solid.Shape.common(initial_tube_wall).Shells[0],
name=f'Pipe interface',
linear_deflection=0.5,
angular_deflection=0.5)
layer_pipe_interfaces.append(pipe_interface)
solid.faces.append(pipe_interface)
solid.interfaces.append(pipe_interface)
solid.generate_solid_from_faces()
solid.features['pipe_faces'] = pipe_interface
# generate pipe solid
pipe_solid = Solid(faces=[inlet, outlet, *[Face(fc_face=x) for x in pipe_faces.Faces]],
name='PipeSolid')
pipe_solid.generate_solid_from_faces()
pipe_wall_solid = Solid(faces=[Face(fc_face=x) for x in tube_wall.Solids[0].Faces],
name='PipeWallSolid')
pipe_wall_solid.generate_solid_from_faces()
export_objects(tube_wall, '/tmp/pipe_wall_solid.FCStd')
export_objects(pipe_solid.fc_solid.Shape, '/tmp/pipe_solid.FCStd')
pipe_solid.features['inlet'] = inlet
pipe_solid.features['outlet'] = outlet
pipe_solid.features['layer_interfaces'] = layer_pipe_interfaces
pipe_solid.interfaces = layer_pipe_interfaces
logger.info(f'Updating assembly of reference face {self.reference_face.name} {self.reference_face.id}')
self.reference_face.assembly.solids.append(pipe_solid)
self.reference_face.assembly.solids.append(pipe_wall_solid)
self.reference_face.assembly.features['pipe'] = pipe_solid
self.reference_face.assembly.features['pipe_wall_solid'] = pipe_wall_solid
self.reference_face.assembly.faces.extend([inlet, outlet, *layer_pipe_interfaces])
self.reference_face.assembly.interfaces.extend(layer_pipe_interfaces)
logger.info(f'Successfully created solid for pipe {self.name} {self.id}')
return pipe_solid
def export_tube_wire(self, filename):
__objs__ = [self.pipe_wire]
try:
FCPart.export(__objs__, filename)
except Exception as e:
print(e)
raise e
def print_info(self):
print(f'\nPipe info:\n'
f'----------------------------------\n\n'
f'Tube diameter: {self.tube_diameter} mm\n'
f'Distance between tubes: {self.tube_distance} mm\n'
f'Bending radius: {self.bending_radius} mm\n'
f'Tube length: {self.pipe_length / 1000} m\n\n')
def __repr__(self):
rep = f'Solid {self.name} {self.id}'
return rep
| import os
import sys
import uuid
import tempfile
import time
from io import StringIO
import re
import numpy as np
import trimesh
from pyobb.obb import OBB
from scipy.spatial import ConvexHull
from .meshing.surface_mesh_parameters import default_surface_mesh_parameter
from .face import Face
from .tools import export_objects, add_radius_to_edges, vector_to_np_array, perpendicular_vector, extrude, create_pipe, create_pipe_wire, add_radius_to_edges
from .logger import logger
import FreeCAD
import Part as FCPart
import BOPTools.SplitAPI
from FreeCAD import Base
from Draft import make_fillet
from Arch import makePipe
import Arch
App = FreeCAD
class Solid(object):
def __init__(self, *args, **kwargs):
self.id = kwargs.get('id', uuid.uuid4())
self.type = kwargs.get('type', None)
# logger.debug(f'initializing solid {self.id}')
self.name = kwargs.get('name', None)
self.normal = kwargs.get('normal', None)
self._fc_solid = kwargs.get('fc_solid', None)
self._faces = kwargs.get('faces', kwargs.get('_faces', None))
self.interfaces = kwargs.get('interfaces', [])
self.features = kwargs.get('features', {})
self.surface_mesh_setup = kwargs.get('_surface_mesh_setup',
kwargs.get('surface_mesh_setup', default_surface_mesh_parameter))
self.layer = kwargs.get('layer', None)
self.state = kwargs.get('state', 'solid')
self._obb = kwargs.get('obb', None)
@property
def obb(self):
if self._obb is None:
self.calc_obb()
return self._obb
@property
def txt_id(self):
return re.sub('\W+','', 'a' + str(self.id))
@property
def faces(self):
if self._faces is None:
if self._fc_solid is not None:
self._faces = [Face(fc_face=x) for x in self._fc_solid.Shape.Faces]
else:
self._faces = []
return self._faces
@faces.setter
def faces(self, value):
self._faces = value
self.generate_solid_from_faces()
@property
def fc_solid(self):
if self._fc_solid is None:
self.generate_solid_from_faces()
return self._fc_solid
@fc_solid.setter
def fc_solid(self, value):
self._fc_solid = value
@property
def Volume(self):
return self.fc_solid.Shape.Volume
@property
def stl(self):
return ''.join([x.stl for x in self.faces])
@property
def face_names(self):
return [str(x.id) for x in self.faces]
def update_face(self, face, new_face):
face.fc_face = new_face.fc_face
face.normal = None
# if new_face.name is None:
# new_face.name = face.name
#
# if face in self.faces:
# offset = self.faces.index(face, 0)
# self.faces[offset] = new_face
#
# if face in self.interfaces:
# offset = self.interfaces.index(face, 0)
# self.interfaces[offset] = new_face
#
# for key in self.features.keys():
# feature_faces = self.features[key]
# if face in feature_faces:
# offset = feature_faces.index(face, 0)
# feature_faces[offset] = new_face
def export_stl(self, filename):
try:
logger.debug(f'exporting .stl for solid {self.id}')
new_file = open(filename, 'w')
new_file.writelines(self.stl)
new_file.close()
logger.debug(f' finished exporting .stl for solid {self.id}')
except Exception as e:
logger.error(f'error while exporting .stl for solid {self.id}: {e}')
def export_step(self, filename):
logger.debug(f'exporting .stp for solid {self.id}')
path = os.path.dirname(filename)
os.makedirs(path, exist_ok=True)
try:
from .tools import name_step_faces
__objs__ = [self.fc_solid]
fd, tmp_file = tempfile.mkstemp(suffix='.stp')
os.close(fd)
FCPart.export(__objs__, tmp_file)
names = self.face_names
names_dict = {k: v for k, v in zip(range(names.__len__()), names)}
name_step_faces(fname=tmp_file, name=names_dict, new_fname=filename)
except Exception as e:
logger.error(f'error while exporting .stp for solid {self.id}:\n{e}')
finally:
try:
os.remove(tmp_file)
except FileNotFoundError as e:
pass
logger.debug(f' finished exporting .stp for solid {self.id}')
def generate_solid_from_faces(self):
# logger.debug(f'generating solid from faces: {self.id}')
start_time = time.time()
faces = []
[faces.extend(x.fc_face.Faces) for x in self.faces]
shell = FCPart.makeShell(faces)
shell.sewShape()
shell.fix(1e-7, 1e-7, 1e-7)
solid = FCPart.Solid(shell)
if not solid.isClosed():
logger.error(f'Solid {self.id}: solid is not closed')
# doc_start_time = time.time()
doc = App.newDocument()
__o__ = doc.addObject("Part::Feature", f'{str(self.id)}')
__o__.Label = f'{str(self.id)}'
__o__.Shape = solid
# logger.debug(f' doc time: {time.time() - doc_start_time} s')
self.fc_solid = __o__
# logger.debug(f' finished generation of solid from faces: {self.id} in {time.time() - start_time} s')
return self.fc_solid
def generate_faces_from_solid(self, solid):
pass
def write_of_geo(self, directory):
stl_str = ''.join([x.create_stl_str(of=True) for x in set(self.faces) - set(self.interfaces)])
new_file = open(os.path.join(directory, str(self.txt_id) + '.stl'), 'w')
new_file.writelines(stl_str)
new_file.close()
for interface in self.interfaces:
interface_path = os.path.join(directory, str(interface.txt_id) + '.stl')
if not os.path.exists(interface_path):
new_file = open(interface_path, 'w')
new_file.writelines(interface.create_stl_str(of=True))
new_file.close()
@property
def shm_geo_entry(self, offset=0):
local_offset = 4
offset = offset + local_offset
solid_faces = set(self.faces) - set(self.interfaces)
buf = StringIO()
buf.write(f"{' ' * offset}{str(self.txt_id)}\n")
buf.write(f"{' ' * offset}{'{'}\n")
buf.write(f"{' ' * (offset + 4)}type triSurfaceMesh;\n")
buf.write(f"{' ' * (offset + 4)}file \"{str(self.txt_id)}.stl\";\n")
buf.write(f"{' ' * (offset + 4)}regions\n")
buf.write(f"{' ' * (offset + 4)}{'{'}\n")
for face in solid_faces:
buf.write(f"{' ' * (offset + 8)}{str(face.txt_id)}\t{'{'} name {str(face.txt_id)};\t{'}'}\n")
buf.write(f"{' ' * (offset + 4)}{'}'}\n")
buf.write(f"{' ' * offset}{'}'}\n")
return buf.getvalue()
@property
def shm_refinement_entry(self, offset=0):
local_offset = 4
offset = offset + local_offset
hull_faces = set(self.faces) - set(self.interfaces)
buf = StringIO()
buf.write(f"{' ' * offset}{str(self.txt_id)}\n")
buf.write(f"{' ' * offset}{'{'}\n")
buf.write(f"{' ' * (offset + 4)}level ({self.surface_mesh_setup.min_refinement_level} {self.surface_mesh_setup.max_refinement_level});\n")
buf.write(f"{' ' * (offset + 4)}regions\n")
buf.write(f"{' ' * (offset + 4)}{'{'}\n")
for face in hull_faces:
face_level = f"({face.surface_mesh_setup.min_refinement_level} {face.surface_mesh_setup.max_refinement_level})"
buf.write(f"{' ' * (offset + 8)}{str(face.txt_id)} {'{'} level {face_level}; patchInfo {'{'} type patch; {'}'} {'}'}\n")
buf.write(f"{' ' * (offset + 4)}{'}'}\n")
buf.write(f"{' ' * offset}{'}'}\n")
return buf.getvalue()
@property
def point_in_mesh(self):
if self.fc_solid is None:
return None
solid = self.fc_solid.Shape
b_box = self.fc_solid.Shape.BoundBox
location_in_mesh = np.array([b_box.Center.x + np.random.uniform(-0.1 + 0.1),
b_box.Center.y + np.random.uniform(-0.1 + 0.1),
b_box.Center.z + np.random.uniform(-0.1 + 0.1)])
if solid.isInside(Base.Vector(location_in_mesh), 0, True):
return location_in_mesh
else:
while not solid.isInside(Base.Vector(location_in_mesh), 0, True):
location_in_mesh = np.array([np.random.uniform(b_box.XMin, b_box.XMax),
np.random.uniform(b_box.YMin, b_box.YMax),
np.random.uniform(b_box.ZMin, b_box.ZMax)])
return location_in_mesh
def calc_obb(self):
pts = np.stack([np.array([x.X, x.Y, x.Z]) for x in self.fc_solid.Shape.Vertexes], axis=0)
hull = ConvexHull(pts)
hullpts = [pts[i] for i in hull.vertices]
obb = OBB.build_from_points(hullpts)
obbvec = [FreeCAD.Vector(p)for p in obb.points]
faces = []
idx = [[0, 1, 2, 3, 0],
[4, 5, 6, 7, 4],
[0, 1, 4, 5, 0],
[2, 3, 6, 7, 2],
[1, 2, 7, 4, 1],
[0, 5, 6, 3, 0]]
for ix in idx:
wire = FCPart.makePolygon([obbvec[i] for i in ix])
faces.append(FCPart.Face(wire))
shell = FCPart.makeShell(faces)
FCPart.show(shell)
p = trimesh.points.PointCloud(pts)
self._obb = p.bounding_box_oriented
return self._obb
def save_fcstd(self, filename, shape_type='solid'):
"""
save as freecad document
:param filename: full filename; example: '/tmp/test.FCStd'
:param shape_type: 'solid', 'faces'
"""
doc = App.newDocument(f"Solid {self.name}")
if shape_type == 'solid':
__o__ = doc.addObject("Part::Feature", f'Solid {self.name} {self.id}')
__o__.Shape = self.fc_solid.Shape
elif shape_type == 'face':
for face in self.faces:
__o__ = doc.addObject("Part::Face", f'Face {face.name} {face.id}')
__o__.Shape = face.fc_solid.Shape
doc.recompute()
doc.saveCopy(filename)
def is_inside(self, vec: Base.Vector):
return self.fc_solid.Shape.isInside(vec, 0, True)
def __repr__(self):
rep = f'Solid {self.name} {self.id} {self.Volume}'
return rep
class PipeSolid(Solid):
def __init__(self, *args, **kwargs):
self.id = kwargs.get('id', uuid.uuid4())
self.name = kwargs.get('name', None)
self.reference_face = kwargs.get('reference_face', None)
self.reference_edge_id = kwargs.get('reference_edge_id', 0)
self.tube_diameter = kwargs.get('tube_diameter', 0.02)
self.tube_inner_diameter = kwargs.get('tube_inner_diameter', 0.016)
self.tube_distance = kwargs.get('tube_distance', 0.50)
self.tube_side_1_offset = kwargs.get('tube_side_1_offset', 0.085)
self.tube_edge_distance = kwargs.get('tube_edge_distance', 0.50)
self.bending_radius = kwargs.get('bending_radius', 0.05)
self.reference_edge = None
self._initial_pipe_wire = None # pipe wire without radius
self._pipe_wire = None # pipe wire with radius
self._horizontal_lines = None
try:
pipe = self.generate_solid()
kwargs['fc_solid'] = pipe.fc_solid
kwargs['faces'] = pipe.faces
kwargs['interfaces'] = pipe.interfaces
kwargs['features'] = pipe.features
kwargs['type'] = 'pipe'
except Exception as e:
logger.error(f'Error generating pipe solid for {self.name} {self.id}')
Solid.__init__(self, *args, **kwargs)
@property
def initial_pipe_wire(self):
if self._initial_pipe_wire is None:
self._initial_pipe_wire, _ = self.generate_initial_pipe_wire()
return self._initial_pipe_wire
@property
def pipe_wire(self):
if self._pipe_wire is None:
self.pipe_wire = self.generate_pipe_wire()
return self._pipe_wire
@pipe_wire.setter
def pipe_wire(self, value):
self._pipe_wire = value
@property
def pipe_length(self):
return self.pipe_wire.Length
def generate_initial_pipe_wire(self):
pipe_wire, self._horizontal_lines = create_pipe_wire(self.reference_face.reference_face,
self.reference_edge_id,
self.tube_distance,
self.tube_edge_distance,
self.bending_radius,
self.tube_diameter
)
reference_face = self.reference_face.reference_face
self.reference_edge = reference_face.Edges[self.reference_edge_id]
normal = self.reference_face.get_normal(Base.Vector(self.reference_edge.Vertexes[0].X,
self.reference_edge.Vertexes[0].Y,
self.reference_edge.Vertexes[0].Z))
pipe_wire.Placement.move(self.reference_face.layer_dir * normal *
(- self.reference_face.component_construction.side_1_offset +
self.reference_face.tube_side_1_offset))
return pipe_wire, self._horizontal_lines
def generate_pipe_wire(self):
return add_radius_to_edges(self.initial_pipe_wire, self.bending_radius)
# from .tools import project_point_on_line
#
# reference_face = self.reference_face.reference_face
#
# self.reference_edge = reference_face.Edges[self.reference_edge_id]
# normal = self.reference_face.get_normal(Base.Vector(self.reference_edge.Vertexes[0].X,
# self.reference_edge.Vertexes[0].Y,
# self.reference_edge.Vertexes[0].Z))
# tube_main_dir = self.reference_edge.Curve.Direction.cross(normal)
#
# offset = -self.tube_edge_distance
# wires = []
# offset_possible = True
#
# while offset_possible:
# try:
# wire = reference_face.OuterWire.makeOffset2D(offset, join=1, openResult=False, intersection=False)
#
# # check if another is possible (return wire)
# try:
# reference_face.OuterWire.makeOffset2D(offset - self.tube_distance, join=1, openResult=False,
# intersection=False)
# wires.append(wire)
# offset = offset - 2 * self.tube_distance
# except Exception as e:
# logger.debug(f'no further wire generation possible{e}')
# offset_possible = False
# except Exception as e:
# logger.debug(f'no further wire generation possible{e}')
# offset_possible = False
#
# # check if last circle is possible:
# # try:
# # last_wire = reference_face.OuterWire.makeOffset2D(offset, join=1, openResult=False, intersection=False)
# # except Exception as e:
# # last_wire = None
# # logger.debug(f'no further wire generation possible{e}')
#
# last_wire = None
#
# # export_objects([*wires, last_wire], '/tmp/initial_wires2.FCStd')
#
# pipe_edges = []
#
# if (reference_face.Edges.__len__() - 1) >= (self.reference_edge_id + 1):
# start_edge_id = self.reference_edge_id + 1
# else:
# start_edge_id = 0
#
# # create inflow
# V1 = wires[0].Edges[start_edge_id].Vertex1.Point + tube_main_dir * 2 * self.tube_edge_distance
# V2 = wires[0].Edges[start_edge_id].Vertex1.Point + tube_main_dir * 1 * self.tube_edge_distance
# pipe_edges.append(FCPart.LineSegment(V1, V2).toShape())
#
# V1 = wires[0].Edges[start_edge_id].Vertex1.Point + tube_main_dir * 1 * self.tube_edge_distance
# V2 = wires[0].Edges[start_edge_id].Vertex1.Point
# pipe_edges.append(FCPart.LineSegment(V1, V2).toShape())
#
# # add edges except the start_edge
# pipe_edges.extend(wires[0].Edges[self.reference_edge_id + 1:])
# pipe_edges.extend(wires[0].Edges[0:self.reference_edge_id:])
#
# # modify reference_edge_id edge
# p1 = wires[0].Edges[self.reference_edge_id].Vertex1.Point
# p2 = wires[0].Edges[self.reference_edge_id].Vertex2.Point
# v1 = p1
# v2 = p2 - 2 * (p2 - p1).normalize() * self.tube_distance
# pipe_edges.append(FCPart.LineSegment(v1, v2).toShape())
#
# # export_objects(pipe_edges, '/tmp/pipe_edges7.FCStd')
# # export_wire([self.reference_face.OuterWire, *pipe_edges])
# # export_objects(wires, '/tmp/wires.FCStd')
#
# i = 1
# while i <= (wires.__len__() - 1):
# # create connection from previous wire to current wire:
# dir1 = (wires[i].Edges[start_edge_id].Vertex1.Point - pipe_edges[-1].Vertex2.Point).normalize()
# dir2 = (wires[i].Edges[start_edge_id].Vertexes[1].Point - pipe_edges[-1].Vertex2.Point).normalize()
#
# if sum(abs(abs(dir1) - abs(dir2))) < 1e-10:
# # export_objects([wires[i].Edges[start_edge_id]], '/tmp/pipe_edges6.FCStd')
# pipe_edges.append(FCPart.LineSegment(pipe_edges[-1].Vertex2.Point,
# wires[i].Edges[start_edge_id].Vertexes[0].Point).toShape())
# pipe_edges.append(wires[i].Edges[start_edge_id])
# # pipe_edges.append(FCPart.LineSegment(pipe_edges[-1].Vertex2.Point,
# # wires[i].Edges[start_edge_id].Vertexes[1].Point).toShape())
# else:
# projected_point = FreeCAD.Base.Vector(
# project_point_on_line(point=wires[i].Edges[start_edge_id].Vertex1.Point, line=pipe_edges[-1]))
#
# # change_previous end edge:
# pipe_edges[-1] = FCPart.LineSegment(pipe_edges[-1].Vertex1.Point, projected_point).toShape()
#
# pipe_edges.append(FCPart.LineSegment(wires[i].Edges[start_edge_id].Vertex1.Point,
# projected_point).toShape())
# pipe_edges.append(wires[i].Edges[start_edge_id])
#
# # #pipe_edges.append(FCPart.LineSegment(v1, v2).toShape())
# #
# # pipe_edges.append(FCPart.LineSegment(pipe_edges[-1].Vertex2.Point,
# # wires[i].Edges[start_edge_id].Vertexes[1].Point).toShape())
#
# # add other edges except start_edge
# pipe_edges.extend(wires[i].Edges[self.reference_edge_id + 2:])
# pipe_edges.extend(wires[i].Edges[0:self.reference_edge_id:])
#
# # modify reference_edge_id edge
# p1 = wires[i].Edges[self.reference_edge_id].Vertex1.Point
# p2 = wires[i].Edges[self.reference_edge_id].Vertex2.Point
# v1 = p1
# v2 = p2 - 2 * (p2 - p1).normalize() * self.tube_distance
# pipe_edges.append(FCPart.LineSegment(v1, v2).toShape())
#
# i = i + 1
#
# # export_objects(pipe_edges, '/tmp/all_edges_io4.FCStd')
# # export_objects(wire_out_edges, '/tmp/all_edges_io2.FCStd')
# # export_objects([wire_in], '/tmp/wire_in.FCStd')
# # export_objects([wire_out], '/tmp/wire_out9.FCStd')
# # export_objects([last_wire], '/tmp/last_wire.FCStd')
# # export_objects([wire_in, wire_out], '/tmp/wires.FCStd')
#
# # create
# succeeded = False
# while not succeeded:
# wire_in = FCPart.Wire(pipe_edges)
# wire_out = wire_in.makeOffset2D(-self.tube_distance,
# join=0,
# openResult=True,
# intersection=True,
# fill=False)
# # wire_in.distToShape(wire_out)
#
# if last_wire is not None:
# wire_in_edges = pipe_edges
#
# dir1 = (last_wire.Edges[start_edge_id].Vertex1.Point - pipe_edges[-1].Vertex2.Point).normalize()
# dir2 = (last_wire.Edges[start_edge_id].Vertexes[1].Point - pipe_edges[-1].Vertex2.Point).normalize()
#
# if sum(abs(abs(dir1) - abs(dir2))) < 1e-10:
# wire_in_edges.append(FCPart.LineSegment(wire_in_edges[-1].Vertex2.Point,
# last_wire.Edges[start_edge_id].Vertexes[1].Point).toShape())
# else:
# projected_point = FreeCAD.Base.Vector(
# project_point_on_line(point=last_wire.Edges[start_edge_id].Vertex1.Point, line=wire_in_edges[-1]))
#
# # change_previous end edge:
# wire_in_edges[-1] = FCPart.LineSegment(wire_in_edges[-1].Vertex1.Point, projected_point).toShape()
#
# wire_in_edges.append(FCPart.LineSegment(last_wire.Edges[start_edge_id].Vertex1.Point,
# projected_point).toShape())
# wire_in_edges.append(wires[i].Edges[start_edge_id])
#
# last_wire_edges = last_wire.Edges
# start_edge = last_wire.Edges[start_edge_id - 1]
# # del last_wire_edges[start_edge_id - 1]
# # del last_wire_edges[start_edge_id - 1]
# last_wire_edges.append(start_edge.split(start_edge.LastParameter - self.tube_distance).SubShapes[0])
# # wire_in_edges.extend(last_wire_edges)
# wire_in_edges.extend(last_wire_edges[self.reference_edge_id + 1:])
# wire_in_edges.extend(last_wire_edges[0:self.reference_edge_id:])
# wire_in = FCPart.Wire(wire_in_edges)
#
# # cut last wire out edge:
# wire_out_edges = wire_out.Edges
# wire_out_edges[-1] = wire_out_edges[-1].split(wire_out_edges[-1].LastParameter -
# self.tube_distance).SubShapes[0]
#
# wire_out = FCPart.Wire(wire_out_edges)
#
# # create connection between wire_in and wire_out:
# v1 = wire_in.Edges[-1].Vertex2.Point
# v2 = wire_out.Edges[-1].Vertex2.Point
# connection_edge = FCPart.LineSegment(v1, v2).toShape()
#
# edges_out = wire_out.Edges
# edges_out.reverse()
#
# all_edges = [*wire_in.Edges, connection_edge, *edges_out]
#
# try:
# FCPart.Wire(all_edges, intersection=False)
# succeeded = True
# except Exception as e:
# succeeded = False
# del pipe_edges[-1]
#
# if self.bending_radius is not None:
# all_edges = add_radius_to_edges(FCPart.Wire(all_edges).OrderedEdges, self.bending_radius)
#
# pipe_wire = FCPart.Wire(all_edges)
#
# pipe_wire.Placement.move(
# self.reference_face.layer_dir * normal * (- self.reference_face.component_construction.side_1_offset + self.reference_face.tube_side_1_offset))
#
# pipe_wire.Edges[0].reverse()
#
# return FCPart.Wire(pipe_wire.OrderedEdges)
def generate_solid(self):
logger.info(f'Creating solid for pipe {self.name} {self.id}')
hull = self.reference_face.plain_reference_face_solid.assembly.hull
pipe_shape = create_pipe(self.pipe_wire.Edges, self.tube_inner_diameter, self.reference_face.normal)
initial_tube_wall = create_pipe(self.pipe_wire.Edges, self.tube_diameter, self.reference_face.normal)
tube_wall = initial_tube_wall.cut(pipe_shape).common(hull.fc_solid.Shape)
# export_objects([tube_wall, pipe_shape], '/tmp/tube_wall.FCStd')
inlet_outlet = hull.fc_solid.Shape.Shells[0].common(pipe_shape)
if inlet_outlet.SubShapes.__len__() == 2:
inlet = Face(fc_face=inlet_outlet.SubShapes[0].removeSplitter(),
name='Pipe_Inlet')
outlet = Face(fc_face=inlet_outlet.SubShapes[1].removeSplitter(),
name='Pipe_Outlet')
else:
raise Exception('can not identify inlet and outlet')
pipe_faces = BOPTools.SplitAPI.slice(pipe_shape.Shells[0], hull.fc_solid.Shape.Shells, "Split",
1e-3)
faces = [*inlet.fc_face.Faces, *outlet.fc_face.Faces, *pipe_faces.Faces]
shell = FCPart.makeShell(faces)
shell.sewShape()
shell.fix(1e-3, 1e-3, 1e-3)
pipe = FCPart.Solid(shell)
layer_pipe_interfaces = []
logger.info(f'Updating layer solids reference face {self.reference_face.name} {self.reference_face.id}')
for i, solid in enumerate(self.reference_face.assembly.solids):
logger.info(f'Updating layer solid {i+1} of {self.reference_face.assembly.solids.__len__()}: '
f'{solid.name} {solid.id}')
common = solid.fc_solid.Shape.common(initial_tube_wall)
if common.Faces:
new_faces = []
for face in solid.faces:
new_face = Face(fc_face=face.fc_face.cut(initial_tube_wall))
new_faces.append(new_face)
solid.update_face(face, new_face)
solid.generate_solid_from_faces()
# export_objects([solid.fc_solid.Shape], '/tmp/solid.FCStd')
# export_objects([common], '/tmp/common.FCStd')
pipe_interface = Face(fc_face=solid.fc_solid.Shape.common(initial_tube_wall).Shells[0],
name=f'Pipe interface',
linear_deflection=0.5,
angular_deflection=0.5)
layer_pipe_interfaces.append(pipe_interface)
solid.faces.append(pipe_interface)
solid.interfaces.append(pipe_interface)
solid.generate_solid_from_faces()
solid.features['pipe_faces'] = pipe_interface
# generate pipe solid
pipe_solid = Solid(faces=[inlet, outlet, *[Face(fc_face=x) for x in pipe_faces.Faces]],
name='PipeSolid')
pipe_solid.generate_solid_from_faces()
pipe_wall_solid = Solid(faces=[Face(fc_face=x) for x in tube_wall.Solids[0].Faces],
name='PipeWallSolid')
pipe_wall_solid.generate_solid_from_faces()
export_objects(tube_wall, '/tmp/pipe_wall_solid.FCStd')
export_objects(pipe_solid.fc_solid.Shape, '/tmp/pipe_solid.FCStd')
pipe_solid.features['inlet'] = inlet
pipe_solid.features['outlet'] = outlet
pipe_solid.features['layer_interfaces'] = layer_pipe_interfaces
pipe_solid.interfaces = layer_pipe_interfaces
logger.info(f'Updating assembly of reference face {self.reference_face.name} {self.reference_face.id}')
self.reference_face.assembly.solids.append(pipe_solid)
self.reference_face.assembly.solids.append(pipe_wall_solid)
self.reference_face.assembly.features['pipe'] = pipe_solid
self.reference_face.assembly.features['pipe_wall_solid'] = pipe_wall_solid
self.reference_face.assembly.faces.extend([inlet, outlet, *layer_pipe_interfaces])
self.reference_face.assembly.interfaces.extend(layer_pipe_interfaces)
logger.info(f'Successfully created solid for pipe {self.name} {self.id}')
return pipe_solid
def export_tube_wire(self, filename):
__objs__ = [self.pipe_wire]
try:
FCPart.export(__objs__, filename)
except Exception as e:
print(e)
raise e
def print_info(self):
print(f'\nPipe info:\n'
f'----------------------------------\n\n'
f'Tube diameter: {self.tube_diameter} mm\n'
f'Distance between tubes: {self.tube_distance} mm\n'
f'Bending radius: {self.bending_radius} mm\n'
f'Tube length: {self.pipe_length / 1000} m\n\n')
def __repr__(self):
rep = f'Solid {self.name} {self.id}'
return rep
|
import bagel
import pathlib
def main():
bagel.utils.mkdirs(output_path)
file_list = bagel.utils.file_list(input_path)
for file in file_list:
kpi = bagel.utils.load_kpi(file)
print(f'KPI: {kpi.name}')
kpi.complete_timestamp()
train_kpi, valid_kpi, test_kpi = kpi.split((0.49, 0.21, 0.3))
train_kpi, mean, std = train_kpi.standardize()
valid_kpi, _, _ = valid_kpi.standardize(mean=mean, std=std)
test_kpi, _, _ = test_kpi.standardize(mean=mean, std=std)
model = bagel.Bagel()
model.fit(kpi=train_kpi.use_labels(0.), validation_kpi=valid_kpi, epochs=epochs, verbose=1)
anomaly_scores = model.predict(test_kpi)
results = bagel.testing.get_test_results(labels=test_kpi.labels,
scores=anomaly_scores,
missing=test_kpi.missing,
window_size=120)
stats = bagel.testing.get_kpi_stats(kpi, test_kpi)
print('Metrics')
print(f'precision: {results.get('precision'):.3f} - '
f'recall: {results.get('recall'):.3f} - '
f'f1score: {results.get('f1score'):.3f}\n')
with open(output_path.joinpath(f'{kpi.name}.txt'), 'w') as output:
output.write(f'kpi_name={kpi.name}\n\n'
'[result]\n'
f'threshold={results.get('threshold')}\n'
f'precision={results.get('precision'):.3f}\n'
f'recall={results.get('recall'):.3f}\n'
f'f1_score={results.get('f1score'):.3f}\n\n'
'[overall]\n'
f'num_points={stats[0].num_points}\n'
f'num_missing_points={stats[0].num_missing}\n'
f'missing_rate={stats[0].missing_rate:.6f}\n'
f'num_anomaly_points={stats[0].num_anomaly}\n'
f'anomaly_rate={stats[0].anomaly_rate:.6f}\n\n'
'[test]\n'
f'num_points={stats[1].num_points}\n'
f'num_missing_points={stats[1].num_missing}\n'
f'missing_rate={stats[1].missing_rate:.6f}\n'
f'num_anomaly_points={stats[1].num_anomaly}\n'
f'anomaly_rate={stats[1].anomaly_rate:.6f}\n')
if __name__ == '__main__':
epochs = 50
input_path = pathlib.Path('data')
output_path = pathlib.Path('out').joinpath('bagel')
main()
| import bagel
import pathlib
def main():
bagel.utils.mkdirs(output_path)
file_list = bagel.utils.file_list(input_path)
for file in file_list:
kpi = bagel.utils.load_kpi(file)
print(f'KPI: {kpi.name}')
kpi.complete_timestamp()
train_kpi, valid_kpi, test_kpi = kpi.split((0.49, 0.21, 0.3))
train_kpi, mean, std = train_kpi.standardize()
valid_kpi, _, _ = valid_kpi.standardize(mean=mean, std=std)
test_kpi, _, _ = test_kpi.standardize(mean=mean, std=std)
model = bagel.Bagel()
model.fit(kpi=train_kpi.use_labels(0.), validation_kpi=valid_kpi, epochs=epochs, verbose=1)
anomaly_scores = model.predict(test_kpi)
results = bagel.testing.get_test_results(labels=test_kpi.labels,
scores=anomaly_scores,
missing=test_kpi.missing,
window_size=120)
stats = bagel.testing.get_kpi_stats(kpi, test_kpi)
print('Metrics')
print(f'precision: {results.get("precision"):.3f} - '
f'recall: {results.get("recall"):.3f} - '
f'f1score: {results.get("f1score"):.3f}\n')
with open(output_path.joinpath(f'{kpi.name}.txt'), 'w') as output:
output.write(f'kpi_name={kpi.name}\n\n'
'[result]\n'
f'threshold={results.get("threshold")}\n'
f'precision={results.get("precision"):.3f}\n'
f'recall={results.get("recall"):.3f}\n'
f'f1_score={results.get("f1score"):.3f}\n\n'
'[overall]\n'
f'num_points={stats[0].num_points}\n'
f'num_missing_points={stats[0].num_missing}\n'
f'missing_rate={stats[0].missing_rate:.6f}\n'
f'num_anomaly_points={stats[0].num_anomaly}\n'
f'anomaly_rate={stats[0].anomaly_rate:.6f}\n\n'
'[test]\n'
f'num_points={stats[1].num_points}\n'
f'num_missing_points={stats[1].num_missing}\n'
f'missing_rate={stats[1].missing_rate:.6f}\n'
f'num_anomaly_points={stats[1].num_anomaly}\n'
f'anomaly_rate={stats[1].anomaly_rate:.6f}\n')
if __name__ == '__main__':
epochs = 50
input_path = pathlib.Path('data')
output_path = pathlib.Path('out').joinpath('bagel')
main()
|
#!/usr/bin/python3
import argparse, logging, os, sys, time
from utils.setup import *
from utils.dataset import DepSpaceDataset
def parse_arguments():
arg_parser = argparse.ArgumentParser(description='Probe Training')
arg_parser.add_argument('ud_path', help='path to Universal Dependencies directory')
arg_parser.add_argument('out_path', help='path to output directory')
# parser setup
arg_parser.add_argument(
'-lm', '--language_model', default='bert-base-multilingual-cased',
help='language model name in the transformers library (default: bert-base-multilingual-cased')
arg_parser.add_argument(
'-el', '--embedding_layers', nargs='+', type=int, default=[6, 7],
help='list of embedding layers (0: WordPiece -> 12: Layer 12, default: [6, 7])')
arg_parser.add_argument(
'-ec', '--embedding_cache',
help='path to pre-computed embedding cache or set to "local" for in-memory caching (default: None)')
arg_parser.add_argument(
'-ds', '--dependency_size', type=int, default=128,
help='dimensionality of dependency space transformation (default: 128)')
arg_parser.add_argument(
'-pt', '--parser_type', default='depprobe', choices=['structural', 'directed', 'depprobe'],
help='parser type (default: depprobe)')
arg_parser.add_argument(
'-pd', '--parser_decode', default=False, action='store_true',
help='set flag to decode parses during training (default: False)')
# experiment setup
arg_parser.add_argument(
'-s', '--split', help='path to data split definition pickle (default: None - full UD)')
arg_parser.add_argument(
'-e', '--epochs', type=int, default=100, help='maximum number of epochs (default: 100)')
arg_parser.add_argument(
'-es', '--early_stop', type=int, default=5, help='maximum number of epochs without improvement (default: 5)')
arg_parser.add_argument(
'-bs', '--batch_size', type=int, default=64, help='maximum number of sentences per batch (default: 64)')
arg_parser.add_argument(
'-lr', '--learning_rate', type=float, default=1e-3, help='learning rate (default: 1e-3)')
arg_parser.add_argument(
'-rs', '--seed', type=int, default=42, help='seed for probabilistic components (default: 42)')
return arg_parser.parse_args()
def main():
args = parse_arguments()
# check if output dir exists
setup_output_directory(args.out_path)
# setup logging
setup_logging(os.path.join(args.out_path, 'train.log'))
# set random seeds
np.random.seed(args.seed)
torch.random.manual_seed(args.seed)
transformers.set_seed(args.seed)
# setup UD data
ud, splits, rel_map = setup_data(args.ud_path, args.split)
train_data = DepSpaceDataset(ud, rel_map, splits['train'], args.batch_size)
eval_data = DepSpaceDataset(ud, rel_map, splits['dev'], args.batch_size)
# setup parser model
parser = setup_model(
lm_name=args.language_model, dep_dim=args.dependency_size,
parser_type=args.parser_type,
emb_layers=args.embedding_layers,
emb_cache=args.embedding_cache
)
# setup loss
criterion = setup_criterion(parser_type=args.parser_type)
# setup optimizer
optimizer = torch.optim.AdamW(params=parser.get_trainable_parameters(), lr=args.learning_rate)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=0)
logging.info(f"Optimizing using {optimizer.__class__.__name__} with learning rate {args.learning_rate}.")
logging.info(f"Scheduler {scheduler.__class__.__name__} reduces learning rate by 0.1 after 1 epoch without improvement.")
# main training loop
stats = defaultdict(list)
stats['time'].append(time.time())
for ep_idx in range(args.epochs):
# iterate over batches in training split
cur_stats = run(
parser, criterion, optimizer,
train_data, mode='train', decode=args.parser_decode
)
# store and print statistics
statistics('train', stats, cur_stats, ep_idx, args.epochs)
# iterate over batches in dev split
cur_stats = run(
parser, criterion, None,
eval_data, mode='eval', decode=True
)
stats['time'].append(time.time())
# store and print statistics
statistics('eval', stats, cur_stats, ep_idx, args.epochs)
cur_eval_loss = stats['eval/loss'][-1]
# save most recent model
path = os.path.join(args.out_path, 'newest.tar')
save_checkpoint(parser, optimizer, ep_idx, stats, path)
logging.info(f"Saved model from epoch {ep_idx + 1} to '{path}'.")
# save best model
if cur_eval_loss <= min(stats['eval/loss']):
path = os.path.join(args.out_path, 'best.tar')
save_checkpoint(parser, optimizer, ep_idx, stats, path)
logging.info(f"Saved model with best loss {cur_eval_loss:.4f} to '{path}'.")
# update scheduler
scheduler.step(cur_eval_loss)
# check for early stopping
if (ep_idx - stats['eval/loss'].index(min(stats['eval/loss']))) >= args.early_stop:
logging.info(f"No improvement since {args.early_stop} epochs ({min(stats["eval/loss"]):.4f} loss). Early stop.")
break
stats['time'].append(time.time())
logging.info(f"Training completed after {ep_idx + 1} epochs and {stats["time"][-1] - stats["time"][0]:.2f} seconds.")
logging.info(f"Total training time {sum(stats["train/time"]):.2f} seconds across {sum(stats["train/tokens"])} ({sum(stats["train/time"])/sum(stats["train/tokens"]):.2f} tokens/sec).")
if __name__ == '__main__':
main()
| #!/usr/bin/python3
import argparse, logging, os, sys, time
from utils.setup import *
from utils.dataset import DepSpaceDataset
def parse_arguments():
arg_parser = argparse.ArgumentParser(description='Probe Training')
arg_parser.add_argument('ud_path', help='path to Universal Dependencies directory')
arg_parser.add_argument('out_path', help='path to output directory')
# parser setup
arg_parser.add_argument(
'-lm', '--language_model', default='bert-base-multilingual-cased',
help='language model name in the transformers library (default: bert-base-multilingual-cased')
arg_parser.add_argument(
'-el', '--embedding_layers', nargs='+', type=int, default=[6, 7],
help='list of embedding layers (0: WordPiece -> 12: Layer 12, default: [6, 7])')
arg_parser.add_argument(
'-ec', '--embedding_cache',
help='path to pre-computed embedding cache or set to "local" for in-memory caching (default: None)')
arg_parser.add_argument(
'-ds', '--dependency_size', type=int, default=128,
help='dimensionality of dependency space transformation (default: 128)')
arg_parser.add_argument(
'-pt', '--parser_type', default='depprobe', choices=['structural', 'directed', 'depprobe'],
help='parser type (default: depprobe)')
arg_parser.add_argument(
'-pd', '--parser_decode', default=False, action='store_true',
help='set flag to decode parses during training (default: False)')
# experiment setup
arg_parser.add_argument(
'-s', '--split', help='path to data split definition pickle (default: None - full UD)')
arg_parser.add_argument(
'-e', '--epochs', type=int, default=100, help='maximum number of epochs (default: 100)')
arg_parser.add_argument(
'-es', '--early_stop', type=int, default=5, help='maximum number of epochs without improvement (default: 5)')
arg_parser.add_argument(
'-bs', '--batch_size', type=int, default=64, help='maximum number of sentences per batch (default: 64)')
arg_parser.add_argument(
'-lr', '--learning_rate', type=float, default=1e-3, help='learning rate (default: 1e-3)')
arg_parser.add_argument(
'-rs', '--seed', type=int, default=42, help='seed for probabilistic components (default: 42)')
return arg_parser.parse_args()
def main():
args = parse_arguments()
# check if output dir exists
setup_output_directory(args.out_path)
# setup logging
setup_logging(os.path.join(args.out_path, 'train.log'))
# set random seeds
np.random.seed(args.seed)
torch.random.manual_seed(args.seed)
transformers.set_seed(args.seed)
# setup UD data
ud, splits, rel_map = setup_data(args.ud_path, args.split)
train_data = DepSpaceDataset(ud, rel_map, splits['train'], args.batch_size)
eval_data = DepSpaceDataset(ud, rel_map, splits['dev'], args.batch_size)
# setup parser model
parser = setup_model(
lm_name=args.language_model, dep_dim=args.dependency_size,
parser_type=args.parser_type,
emb_layers=args.embedding_layers,
emb_cache=args.embedding_cache
)
# setup loss
criterion = setup_criterion(parser_type=args.parser_type)
# setup optimizer
optimizer = torch.optim.AdamW(params=parser.get_trainable_parameters(), lr=args.learning_rate)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=0)
logging.info(f"Optimizing using {optimizer.__class__.__name__} with learning rate {args.learning_rate}.")
logging.info(f"Scheduler {scheduler.__class__.__name__} reduces learning rate by 0.1 after 1 epoch without improvement.")
# main training loop
stats = defaultdict(list)
stats['time'].append(time.time())
for ep_idx in range(args.epochs):
# iterate over batches in training split
cur_stats = run(
parser, criterion, optimizer,
train_data, mode='train', decode=args.parser_decode
)
# store and print statistics
statistics('train', stats, cur_stats, ep_idx, args.epochs)
# iterate over batches in dev split
cur_stats = run(
parser, criterion, None,
eval_data, mode='eval', decode=True
)
stats['time'].append(time.time())
# store and print statistics
statistics('eval', stats, cur_stats, ep_idx, args.epochs)
cur_eval_loss = stats['eval/loss'][-1]
# save most recent model
path = os.path.join(args.out_path, 'newest.tar')
save_checkpoint(parser, optimizer, ep_idx, stats, path)
logging.info(f"Saved model from epoch {ep_idx + 1} to '{path}'.")
# save best model
if cur_eval_loss <= min(stats['eval/loss']):
path = os.path.join(args.out_path, 'best.tar')
save_checkpoint(parser, optimizer, ep_idx, stats, path)
logging.info(f"Saved model with best loss {cur_eval_loss:.4f} to '{path}'.")
# update scheduler
scheduler.step(cur_eval_loss)
# check for early stopping
if (ep_idx - stats['eval/loss'].index(min(stats['eval/loss']))) >= args.early_stop:
logging.info(f"No improvement since {args.early_stop} epochs ({min(stats['eval/loss']):.4f} loss). Early stop.")
break
stats['time'].append(time.time())
logging.info(f"Training completed after {ep_idx + 1} epochs and {stats['time'][-1] - stats['time'][0]:.2f} seconds.")
logging.info(f"Total training time {sum(stats['train/time']):.2f} seconds across {sum(stats['train/tokens'])} ({sum(stats['train/time'])/sum(stats['train/tokens']):.2f} tokens/sec).")
if __name__ == '__main__':
main()
|
from discord.ext import commands
import random as rng
from collections import Counter
from typing import Optional
from .utils.formats import plural
class RNG(commands.Cog):
"""Utilities that provide pseudo-RNG."""
def __init__(self, bot):
self.bot = bot
@commands.group(pass_context=True)
async def random(self, ctx):
"""Displays a random thing you request."""
if ctx.invoked_subcommand is None:
await ctx.send(f'Incorrect random subcommand passed. Try {ctx.prefix}help random')
@random.command()
async def weapon(self, ctx, count=1):
"""Displays a random Splatoon 2 weapon.
The count parameter is how many to generate. It cannot be
negative. If it's negative or zero then only one weapon will be
selected. The maximum number of random weapons generated is 8.
"""
splatoon = self.bot.get_cog('Splatoon')
if splatoon is None:
return await ctx.send('Splatoon commands currently disabled.')
count = min(max(count, 1), 8)
weapons = splatoon.splat2_data.get('weapons', [])
if weapons:
if count == 1:
weapon = rng.choice(weapons)
await ctx.send(f'{weapon['name']} with {weapon['sub']} and {weapon['special']} special.')
else:
sample = rng.sample(weapons, count)
await ctx.send('\n'.join(w['name'] for w in sample))
@random.command()
async def private(self, ctx):
"""Displays an all private Splatoon 2 match.
The map and mode is randomised along with both team's weapons.
"""
splatoon = self.bot.get_cog('Splatoon')
if splatoon is None:
return await ctx.send('Splatoon commands currently disabled.')
maps = splatoon.splat2_data.get('maps', [])
stage = rng.choice(maps) if maps else 'Random Stage'
modes = [ 'Turf War', 'Splat Zones', 'Rainmaker', 'Tower Control' ]
mode = rng.choice(modes)
result = [f'Playing {mode} on {stage}', '', '**Team Alpha**']
weapons = rng.sample(splatoon.splat2_data.get('weapons', []), 8)
for i in range(8):
if i == 4:
result.append('')
result.append('**Team Bravo**')
result.append(f'Player {i + 1}: {weapons[i]['name']}')
await ctx.send('\n'.join(result))
@random.command()
async def tag(self, ctx):
"""Displays a random tag.
A tag showing up in this does not get its usage count increased.
"""
tags = self.bot.get_cog('Tags')
if tags is None:
return await ctx.send('Tag commands currently disabled.')
tag = await tags.get_random_tag(ctx.guild, connection=ctx.db)
if tag is None:
return await ctx.send('This server has no tags.')
await ctx.send(f'Random tag found: {tag['name']}\n{tag['content']}')
@random.command(name='map')
async def _map(self, ctx):
"""Displays a random Splatoon 2 map."""
splatoon = self.bot.get_cog('Splatoon')
if splatoon is None:
await ctx.send('Splatoon commands currently disabled.')
return
maps = splatoon.splat2_data.get('maps', [])
if maps:
await ctx.send(rng.choice(maps))
del splatoon
@random.command()
async def mode(self, ctx):
"""Displays a random Splatoon mode."""
mode = rng.choice(['Turf War', 'Splat Zones', 'Clam Blitz', 'Rainmaker', 'Tower Control'])
await ctx.send(mode)
@random.command()
async def game(self, ctx):
"""Displays a random map/mode combination (no Turf War)"""
splatoon = self.bot.get_cog('Splatoon')
if splatoon is None:
await ctx.send('Splatoon commands currently disabled.')
return
maps = splatoon.splat2_data.get('maps', [])
if maps:
mode = rng.choice(['Splat Zones', 'Tower Control', 'Rainmaker'])
stage = rng.choice(maps)
await ctx.send(f'{mode} on {stage}')
del splatoon
@random.command()
async def number(self, ctx, minimum=0, maximum=100):
"""Displays a random number within an optional range.
The minimum must be smaller than the maximum and the maximum number
accepted is 1000.
"""
maximum = min(maximum, 1000)
if minimum >= maximum:
await ctx.send('Maximum is smaller than minimum.')
return
await ctx.send(rng.randint(minimum, maximum))
@random.command()
async def lenny(self, ctx):
"""Displays a random lenny face."""
lenny = rng.choice([
"( ͡° ͜ʖ ͡°)", "( ͠° ͟ʖ ͡°)", "ᕦ( ͡° ͜ʖ ͡°)ᕤ", "( ͡~ ͜ʖ ͡°)",
"( ͡o ͜ʖ ͡o)", "͡(° ͜ʖ ͡ -)", "( ͡͡ ° ͜ ʖ ͡ °)", "(ง ͠° ͟ل͜ ͡°)ง",
"ヽ༼ຈل͜ຈ༽ノ"
])
await ctx.send(lenny)
@commands.command()
async def choose(self, ctx, *choices: commands.clean_content):
"""Chooses between multiple choices.
To denote multiple choices, you should use double quotes.
"""
if len(choices) < 2:
return await ctx.send('Not enough choices to pick from.')
await ctx.send(rng.choice(choices))
@commands.command()
async def choosebestof(self, ctx, times: Optional[int], *choices: commands.clean_content):
"""Chooses between multiple choices N times.
To denote multiple choices, you should use double quotes.
You can only choose up to 10001 times and only the top 10 results are shown.
"""
if len(choices) < 2:
return await ctx.send('Not enough choices to pick from.')
if times is None:
times = (len(choices) ** 2) + 1
times = min(10001, max(1, times))
results = Counter(rng.choice(choices) for i in range(times))
builder = []
if len(results) > 10:
builder.append('Only showing top 10 results...')
for index, (elem, count) in enumerate(results.most_common(10), start=1):
builder.append(f'{index}. {elem} ({plural(count):time}, {count/times:.2%})')
await ctx.send('\n'.join(builder))
def setup(bot):
bot.add_cog(RNG(bot))
| from discord.ext import commands
import random as rng
from collections import Counter
from typing import Optional
from .utils.formats import plural
class RNG(commands.Cog):
"""Utilities that provide pseudo-RNG."""
def __init__(self, bot):
self.bot = bot
@commands.group(pass_context=True)
async def random(self, ctx):
"""Displays a random thing you request."""
if ctx.invoked_subcommand is None:
await ctx.send(f'Incorrect random subcommand passed. Try {ctx.prefix}help random')
@random.command()
async def weapon(self, ctx, count=1):
"""Displays a random Splatoon 2 weapon.
The count parameter is how many to generate. It cannot be
negative. If it's negative or zero then only one weapon will be
selected. The maximum number of random weapons generated is 8.
"""
splatoon = self.bot.get_cog('Splatoon')
if splatoon is None:
return await ctx.send('Splatoon commands currently disabled.')
count = min(max(count, 1), 8)
weapons = splatoon.splat2_data.get('weapons', [])
if weapons:
if count == 1:
weapon = rng.choice(weapons)
await ctx.send(f'{weapon["name"]} with {weapon["sub"]} and {weapon["special"]} special.')
else:
sample = rng.sample(weapons, count)
await ctx.send('\n'.join(w['name'] for w in sample))
@random.command()
async def private(self, ctx):
"""Displays an all private Splatoon 2 match.
The map and mode is randomised along with both team's weapons.
"""
splatoon = self.bot.get_cog('Splatoon')
if splatoon is None:
return await ctx.send('Splatoon commands currently disabled.')
maps = splatoon.splat2_data.get('maps', [])
stage = rng.choice(maps) if maps else 'Random Stage'
modes = [ 'Turf War', 'Splat Zones', 'Rainmaker', 'Tower Control' ]
mode = rng.choice(modes)
result = [f'Playing {mode} on {stage}', '', '**Team Alpha**']
weapons = rng.sample(splatoon.splat2_data.get('weapons', []), 8)
for i in range(8):
if i == 4:
result.append('')
result.append('**Team Bravo**')
result.append(f'Player {i + 1}: {weapons[i]["name"]}')
await ctx.send('\n'.join(result))
@random.command()
async def tag(self, ctx):
"""Displays a random tag.
A tag showing up in this does not get its usage count increased.
"""
tags = self.bot.get_cog('Tags')
if tags is None:
return await ctx.send('Tag commands currently disabled.')
tag = await tags.get_random_tag(ctx.guild, connection=ctx.db)
if tag is None:
return await ctx.send('This server has no tags.')
await ctx.send(f'Random tag found: {tag["name"]}\n{tag["content"]}')
@random.command(name='map')
async def _map(self, ctx):
"""Displays a random Splatoon 2 map."""
splatoon = self.bot.get_cog('Splatoon')
if splatoon is None:
await ctx.send('Splatoon commands currently disabled.')
return
maps = splatoon.splat2_data.get('maps', [])
if maps:
await ctx.send(rng.choice(maps))
del splatoon
@random.command()
async def mode(self, ctx):
"""Displays a random Splatoon mode."""
mode = rng.choice(['Turf War', 'Splat Zones', 'Clam Blitz', 'Rainmaker', 'Tower Control'])
await ctx.send(mode)
@random.command()
async def game(self, ctx):
"""Displays a random map/mode combination (no Turf War)"""
splatoon = self.bot.get_cog('Splatoon')
if splatoon is None:
await ctx.send('Splatoon commands currently disabled.')
return
maps = splatoon.splat2_data.get('maps', [])
if maps:
mode = rng.choice(['Splat Zones', 'Tower Control', 'Rainmaker'])
stage = rng.choice(maps)
await ctx.send(f'{mode} on {stage}')
del splatoon
@random.command()
async def number(self, ctx, minimum=0, maximum=100):
"""Displays a random number within an optional range.
The minimum must be smaller than the maximum and the maximum number
accepted is 1000.
"""
maximum = min(maximum, 1000)
if minimum >= maximum:
await ctx.send('Maximum is smaller than minimum.')
return
await ctx.send(rng.randint(minimum, maximum))
@random.command()
async def lenny(self, ctx):
"""Displays a random lenny face."""
lenny = rng.choice([
"( ͡° ͜ʖ ͡°)", "( ͠° ͟ʖ ͡°)", "ᕦ( ͡° ͜ʖ ͡°)ᕤ", "( ͡~ ͜ʖ ͡°)",
"( ͡o ͜ʖ ͡o)", "͡(° ͜ʖ ͡ -)", "( ͡͡ ° ͜ ʖ ͡ °)", "(ง ͠° ͟ل͜ ͡°)ง",
"ヽ༼ຈل͜ຈ༽ノ"
])
await ctx.send(lenny)
@commands.command()
async def choose(self, ctx, *choices: commands.clean_content):
"""Chooses between multiple choices.
To denote multiple choices, you should use double quotes.
"""
if len(choices) < 2:
return await ctx.send('Not enough choices to pick from.')
await ctx.send(rng.choice(choices))
@commands.command()
async def choosebestof(self, ctx, times: Optional[int], *choices: commands.clean_content):
"""Chooses between multiple choices N times.
To denote multiple choices, you should use double quotes.
You can only choose up to 10001 times and only the top 10 results are shown.
"""
if len(choices) < 2:
return await ctx.send('Not enough choices to pick from.')
if times is None:
times = (len(choices) ** 2) + 1
times = min(10001, max(1, times))
results = Counter(rng.choice(choices) for i in range(times))
builder = []
if len(results) > 10:
builder.append('Only showing top 10 results...')
for index, (elem, count) in enumerate(results.most_common(10), start=1):
builder.append(f'{index}. {elem} ({plural(count):time}, {count/times:.2%})')
await ctx.send('\n'.join(builder))
def setup(bot):
bot.add_cog(RNG(bot))
|
import argparse
import ast
import codecs
import collections
import contextlib
import keyword
import re
import string
import sys
import tokenize
import warnings
from typing import Any
from typing import cast
from typing import Container
from typing import Dict
from typing import Generator
from typing import Iterable
from typing import List
from typing import Match
from typing import NamedTuple
from typing import Optional
from typing import Pattern
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import Union
from tokenize_rt import NON_CODING_TOKENS
from tokenize_rt import Offset
from tokenize_rt import parse_string_literal
from tokenize_rt import reversed_enumerate
from tokenize_rt import rfind_string_parts
from tokenize_rt import src_to_tokens
from tokenize_rt import Token
from tokenize_rt import tokens_to_src
from tokenize_rt import UNIMPORTANT_WS
MinVersion = Tuple[int, ...]
DotFormatPart = Tuple[str, Optional[str], Optional[str], Optional[str]]
PercentFormatPart = Tuple[
Optional[str],
Optional[str],
Optional[str],
Optional[str],
str,
]
PercentFormat = Tuple[str, Optional[PercentFormatPart]]
ListCompOrGeneratorExp = Union[ast.ListComp, ast.GeneratorExp]
ListOrTuple = Union[ast.List, ast.Tuple]
NameOrAttr = Union[ast.Name, ast.Attribute]
AnyFunctionDef = Union[ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda]
SyncFunctionDef = Union[ast.FunctionDef, ast.Lambda]
_stdlib_parse_format = string.Formatter().parse
_KEYWORDS = frozenset(keyword.kwlist)
def parse_format(s: str) -> Tuple[DotFormatPart, ...]:
"""Makes the empty string not a special case. In the stdlib, there's
loss of information (the type) on the empty string.
"""
parsed = tuple(_stdlib_parse_format(s))
if not parsed:
return ((s, None, None, None),)
else:
return parsed
def unparse_parsed_string(parsed: Sequence[DotFormatPart]) -> str:
def _convert_tup(tup: DotFormatPart) -> str:
ret, field_name, format_spec, conversion = tup
ret = ret.replace('{', '{{')
ret = ret.replace('}', '}}')
if field_name is not None:
ret += '{' + field_name
if conversion:
ret += '!' + conversion
if format_spec:
ret += ':' + format_spec
ret += '}'
return ret
return ''.join(_convert_tup(tup) for tup in parsed)
def _ast_to_offset(node: Union[ast.expr, ast.stmt]) -> Offset:
return Offset(node.lineno, node.col_offset)
def ast_parse(contents_text: str) -> ast.Module:
# intentionally ignore warnings, we might be fixing warning-ridden syntax
with warnings.catch_warnings():
warnings.simplefilter('ignore')
return ast.parse(contents_text.encode())
def inty(s: str) -> bool:
try:
int(s)
return True
except (ValueError, TypeError):
return False
BRACES = {'(': ')', '[': ']', '{': '}'}
OPENING, CLOSING = frozenset(BRACES), frozenset(BRACES.values())
SET_TRANSFORM = (ast.List, ast.ListComp, ast.GeneratorExp, ast.Tuple)
def _is_wtf(func: str, tokens: List[Token], i: int) -> bool:
return tokens[i].src != func or tokens[i + 1].src != '('
def _process_set_empty_literal(tokens: List[Token], start: int) -> None:
if _is_wtf('set', tokens, start):
return
i = start + 2
brace_stack = ['(']
while brace_stack:
token = tokens[i].src
if token == BRACES[brace_stack[-1]]:
brace_stack.pop()
elif token in BRACES:
brace_stack.append(token)
elif '\n' in token:
# Contains a newline, could cause a SyntaxError, bail
return
i += 1
# Remove the inner tokens
del tokens[start + 2:i - 1]
def _search_until(tokens: List[Token], idx: int, arg: ast.expr) -> int:
while (
idx < len(tokens) and
not (
tokens[idx].line == arg.lineno and
tokens[idx].utf8_byte_offset == arg.col_offset
)
):
idx += 1
return idx
if sys.version_info >= (3, 8): # pragma: no cover (py38+)
# python 3.8 fixed the offsets of generators / tuples
def _arg_token_index(tokens: List[Token], i: int, arg: ast.expr) -> int:
idx = _search_until(tokens, i, arg) + 1
while idx < len(tokens) and tokens[idx].name in NON_CODING_TOKENS:
idx += 1
return idx
else: # pragma: no cover (<py38)
def _arg_token_index(tokens: List[Token], i: int, arg: ast.expr) -> int:
# lists containing non-tuples report the first element correctly
if isinstance(arg, ast.List):
# If the first element is a tuple, the ast lies to us about its col
# offset. We must find the first `(` token after the start of the
# list element.
if isinstance(arg.elts[0], ast.Tuple):
i = _search_until(tokens, i, arg)
return _find_open_paren(tokens, i)
else:
return _search_until(tokens, i, arg.elts[0])
# others' start position points at their first child node already
else:
return _search_until(tokens, i, arg)
class Victims(NamedTuple):
starts: List[int]
ends: List[int]
first_comma_index: Optional[int]
arg_index: int
def _victims(
tokens: List[Token],
start: int,
arg: ast.expr,
gen: bool,
) -> Victims:
starts = [start]
start_depths = [1]
ends: List[int] = []
first_comma_index = None
arg_depth = None
arg_index = _arg_token_index(tokens, start, arg)
brace_stack = [tokens[start].src]
i = start + 1
while brace_stack:
token = tokens[i].src
is_start_brace = token in BRACES
is_end_brace = token == BRACES[brace_stack[-1]]
if i == arg_index:
arg_depth = len(brace_stack)
if is_start_brace:
brace_stack.append(token)
# Remove all braces before the first element of the inner
# comprehension's target.
if is_start_brace and arg_depth is None:
start_depths.append(len(brace_stack))
starts.append(i)
if (
token == ',' and
len(brace_stack) == arg_depth and
first_comma_index is None
):
first_comma_index = i
if is_end_brace and len(brace_stack) in start_depths:
if tokens[i - 2].src == ',' and tokens[i - 1].src == ' ':
ends.extend((i - 2, i - 1, i))
elif tokens[i - 1].src == ',':
ends.extend((i - 1, i))
else:
ends.append(i)
if len(brace_stack) > 1 and tokens[i + 1].src == ',':
ends.append(i + 1)
if is_end_brace:
brace_stack.pop()
i += 1
# May need to remove a trailing comma for a comprehension
if gen:
i -= 2
while tokens[i].name in NON_CODING_TOKENS:
i -= 1
if tokens[i].src == ',':
ends.append(i)
return Victims(starts, sorted(set(ends)), first_comma_index, arg_index)
def _find_token(tokens: List[Token], i: int, src: str) -> int:
while tokens[i].src != src:
i += 1
return i
def _find_open_paren(tokens: List[Token], i: int) -> int:
return _find_token(tokens, i, '(')
def _is_on_a_line_by_self(tokens: List[Token], i: int) -> bool:
return (
tokens[i - 2].name == 'NL' and
tokens[i - 1].name == UNIMPORTANT_WS and
tokens[i + 1].name == 'NL'
)
def _remove_brace(tokens: List[Token], i: int) -> None:
if _is_on_a_line_by_self(tokens, i):
del tokens[i - 1:i + 2]
else:
del tokens[i]
def _process_set_literal(
tokens: List[Token],
start: int,
arg: ast.expr,
) -> None:
if _is_wtf('set', tokens, start):
return
gen = isinstance(arg, ast.GeneratorExp)
set_victims = _victims(tokens, start + 1, arg, gen=gen)
del set_victims.starts[0]
end_index = set_victims.ends.pop()
tokens[end_index] = Token('OP', '}')
for index in reversed(set_victims.starts + set_victims.ends):
_remove_brace(tokens, index)
tokens[start:start + 2] = [Token('OP', '{')]
def _process_dict_comp(
tokens: List[Token],
start: int,
arg: ListCompOrGeneratorExp,
) -> None:
if _is_wtf('dict', tokens, start):
return
dict_victims = _victims(tokens, start + 1, arg, gen=True)
elt_victims = _victims(tokens, dict_victims.arg_index, arg.elt, gen=True)
del dict_victims.starts[0]
end_index = dict_victims.ends.pop()
tokens[end_index] = Token('OP', '}')
for index in reversed(dict_victims.ends):
_remove_brace(tokens, index)
# See #6, Fix SyntaxError from rewriting dict((a, b)for a, b in y)
if tokens[elt_victims.ends[-1] + 1].src == 'for':
tokens.insert(elt_victims.ends[-1] + 1, Token(UNIMPORTANT_WS, ' '))
for index in reversed(elt_victims.ends):
_remove_brace(tokens, index)
assert elt_victims.first_comma_index is not None
tokens[elt_victims.first_comma_index] = Token('OP', ':')
for index in reversed(dict_victims.starts + elt_victims.starts):
_remove_brace(tokens, index)
tokens[start:start + 2] = [Token('OP', '{')]
def _process_is_literal(
tokens: List[Token],
i: int,
compare: Union[ast.Is, ast.IsNot],
) -> None:
while tokens[i].src != 'is':
i -= 1
if isinstance(compare, ast.Is):
tokens[i] = tokens[i]._replace(src='==')
else:
tokens[i] = tokens[i]._replace(src='!=')
# since we iterate backward, the dummy tokens keep the same length
i += 1
while tokens[i].src != 'not':
tokens[i] = Token('DUMMY', '')
i += 1
tokens[i] = Token('DUMMY', '')
LITERAL_TYPES = (ast.Str, ast.Num, ast.Bytes)
class Py2CompatibleVisitor(ast.NodeVisitor):
def __init__(self) -> None:
self.dicts: Dict[Offset, ListCompOrGeneratorExp] = {}
self.sets: Dict[Offset, ast.expr] = {}
self.set_empty_literals: Dict[Offset, ListOrTuple] = {}
self.is_literal: Dict[Offset, Union[ast.Is, ast.IsNot]] = {}
def visit_Call(self, node: ast.Call) -> None:
if (
isinstance(node.func, ast.Name) and
node.func.id == 'set' and
len(node.args) == 1 and
not node.keywords and
isinstance(node.args[0], SET_TRANSFORM)
):
arg, = node.args
key = _ast_to_offset(node.func)
if isinstance(arg, (ast.List, ast.Tuple)) and not arg.elts:
self.set_empty_literals[key] = arg
else:
self.sets[key] = arg
elif (
isinstance(node.func, ast.Name) and
node.func.id == 'dict' and
len(node.args) == 1 and
not node.keywords and
isinstance(node.args[0], (ast.ListComp, ast.GeneratorExp)) and
isinstance(node.args[0].elt, (ast.Tuple, ast.List)) and
len(node.args[0].elt.elts) == 2
):
self.dicts[_ast_to_offset(node.func)] = node.args[0]
self.generic_visit(node)
def visit_Compare(self, node: ast.Compare) -> None:
left = node.left
for op, right in zip(node.ops, node.comparators):
if (
isinstance(op, (ast.Is, ast.IsNot)) and
(
isinstance(left, LITERAL_TYPES) or
isinstance(right, LITERAL_TYPES)
)
):
self.is_literal[_ast_to_offset(right)] = op
left = right
self.generic_visit(node)
def _fix_py2_compatible(contents_text: str) -> str:
try:
ast_obj = ast_parse(contents_text)
except SyntaxError:
return contents_text
visitor = Py2CompatibleVisitor()
visitor.visit(ast_obj)
if not any((
visitor.dicts,
visitor.sets,
visitor.set_empty_literals,
visitor.is_literal,
)):
return contents_text
try:
tokens = src_to_tokens(contents_text)
except tokenize.TokenError: # pragma: no cover (bpo-2180)
return contents_text
for i, token in reversed_enumerate(tokens):
if token.offset in visitor.dicts:
_process_dict_comp(tokens, i, visitor.dicts[token.offset])
elif token.offset in visitor.set_empty_literals:
_process_set_empty_literal(tokens, i)
elif token.offset in visitor.sets:
_process_set_literal(tokens, i, visitor.sets[token.offset])
elif token.offset in visitor.is_literal:
_process_is_literal(tokens, i, visitor.is_literal[token.offset])
return tokens_to_src(tokens)
def _imports_unicode_literals(contents_text: str) -> bool:
try:
ast_obj = ast_parse(contents_text)
except SyntaxError:
return False
for node in ast_obj.body:
# Docstring
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Str):
continue
elif isinstance(node, ast.ImportFrom):
if (
node.level == 0 and
node.module == '__future__' and
any(name.name == 'unicode_literals' for name in node.names)
):
return True
elif node.module == '__future__':
continue
else:
return False
else:
return False
return False
# https://docs.python.org/3/reference/lexical_analysis.html
ESCAPE_STARTS = frozenset((
'\n', '\r', '\\', "'", '"', 'a', 'b', 'f', 'n', 'r', 't', 'v',
'0', '1', '2', '3', '4', '5', '6', '7', # octal escapes
'x', # hex escapes
))
ESCAPE_RE = re.compile(r'\\.', re.DOTALL)
NAMED_ESCAPE_NAME = re.compile(r'\{[^}]+\}')
def _fix_escape_sequences(token: Token) -> Token:
prefix, rest = parse_string_literal(token.src)
actual_prefix = prefix.lower()
if 'r' in actual_prefix or '\\' not in rest:
return token
is_bytestring = 'b' in actual_prefix
def _is_valid_escape(match: Match[str]) -> bool:
c = match.group()[1]
return (
c in ESCAPE_STARTS or
(not is_bytestring and c in 'uU') or
(
not is_bytestring and
c == 'N' and
bool(NAMED_ESCAPE_NAME.match(rest, match.end()))
)
)
has_valid_escapes = False
has_invalid_escapes = False
for match in ESCAPE_RE.finditer(rest):
if _is_valid_escape(match):
has_valid_escapes = True
else:
has_invalid_escapes = True
def cb(match: Match[str]) -> str:
matched = match.group()
if _is_valid_escape(match):
return matched
else:
return fr'\{matched}'
if has_invalid_escapes and (has_valid_escapes or 'u' in actual_prefix):
return token._replace(src=prefix + ESCAPE_RE.sub(cb, rest))
elif has_invalid_escapes and not has_valid_escapes:
return token._replace(src=prefix + 'r' + rest)
else:
return token
def _remove_u_prefix(token: Token) -> Token:
prefix, rest = parse_string_literal(token.src)
if 'u' not in prefix.lower():
return token
else:
new_prefix = prefix.replace('u', '').replace('U', '')
return token._replace(src=new_prefix + rest)
def _fix_ur_literals(token: Token) -> Token:
prefix, rest = parse_string_literal(token.src)
if prefix.lower() != 'ur':
return token
else:
def cb(match: Match[str]) -> str:
escape = match.group()
if escape[1].lower() == 'u':
return escape
else:
return '\\' + match.group()
rest = ESCAPE_RE.sub(cb, rest)
prefix = prefix.replace('r', '').replace('R', '')
return token._replace(src=prefix + rest)
def _fix_long(src: str) -> str:
return src.rstrip('lL')
def _fix_octal(s: str) -> str:
if not s.startswith('0') or not s.isdigit() or s == len(s) * '0':
return s
elif len(s) == 2:
return s[1:]
else:
return '0o' + s[1:]
def _fix_extraneous_parens(tokens: List[Token], i: int) -> None:
# search forward for another non-coding token
i += 1
while tokens[i].name in NON_CODING_TOKENS:
i += 1
# if we did not find another brace, return immediately
if tokens[i].src != '(':
return
start = i
depth = 1
while depth:
i += 1
# found comma or yield at depth 1: this is a tuple / coroutine
if depth == 1 and tokens[i].src in {',', 'yield'}:
return
elif tokens[i].src in OPENING:
depth += 1
elif tokens[i].src in CLOSING:
depth -= 1
end = i
# empty tuple
if all(t.name in NON_CODING_TOKENS for t in tokens[start + 1:i]):
return
# search forward for the next non-coding token
i += 1
while tokens[i].name in NON_CODING_TOKENS:
i += 1
if tokens[i].src == ')':
_remove_brace(tokens, end)
_remove_brace(tokens, start)
def _remove_fmt(tup: DotFormatPart) -> DotFormatPart:
if tup[1] is None:
return tup
else:
return (tup[0], '', tup[2], tup[3])
def _fix_format_literal(tokens: List[Token], end: int) -> None:
parts = rfind_string_parts(tokens, end)
parsed_parts = []
last_int = -1
for i in parts:
# f'foo {0}'.format(...) would get turned into a SyntaxError
prefix, _ = parse_string_literal(tokens[i].src)
if 'f' in prefix.lower():
return
try:
parsed = parse_format(tokens[i].src)
except ValueError:
# the format literal was malformed, skip it
return
# The last segment will always be the end of the string and not a
# format, slice avoids the `None` format key
for _, fmtkey, spec, _ in parsed[:-1]:
if (
fmtkey is not None and inty(fmtkey) and
int(fmtkey) == last_int + 1 and
spec is not None and '{' not in spec
):
last_int += 1
else:
return
parsed_parts.append(tuple(_remove_fmt(tup) for tup in parsed))
for i, parsed in zip(parts, parsed_parts):
tokens[i] = tokens[i]._replace(src=unparse_parsed_string(parsed))
def _fix_encode_to_binary(tokens: List[Token], i: int) -> None:
# .encode()
if (
i + 2 < len(tokens) and
tokens[i + 1].src == '(' and
tokens[i + 2].src == ')'
):
victims = slice(i - 1, i + 3)
latin1_ok = False
# .encode('encoding')
elif (
i + 3 < len(tokens) and
tokens[i + 1].src == '(' and
tokens[i + 2].name == 'STRING' and
tokens[i + 3].src == ')'
):
victims = slice(i - 1, i + 4)
prefix, rest = parse_string_literal(tokens[i + 2].src)
if 'f' in prefix.lower():
return
encoding = ast.literal_eval(prefix + rest)
if _is_codec(encoding, 'ascii') or _is_codec(encoding, 'utf-8'):
latin1_ok = False
elif _is_codec(encoding, 'iso8859-1'):
latin1_ok = True
else:
return
else:
return
parts = rfind_string_parts(tokens, i - 2)
if not parts:
return
for part in parts:
prefix, rest = parse_string_literal(tokens[part].src)
escapes = set(ESCAPE_RE.findall(rest))
if (
not _is_ascii(rest) or
'\\u' in escapes or
'\\U' in escapes or
'\\N' in escapes or
('\\x' in escapes and not latin1_ok) or
'f' in prefix.lower()
):
return
for part in parts:
prefix, rest = parse_string_literal(tokens[part].src)
prefix = 'b' + prefix.replace('u', '').replace('U', '')
tokens[part] = tokens[part]._replace(src=prefix + rest)
del tokens[victims]
def _build_import_removals() -> Dict[MinVersion, Dict[str, Tuple[str, ...]]]:
ret = {}
future: Tuple[Tuple[MinVersion, Tuple[str, ...]], ...] = (
((2, 7), ('nested_scopes', 'generators', 'with_statement')),
(
(3,), (
'absolute_import', 'division', 'print_function',
'unicode_literals',
),
),
((3, 6), ()),
((3, 7), ('generator_stop',)),
((3, 8), ()),
)
prev: Tuple[str, ...] = ()
for min_version, names in future:
prev += names
ret[min_version] = {'__future__': prev}
# see reorder_python_imports
for k, v in ret.items():
if k >= (3,):
v.update({
'builtins': (
'ascii', 'bytes', 'chr', 'dict', 'filter', 'hex', 'input',
'int', 'list', 'map', 'max', 'min', 'next', 'object',
'oct', 'open', 'pow', 'range', 'round', 'str', 'super',
'zip', '*',
),
'io': ('open',),
'six': ('callable', 'next'),
'six.moves': ('filter', 'input', 'map', 'range', 'zip'),
})
return ret
IMPORT_REMOVALS = _build_import_removals()
def _fix_import_removals(
tokens: List[Token],
start: int,
min_version: MinVersion,
) -> None:
i = start + 1
name_parts = []
while tokens[i].src != 'import':
if tokens[i].name in {'NAME', 'OP'}:
name_parts.append(tokens[i].src)
i += 1
modname = ''.join(name_parts)
if modname not in IMPORT_REMOVALS[min_version]:
return
found: List[Optional[int]] = []
i += 1
while tokens[i].name not in {'NEWLINE', 'ENDMARKER'}:
if tokens[i].name == 'NAME' or tokens[i].src == '*':
# don't touch aliases
if (
found and found[-1] is not None and
tokens[found[-1]].src == 'as'
):
found[-2:] = [None]
else:
found.append(i)
i += 1
# depending on the version of python, some will not emit NEWLINE('') at the
# end of a file which does not end with a newline (for example 3.6.5)
if tokens[i].name == 'ENDMARKER': # pragma: no cover
i -= 1
remove_names = IMPORT_REMOVALS[min_version][modname]
to_remove = [
x for x in found if x is not None and tokens[x].src in remove_names
]
if len(to_remove) == len(found):
del tokens[start:i + 1]
else:
for idx in reversed(to_remove):
if found[0] == idx: # look forward until next name and del
j = idx + 1
while tokens[j].name != 'NAME':
j += 1
del tokens[idx:j]
else: # look backward for comma and del
j = idx
while tokens[j].src != ',':
j -= 1
del tokens[j:idx + 1]
def _fix_tokens(contents_text: str, min_version: MinVersion) -> str:
remove_u = min_version >= (3,) or _imports_unicode_literals(contents_text)
try:
tokens = src_to_tokens(contents_text)
except tokenize.TokenError:
return contents_text
for i, token in reversed_enumerate(tokens):
if token.name == 'NUMBER':
tokens[i] = token._replace(src=_fix_long(_fix_octal(token.src)))
elif token.name == 'STRING':
tokens[i] = _fix_ur_literals(tokens[i])
if remove_u:
tokens[i] = _remove_u_prefix(tokens[i])
tokens[i] = _fix_escape_sequences(tokens[i])
elif token.src == '(':
_fix_extraneous_parens(tokens, i)
elif token.src == 'format' and i > 0 and tokens[i - 1].src == '.':
_fix_format_literal(tokens, i - 2)
elif token.src == 'encode' and i > 0 and tokens[i - 1].src == '.':
_fix_encode_to_binary(tokens, i)
elif (
min_version >= (3,) and
token.utf8_byte_offset == 0 and
token.line < 3 and
token.name == 'COMMENT' and
tokenize.cookie_re.match(token.src)
):
del tokens[i]
assert tokens[i].name == 'NL', tokens[i].name
del tokens[i]
elif token.src == 'from' and token.utf8_byte_offset == 0:
_fix_import_removals(tokens, i, min_version)
return tokens_to_src(tokens).lstrip()
MAPPING_KEY_RE = re.compile(r'\(([^()]*)\)')
CONVERSION_FLAG_RE = re.compile('[#0+ -]*')
WIDTH_RE = re.compile(r'(?:\*|\d*)')
PRECISION_RE = re.compile(r'(?:\.(?:\*|\d*))?')
LENGTH_RE = re.compile('[hlL]?')
def _must_match(regex: Pattern[str], string: str, pos: int) -> Match[str]:
match = regex.match(string, pos)
assert match is not None
return match
def parse_percent_format(s: str) -> Tuple[PercentFormat, ...]:
def _parse_inner() -> Generator[PercentFormat, None, None]:
string_start = 0
string_end = 0
in_fmt = False
i = 0
while i < len(s):
if not in_fmt:
try:
i = s.index('%', i)
except ValueError: # no more % fields!
yield s[string_start:], None
return
else:
string_end = i
i += 1
in_fmt = True
else:
key_match = MAPPING_KEY_RE.match(s, i)
if key_match:
key: Optional[str] = key_match.group(1)
i = key_match.end()
else:
key = None
conversion_flag_match = _must_match(CONVERSION_FLAG_RE, s, i)
conversion_flag = conversion_flag_match.group() or None
i = conversion_flag_match.end()
width_match = _must_match(WIDTH_RE, s, i)
width = width_match.group() or None
i = width_match.end()
precision_match = _must_match(PRECISION_RE, s, i)
precision = precision_match.group() or None
i = precision_match.end()
# length modifier is ignored
i = _must_match(LENGTH_RE, s, i).end()
try:
conversion = s[i]
except IndexError:
raise ValueError('end-of-string while parsing format')
i += 1
fmt = (key, conversion_flag, width, precision, conversion)
yield s[string_start:string_end], fmt
in_fmt = False
string_start = i
if in_fmt:
raise ValueError('end-of-string while parsing format')
return tuple(_parse_inner())
class FindPercentFormats(ast.NodeVisitor):
def __init__(self) -> None:
self.found: Dict[Offset, ast.BinOp] = {}
def visit_BinOp(self, node: ast.BinOp) -> None:
if isinstance(node.op, ast.Mod) and isinstance(node.left, ast.Str):
try:
parsed = parse_percent_format(node.left.s)
except ValueError:
pass
else:
for _, fmt in parsed:
if not fmt:
continue
key, conversion_flag, width, precision, conversion = fmt
# timid: these require out-of-order parameter consumption
if width == '*' or precision == '.*':
break
# these conversions require modification of parameters
if conversion in {'d', 'i', 'u', 'c'}:
break
# timid: py2: %#o formats different from {:#o} (--py3?)
if '#' in (conversion_flag or '') and conversion == 'o':
break
# no equivalent in format
if key == '':
break
# timid: py2: conversion is subject to modifiers (--py3?)
nontrivial_fmt = any((conversion_flag, width, precision))
if conversion == '%' and nontrivial_fmt:
break
# no equivalent in format
if conversion in {'a', 'r'} and nontrivial_fmt:
break
# all dict substitutions must be named
if isinstance(node.right, ast.Dict) and not key:
break
else:
self.found[_ast_to_offset(node)] = node
self.generic_visit(node)
def _simplify_conversion_flag(flag: str) -> str:
parts: List[str] = []
for c in flag:
if c in parts:
continue
c = c.replace('-', '<')
parts.append(c)
if c == '<' and '0' in parts:
parts.remove('0')
elif c == '+' and ' ' in parts:
parts.remove(' ')
return ''.join(parts)
def _percent_to_format(s: str) -> str:
def _handle_part(part: PercentFormat) -> str:
s, fmt = part
s = s.replace('{', '{{').replace('}', '}}')
if fmt is None:
return s
else:
key, conversion_flag, width, precision, conversion = fmt
if conversion == '%':
return s + '%'
parts = [s, '{']
if width and conversion == 's' and not conversion_flag:
conversion_flag = '>'
if conversion == 's':
conversion = ''
if key:
parts.append(key)
if conversion in {'r', 'a'}:
converter = f'!{conversion}'
conversion = ''
else:
converter = ''
if any((conversion_flag, width, precision, conversion)):
parts.append(':')
if conversion_flag:
parts.append(_simplify_conversion_flag(conversion_flag))
parts.extend(x for x in (width, precision, conversion) if x)
parts.extend(converter)
parts.append('}')
return ''.join(parts)
return ''.join(_handle_part(part) for part in parse_percent_format(s))
def _is_ascii(s: str) -> bool:
if sys.version_info >= (3, 7): # pragma: no cover (py37+)
return s.isascii()
else: # pragma: no cover (<py37)
return all(c in string.printable for c in s)
def _fix_percent_format_tuple(
tokens: List[Token],
start: int,
node: ast.BinOp,
) -> None:
# TODO: this is overly timid
paren = start + 4
if tokens_to_src(tokens[start + 1:paren + 1]) != ' % (':
return
victims = _victims(tokens, paren, node.right, gen=False)
victims.ends.pop()
for index in reversed(victims.starts + victims.ends):
_remove_brace(tokens, index)
newsrc = _percent_to_format(tokens[start].src)
tokens[start] = tokens[start]._replace(src=newsrc)
tokens[start + 1:paren] = [Token('Format', '.format'), Token('OP', '(')]
def _fix_percent_format_dict(
tokens: List[Token],
start: int,
node: ast.BinOp,
) -> None:
seen_keys: Set[str] = set()
keys = {}
# the caller has enforced this
assert isinstance(node.right, ast.Dict)
for k in node.right.keys:
# not a string key
if not isinstance(k, ast.Str):
return
# duplicate key
elif k.s in seen_keys:
return
# not an identifier
elif not k.s.isidentifier():
return
# a keyword
elif k.s in _KEYWORDS:
return
seen_keys.add(k.s)
keys[_ast_to_offset(k)] = k
# TODO: this is overly timid
brace = start + 4
if tokens_to_src(tokens[start + 1:brace + 1]) != ' % {':
return
victims = _victims(tokens, brace, node.right, gen=False)
brace_end = victims.ends[-1]
key_indices = []
for i, token in enumerate(tokens[brace:brace_end], brace):
key = keys.pop(token.offset, None)
if key is None:
continue
# we found the key, but the string didn't match (implicit join?)
elif ast.literal_eval(token.src) != key.s:
return
# the map uses some strange syntax that's not `'key': value`
elif tokens_to_src(tokens[i + 1:i + 3]) != ': ':
return
else:
key_indices.append((i, key.s))
assert not keys, keys
tokens[brace_end] = tokens[brace_end]._replace(src=')')
for (key_index, s) in reversed(key_indices):
tokens[key_index:key_index + 3] = [Token('CODE', f'{s}=')]
newsrc = _percent_to_format(tokens[start].src)
tokens[start] = tokens[start]._replace(src=newsrc)
tokens[start + 1:brace + 1] = [Token('CODE', '.format'), Token('OP', '(')]
def _fix_percent_format(contents_text: str) -> str:
try:
ast_obj = ast_parse(contents_text)
except SyntaxError:
return contents_text
visitor = FindPercentFormats()
visitor.visit(ast_obj)
if not visitor.found:
return contents_text
try:
tokens = src_to_tokens(contents_text)
except tokenize.TokenError: # pragma: no cover (bpo-2180)
return contents_text
for i, token in reversed_enumerate(tokens):
node = visitor.found.get(token.offset)
if node is None:
continue
# TODO: handle \N escape sequences
if r'\N' in token.src:
continue
if isinstance(node.right, ast.Tuple):
_fix_percent_format_tuple(tokens, i, node)
elif isinstance(node.right, ast.Dict):
_fix_percent_format_dict(tokens, i, node)
return tokens_to_src(tokens)
SIX_SIMPLE_ATTRS = {
'text_type': 'str',
'binary_type': 'bytes',
'class_types': '(type,)',
'string_types': '(str,)',
'integer_types': '(int,)',
'unichr': 'chr',
'iterbytes': 'iter',
'print_': 'print',
'exec_': 'exec',
'advance_iterator': 'next',
'next': 'next',
'callable': 'callable',
}
SIX_TYPE_CTX_ATTRS = {
'class_types': 'type',
'string_types': 'str',
'integer_types': 'int',
}
SIX_CALLS = {
'u': '{args[0]}',
'byte2int': '{args[0]}[0]',
'indexbytes': '{args[0]}[{rest}]',
'int2byte': 'bytes(({args[0]},))',
'iteritems': '{args[0]}.items()',
'iterkeys': '{args[0]}.keys()',
'itervalues': '{args[0]}.values()',
'viewitems': '{args[0]}.items()',
'viewkeys': '{args[0]}.keys()',
'viewvalues': '{args[0]}.values()',
'create_unbound_method': '{args[0]}',
'get_unbound_function': '{args[0]}',
'get_method_function': '{args[0]}.__func__',
'get_method_self': '{args[0]}.__self__',
'get_function_closure': '{args[0]}.__closure__',
'get_function_code': '{args[0]}.__code__',
'get_function_defaults': '{args[0]}.__defaults__',
'get_function_globals': '{args[0]}.__globals__',
'assertCountEqual': '{args[0]}.assertCountEqual({rest})',
'assertRaisesRegex': '{args[0]}.assertRaisesRegex({rest})',
'assertRegex': '{args[0]}.assertRegex({rest})',
}
SIX_B_TMPL = 'b{args[0]}'
WITH_METACLASS_NO_BASES_TMPL = 'metaclass={args[0]}'
WITH_METACLASS_BASES_TMPL = '{rest}, metaclass={args[0]}'
RAISE_FROM_TMPL = 'raise {args[0]} from {rest}'
RERAISE_TMPL = 'raise'
RERAISE_2_TMPL = 'raise {args[1]}.with_traceback(None)'
RERAISE_3_TMPL = 'raise {args[1]}.with_traceback({args[2]})'
SIX_NATIVE_STR = frozenset(('ensure_str', 'ensure_text', 'text_type'))
U_MODE_REMOVE = frozenset(('U', 'Ur', 'rU', 'r', 'rt', 'tr'))
U_MODE_REPLACE_R = frozenset(('Ub', 'bU'))
U_MODE_REMOVE_U = frozenset(('rUb', 'Urb', 'rbU', 'Ubr', 'bUr', 'brU'))
U_MODE_REPLACE = U_MODE_REPLACE_R | U_MODE_REMOVE_U
def _all_isinstance(
vals: Iterable[Any],
tp: Union[Type[Any], Tuple[Type[Any], ...]],
) -> bool:
return all(isinstance(v, tp) for v in vals)
def fields_same(n1: ast.AST, n2: ast.AST) -> bool:
for (a1, v1), (a2, v2) in zip(ast.iter_fields(n1), ast.iter_fields(n2)):
# ignore ast attributes, they'll be covered by walk
if a1 != a2:
return False
elif _all_isinstance((v1, v2), ast.AST):
continue
elif _all_isinstance((v1, v2), (list, tuple)):
if len(v1) != len(v2):
return False
# ignore sequences which are all-ast, they'll be covered by walk
elif _all_isinstance(v1, ast.AST) and _all_isinstance(v2, ast.AST):
continue
elif v1 != v2:
return False
elif v1 != v2:
return False
return True
def targets_same(target: ast.AST, yield_value: ast.AST) -> bool:
for t1, t2 in zip(ast.walk(target), ast.walk(yield_value)):
# ignore `ast.Load` / `ast.Store`
if _all_isinstance((t1, t2), ast.expr_context):
continue
elif type(t1) != type(t2):
return False
elif not fields_same(t1, t2):
return False
else:
return True
def _is_codec(encoding: str, name: str) -> bool:
try:
return codecs.lookup(encoding).name == name
except LookupError:
return False
class FindPy3Plus(ast.NodeVisitor):
OS_ERROR_ALIASES = frozenset((
'EnvironmentError',
'IOError',
'WindowsError',
))
OS_ERROR_ALIAS_MODULES = frozenset((
'mmap',
'select',
'socket',
))
FROM_IMPORTED_MODULES = OS_ERROR_ALIAS_MODULES.union(('functools', 'six'))
MOCK_MODULES = frozenset(('mock', 'mock.mock'))
class ClassInfo:
def __init__(self, name: str) -> None:
self.name = name
self.def_depth = 0
self.first_arg_name = ''
class Scope:
def __init__(self) -> None:
self.reads: Set[str] = set()
self.writes: Set[str] = set()
self.yield_from_fors: Set[Offset] = set()
self.yield_from_names: Dict[str, Set[Offset]]
self.yield_from_names = collections.defaultdict(set)
def __init__(self, keep_mock: bool) -> None:
self._find_mock = not keep_mock
self.bases_to_remove: Set[Offset] = set()
self.encode_calls: Dict[Offset, ast.Call] = {}
self._exc_info_imported = False
self._version_info_imported = False
self.if_py3_blocks: Set[Offset] = set()
self.if_py2_blocks_else: Set[Offset] = set()
self.if_py3_blocks_else: Set[Offset] = set()
self.metaclass_type_assignments: Set[Offset] = set()
self.native_literals: Set[Offset] = set()
self._from_imports: Dict[str, Set[str]] = collections.defaultdict(set)
self.io_open_calls: Set[Offset] = set()
self.mock_mock: Set[Offset] = set()
self.mock_absolute_imports: Set[Offset] = set()
self.mock_relative_imports: Set[Offset] = set()
self.open_mode_calls: Set[Offset] = set()
self.os_error_alias_calls: Set[Offset] = set()
self.os_error_alias_simple: Dict[Offset, NameOrAttr] = {}
self.os_error_alias_excepts: Set[Offset] = set()
self.six_add_metaclass: Set[Offset] = set()
self.six_b: Set[Offset] = set()
self.six_calls: Dict[Offset, ast.Call] = {}
self.six_iter: Dict[Offset, ast.Call] = {}
self._previous_node: Optional[ast.AST] = None
self.six_raise_from: Set[Offset] = set()
self.six_reraise: Set[Offset] = set()
self.six_remove_decorators: Set[Offset] = set()
self.six_simple: Dict[Offset, NameOrAttr] = {}
self.six_type_ctx: Dict[Offset, NameOrAttr] = {}
self.six_with_metaclass: Set[Offset] = set()
self._class_info_stack: List[FindPy3Plus.ClassInfo] = []
self._in_comp = 0
self.super_calls: Dict[Offset, ast.Call] = {}
self._in_async_def = False
self._scope_stack: List[FindPy3Plus.Scope] = []
self.yield_from_fors: Set[Offset] = set()
self.no_arg_decorators: Set[Offset] = set()
def _is_six(self, node: ast.expr, names: Container[str]) -> bool:
return (
isinstance(node, ast.Name) and
node.id in names and
node.id in self._from_imports['six']
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'six' and
node.attr in names
)
def _is_star_sys_exc_info(self, node: ast.Call) -> bool:
return (
len(node.args) == 1 and
isinstance(node.args[0], ast.Starred) and
isinstance(node.args[0].value, ast.Call) and
self._is_exc_info(node.args[0].value.func)
)
def _is_lru_cache(self, node: ast.expr) -> bool:
return (
isinstance(node, ast.Name) and
node.id == 'lru_cache' and
node.id in self._from_imports['functools']
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'functools' and
node.attr == 'lru_cache'
)
def _is_mock_mock(self, node: ast.expr) -> bool:
return (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'mock' and
node.attr == 'mock'
)
def _is_io_open(self, node: ast.expr) -> bool:
return (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'io' and
node.attr == 'open'
)
def _is_os_error_alias(self, node: Optional[ast.expr]) -> bool:
return (
isinstance(node, ast.Name) and
node.id in self.OS_ERROR_ALIASES
) or (
isinstance(node, ast.Name) and
node.id == 'error' and
(
node.id in self._from_imports['mmap'] or
node.id in self._from_imports['select'] or
node.id in self._from_imports['socket']
)
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id in self.OS_ERROR_ALIAS_MODULES and
node.attr == 'error'
)
def _is_exc_info(self, node: ast.expr) -> bool:
return (
isinstance(node, ast.Name) and
node.id == 'exc_info' and
self._exc_info_imported
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'sys' and
node.attr == 'exc_info'
)
def _is_version_info(self, node: ast.expr) -> bool:
return (
isinstance(node, ast.Name) and
node.id == 'version_info' and
self._version_info_imported
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'sys' and
node.attr == 'version_info'
)
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
if not node.level:
if node.module in self.FROM_IMPORTED_MODULES:
for name in node.names:
if not name.asname:
self._from_imports[node.module].add(name.name)
elif self._find_mock and node.module in self.MOCK_MODULES:
self.mock_relative_imports.add(_ast_to_offset(node))
elif node.module == 'sys' and any(
name.name == 'exc_info' and not name.asname
for name in node.names
):
self._exc_info_imported = True
elif node.module == 'sys' and any(
name.name == 'version_info' and not name.asname
for name in node.names
):
self._version_info_imported = True
self.generic_visit(node)
def visit_Import(self, node: ast.Import) -> None:
if (
self._find_mock and
len(node.names) == 1 and
node.names[0].name in self.MOCK_MODULES
):
self.mock_absolute_imports.add(_ast_to_offset(node))
self.generic_visit(node)
def visit_ClassDef(self, node: ast.ClassDef) -> None:
for decorator in node.decorator_list:
if self._is_six(decorator, ('python_2_unicode_compatible',)):
self.six_remove_decorators.add(_ast_to_offset(decorator))
elif (
isinstance(decorator, ast.Call) and
self._is_six(decorator.func, ('add_metaclass',)) and
not _starargs(decorator)
):
self.six_add_metaclass.add(_ast_to_offset(decorator))
for base in node.bases:
if isinstance(base, ast.Name) and base.id == 'object':
self.bases_to_remove.add(_ast_to_offset(base))
elif self._is_six(base, ('Iterator',)):
self.bases_to_remove.add(_ast_to_offset(base))
if (
len(node.bases) == 1 and
isinstance(node.bases[0], ast.Call) and
self._is_six(node.bases[0].func, ('with_metaclass',)) and
not _starargs(node.bases[0])
):
self.six_with_metaclass.add(_ast_to_offset(node.bases[0]))
self._class_info_stack.append(FindPy3Plus.ClassInfo(node.name))
self.generic_visit(node)
self._class_info_stack.pop()
@contextlib.contextmanager
def _track_def_depth(
self,
node: AnyFunctionDef,
) -> Generator[None, None, None]:
class_info = self._class_info_stack[-1]
class_info.def_depth += 1
if class_info.def_depth == 1 and node.args.args:
class_info.first_arg_name = node.args.args[0].arg
try:
yield
finally:
class_info.def_depth -= 1
@contextlib.contextmanager
def _scope(self) -> Generator[None, None, None]:
self._scope_stack.append(FindPy3Plus.Scope())
try:
yield
finally:
info = self._scope_stack.pop()
# discard any that were referenced outside of the loop
for name in info.reads:
offsets = info.yield_from_names[name]
info.yield_from_fors.difference_update(offsets)
self.yield_from_fors.update(info.yield_from_fors)
if self._scope_stack:
cell_reads = info.reads - info.writes
self._scope_stack[-1].reads.update(cell_reads)
def _visit_func(self, node: AnyFunctionDef) -> None:
with contextlib.ExitStack() as ctx, self._scope():
if self._class_info_stack:
ctx.enter_context(self._track_def_depth(node))
self.generic_visit(node)
def _visit_sync_func(self, node: SyncFunctionDef) -> None:
self._in_async_def, orig = False, self._in_async_def
self._visit_func(node)
self._in_async_def = orig
visit_FunctionDef = visit_Lambda = _visit_sync_func
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
self._in_async_def, orig = True, self._in_async_def
self._visit_func(node)
self._in_async_def = orig
def _visit_comp(self, node: ast.expr) -> None:
self._in_comp += 1
with self._scope():
self.generic_visit(node)
self._in_comp -= 1
visit_ListComp = visit_SetComp = _visit_comp
visit_DictComp = visit_GeneratorExp = _visit_comp
def visit_Attribute(self, node: ast.Attribute) -> None:
if self._is_six(node, SIX_SIMPLE_ATTRS):
self.six_simple[_ast_to_offset(node)] = node
elif self._find_mock and self._is_mock_mock(node):
self.mock_mock.add(_ast_to_offset(node))
self.generic_visit(node)
def visit_Name(self, node: ast.Name) -> None:
if self._is_six(node, SIX_SIMPLE_ATTRS):
self.six_simple[_ast_to_offset(node)] = node
if self._scope_stack:
if isinstance(node.ctx, ast.Load):
self._scope_stack[-1].reads.add(node.id)
elif isinstance(node.ctx, (ast.Store, ast.Del)):
self._scope_stack[-1].writes.add(node.id)
else:
raise AssertionError(node)
self.generic_visit(node)
def visit_Try(self, node: ast.Try) -> None:
for handler in node.handlers:
htype = handler.type
if self._is_os_error_alias(htype):
assert isinstance(htype, (ast.Name, ast.Attribute))
self.os_error_alias_simple[_ast_to_offset(htype)] = htype
elif (
isinstance(htype, ast.Tuple) and
any(
self._is_os_error_alias(elt)
for elt in htype.elts
)
):
self.os_error_alias_excepts.add(_ast_to_offset(htype))
self.generic_visit(node)
def visit_Raise(self, node: ast.Raise) -> None:
exc = node.exc
if exc is not None and self._is_os_error_alias(exc):
assert isinstance(exc, (ast.Name, ast.Attribute))
self.os_error_alias_simple[_ast_to_offset(exc)] = exc
elif (
isinstance(exc, ast.Call) and
self._is_os_error_alias(exc.func)
):
self.os_error_alias_calls.add(_ast_to_offset(exc))
self.generic_visit(node)
def visit_Call(self, node: ast.Call) -> None:
if (
isinstance(node.func, ast.Name) and
node.func.id in {'isinstance', 'issubclass'} and
len(node.args) == 2 and
self._is_six(node.args[1], SIX_TYPE_CTX_ATTRS)
):
arg = node.args[1]
# _is_six() enforces this
assert isinstance(arg, (ast.Name, ast.Attribute))
self.six_type_ctx[_ast_to_offset(node.args[1])] = arg
elif self._is_six(node.func, ('b', 'ensure_binary')):
self.six_b.add(_ast_to_offset(node))
elif self._is_six(node.func, SIX_CALLS) and not _starargs(node):
self.six_calls[_ast_to_offset(node)] = node
elif (
isinstance(node.func, ast.Name) and
node.func.id == 'next' and
not _starargs(node) and
len(node.args) == 1 and
isinstance(node.args[0], ast.Call) and
self._is_six(
node.args[0].func,
('iteritems', 'iterkeys', 'itervalues'),
) and
not _starargs(node.args[0])
):
self.six_iter[_ast_to_offset(node.args[0])] = node.args[0]
elif (
isinstance(self._previous_node, ast.Expr) and
self._is_six(node.func, ('raise_from',)) and
not _starargs(node)
):
self.six_raise_from.add(_ast_to_offset(node))
elif (
isinstance(self._previous_node, ast.Expr) and
self._is_six(node.func, ('reraise',)) and
(not _starargs(node) or self._is_star_sys_exc_info(node))
):
self.six_reraise.add(_ast_to_offset(node))
elif (
not self._in_comp and
self._class_info_stack and
self._class_info_stack[-1].def_depth == 1 and
isinstance(node.func, ast.Name) and
node.func.id == 'super' and
len(node.args) == 2 and
isinstance(node.args[0], ast.Name) and
isinstance(node.args[1], ast.Name) and
node.args[0].id == self._class_info_stack[-1].name and
node.args[1].id == self._class_info_stack[-1].first_arg_name
):
self.super_calls[_ast_to_offset(node)] = node
elif (
(
self._is_six(node.func, SIX_NATIVE_STR) or
isinstance(node.func, ast.Name) and node.func.id == 'str'
) and
not node.keywords and
not _starargs(node) and
(
len(node.args) == 0 or
(
len(node.args) == 1 and
isinstance(node.args[0], ast.Str)
)
)
):
self.native_literals.add(_ast_to_offset(node))
elif (
isinstance(node.func, ast.Attribute) and
isinstance(node.func.value, ast.Str) and
node.func.attr == 'encode' and
not _starargs(node) and
len(node.args) == 1 and
isinstance(node.args[0], ast.Str) and
_is_codec(node.args[0].s, 'utf-8')
):
self.encode_calls[_ast_to_offset(node)] = node
elif self._is_io_open(node.func):
self.io_open_calls.add(_ast_to_offset(node))
elif (
isinstance(node.func, ast.Name) and
node.func.id == 'open' and
not _starargs(node) and
len(node.args) >= 2 and
isinstance(node.args[1], ast.Str) and (
node.args[1].s in U_MODE_REPLACE or
(len(node.args) == 2 and node.args[1].s in U_MODE_REMOVE)
)
):
self.open_mode_calls.add(_ast_to_offset(node))
elif (
not node.args and
not node.keywords and
self._is_lru_cache(node.func)
):
self.no_arg_decorators.add(_ast_to_offset(node))
self.generic_visit(node)
def visit_Assign(self, node: ast.Assign) -> None:
if (
len(node.targets) == 1 and
isinstance(node.targets[0], ast.Name) and
node.targets[0].col_offset == 0 and
node.targets[0].id == '__metaclass__' and
isinstance(node.value, ast.Name) and
node.value.id == 'type'
):
self.metaclass_type_assignments.add(_ast_to_offset(node))
self.generic_visit(node)
@staticmethod
def _eq(test: ast.Compare, n: int) -> bool:
return (
isinstance(test.ops[0], ast.Eq) and
isinstance(test.comparators[0], ast.Num) and
test.comparators[0].n == n
)
@staticmethod
def _compare_to_3(
test: ast.Compare,
op: Union[Type[ast.cmpop], Tuple[Type[ast.cmpop], ...]],
) -> bool:
if not (
isinstance(test.ops[0], op) and
isinstance(test.comparators[0], ast.Tuple) and
len(test.comparators[0].elts) >= 1 and
all(isinstance(n, ast.Num) for n in test.comparators[0].elts)
):
return False
# checked above but mypy needs help
elts = cast('List[ast.Num]', test.comparators[0].elts)
return elts[0].n == 3 and all(n.n == 0 for n in elts[1:])
def visit_If(self, node: ast.If) -> None:
if (
# if six.PY2:
self._is_six(node.test, ('PY2',)) or
# if not six.PY3:
(
isinstance(node.test, ast.UnaryOp) and
isinstance(node.test.op, ast.Not) and
self._is_six(node.test.operand, ('PY3',))
) or
# sys.version_info == 2 or < (3,)
(
isinstance(node.test, ast.Compare) and
self._is_version_info(node.test.left) and
len(node.test.ops) == 1 and (
self._eq(node.test, 2) or
self._compare_to_3(node.test, ast.Lt)
)
)
):
if node.orelse and not isinstance(node.orelse[0], ast.If):
self.if_py2_blocks_else.add(_ast_to_offset(node))
elif (
# if six.PY3:
self._is_six(node.test, 'PY3') or
# if not six.PY2:
(
isinstance(node.test, ast.UnaryOp) and
isinstance(node.test.op, ast.Not) and
self._is_six(node.test.operand, ('PY2',))
) or
# sys.version_info == 3 or >= (3,) or > (3,)
(
isinstance(node.test, ast.Compare) and
self._is_version_info(node.test.left) and
len(node.test.ops) == 1 and (
self._eq(node.test, 3) or
self._compare_to_3(node.test, (ast.Gt, ast.GtE))
)
)
):
if node.orelse and not isinstance(node.orelse[0], ast.If):
self.if_py3_blocks_else.add(_ast_to_offset(node))
elif not node.orelse:
self.if_py3_blocks.add(_ast_to_offset(node))
self.generic_visit(node)
def visit_For(self, node: ast.For) -> None:
if (
not self._in_async_def and
len(node.body) == 1 and
isinstance(node.body[0], ast.Expr) and
isinstance(node.body[0].value, ast.Yield) and
node.body[0].value.value is not None and
targets_same(node.target, node.body[0].value.value) and
not node.orelse
):
offset = _ast_to_offset(node)
func_info = self._scope_stack[-1]
func_info.yield_from_fors.add(offset)
for target_node in ast.walk(node.target):
if (
isinstance(target_node, ast.Name) and
isinstance(target_node.ctx, ast.Store)
):
func_info.yield_from_names[target_node.id].add(offset)
# manually visit, but with target+body as a separate scope
self.visit(node.iter)
with self._scope():
self.visit(node.target)
for stmt in node.body:
self.visit(stmt)
assert not node.orelse
else:
self.generic_visit(node)
def generic_visit(self, node: ast.AST) -> None:
self._previous_node = node
super().generic_visit(node)
def _fixup_dedent_tokens(tokens: List[Token]) -> None:
"""For whatever reason the DEDENT / UNIMPORTANT_WS tokens are misordered
| if True:
| if True:
| pass
| else:
|^ ^- DEDENT
|+----UNIMPORTANT_WS
"""
for i, token in enumerate(tokens):
if token.name == UNIMPORTANT_WS and tokens[i + 1].name == 'DEDENT':
tokens[i], tokens[i + 1] = tokens[i + 1], tokens[i]
def _find_block_start(tokens: List[Token], i: int) -> int:
depth = 0
while depth or tokens[i].src != ':':
if tokens[i].src in OPENING:
depth += 1
elif tokens[i].src in CLOSING:
depth -= 1
i += 1
return i
class Block(NamedTuple):
start: int
colon: int
block: int
end: int
line: bool
def _initial_indent(self, tokens: List[Token]) -> int:
if tokens[self.start].src.isspace():
return len(tokens[self.start].src)
else:
return 0
def _minimum_indent(self, tokens: List[Token]) -> int:
block_indent = None
for i in range(self.block, self.end):
if (
tokens[i - 1].name in ('NL', 'NEWLINE') and
tokens[i].name in ('INDENT', UNIMPORTANT_WS)
):
token_indent = len(tokens[i].src)
if block_indent is None:
block_indent = token_indent
else:
block_indent = min(block_indent, token_indent)
assert block_indent is not None
return block_indent
def dedent(self, tokens: List[Token]) -> None:
if self.line:
return
diff = self._minimum_indent(tokens) - self._initial_indent(tokens)
for i in range(self.block, self.end):
if (
tokens[i - 1].name in ('DEDENT', 'NL', 'NEWLINE') and
tokens[i].name in ('INDENT', UNIMPORTANT_WS)
):
tokens[i] = tokens[i]._replace(src=tokens[i].src[diff:])
def replace_condition(self, tokens: List[Token], new: List[Token]) -> None:
tokens[self.start:self.colon] = new
def _trim_end(self, tokens: List[Token]) -> 'Block':
"""the tokenizer reports the end of the block at the beginning of
the next block
"""
i = last_token = self.end - 1
while tokens[i].name in NON_CODING_TOKENS | {'DEDENT', 'NEWLINE'}:
# if we find an indented comment inside our block, keep it
if (
tokens[i].name in {'NL', 'NEWLINE'} and
tokens[i + 1].name == UNIMPORTANT_WS and
len(tokens[i + 1].src) > self._initial_indent(tokens)
):
break
# otherwise we've found another line to remove
elif tokens[i].name in {'NL', 'NEWLINE'}:
last_token = i
i -= 1
return self._replace(end=last_token + 1)
@classmethod
def find(
cls,
tokens: List[Token],
i: int,
trim_end: bool = False,
) -> 'Block':
if i > 0 and tokens[i - 1].name in {'INDENT', UNIMPORTANT_WS}:
i -= 1
start = i
colon = _find_block_start(tokens, i)
j = colon + 1
while (
tokens[j].name != 'NEWLINE' and
tokens[j].name in NON_CODING_TOKENS
):
j += 1
if tokens[j].name == 'NEWLINE': # multi line block
block = j + 1
while tokens[j].name != 'INDENT':
j += 1
level = 1
j += 1
while level:
level += {'INDENT': 1, 'DEDENT': -1}.get(tokens[j].name, 0)
j += 1
ret = cls(start, colon, block, j, line=False)
if trim_end:
return ret._trim_end(tokens)
else:
return ret
else: # single line block
block = j
j = _find_end(tokens, j)
return cls(start, colon, block, j, line=True)
def _find_end(tokens: List[Token], i: int) -> int:
while tokens[i].name not in {'NEWLINE', 'ENDMARKER'}:
i += 1
# depending on the version of python, some will not emit
# NEWLINE('') at the end of a file which does not end with a
# newline (for example 3.6.5)
if tokens[i].name == 'ENDMARKER': # pragma: no cover
i -= 1
else:
i += 1
return i
def _find_if_else_block(tokens: List[Token], i: int) -> Tuple[Block, Block]:
if_block = Block.find(tokens, i)
i = if_block.end
while tokens[i].src != 'else':
i += 1
else_block = Block.find(tokens, i, trim_end=True)
return if_block, else_block
def _find_elif(tokens: List[Token], i: int) -> int:
while tokens[i].src != 'elif': # pragma: no cover (only for <3.8.1)
i -= 1
return i
def _remove_decorator(tokens: List[Token], i: int) -> None:
while tokens[i - 1].src != '@':
i -= 1
if i > 1 and tokens[i - 2].name not in {'NEWLINE', 'NL'}:
i -= 1
end = i + 1
while tokens[end].name != 'NEWLINE':
end += 1
del tokens[i - 1:end + 1]
def _remove_base_class(tokens: List[Token], i: int) -> None:
# look forward and backward to find commas / parens
brace_stack = []
j = i
while tokens[j].src not in {',', ':'}:
if tokens[j].src == ')':
brace_stack.append(j)
j += 1
right = j
if tokens[right].src == ':':
brace_stack.pop()
else:
# if there's a close-paren after a trailing comma
j = right + 1
while tokens[j].name in NON_CODING_TOKENS:
j += 1
if tokens[j].src == ')':
while tokens[j].src != ':':
j += 1
right = j
if brace_stack:
last_part = brace_stack[-1]
else:
last_part = i
j = i
while brace_stack:
if tokens[j].src == '(':
brace_stack.pop()
j -= 1
while tokens[j].src not in {',', '('}:
j -= 1
left = j
# single base, remove the entire bases
if tokens[left].src == '(' and tokens[right].src == ':':
del tokens[left:right]
# multiple bases, base is first
elif tokens[left].src == '(' and tokens[right].src != ':':
# if there's space / comment afterwards remove that too
while tokens[right + 1].name in {UNIMPORTANT_WS, 'COMMENT'}:
right += 1
del tokens[left + 1:right + 1]
# multiple bases, base is not first
else:
del tokens[left:last_part + 1]
def _parse_call_args(
tokens: List[Token],
i: int,
) -> Tuple[List[Tuple[int, int]], int]:
args = []
stack = [i]
i += 1
arg_start = i
while stack:
token = tokens[i]
if len(stack) == 1 and token.src == ',':
args.append((arg_start, i))
arg_start = i + 1
elif token.src in BRACES:
stack.append(i)
elif token.src == BRACES[tokens[stack[-1]].src]:
stack.pop()
# if we're at the end, append that argument
if not stack and tokens_to_src(tokens[arg_start:i]).strip():
args.append((arg_start, i))
i += 1
return args, i
def _get_tmpl(mapping: Dict[str, str], node: NameOrAttr) -> str:
if isinstance(node, ast.Name):
return mapping[node.id]
else:
return mapping[node.attr]
def _arg_str(tokens: List[Token], start: int, end: int) -> str:
return tokens_to_src(tokens[start:end]).strip()
def _replace_call(
tokens: List[Token],
start: int,
end: int,
args: List[Tuple[int, int]],
tmpl: str,
) -> None:
arg_strs = [_arg_str(tokens, *arg) for arg in args]
start_rest = args[0][1] + 1
while (
start_rest < end and
tokens[start_rest].name in {'COMMENT', UNIMPORTANT_WS}
):
start_rest += 1
rest = tokens_to_src(tokens[start_rest:end - 1])
src = tmpl.format(args=arg_strs, rest=rest)
tokens[start:end] = [Token('CODE', src)]
def _replace_yield(tokens: List[Token], i: int) -> None:
in_token = _find_token(tokens, i, 'in')
colon = _find_block_start(tokens, i)
block = Block.find(tokens, i, trim_end=True)
container = tokens_to_src(tokens[in_token + 1:colon]).strip()
tokens[i:block.end] = [Token('CODE', f'yield from {container}\n')]
def _fix_py3_plus(
contents_text: str,
min_version: MinVersion,
keep_mock: bool = False,
) -> str:
try:
ast_obj = ast_parse(contents_text)
except SyntaxError:
return contents_text
visitor = FindPy3Plus(keep_mock)
visitor.visit(ast_obj)
if not any((
visitor.bases_to_remove,
visitor.encode_calls,
visitor.if_py2_blocks_else,
visitor.if_py3_blocks,
visitor.if_py3_blocks_else,
visitor.metaclass_type_assignments,
visitor.native_literals,
visitor.io_open_calls,
visitor.open_mode_calls,
visitor.mock_mock,
visitor.mock_absolute_imports,
visitor.mock_relative_imports,
visitor.os_error_alias_calls,
visitor.os_error_alias_simple,
visitor.os_error_alias_excepts,
visitor.no_arg_decorators,
visitor.six_add_metaclass,
visitor.six_b,
visitor.six_calls,
visitor.six_iter,
visitor.six_raise_from,
visitor.six_reraise,
visitor.six_remove_decorators,
visitor.six_simple,
visitor.six_type_ctx,
visitor.six_with_metaclass,
visitor.super_calls,
visitor.yield_from_fors,
)):
return contents_text
try:
tokens = src_to_tokens(contents_text)
except tokenize.TokenError: # pragma: no cover (bpo-2180)
return contents_text
_fixup_dedent_tokens(tokens)
def _replace(i: int, mapping: Dict[str, str], node: NameOrAttr) -> None:
new_token = Token('CODE', _get_tmpl(mapping, node))
if isinstance(node, ast.Name):
tokens[i] = new_token
else:
j = i
while tokens[j].src != node.attr:
# timid: if we see a parenthesis here, skip it
if tokens[j].src == ')':
return
j += 1
tokens[i:j + 1] = [new_token]
for i, token in reversed_enumerate(tokens):
if not token.src:
continue
elif token.offset in visitor.bases_to_remove:
_remove_base_class(tokens, i)
elif token.offset in visitor.if_py3_blocks:
if tokens[i].src == 'if':
if_block = Block.find(tokens, i)
if_block.dedent(tokens)
del tokens[if_block.start:if_block.block]
else:
if_block = Block.find(tokens, _find_elif(tokens, i))
if_block.replace_condition(tokens, [Token('NAME', 'else')])
elif token.offset in visitor.if_py2_blocks_else:
if tokens[i].src == 'if':
if_block, else_block = _find_if_else_block(tokens, i)
else_block.dedent(tokens)
del tokens[if_block.start:else_block.block]
else:
j = _find_elif(tokens, i)
if_block, else_block = _find_if_else_block(tokens, j)
del tokens[if_block.start:else_block.start]
elif token.offset in visitor.if_py3_blocks_else:
if tokens[i].src == 'if':
if_block, else_block = _find_if_else_block(tokens, i)
if_block.dedent(tokens)
del tokens[if_block.end:else_block.end]
del tokens[if_block.start:if_block.block]
else:
j = _find_elif(tokens, i)
if_block, else_block = _find_if_else_block(tokens, j)
del tokens[if_block.end:else_block.end]
if_block.replace_condition(tokens, [Token('NAME', 'else')])
elif token.offset in visitor.metaclass_type_assignments:
j = _find_end(tokens, i)
del tokens[i:j + 1]
elif token.offset in visitor.native_literals:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
if any(tok.name == 'NL' for tok in tokens[i:end]):
continue
if func_args:
_replace_call(tokens, i, end, func_args, '{args[0]}')
else:
tokens[i:end] = [token._replace(name='STRING', src="''")]
elif token.offset in visitor.six_type_ctx:
_replace(i, SIX_TYPE_CTX_ATTRS, visitor.six_type_ctx[token.offset])
elif token.offset in visitor.six_simple:
_replace(i, SIX_SIMPLE_ATTRS, visitor.six_simple[token.offset])
elif token.offset in visitor.six_remove_decorators:
_remove_decorator(tokens, i)
elif token.offset in visitor.six_b:
j = _find_open_paren(tokens, i)
if (
tokens[j + 1].name == 'STRING' and
_is_ascii(tokens[j + 1].src) and
tokens[j + 2].src == ')'
):
func_args, end = _parse_call_args(tokens, j)
_replace_call(tokens, i, end, func_args, SIX_B_TMPL)
elif token.offset in visitor.six_iter:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
call = visitor.six_iter[token.offset]
assert isinstance(call.func, (ast.Name, ast.Attribute))
template = f'iter({_get_tmpl(SIX_CALLS, call.func)})'
_replace_call(tokens, i, end, func_args, template)
elif token.offset in visitor.six_calls:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
call = visitor.six_calls[token.offset]
assert isinstance(call.func, (ast.Name, ast.Attribute))
template = _get_tmpl(SIX_CALLS, call.func)
_replace_call(tokens, i, end, func_args, template)
elif token.offset in visitor.six_raise_from:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
_replace_call(tokens, i, end, func_args, RAISE_FROM_TMPL)
elif token.offset in visitor.six_reraise:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
if len(func_args) == 1:
tmpl = RERAISE_TMPL
elif len(func_args) == 2:
tmpl = RERAISE_2_TMPL
else:
tmpl = RERAISE_3_TMPL
_replace_call(tokens, i, end, func_args, tmpl)
elif token.offset in visitor.six_add_metaclass:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
metaclass = f'metaclass={_arg_str(tokens, *func_args[0])}'
# insert `metaclass={args[0]}` into `class:`
# search forward for the `class` token
j = i + 1
while tokens[j].src != 'class':
j += 1
class_token = j
# then search forward for a `:` token, not inside a brace
j = _find_block_start(tokens, j)
last_paren = -1
for k in range(class_token, j):
if tokens[k].src == ')':
last_paren = k
if last_paren == -1:
tokens.insert(j, Token('CODE', f'({metaclass})'))
else:
insert = last_paren - 1
while tokens[insert].name in NON_CODING_TOKENS:
insert -= 1
if tokens[insert].src == '(': # no bases
src = metaclass
elif tokens[insert].src != ',':
src = f', {metaclass}'
else:
src = f' {metaclass},'
tokens.insert(insert + 1, Token('CODE', src))
_remove_decorator(tokens, i)
elif token.offset in visitor.six_with_metaclass:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
if len(func_args) == 1:
tmpl = WITH_METACLASS_NO_BASES_TMPL
elif len(func_args) == 2:
base = _arg_str(tokens, *func_args[1])
if base == 'object':
tmpl = WITH_METACLASS_NO_BASES_TMPL
else:
tmpl = WITH_METACLASS_BASES_TMPL
else:
tmpl = WITH_METACLASS_BASES_TMPL
_replace_call(tokens, i, end, func_args, tmpl)
elif token.offset in visitor.super_calls:
i = _find_open_paren(tokens, i)
call = visitor.super_calls[token.offset]
victims = _victims(tokens, i, call, gen=False)
del tokens[victims.starts[0] + 1:victims.ends[-1]]
elif token.offset in visitor.encode_calls:
i = _find_open_paren(tokens, i + 1)
call = visitor.encode_calls[token.offset]
victims = _victims(tokens, i, call, gen=False)
del tokens[victims.starts[0] + 1:victims.ends[-1]]
elif token.offset in visitor.io_open_calls:
j = _find_open_paren(tokens, i)
tokens[i:j] = [token._replace(name='NAME', src='open')]
elif token.offset in visitor.mock_mock:
j = _find_token(tokens, i + 1, 'mock')
del tokens[i + 1:j + 1]
elif token.offset in visitor.mock_absolute_imports:
j = _find_token(tokens, i, 'mock')
if (
j + 2 < len(tokens) and
tokens[j + 1].src == '.' and
tokens[j + 2].src == 'mock'
):
j += 2
src = 'from unittest import mock'
tokens[i:j + 1] = [tokens[j]._replace(name='NAME', src=src)]
elif token.offset in visitor.mock_relative_imports:
j = _find_token(tokens, i, 'mock')
if (
j + 2 < len(tokens) and
tokens[j + 1].src == '.' and
tokens[j + 2].src == 'mock'
):
k = j + 2
else:
k = j
src = 'unittest.mock'
tokens[j:k + 1] = [tokens[j]._replace(name='NAME', src=src)]
elif token.offset in visitor.open_mode_calls:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
mode = tokens_to_src(tokens[slice(*func_args[1])])
mode_stripped = mode.strip().strip('"\'')
if mode_stripped in U_MODE_REMOVE:
del tokens[func_args[0][1]:func_args[1][1]]
elif mode_stripped in U_MODE_REPLACE_R:
new_mode = mode.replace('U', 'r')
tokens[slice(*func_args[1])] = [Token('SRC', new_mode)]
elif mode_stripped in U_MODE_REMOVE_U:
new_mode = mode.replace('U', '')
tokens[slice(*func_args[1])] = [Token('SRC', new_mode)]
else:
raise AssertionError(f'unreachable: {mode!r}')
elif token.offset in visitor.os_error_alias_calls:
j = _find_open_paren(tokens, i)
tokens[i:j] = [token._replace(name='NAME', src='OSError')]
elif token.offset in visitor.os_error_alias_simple:
node = visitor.os_error_alias_simple[token.offset]
_replace(i, collections.defaultdict(lambda: 'OSError'), node)
elif token.offset in visitor.os_error_alias_excepts:
line, utf8_byte_offset = token.line, token.utf8_byte_offset
# find all the arg strs in the tuple
except_index = i
while tokens[except_index].src != 'except':
except_index -= 1
start = _find_open_paren(tokens, except_index)
func_args, end = _parse_call_args(tokens, start)
# save the exceptions and remove the block
arg_strs = [_arg_str(tokens, *arg) for arg in func_args]
del tokens[start:end]
# rewrite the block without dupes
args = []
for arg in arg_strs:
left, part, right = arg.partition('.')
if (
left in visitor.OS_ERROR_ALIAS_MODULES and
part == '.' and
right == 'error'
):
args.append('OSError')
elif (
left in visitor.OS_ERROR_ALIASES and
part == right == ''
):
args.append('OSError')
elif (
left == 'error' and
part == right == '' and
(
'error' in visitor._from_imports['mmap'] or
'error' in visitor._from_imports['select'] or
'error' in visitor._from_imports['socket']
)
):
args.append('OSError')
else:
args.append(arg)
unique_args = tuple(collections.OrderedDict.fromkeys(args))
if len(unique_args) > 1:
joined = '({})'.format(', '.join(unique_args))
elif tokens[start - 1].name != 'UNIMPORTANT_WS':
joined = ' {}'.format(unique_args[0])
else:
joined = unique_args[0]
new = Token('CODE', joined, line, utf8_byte_offset)
tokens.insert(start, new)
visitor.os_error_alias_excepts.discard(token.offset)
elif token.offset in visitor.yield_from_fors:
_replace_yield(tokens, i)
elif (
min_version >= (3, 8) and
token.offset in visitor.no_arg_decorators
):
i = _find_open_paren(tokens, i)
j = _find_token(tokens, i, ')')
del tokens[i:j + 1]
return tokens_to_src(tokens)
def _simple_arg(arg: ast.expr) -> bool:
return (
isinstance(arg, ast.Name) or
(isinstance(arg, ast.Attribute) and _simple_arg(arg.value)) or
(
isinstance(arg, ast.Call) and
_simple_arg(arg.func) and
not arg.args and not arg.keywords
)
)
def _starargs(call: ast.Call) -> bool:
return (
any(k.arg is None for k in call.keywords) or
any(isinstance(a, ast.Starred) for a in call.args)
)
def _format_params(call: ast.Call) -> Dict[str, str]:
params = {}
for i, arg in enumerate(call.args):
params[str(i)] = _unparse(arg)
for kwd in call.keywords:
# kwd.arg can't be None here because we exclude starargs
assert kwd.arg is not None
params[kwd.arg] = _unparse(kwd.value)
return params
class FindPy36Plus(ast.NodeVisitor):
def __init__(self) -> None:
self.fstrings: Dict[Offset, ast.Call] = {}
self.named_tuples: Dict[Offset, ast.Call] = {}
self.dict_typed_dicts: Dict[Offset, ast.Call] = {}
self.kw_typed_dicts: Dict[Offset, ast.Call] = {}
self._from_imports: Dict[str, Set[str]] = collections.defaultdict(set)
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
if node.level == 0 and node.module in {'typing', 'typing_extensions'}:
for name in node.names:
if not name.asname:
self._from_imports[node.module].add(name.name)
self.generic_visit(node)
def _is_attr(self, node: ast.AST, mods: Set[str], name: str) -> bool:
return (
(
isinstance(node, ast.Name) and
node.id == name and
any(name in self._from_imports[mod] for mod in mods)
) or
(
isinstance(node, ast.Attribute) and
node.attr == name and
isinstance(node.value, ast.Name) and
node.value.id in mods
)
)
def _parse(self, node: ast.Call) -> Optional[Tuple[DotFormatPart, ...]]:
if not (
isinstance(node.func, ast.Attribute) and
isinstance(node.func.value, ast.Str) and
node.func.attr == 'format' and
all(_simple_arg(arg) for arg in node.args) and
all(_simple_arg(k.value) for k in node.keywords) and
not _starargs(node)
):
return None
try:
return parse_format(node.func.value.s)
except ValueError:
return None
def visit_Call(self, node: ast.Call) -> None:
parsed = self._parse(node)
if parsed is not None:
params = _format_params(node)
seen: Set[str] = set()
i = 0
for _, name, spec, _ in parsed:
# timid: difficult to rewrite correctly
if spec is not None and '{' in spec:
break
if name is not None:
candidate, _, _ = name.partition('.')
# timid: could make the f-string longer
if candidate and candidate in seen:
break
# timid: bracketed
elif '[' in name:
break
seen.add(candidate)
key = candidate or str(i)
# their .format() call is broken currently
if key not in params:
break
if not candidate:
i += 1
else:
self.fstrings[_ast_to_offset(node)] = node
self.generic_visit(node)
def visit_Assign(self, node: ast.Assign) -> None:
if (
# NT = ...("NT", ...)
len(node.targets) == 1 and
isinstance(node.targets[0], ast.Name) and
isinstance(node.value, ast.Call) and
len(node.value.args) >= 1 and
isinstance(node.value.args[0], ast.Str) and
node.targets[0].id == node.value.args[0].s and
not _starargs(node.value)
):
if (
self._is_attr(
node.value.func, {'typing'}, 'NamedTuple',
) and
len(node.value.args) == 2 and
not node.value.keywords and
isinstance(node.value.args[1], (ast.List, ast.Tuple)) and
len(node.value.args[1].elts) > 0 and
all(
isinstance(tup, ast.Tuple) and
len(tup.elts) == 2 and
isinstance(tup.elts[0], ast.Str) and
tup.elts[0].s.isidentifier() and
tup.elts[0].s not in _KEYWORDS
for tup in node.value.args[1].elts
)
):
self.named_tuples[_ast_to_offset(node)] = node.value
elif (
self._is_attr(
node.value.func,
{'typing', 'typing_extensions'},
'TypedDict',
) and
len(node.value.args) == 1 and
len(node.value.keywords) > 0
):
self.kw_typed_dicts[_ast_to_offset(node)] = node.value
elif (
self._is_attr(
node.value.func,
{'typing', 'typing_extensions'},
'TypedDict',
) and
len(node.value.args) == 2 and
not node.value.keywords and
isinstance(node.value.args[1], ast.Dict) and
node.value.args[1].keys and
all(
isinstance(k, ast.Str) and
k.s.isidentifier() and
k.s not in _KEYWORDS
for k in node.value.args[1].keys
)
):
self.dict_typed_dicts[_ast_to_offset(node)] = node.value
self.generic_visit(node)
def _unparse(node: ast.expr) -> str:
if isinstance(node, ast.Name):
return node.id
elif isinstance(node, ast.Attribute):
return ''.join((_unparse(node.value), '.', node.attr))
elif isinstance(node, ast.Call):
return '{}()'.format(_unparse(node.func))
elif isinstance(node, ast.Subscript):
if sys.version_info >= (3, 9): # pragma: no cover (py39+)
node_slice: ast.expr = node.slice
elif isinstance(node.slice, ast.Index): # pragma: no cover (<py39)
node_slice = node.slice.value
else:
raise AssertionError(f'expected Slice: {ast.dump(node)}')
if isinstance(node_slice, ast.Tuple):
if len(node_slice.elts) == 1:
slice_s = f'{_unparse(node_slice.elts[0])},'
else:
slice_s = ', '.join(_unparse(elt) for elt in node_slice.elts)
else:
slice_s = _unparse(node_slice)
return '{}[{}]'.format(_unparse(node.value), slice_s)
elif isinstance(node, ast.Str):
return repr(node.s)
elif isinstance(node, ast.Ellipsis):
return '...'
elif isinstance(node, ast.List):
return '[{}]'.format(', '.join(_unparse(elt) for elt in node.elts))
elif isinstance(node, ast.NameConstant):
return repr(node.value)
else:
raise NotImplementedError(ast.dump(node))
def _to_fstring(src: str, call: ast.Call) -> str:
params = _format_params(call)
parts = []
i = 0
for s, name, spec, conv in parse_format('f' + src):
if name is not None:
k, dot, rest = name.partition('.')
name = ''.join((params[k or str(i)], dot, rest))
if not k: # named and auto params can be in different orders
i += 1
parts.append((s, name, spec, conv))
return unparse_parsed_string(parts)
def _replace_typed_class(
tokens: List[Token],
i: int,
call: ast.Call,
types: Dict[str, ast.expr],
) -> None:
if i > 0 and tokens[i - 1].name in {'INDENT', UNIMPORTANT_WS}:
indent = f'{tokens[i - 1].src}{' ' * 4}'
else:
indent = ' ' * 4
# NT = NamedTuple("nt", [("a", int)])
# ^i ^end
end = i + 1
while end < len(tokens) and tokens[end].name != 'NEWLINE':
end += 1
attrs = '\n'.join(f'{indent}{k}: {_unparse(v)}' for k, v in types.items())
src = f'class {tokens[i].src}({_unparse(call.func)}):\n{attrs}'
tokens[i:end] = [Token('CODE', src)]
def _fix_py36_plus(contents_text: str) -> str:
try:
ast_obj = ast_parse(contents_text)
except SyntaxError:
return contents_text
visitor = FindPy36Plus()
visitor.visit(ast_obj)
if not any((
visitor.fstrings,
visitor.named_tuples,
visitor.dict_typed_dicts,
visitor.kw_typed_dicts,
)):
return contents_text
try:
tokens = src_to_tokens(contents_text)
except tokenize.TokenError: # pragma: no cover (bpo-2180)
return contents_text
for i, token in reversed_enumerate(tokens):
if token.offset in visitor.fstrings:
node = visitor.fstrings[token.offset]
# TODO: handle \N escape sequences
if r'\N' in token.src:
continue
paren = i + 3
if tokens_to_src(tokens[i + 1:paren + 1]) != '.format(':
continue
# we don't actually care about arg position, so we pass `node`
victims = _victims(tokens, paren, node, gen=False)
end = victims.ends[-1]
# if it spans more than one line, bail
if tokens[end].line != token.line:
continue
tokens[i] = token._replace(src=_to_fstring(token.src, node))
del tokens[i + 1:end + 1]
elif token.offset in visitor.named_tuples and token.name == 'NAME':
call = visitor.named_tuples[token.offset]
types: Dict[str, ast.expr] = {
tup.elts[0].s: tup.elts[1] # type: ignore # (checked above)
for tup in call.args[1].elts # type: ignore # (checked above)
}
_replace_typed_class(tokens, i, call, types)
elif token.offset in visitor.kw_typed_dicts and token.name == 'NAME':
call = visitor.kw_typed_dicts[token.offset]
types = {
arg.arg: arg.value # type: ignore # (checked above)
for arg in call.keywords
}
_replace_typed_class(tokens, i, call, types)
elif token.offset in visitor.dict_typed_dicts and token.name == 'NAME':
call = visitor.dict_typed_dicts[token.offset]
types = {
k.s: v # type: ignore # (checked above)
for k, v in zip(
call.args[1].keys, # type: ignore # (checked above)
call.args[1].values, # type: ignore # (checked above)
)
}
_replace_typed_class(tokens, i, call, types)
return tokens_to_src(tokens)
def _fix_file(filename: str, args: argparse.Namespace) -> int:
if filename == '-':
contents_bytes = sys.stdin.buffer.read()
else:
with open(filename, 'rb') as fb:
contents_bytes = fb.read()
try:
contents_text_orig = contents_text = contents_bytes.decode()
except UnicodeDecodeError:
print(f'{filename} is non-utf-8 (not supported)')
return 1
contents_text = _fix_py2_compatible(contents_text)
contents_text = _fix_tokens(contents_text, min_version=args.min_version)
if not args.keep_percent_format:
contents_text = _fix_percent_format(contents_text)
if args.min_version >= (3,):
contents_text = _fix_py3_plus(
contents_text, args.min_version, args.keep_mock,
)
if args.min_version >= (3, 6):
contents_text = _fix_py36_plus(contents_text)
if filename == '-':
print(contents_text, end='')
elif contents_text != contents_text_orig:
print(f'Rewriting {filename}', file=sys.stderr)
with open(filename, 'w', encoding='UTF-8', newline='') as f:
f.write(contents_text)
if args.exit_zero_even_if_changed:
return 0
else:
return contents_text != contents_text_orig
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*')
parser.add_argument('--exit-zero-even-if-changed', action='store_true')
parser.add_argument('--keep-percent-format', action='store_true')
parser.add_argument('--keep-mock', action='store_true')
parser.add_argument(
'--py3-plus', '--py3-only',
action='store_const', dest='min_version', default=(2, 7), const=(3,),
)
parser.add_argument(
'--py36-plus',
action='store_const', dest='min_version', const=(3, 6),
)
parser.add_argument(
'--py37-plus',
action='store_const', dest='min_version', const=(3, 7),
)
parser.add_argument(
'--py38-plus',
action='store_const', dest='min_version', const=(3, 8),
)
args = parser.parse_args(argv)
ret = 0
for filename in args.filenames:
ret |= _fix_file(filename, args)
return ret
if __name__ == '__main__':
exit(main())
| import argparse
import ast
import codecs
import collections
import contextlib
import keyword
import re
import string
import sys
import tokenize
import warnings
from typing import Any
from typing import cast
from typing import Container
from typing import Dict
from typing import Generator
from typing import Iterable
from typing import List
from typing import Match
from typing import NamedTuple
from typing import Optional
from typing import Pattern
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import Union
from tokenize_rt import NON_CODING_TOKENS
from tokenize_rt import Offset
from tokenize_rt import parse_string_literal
from tokenize_rt import reversed_enumerate
from tokenize_rt import rfind_string_parts
from tokenize_rt import src_to_tokens
from tokenize_rt import Token
from tokenize_rt import tokens_to_src
from tokenize_rt import UNIMPORTANT_WS
MinVersion = Tuple[int, ...]
DotFormatPart = Tuple[str, Optional[str], Optional[str], Optional[str]]
PercentFormatPart = Tuple[
Optional[str],
Optional[str],
Optional[str],
Optional[str],
str,
]
PercentFormat = Tuple[str, Optional[PercentFormatPart]]
ListCompOrGeneratorExp = Union[ast.ListComp, ast.GeneratorExp]
ListOrTuple = Union[ast.List, ast.Tuple]
NameOrAttr = Union[ast.Name, ast.Attribute]
AnyFunctionDef = Union[ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda]
SyncFunctionDef = Union[ast.FunctionDef, ast.Lambda]
_stdlib_parse_format = string.Formatter().parse
_KEYWORDS = frozenset(keyword.kwlist)
def parse_format(s: str) -> Tuple[DotFormatPart, ...]:
"""Makes the empty string not a special case. In the stdlib, there's
loss of information (the type) on the empty string.
"""
parsed = tuple(_stdlib_parse_format(s))
if not parsed:
return ((s, None, None, None),)
else:
return parsed
def unparse_parsed_string(parsed: Sequence[DotFormatPart]) -> str:
def _convert_tup(tup: DotFormatPart) -> str:
ret, field_name, format_spec, conversion = tup
ret = ret.replace('{', '{{')
ret = ret.replace('}', '}}')
if field_name is not None:
ret += '{' + field_name
if conversion:
ret += '!' + conversion
if format_spec:
ret += ':' + format_spec
ret += '}'
return ret
return ''.join(_convert_tup(tup) for tup in parsed)
def _ast_to_offset(node: Union[ast.expr, ast.stmt]) -> Offset:
return Offset(node.lineno, node.col_offset)
def ast_parse(contents_text: str) -> ast.Module:
# intentionally ignore warnings, we might be fixing warning-ridden syntax
with warnings.catch_warnings():
warnings.simplefilter('ignore')
return ast.parse(contents_text.encode())
def inty(s: str) -> bool:
try:
int(s)
return True
except (ValueError, TypeError):
return False
BRACES = {'(': ')', '[': ']', '{': '}'}
OPENING, CLOSING = frozenset(BRACES), frozenset(BRACES.values())
SET_TRANSFORM = (ast.List, ast.ListComp, ast.GeneratorExp, ast.Tuple)
def _is_wtf(func: str, tokens: List[Token], i: int) -> bool:
return tokens[i].src != func or tokens[i + 1].src != '('
def _process_set_empty_literal(tokens: List[Token], start: int) -> None:
if _is_wtf('set', tokens, start):
return
i = start + 2
brace_stack = ['(']
while brace_stack:
token = tokens[i].src
if token == BRACES[brace_stack[-1]]:
brace_stack.pop()
elif token in BRACES:
brace_stack.append(token)
elif '\n' in token:
# Contains a newline, could cause a SyntaxError, bail
return
i += 1
# Remove the inner tokens
del tokens[start + 2:i - 1]
def _search_until(tokens: List[Token], idx: int, arg: ast.expr) -> int:
while (
idx < len(tokens) and
not (
tokens[idx].line == arg.lineno and
tokens[idx].utf8_byte_offset == arg.col_offset
)
):
idx += 1
return idx
if sys.version_info >= (3, 8): # pragma: no cover (py38+)
# python 3.8 fixed the offsets of generators / tuples
def _arg_token_index(tokens: List[Token], i: int, arg: ast.expr) -> int:
idx = _search_until(tokens, i, arg) + 1
while idx < len(tokens) and tokens[idx].name in NON_CODING_TOKENS:
idx += 1
return idx
else: # pragma: no cover (<py38)
def _arg_token_index(tokens: List[Token], i: int, arg: ast.expr) -> int:
# lists containing non-tuples report the first element correctly
if isinstance(arg, ast.List):
# If the first element is a tuple, the ast lies to us about its col
# offset. We must find the first `(` token after the start of the
# list element.
if isinstance(arg.elts[0], ast.Tuple):
i = _search_until(tokens, i, arg)
return _find_open_paren(tokens, i)
else:
return _search_until(tokens, i, arg.elts[0])
# others' start position points at their first child node already
else:
return _search_until(tokens, i, arg)
class Victims(NamedTuple):
starts: List[int]
ends: List[int]
first_comma_index: Optional[int]
arg_index: int
def _victims(
tokens: List[Token],
start: int,
arg: ast.expr,
gen: bool,
) -> Victims:
starts = [start]
start_depths = [1]
ends: List[int] = []
first_comma_index = None
arg_depth = None
arg_index = _arg_token_index(tokens, start, arg)
brace_stack = [tokens[start].src]
i = start + 1
while brace_stack:
token = tokens[i].src
is_start_brace = token in BRACES
is_end_brace = token == BRACES[brace_stack[-1]]
if i == arg_index:
arg_depth = len(brace_stack)
if is_start_brace:
brace_stack.append(token)
# Remove all braces before the first element of the inner
# comprehension's target.
if is_start_brace and arg_depth is None:
start_depths.append(len(brace_stack))
starts.append(i)
if (
token == ',' and
len(brace_stack) == arg_depth and
first_comma_index is None
):
first_comma_index = i
if is_end_brace and len(brace_stack) in start_depths:
if tokens[i - 2].src == ',' and tokens[i - 1].src == ' ':
ends.extend((i - 2, i - 1, i))
elif tokens[i - 1].src == ',':
ends.extend((i - 1, i))
else:
ends.append(i)
if len(brace_stack) > 1 and tokens[i + 1].src == ',':
ends.append(i + 1)
if is_end_brace:
brace_stack.pop()
i += 1
# May need to remove a trailing comma for a comprehension
if gen:
i -= 2
while tokens[i].name in NON_CODING_TOKENS:
i -= 1
if tokens[i].src == ',':
ends.append(i)
return Victims(starts, sorted(set(ends)), first_comma_index, arg_index)
def _find_token(tokens: List[Token], i: int, src: str) -> int:
while tokens[i].src != src:
i += 1
return i
def _find_open_paren(tokens: List[Token], i: int) -> int:
return _find_token(tokens, i, '(')
def _is_on_a_line_by_self(tokens: List[Token], i: int) -> bool:
return (
tokens[i - 2].name == 'NL' and
tokens[i - 1].name == UNIMPORTANT_WS and
tokens[i + 1].name == 'NL'
)
def _remove_brace(tokens: List[Token], i: int) -> None:
if _is_on_a_line_by_self(tokens, i):
del tokens[i - 1:i + 2]
else:
del tokens[i]
def _process_set_literal(
tokens: List[Token],
start: int,
arg: ast.expr,
) -> None:
if _is_wtf('set', tokens, start):
return
gen = isinstance(arg, ast.GeneratorExp)
set_victims = _victims(tokens, start + 1, arg, gen=gen)
del set_victims.starts[0]
end_index = set_victims.ends.pop()
tokens[end_index] = Token('OP', '}')
for index in reversed(set_victims.starts + set_victims.ends):
_remove_brace(tokens, index)
tokens[start:start + 2] = [Token('OP', '{')]
def _process_dict_comp(
tokens: List[Token],
start: int,
arg: ListCompOrGeneratorExp,
) -> None:
if _is_wtf('dict', tokens, start):
return
dict_victims = _victims(tokens, start + 1, arg, gen=True)
elt_victims = _victims(tokens, dict_victims.arg_index, arg.elt, gen=True)
del dict_victims.starts[0]
end_index = dict_victims.ends.pop()
tokens[end_index] = Token('OP', '}')
for index in reversed(dict_victims.ends):
_remove_brace(tokens, index)
# See #6, Fix SyntaxError from rewriting dict((a, b)for a, b in y)
if tokens[elt_victims.ends[-1] + 1].src == 'for':
tokens.insert(elt_victims.ends[-1] + 1, Token(UNIMPORTANT_WS, ' '))
for index in reversed(elt_victims.ends):
_remove_brace(tokens, index)
assert elt_victims.first_comma_index is not None
tokens[elt_victims.first_comma_index] = Token('OP', ':')
for index in reversed(dict_victims.starts + elt_victims.starts):
_remove_brace(tokens, index)
tokens[start:start + 2] = [Token('OP', '{')]
def _process_is_literal(
tokens: List[Token],
i: int,
compare: Union[ast.Is, ast.IsNot],
) -> None:
while tokens[i].src != 'is':
i -= 1
if isinstance(compare, ast.Is):
tokens[i] = tokens[i]._replace(src='==')
else:
tokens[i] = tokens[i]._replace(src='!=')
# since we iterate backward, the dummy tokens keep the same length
i += 1
while tokens[i].src != 'not':
tokens[i] = Token('DUMMY', '')
i += 1
tokens[i] = Token('DUMMY', '')
LITERAL_TYPES = (ast.Str, ast.Num, ast.Bytes)
class Py2CompatibleVisitor(ast.NodeVisitor):
def __init__(self) -> None:
self.dicts: Dict[Offset, ListCompOrGeneratorExp] = {}
self.sets: Dict[Offset, ast.expr] = {}
self.set_empty_literals: Dict[Offset, ListOrTuple] = {}
self.is_literal: Dict[Offset, Union[ast.Is, ast.IsNot]] = {}
def visit_Call(self, node: ast.Call) -> None:
if (
isinstance(node.func, ast.Name) and
node.func.id == 'set' and
len(node.args) == 1 and
not node.keywords and
isinstance(node.args[0], SET_TRANSFORM)
):
arg, = node.args
key = _ast_to_offset(node.func)
if isinstance(arg, (ast.List, ast.Tuple)) and not arg.elts:
self.set_empty_literals[key] = arg
else:
self.sets[key] = arg
elif (
isinstance(node.func, ast.Name) and
node.func.id == 'dict' and
len(node.args) == 1 and
not node.keywords and
isinstance(node.args[0], (ast.ListComp, ast.GeneratorExp)) and
isinstance(node.args[0].elt, (ast.Tuple, ast.List)) and
len(node.args[0].elt.elts) == 2
):
self.dicts[_ast_to_offset(node.func)] = node.args[0]
self.generic_visit(node)
def visit_Compare(self, node: ast.Compare) -> None:
left = node.left
for op, right in zip(node.ops, node.comparators):
if (
isinstance(op, (ast.Is, ast.IsNot)) and
(
isinstance(left, LITERAL_TYPES) or
isinstance(right, LITERAL_TYPES)
)
):
self.is_literal[_ast_to_offset(right)] = op
left = right
self.generic_visit(node)
def _fix_py2_compatible(contents_text: str) -> str:
try:
ast_obj = ast_parse(contents_text)
except SyntaxError:
return contents_text
visitor = Py2CompatibleVisitor()
visitor.visit(ast_obj)
if not any((
visitor.dicts,
visitor.sets,
visitor.set_empty_literals,
visitor.is_literal,
)):
return contents_text
try:
tokens = src_to_tokens(contents_text)
except tokenize.TokenError: # pragma: no cover (bpo-2180)
return contents_text
for i, token in reversed_enumerate(tokens):
if token.offset in visitor.dicts:
_process_dict_comp(tokens, i, visitor.dicts[token.offset])
elif token.offset in visitor.set_empty_literals:
_process_set_empty_literal(tokens, i)
elif token.offset in visitor.sets:
_process_set_literal(tokens, i, visitor.sets[token.offset])
elif token.offset in visitor.is_literal:
_process_is_literal(tokens, i, visitor.is_literal[token.offset])
return tokens_to_src(tokens)
def _imports_unicode_literals(contents_text: str) -> bool:
try:
ast_obj = ast_parse(contents_text)
except SyntaxError:
return False
for node in ast_obj.body:
# Docstring
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Str):
continue
elif isinstance(node, ast.ImportFrom):
if (
node.level == 0 and
node.module == '__future__' and
any(name.name == 'unicode_literals' for name in node.names)
):
return True
elif node.module == '__future__':
continue
else:
return False
else:
return False
return False
# https://docs.python.org/3/reference/lexical_analysis.html
ESCAPE_STARTS = frozenset((
'\n', '\r', '\\', "'", '"', 'a', 'b', 'f', 'n', 'r', 't', 'v',
'0', '1', '2', '3', '4', '5', '6', '7', # octal escapes
'x', # hex escapes
))
ESCAPE_RE = re.compile(r'\\.', re.DOTALL)
NAMED_ESCAPE_NAME = re.compile(r'\{[^}]+\}')
def _fix_escape_sequences(token: Token) -> Token:
prefix, rest = parse_string_literal(token.src)
actual_prefix = prefix.lower()
if 'r' in actual_prefix or '\\' not in rest:
return token
is_bytestring = 'b' in actual_prefix
def _is_valid_escape(match: Match[str]) -> bool:
c = match.group()[1]
return (
c in ESCAPE_STARTS or
(not is_bytestring and c in 'uU') or
(
not is_bytestring and
c == 'N' and
bool(NAMED_ESCAPE_NAME.match(rest, match.end()))
)
)
has_valid_escapes = False
has_invalid_escapes = False
for match in ESCAPE_RE.finditer(rest):
if _is_valid_escape(match):
has_valid_escapes = True
else:
has_invalid_escapes = True
def cb(match: Match[str]) -> str:
matched = match.group()
if _is_valid_escape(match):
return matched
else:
return fr'\{matched}'
if has_invalid_escapes and (has_valid_escapes or 'u' in actual_prefix):
return token._replace(src=prefix + ESCAPE_RE.sub(cb, rest))
elif has_invalid_escapes and not has_valid_escapes:
return token._replace(src=prefix + 'r' + rest)
else:
return token
def _remove_u_prefix(token: Token) -> Token:
prefix, rest = parse_string_literal(token.src)
if 'u' not in prefix.lower():
return token
else:
new_prefix = prefix.replace('u', '').replace('U', '')
return token._replace(src=new_prefix + rest)
def _fix_ur_literals(token: Token) -> Token:
prefix, rest = parse_string_literal(token.src)
if prefix.lower() != 'ur':
return token
else:
def cb(match: Match[str]) -> str:
escape = match.group()
if escape[1].lower() == 'u':
return escape
else:
return '\\' + match.group()
rest = ESCAPE_RE.sub(cb, rest)
prefix = prefix.replace('r', '').replace('R', '')
return token._replace(src=prefix + rest)
def _fix_long(src: str) -> str:
return src.rstrip('lL')
def _fix_octal(s: str) -> str:
if not s.startswith('0') or not s.isdigit() or s == len(s) * '0':
return s
elif len(s) == 2:
return s[1:]
else:
return '0o' + s[1:]
def _fix_extraneous_parens(tokens: List[Token], i: int) -> None:
# search forward for another non-coding token
i += 1
while tokens[i].name in NON_CODING_TOKENS:
i += 1
# if we did not find another brace, return immediately
if tokens[i].src != '(':
return
start = i
depth = 1
while depth:
i += 1
# found comma or yield at depth 1: this is a tuple / coroutine
if depth == 1 and tokens[i].src in {',', 'yield'}:
return
elif tokens[i].src in OPENING:
depth += 1
elif tokens[i].src in CLOSING:
depth -= 1
end = i
# empty tuple
if all(t.name in NON_CODING_TOKENS for t in tokens[start + 1:i]):
return
# search forward for the next non-coding token
i += 1
while tokens[i].name in NON_CODING_TOKENS:
i += 1
if tokens[i].src == ')':
_remove_brace(tokens, end)
_remove_brace(tokens, start)
def _remove_fmt(tup: DotFormatPart) -> DotFormatPart:
if tup[1] is None:
return tup
else:
return (tup[0], '', tup[2], tup[3])
def _fix_format_literal(tokens: List[Token], end: int) -> None:
parts = rfind_string_parts(tokens, end)
parsed_parts = []
last_int = -1
for i in parts:
# f'foo {0}'.format(...) would get turned into a SyntaxError
prefix, _ = parse_string_literal(tokens[i].src)
if 'f' in prefix.lower():
return
try:
parsed = parse_format(tokens[i].src)
except ValueError:
# the format literal was malformed, skip it
return
# The last segment will always be the end of the string and not a
# format, slice avoids the `None` format key
for _, fmtkey, spec, _ in parsed[:-1]:
if (
fmtkey is not None and inty(fmtkey) and
int(fmtkey) == last_int + 1 and
spec is not None and '{' not in spec
):
last_int += 1
else:
return
parsed_parts.append(tuple(_remove_fmt(tup) for tup in parsed))
for i, parsed in zip(parts, parsed_parts):
tokens[i] = tokens[i]._replace(src=unparse_parsed_string(parsed))
def _fix_encode_to_binary(tokens: List[Token], i: int) -> None:
# .encode()
if (
i + 2 < len(tokens) and
tokens[i + 1].src == '(' and
tokens[i + 2].src == ')'
):
victims = slice(i - 1, i + 3)
latin1_ok = False
# .encode('encoding')
elif (
i + 3 < len(tokens) and
tokens[i + 1].src == '(' and
tokens[i + 2].name == 'STRING' and
tokens[i + 3].src == ')'
):
victims = slice(i - 1, i + 4)
prefix, rest = parse_string_literal(tokens[i + 2].src)
if 'f' in prefix.lower():
return
encoding = ast.literal_eval(prefix + rest)
if _is_codec(encoding, 'ascii') or _is_codec(encoding, 'utf-8'):
latin1_ok = False
elif _is_codec(encoding, 'iso8859-1'):
latin1_ok = True
else:
return
else:
return
parts = rfind_string_parts(tokens, i - 2)
if not parts:
return
for part in parts:
prefix, rest = parse_string_literal(tokens[part].src)
escapes = set(ESCAPE_RE.findall(rest))
if (
not _is_ascii(rest) or
'\\u' in escapes or
'\\U' in escapes or
'\\N' in escapes or
('\\x' in escapes and not latin1_ok) or
'f' in prefix.lower()
):
return
for part in parts:
prefix, rest = parse_string_literal(tokens[part].src)
prefix = 'b' + prefix.replace('u', '').replace('U', '')
tokens[part] = tokens[part]._replace(src=prefix + rest)
del tokens[victims]
def _build_import_removals() -> Dict[MinVersion, Dict[str, Tuple[str, ...]]]:
ret = {}
future: Tuple[Tuple[MinVersion, Tuple[str, ...]], ...] = (
((2, 7), ('nested_scopes', 'generators', 'with_statement')),
(
(3,), (
'absolute_import', 'division', 'print_function',
'unicode_literals',
),
),
((3, 6), ()),
((3, 7), ('generator_stop',)),
((3, 8), ()),
)
prev: Tuple[str, ...] = ()
for min_version, names in future:
prev += names
ret[min_version] = {'__future__': prev}
# see reorder_python_imports
for k, v in ret.items():
if k >= (3,):
v.update({
'builtins': (
'ascii', 'bytes', 'chr', 'dict', 'filter', 'hex', 'input',
'int', 'list', 'map', 'max', 'min', 'next', 'object',
'oct', 'open', 'pow', 'range', 'round', 'str', 'super',
'zip', '*',
),
'io': ('open',),
'six': ('callable', 'next'),
'six.moves': ('filter', 'input', 'map', 'range', 'zip'),
})
return ret
IMPORT_REMOVALS = _build_import_removals()
def _fix_import_removals(
tokens: List[Token],
start: int,
min_version: MinVersion,
) -> None:
i = start + 1
name_parts = []
while tokens[i].src != 'import':
if tokens[i].name in {'NAME', 'OP'}:
name_parts.append(tokens[i].src)
i += 1
modname = ''.join(name_parts)
if modname not in IMPORT_REMOVALS[min_version]:
return
found: List[Optional[int]] = []
i += 1
while tokens[i].name not in {'NEWLINE', 'ENDMARKER'}:
if tokens[i].name == 'NAME' or tokens[i].src == '*':
# don't touch aliases
if (
found and found[-1] is not None and
tokens[found[-1]].src == 'as'
):
found[-2:] = [None]
else:
found.append(i)
i += 1
# depending on the version of python, some will not emit NEWLINE('') at the
# end of a file which does not end with a newline (for example 3.6.5)
if tokens[i].name == 'ENDMARKER': # pragma: no cover
i -= 1
remove_names = IMPORT_REMOVALS[min_version][modname]
to_remove = [
x for x in found if x is not None and tokens[x].src in remove_names
]
if len(to_remove) == len(found):
del tokens[start:i + 1]
else:
for idx in reversed(to_remove):
if found[0] == idx: # look forward until next name and del
j = idx + 1
while tokens[j].name != 'NAME':
j += 1
del tokens[idx:j]
else: # look backward for comma and del
j = idx
while tokens[j].src != ',':
j -= 1
del tokens[j:idx + 1]
def _fix_tokens(contents_text: str, min_version: MinVersion) -> str:
remove_u = min_version >= (3,) or _imports_unicode_literals(contents_text)
try:
tokens = src_to_tokens(contents_text)
except tokenize.TokenError:
return contents_text
for i, token in reversed_enumerate(tokens):
if token.name == 'NUMBER':
tokens[i] = token._replace(src=_fix_long(_fix_octal(token.src)))
elif token.name == 'STRING':
tokens[i] = _fix_ur_literals(tokens[i])
if remove_u:
tokens[i] = _remove_u_prefix(tokens[i])
tokens[i] = _fix_escape_sequences(tokens[i])
elif token.src == '(':
_fix_extraneous_parens(tokens, i)
elif token.src == 'format' and i > 0 and tokens[i - 1].src == '.':
_fix_format_literal(tokens, i - 2)
elif token.src == 'encode' and i > 0 and tokens[i - 1].src == '.':
_fix_encode_to_binary(tokens, i)
elif (
min_version >= (3,) and
token.utf8_byte_offset == 0 and
token.line < 3 and
token.name == 'COMMENT' and
tokenize.cookie_re.match(token.src)
):
del tokens[i]
assert tokens[i].name == 'NL', tokens[i].name
del tokens[i]
elif token.src == 'from' and token.utf8_byte_offset == 0:
_fix_import_removals(tokens, i, min_version)
return tokens_to_src(tokens).lstrip()
MAPPING_KEY_RE = re.compile(r'\(([^()]*)\)')
CONVERSION_FLAG_RE = re.compile('[#0+ -]*')
WIDTH_RE = re.compile(r'(?:\*|\d*)')
PRECISION_RE = re.compile(r'(?:\.(?:\*|\d*))?')
LENGTH_RE = re.compile('[hlL]?')
def _must_match(regex: Pattern[str], string: str, pos: int) -> Match[str]:
match = regex.match(string, pos)
assert match is not None
return match
def parse_percent_format(s: str) -> Tuple[PercentFormat, ...]:
def _parse_inner() -> Generator[PercentFormat, None, None]:
string_start = 0
string_end = 0
in_fmt = False
i = 0
while i < len(s):
if not in_fmt:
try:
i = s.index('%', i)
except ValueError: # no more % fields!
yield s[string_start:], None
return
else:
string_end = i
i += 1
in_fmt = True
else:
key_match = MAPPING_KEY_RE.match(s, i)
if key_match:
key: Optional[str] = key_match.group(1)
i = key_match.end()
else:
key = None
conversion_flag_match = _must_match(CONVERSION_FLAG_RE, s, i)
conversion_flag = conversion_flag_match.group() or None
i = conversion_flag_match.end()
width_match = _must_match(WIDTH_RE, s, i)
width = width_match.group() or None
i = width_match.end()
precision_match = _must_match(PRECISION_RE, s, i)
precision = precision_match.group() or None
i = precision_match.end()
# length modifier is ignored
i = _must_match(LENGTH_RE, s, i).end()
try:
conversion = s[i]
except IndexError:
raise ValueError('end-of-string while parsing format')
i += 1
fmt = (key, conversion_flag, width, precision, conversion)
yield s[string_start:string_end], fmt
in_fmt = False
string_start = i
if in_fmt:
raise ValueError('end-of-string while parsing format')
return tuple(_parse_inner())
class FindPercentFormats(ast.NodeVisitor):
def __init__(self) -> None:
self.found: Dict[Offset, ast.BinOp] = {}
def visit_BinOp(self, node: ast.BinOp) -> None:
if isinstance(node.op, ast.Mod) and isinstance(node.left, ast.Str):
try:
parsed = parse_percent_format(node.left.s)
except ValueError:
pass
else:
for _, fmt in parsed:
if not fmt:
continue
key, conversion_flag, width, precision, conversion = fmt
# timid: these require out-of-order parameter consumption
if width == '*' or precision == '.*':
break
# these conversions require modification of parameters
if conversion in {'d', 'i', 'u', 'c'}:
break
# timid: py2: %#o formats different from {:#o} (--py3?)
if '#' in (conversion_flag or '') and conversion == 'o':
break
# no equivalent in format
if key == '':
break
# timid: py2: conversion is subject to modifiers (--py3?)
nontrivial_fmt = any((conversion_flag, width, precision))
if conversion == '%' and nontrivial_fmt:
break
# no equivalent in format
if conversion in {'a', 'r'} and nontrivial_fmt:
break
# all dict substitutions must be named
if isinstance(node.right, ast.Dict) and not key:
break
else:
self.found[_ast_to_offset(node)] = node
self.generic_visit(node)
def _simplify_conversion_flag(flag: str) -> str:
parts: List[str] = []
for c in flag:
if c in parts:
continue
c = c.replace('-', '<')
parts.append(c)
if c == '<' and '0' in parts:
parts.remove('0')
elif c == '+' and ' ' in parts:
parts.remove(' ')
return ''.join(parts)
def _percent_to_format(s: str) -> str:
def _handle_part(part: PercentFormat) -> str:
s, fmt = part
s = s.replace('{', '{{').replace('}', '}}')
if fmt is None:
return s
else:
key, conversion_flag, width, precision, conversion = fmt
if conversion == '%':
return s + '%'
parts = [s, '{']
if width and conversion == 's' and not conversion_flag:
conversion_flag = '>'
if conversion == 's':
conversion = ''
if key:
parts.append(key)
if conversion in {'r', 'a'}:
converter = f'!{conversion}'
conversion = ''
else:
converter = ''
if any((conversion_flag, width, precision, conversion)):
parts.append(':')
if conversion_flag:
parts.append(_simplify_conversion_flag(conversion_flag))
parts.extend(x for x in (width, precision, conversion) if x)
parts.extend(converter)
parts.append('}')
return ''.join(parts)
return ''.join(_handle_part(part) for part in parse_percent_format(s))
def _is_ascii(s: str) -> bool:
if sys.version_info >= (3, 7): # pragma: no cover (py37+)
return s.isascii()
else: # pragma: no cover (<py37)
return all(c in string.printable for c in s)
def _fix_percent_format_tuple(
tokens: List[Token],
start: int,
node: ast.BinOp,
) -> None:
# TODO: this is overly timid
paren = start + 4
if tokens_to_src(tokens[start + 1:paren + 1]) != ' % (':
return
victims = _victims(tokens, paren, node.right, gen=False)
victims.ends.pop()
for index in reversed(victims.starts + victims.ends):
_remove_brace(tokens, index)
newsrc = _percent_to_format(tokens[start].src)
tokens[start] = tokens[start]._replace(src=newsrc)
tokens[start + 1:paren] = [Token('Format', '.format'), Token('OP', '(')]
def _fix_percent_format_dict(
tokens: List[Token],
start: int,
node: ast.BinOp,
) -> None:
seen_keys: Set[str] = set()
keys = {}
# the caller has enforced this
assert isinstance(node.right, ast.Dict)
for k in node.right.keys:
# not a string key
if not isinstance(k, ast.Str):
return
# duplicate key
elif k.s in seen_keys:
return
# not an identifier
elif not k.s.isidentifier():
return
# a keyword
elif k.s in _KEYWORDS:
return
seen_keys.add(k.s)
keys[_ast_to_offset(k)] = k
# TODO: this is overly timid
brace = start + 4
if tokens_to_src(tokens[start + 1:brace + 1]) != ' % {':
return
victims = _victims(tokens, brace, node.right, gen=False)
brace_end = victims.ends[-1]
key_indices = []
for i, token in enumerate(tokens[brace:brace_end], brace):
key = keys.pop(token.offset, None)
if key is None:
continue
# we found the key, but the string didn't match (implicit join?)
elif ast.literal_eval(token.src) != key.s:
return
# the map uses some strange syntax that's not `'key': value`
elif tokens_to_src(tokens[i + 1:i + 3]) != ': ':
return
else:
key_indices.append((i, key.s))
assert not keys, keys
tokens[brace_end] = tokens[brace_end]._replace(src=')')
for (key_index, s) in reversed(key_indices):
tokens[key_index:key_index + 3] = [Token('CODE', f'{s}=')]
newsrc = _percent_to_format(tokens[start].src)
tokens[start] = tokens[start]._replace(src=newsrc)
tokens[start + 1:brace + 1] = [Token('CODE', '.format'), Token('OP', '(')]
def _fix_percent_format(contents_text: str) -> str:
try:
ast_obj = ast_parse(contents_text)
except SyntaxError:
return contents_text
visitor = FindPercentFormats()
visitor.visit(ast_obj)
if not visitor.found:
return contents_text
try:
tokens = src_to_tokens(contents_text)
except tokenize.TokenError: # pragma: no cover (bpo-2180)
return contents_text
for i, token in reversed_enumerate(tokens):
node = visitor.found.get(token.offset)
if node is None:
continue
# TODO: handle \N escape sequences
if r'\N' in token.src:
continue
if isinstance(node.right, ast.Tuple):
_fix_percent_format_tuple(tokens, i, node)
elif isinstance(node.right, ast.Dict):
_fix_percent_format_dict(tokens, i, node)
return tokens_to_src(tokens)
SIX_SIMPLE_ATTRS = {
'text_type': 'str',
'binary_type': 'bytes',
'class_types': '(type,)',
'string_types': '(str,)',
'integer_types': '(int,)',
'unichr': 'chr',
'iterbytes': 'iter',
'print_': 'print',
'exec_': 'exec',
'advance_iterator': 'next',
'next': 'next',
'callable': 'callable',
}
SIX_TYPE_CTX_ATTRS = {
'class_types': 'type',
'string_types': 'str',
'integer_types': 'int',
}
SIX_CALLS = {
'u': '{args[0]}',
'byte2int': '{args[0]}[0]',
'indexbytes': '{args[0]}[{rest}]',
'int2byte': 'bytes(({args[0]},))',
'iteritems': '{args[0]}.items()',
'iterkeys': '{args[0]}.keys()',
'itervalues': '{args[0]}.values()',
'viewitems': '{args[0]}.items()',
'viewkeys': '{args[0]}.keys()',
'viewvalues': '{args[0]}.values()',
'create_unbound_method': '{args[0]}',
'get_unbound_function': '{args[0]}',
'get_method_function': '{args[0]}.__func__',
'get_method_self': '{args[0]}.__self__',
'get_function_closure': '{args[0]}.__closure__',
'get_function_code': '{args[0]}.__code__',
'get_function_defaults': '{args[0]}.__defaults__',
'get_function_globals': '{args[0]}.__globals__',
'assertCountEqual': '{args[0]}.assertCountEqual({rest})',
'assertRaisesRegex': '{args[0]}.assertRaisesRegex({rest})',
'assertRegex': '{args[0]}.assertRegex({rest})',
}
SIX_B_TMPL = 'b{args[0]}'
WITH_METACLASS_NO_BASES_TMPL = 'metaclass={args[0]}'
WITH_METACLASS_BASES_TMPL = '{rest}, metaclass={args[0]}'
RAISE_FROM_TMPL = 'raise {args[0]} from {rest}'
RERAISE_TMPL = 'raise'
RERAISE_2_TMPL = 'raise {args[1]}.with_traceback(None)'
RERAISE_3_TMPL = 'raise {args[1]}.with_traceback({args[2]})'
SIX_NATIVE_STR = frozenset(('ensure_str', 'ensure_text', 'text_type'))
U_MODE_REMOVE = frozenset(('U', 'Ur', 'rU', 'r', 'rt', 'tr'))
U_MODE_REPLACE_R = frozenset(('Ub', 'bU'))
U_MODE_REMOVE_U = frozenset(('rUb', 'Urb', 'rbU', 'Ubr', 'bUr', 'brU'))
U_MODE_REPLACE = U_MODE_REPLACE_R | U_MODE_REMOVE_U
def _all_isinstance(
vals: Iterable[Any],
tp: Union[Type[Any], Tuple[Type[Any], ...]],
) -> bool:
return all(isinstance(v, tp) for v in vals)
def fields_same(n1: ast.AST, n2: ast.AST) -> bool:
for (a1, v1), (a2, v2) in zip(ast.iter_fields(n1), ast.iter_fields(n2)):
# ignore ast attributes, they'll be covered by walk
if a1 != a2:
return False
elif _all_isinstance((v1, v2), ast.AST):
continue
elif _all_isinstance((v1, v2), (list, tuple)):
if len(v1) != len(v2):
return False
# ignore sequences which are all-ast, they'll be covered by walk
elif _all_isinstance(v1, ast.AST) and _all_isinstance(v2, ast.AST):
continue
elif v1 != v2:
return False
elif v1 != v2:
return False
return True
def targets_same(target: ast.AST, yield_value: ast.AST) -> bool:
for t1, t2 in zip(ast.walk(target), ast.walk(yield_value)):
# ignore `ast.Load` / `ast.Store`
if _all_isinstance((t1, t2), ast.expr_context):
continue
elif type(t1) != type(t2):
return False
elif not fields_same(t1, t2):
return False
else:
return True
def _is_codec(encoding: str, name: str) -> bool:
try:
return codecs.lookup(encoding).name == name
except LookupError:
return False
class FindPy3Plus(ast.NodeVisitor):
OS_ERROR_ALIASES = frozenset((
'EnvironmentError',
'IOError',
'WindowsError',
))
OS_ERROR_ALIAS_MODULES = frozenset((
'mmap',
'select',
'socket',
))
FROM_IMPORTED_MODULES = OS_ERROR_ALIAS_MODULES.union(('functools', 'six'))
MOCK_MODULES = frozenset(('mock', 'mock.mock'))
class ClassInfo:
def __init__(self, name: str) -> None:
self.name = name
self.def_depth = 0
self.first_arg_name = ''
class Scope:
def __init__(self) -> None:
self.reads: Set[str] = set()
self.writes: Set[str] = set()
self.yield_from_fors: Set[Offset] = set()
self.yield_from_names: Dict[str, Set[Offset]]
self.yield_from_names = collections.defaultdict(set)
def __init__(self, keep_mock: bool) -> None:
self._find_mock = not keep_mock
self.bases_to_remove: Set[Offset] = set()
self.encode_calls: Dict[Offset, ast.Call] = {}
self._exc_info_imported = False
self._version_info_imported = False
self.if_py3_blocks: Set[Offset] = set()
self.if_py2_blocks_else: Set[Offset] = set()
self.if_py3_blocks_else: Set[Offset] = set()
self.metaclass_type_assignments: Set[Offset] = set()
self.native_literals: Set[Offset] = set()
self._from_imports: Dict[str, Set[str]] = collections.defaultdict(set)
self.io_open_calls: Set[Offset] = set()
self.mock_mock: Set[Offset] = set()
self.mock_absolute_imports: Set[Offset] = set()
self.mock_relative_imports: Set[Offset] = set()
self.open_mode_calls: Set[Offset] = set()
self.os_error_alias_calls: Set[Offset] = set()
self.os_error_alias_simple: Dict[Offset, NameOrAttr] = {}
self.os_error_alias_excepts: Set[Offset] = set()
self.six_add_metaclass: Set[Offset] = set()
self.six_b: Set[Offset] = set()
self.six_calls: Dict[Offset, ast.Call] = {}
self.six_iter: Dict[Offset, ast.Call] = {}
self._previous_node: Optional[ast.AST] = None
self.six_raise_from: Set[Offset] = set()
self.six_reraise: Set[Offset] = set()
self.six_remove_decorators: Set[Offset] = set()
self.six_simple: Dict[Offset, NameOrAttr] = {}
self.six_type_ctx: Dict[Offset, NameOrAttr] = {}
self.six_with_metaclass: Set[Offset] = set()
self._class_info_stack: List[FindPy3Plus.ClassInfo] = []
self._in_comp = 0
self.super_calls: Dict[Offset, ast.Call] = {}
self._in_async_def = False
self._scope_stack: List[FindPy3Plus.Scope] = []
self.yield_from_fors: Set[Offset] = set()
self.no_arg_decorators: Set[Offset] = set()
def _is_six(self, node: ast.expr, names: Container[str]) -> bool:
return (
isinstance(node, ast.Name) and
node.id in names and
node.id in self._from_imports['six']
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'six' and
node.attr in names
)
def _is_star_sys_exc_info(self, node: ast.Call) -> bool:
return (
len(node.args) == 1 and
isinstance(node.args[0], ast.Starred) and
isinstance(node.args[0].value, ast.Call) and
self._is_exc_info(node.args[0].value.func)
)
def _is_lru_cache(self, node: ast.expr) -> bool:
return (
isinstance(node, ast.Name) and
node.id == 'lru_cache' and
node.id in self._from_imports['functools']
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'functools' and
node.attr == 'lru_cache'
)
def _is_mock_mock(self, node: ast.expr) -> bool:
return (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'mock' and
node.attr == 'mock'
)
def _is_io_open(self, node: ast.expr) -> bool:
return (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'io' and
node.attr == 'open'
)
def _is_os_error_alias(self, node: Optional[ast.expr]) -> bool:
return (
isinstance(node, ast.Name) and
node.id in self.OS_ERROR_ALIASES
) or (
isinstance(node, ast.Name) and
node.id == 'error' and
(
node.id in self._from_imports['mmap'] or
node.id in self._from_imports['select'] or
node.id in self._from_imports['socket']
)
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id in self.OS_ERROR_ALIAS_MODULES and
node.attr == 'error'
)
def _is_exc_info(self, node: ast.expr) -> bool:
return (
isinstance(node, ast.Name) and
node.id == 'exc_info' and
self._exc_info_imported
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'sys' and
node.attr == 'exc_info'
)
def _is_version_info(self, node: ast.expr) -> bool:
return (
isinstance(node, ast.Name) and
node.id == 'version_info' and
self._version_info_imported
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'sys' and
node.attr == 'version_info'
)
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
if not node.level:
if node.module in self.FROM_IMPORTED_MODULES:
for name in node.names:
if not name.asname:
self._from_imports[node.module].add(name.name)
elif self._find_mock and node.module in self.MOCK_MODULES:
self.mock_relative_imports.add(_ast_to_offset(node))
elif node.module == 'sys' and any(
name.name == 'exc_info' and not name.asname
for name in node.names
):
self._exc_info_imported = True
elif node.module == 'sys' and any(
name.name == 'version_info' and not name.asname
for name in node.names
):
self._version_info_imported = True
self.generic_visit(node)
def visit_Import(self, node: ast.Import) -> None:
if (
self._find_mock and
len(node.names) == 1 and
node.names[0].name in self.MOCK_MODULES
):
self.mock_absolute_imports.add(_ast_to_offset(node))
self.generic_visit(node)
def visit_ClassDef(self, node: ast.ClassDef) -> None:
for decorator in node.decorator_list:
if self._is_six(decorator, ('python_2_unicode_compatible',)):
self.six_remove_decorators.add(_ast_to_offset(decorator))
elif (
isinstance(decorator, ast.Call) and
self._is_six(decorator.func, ('add_metaclass',)) and
not _starargs(decorator)
):
self.six_add_metaclass.add(_ast_to_offset(decorator))
for base in node.bases:
if isinstance(base, ast.Name) and base.id == 'object':
self.bases_to_remove.add(_ast_to_offset(base))
elif self._is_six(base, ('Iterator',)):
self.bases_to_remove.add(_ast_to_offset(base))
if (
len(node.bases) == 1 and
isinstance(node.bases[0], ast.Call) and
self._is_six(node.bases[0].func, ('with_metaclass',)) and
not _starargs(node.bases[0])
):
self.six_with_metaclass.add(_ast_to_offset(node.bases[0]))
self._class_info_stack.append(FindPy3Plus.ClassInfo(node.name))
self.generic_visit(node)
self._class_info_stack.pop()
@contextlib.contextmanager
def _track_def_depth(
self,
node: AnyFunctionDef,
) -> Generator[None, None, None]:
class_info = self._class_info_stack[-1]
class_info.def_depth += 1
if class_info.def_depth == 1 and node.args.args:
class_info.first_arg_name = node.args.args[0].arg
try:
yield
finally:
class_info.def_depth -= 1
@contextlib.contextmanager
def _scope(self) -> Generator[None, None, None]:
self._scope_stack.append(FindPy3Plus.Scope())
try:
yield
finally:
info = self._scope_stack.pop()
# discard any that were referenced outside of the loop
for name in info.reads:
offsets = info.yield_from_names[name]
info.yield_from_fors.difference_update(offsets)
self.yield_from_fors.update(info.yield_from_fors)
if self._scope_stack:
cell_reads = info.reads - info.writes
self._scope_stack[-1].reads.update(cell_reads)
def _visit_func(self, node: AnyFunctionDef) -> None:
with contextlib.ExitStack() as ctx, self._scope():
if self._class_info_stack:
ctx.enter_context(self._track_def_depth(node))
self.generic_visit(node)
def _visit_sync_func(self, node: SyncFunctionDef) -> None:
self._in_async_def, orig = False, self._in_async_def
self._visit_func(node)
self._in_async_def = orig
visit_FunctionDef = visit_Lambda = _visit_sync_func
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
self._in_async_def, orig = True, self._in_async_def
self._visit_func(node)
self._in_async_def = orig
def _visit_comp(self, node: ast.expr) -> None:
self._in_comp += 1
with self._scope():
self.generic_visit(node)
self._in_comp -= 1
visit_ListComp = visit_SetComp = _visit_comp
visit_DictComp = visit_GeneratorExp = _visit_comp
def visit_Attribute(self, node: ast.Attribute) -> None:
if self._is_six(node, SIX_SIMPLE_ATTRS):
self.six_simple[_ast_to_offset(node)] = node
elif self._find_mock and self._is_mock_mock(node):
self.mock_mock.add(_ast_to_offset(node))
self.generic_visit(node)
def visit_Name(self, node: ast.Name) -> None:
if self._is_six(node, SIX_SIMPLE_ATTRS):
self.six_simple[_ast_to_offset(node)] = node
if self._scope_stack:
if isinstance(node.ctx, ast.Load):
self._scope_stack[-1].reads.add(node.id)
elif isinstance(node.ctx, (ast.Store, ast.Del)):
self._scope_stack[-1].writes.add(node.id)
else:
raise AssertionError(node)
self.generic_visit(node)
def visit_Try(self, node: ast.Try) -> None:
for handler in node.handlers:
htype = handler.type
if self._is_os_error_alias(htype):
assert isinstance(htype, (ast.Name, ast.Attribute))
self.os_error_alias_simple[_ast_to_offset(htype)] = htype
elif (
isinstance(htype, ast.Tuple) and
any(
self._is_os_error_alias(elt)
for elt in htype.elts
)
):
self.os_error_alias_excepts.add(_ast_to_offset(htype))
self.generic_visit(node)
def visit_Raise(self, node: ast.Raise) -> None:
exc = node.exc
if exc is not None and self._is_os_error_alias(exc):
assert isinstance(exc, (ast.Name, ast.Attribute))
self.os_error_alias_simple[_ast_to_offset(exc)] = exc
elif (
isinstance(exc, ast.Call) and
self._is_os_error_alias(exc.func)
):
self.os_error_alias_calls.add(_ast_to_offset(exc))
self.generic_visit(node)
def visit_Call(self, node: ast.Call) -> None:
if (
isinstance(node.func, ast.Name) and
node.func.id in {'isinstance', 'issubclass'} and
len(node.args) == 2 and
self._is_six(node.args[1], SIX_TYPE_CTX_ATTRS)
):
arg = node.args[1]
# _is_six() enforces this
assert isinstance(arg, (ast.Name, ast.Attribute))
self.six_type_ctx[_ast_to_offset(node.args[1])] = arg
elif self._is_six(node.func, ('b', 'ensure_binary')):
self.six_b.add(_ast_to_offset(node))
elif self._is_six(node.func, SIX_CALLS) and not _starargs(node):
self.six_calls[_ast_to_offset(node)] = node
elif (
isinstance(node.func, ast.Name) and
node.func.id == 'next' and
not _starargs(node) and
len(node.args) == 1 and
isinstance(node.args[0], ast.Call) and
self._is_six(
node.args[0].func,
('iteritems', 'iterkeys', 'itervalues'),
) and
not _starargs(node.args[0])
):
self.six_iter[_ast_to_offset(node.args[0])] = node.args[0]
elif (
isinstance(self._previous_node, ast.Expr) and
self._is_six(node.func, ('raise_from',)) and
not _starargs(node)
):
self.six_raise_from.add(_ast_to_offset(node))
elif (
isinstance(self._previous_node, ast.Expr) and
self._is_six(node.func, ('reraise',)) and
(not _starargs(node) or self._is_star_sys_exc_info(node))
):
self.six_reraise.add(_ast_to_offset(node))
elif (
not self._in_comp and
self._class_info_stack and
self._class_info_stack[-1].def_depth == 1 and
isinstance(node.func, ast.Name) and
node.func.id == 'super' and
len(node.args) == 2 and
isinstance(node.args[0], ast.Name) and
isinstance(node.args[1], ast.Name) and
node.args[0].id == self._class_info_stack[-1].name and
node.args[1].id == self._class_info_stack[-1].first_arg_name
):
self.super_calls[_ast_to_offset(node)] = node
elif (
(
self._is_six(node.func, SIX_NATIVE_STR) or
isinstance(node.func, ast.Name) and node.func.id == 'str'
) and
not node.keywords and
not _starargs(node) and
(
len(node.args) == 0 or
(
len(node.args) == 1 and
isinstance(node.args[0], ast.Str)
)
)
):
self.native_literals.add(_ast_to_offset(node))
elif (
isinstance(node.func, ast.Attribute) and
isinstance(node.func.value, ast.Str) and
node.func.attr == 'encode' and
not _starargs(node) and
len(node.args) == 1 and
isinstance(node.args[0], ast.Str) and
_is_codec(node.args[0].s, 'utf-8')
):
self.encode_calls[_ast_to_offset(node)] = node
elif self._is_io_open(node.func):
self.io_open_calls.add(_ast_to_offset(node))
elif (
isinstance(node.func, ast.Name) and
node.func.id == 'open' and
not _starargs(node) and
len(node.args) >= 2 and
isinstance(node.args[1], ast.Str) and (
node.args[1].s in U_MODE_REPLACE or
(len(node.args) == 2 and node.args[1].s in U_MODE_REMOVE)
)
):
self.open_mode_calls.add(_ast_to_offset(node))
elif (
not node.args and
not node.keywords and
self._is_lru_cache(node.func)
):
self.no_arg_decorators.add(_ast_to_offset(node))
self.generic_visit(node)
def visit_Assign(self, node: ast.Assign) -> None:
if (
len(node.targets) == 1 and
isinstance(node.targets[0], ast.Name) and
node.targets[0].col_offset == 0 and
node.targets[0].id == '__metaclass__' and
isinstance(node.value, ast.Name) and
node.value.id == 'type'
):
self.metaclass_type_assignments.add(_ast_to_offset(node))
self.generic_visit(node)
@staticmethod
def _eq(test: ast.Compare, n: int) -> bool:
return (
isinstance(test.ops[0], ast.Eq) and
isinstance(test.comparators[0], ast.Num) and
test.comparators[0].n == n
)
@staticmethod
def _compare_to_3(
test: ast.Compare,
op: Union[Type[ast.cmpop], Tuple[Type[ast.cmpop], ...]],
) -> bool:
if not (
isinstance(test.ops[0], op) and
isinstance(test.comparators[0], ast.Tuple) and
len(test.comparators[0].elts) >= 1 and
all(isinstance(n, ast.Num) for n in test.comparators[0].elts)
):
return False
# checked above but mypy needs help
elts = cast('List[ast.Num]', test.comparators[0].elts)
return elts[0].n == 3 and all(n.n == 0 for n in elts[1:])
def visit_If(self, node: ast.If) -> None:
if (
# if six.PY2:
self._is_six(node.test, ('PY2',)) or
# if not six.PY3:
(
isinstance(node.test, ast.UnaryOp) and
isinstance(node.test.op, ast.Not) and
self._is_six(node.test.operand, ('PY3',))
) or
# sys.version_info == 2 or < (3,)
(
isinstance(node.test, ast.Compare) and
self._is_version_info(node.test.left) and
len(node.test.ops) == 1 and (
self._eq(node.test, 2) or
self._compare_to_3(node.test, ast.Lt)
)
)
):
if node.orelse and not isinstance(node.orelse[0], ast.If):
self.if_py2_blocks_else.add(_ast_to_offset(node))
elif (
# if six.PY3:
self._is_six(node.test, 'PY3') or
# if not six.PY2:
(
isinstance(node.test, ast.UnaryOp) and
isinstance(node.test.op, ast.Not) and
self._is_six(node.test.operand, ('PY2',))
) or
# sys.version_info == 3 or >= (3,) or > (3,)
(
isinstance(node.test, ast.Compare) and
self._is_version_info(node.test.left) and
len(node.test.ops) == 1 and (
self._eq(node.test, 3) or
self._compare_to_3(node.test, (ast.Gt, ast.GtE))
)
)
):
if node.orelse and not isinstance(node.orelse[0], ast.If):
self.if_py3_blocks_else.add(_ast_to_offset(node))
elif not node.orelse:
self.if_py3_blocks.add(_ast_to_offset(node))
self.generic_visit(node)
def visit_For(self, node: ast.For) -> None:
if (
not self._in_async_def and
len(node.body) == 1 and
isinstance(node.body[0], ast.Expr) and
isinstance(node.body[0].value, ast.Yield) and
node.body[0].value.value is not None and
targets_same(node.target, node.body[0].value.value) and
not node.orelse
):
offset = _ast_to_offset(node)
func_info = self._scope_stack[-1]
func_info.yield_from_fors.add(offset)
for target_node in ast.walk(node.target):
if (
isinstance(target_node, ast.Name) and
isinstance(target_node.ctx, ast.Store)
):
func_info.yield_from_names[target_node.id].add(offset)
# manually visit, but with target+body as a separate scope
self.visit(node.iter)
with self._scope():
self.visit(node.target)
for stmt in node.body:
self.visit(stmt)
assert not node.orelse
else:
self.generic_visit(node)
def generic_visit(self, node: ast.AST) -> None:
self._previous_node = node
super().generic_visit(node)
def _fixup_dedent_tokens(tokens: List[Token]) -> None:
"""For whatever reason the DEDENT / UNIMPORTANT_WS tokens are misordered
| if True:
| if True:
| pass
| else:
|^ ^- DEDENT
|+----UNIMPORTANT_WS
"""
for i, token in enumerate(tokens):
if token.name == UNIMPORTANT_WS and tokens[i + 1].name == 'DEDENT':
tokens[i], tokens[i + 1] = tokens[i + 1], tokens[i]
def _find_block_start(tokens: List[Token], i: int) -> int:
depth = 0
while depth or tokens[i].src != ':':
if tokens[i].src in OPENING:
depth += 1
elif tokens[i].src in CLOSING:
depth -= 1
i += 1
return i
class Block(NamedTuple):
start: int
colon: int
block: int
end: int
line: bool
def _initial_indent(self, tokens: List[Token]) -> int:
if tokens[self.start].src.isspace():
return len(tokens[self.start].src)
else:
return 0
def _minimum_indent(self, tokens: List[Token]) -> int:
block_indent = None
for i in range(self.block, self.end):
if (
tokens[i - 1].name in ('NL', 'NEWLINE') and
tokens[i].name in ('INDENT', UNIMPORTANT_WS)
):
token_indent = len(tokens[i].src)
if block_indent is None:
block_indent = token_indent
else:
block_indent = min(block_indent, token_indent)
assert block_indent is not None
return block_indent
def dedent(self, tokens: List[Token]) -> None:
if self.line:
return
diff = self._minimum_indent(tokens) - self._initial_indent(tokens)
for i in range(self.block, self.end):
if (
tokens[i - 1].name in ('DEDENT', 'NL', 'NEWLINE') and
tokens[i].name in ('INDENT', UNIMPORTANT_WS)
):
tokens[i] = tokens[i]._replace(src=tokens[i].src[diff:])
def replace_condition(self, tokens: List[Token], new: List[Token]) -> None:
tokens[self.start:self.colon] = new
def _trim_end(self, tokens: List[Token]) -> 'Block':
"""the tokenizer reports the end of the block at the beginning of
the next block
"""
i = last_token = self.end - 1
while tokens[i].name in NON_CODING_TOKENS | {'DEDENT', 'NEWLINE'}:
# if we find an indented comment inside our block, keep it
if (
tokens[i].name in {'NL', 'NEWLINE'} and
tokens[i + 1].name == UNIMPORTANT_WS and
len(tokens[i + 1].src) > self._initial_indent(tokens)
):
break
# otherwise we've found another line to remove
elif tokens[i].name in {'NL', 'NEWLINE'}:
last_token = i
i -= 1
return self._replace(end=last_token + 1)
@classmethod
def find(
cls,
tokens: List[Token],
i: int,
trim_end: bool = False,
) -> 'Block':
if i > 0 and tokens[i - 1].name in {'INDENT', UNIMPORTANT_WS}:
i -= 1
start = i
colon = _find_block_start(tokens, i)
j = colon + 1
while (
tokens[j].name != 'NEWLINE' and
tokens[j].name in NON_CODING_TOKENS
):
j += 1
if tokens[j].name == 'NEWLINE': # multi line block
block = j + 1
while tokens[j].name != 'INDENT':
j += 1
level = 1
j += 1
while level:
level += {'INDENT': 1, 'DEDENT': -1}.get(tokens[j].name, 0)
j += 1
ret = cls(start, colon, block, j, line=False)
if trim_end:
return ret._trim_end(tokens)
else:
return ret
else: # single line block
block = j
j = _find_end(tokens, j)
return cls(start, colon, block, j, line=True)
def _find_end(tokens: List[Token], i: int) -> int:
while tokens[i].name not in {'NEWLINE', 'ENDMARKER'}:
i += 1
# depending on the version of python, some will not emit
# NEWLINE('') at the end of a file which does not end with a
# newline (for example 3.6.5)
if tokens[i].name == 'ENDMARKER': # pragma: no cover
i -= 1
else:
i += 1
return i
def _find_if_else_block(tokens: List[Token], i: int) -> Tuple[Block, Block]:
if_block = Block.find(tokens, i)
i = if_block.end
while tokens[i].src != 'else':
i += 1
else_block = Block.find(tokens, i, trim_end=True)
return if_block, else_block
def _find_elif(tokens: List[Token], i: int) -> int:
while tokens[i].src != 'elif': # pragma: no cover (only for <3.8.1)
i -= 1
return i
def _remove_decorator(tokens: List[Token], i: int) -> None:
while tokens[i - 1].src != '@':
i -= 1
if i > 1 and tokens[i - 2].name not in {'NEWLINE', 'NL'}:
i -= 1
end = i + 1
while tokens[end].name != 'NEWLINE':
end += 1
del tokens[i - 1:end + 1]
def _remove_base_class(tokens: List[Token], i: int) -> None:
# look forward and backward to find commas / parens
brace_stack = []
j = i
while tokens[j].src not in {',', ':'}:
if tokens[j].src == ')':
brace_stack.append(j)
j += 1
right = j
if tokens[right].src == ':':
brace_stack.pop()
else:
# if there's a close-paren after a trailing comma
j = right + 1
while tokens[j].name in NON_CODING_TOKENS:
j += 1
if tokens[j].src == ')':
while tokens[j].src != ':':
j += 1
right = j
if brace_stack:
last_part = brace_stack[-1]
else:
last_part = i
j = i
while brace_stack:
if tokens[j].src == '(':
brace_stack.pop()
j -= 1
while tokens[j].src not in {',', '('}:
j -= 1
left = j
# single base, remove the entire bases
if tokens[left].src == '(' and tokens[right].src == ':':
del tokens[left:right]
# multiple bases, base is first
elif tokens[left].src == '(' and tokens[right].src != ':':
# if there's space / comment afterwards remove that too
while tokens[right + 1].name in {UNIMPORTANT_WS, 'COMMENT'}:
right += 1
del tokens[left + 1:right + 1]
# multiple bases, base is not first
else:
del tokens[left:last_part + 1]
def _parse_call_args(
tokens: List[Token],
i: int,
) -> Tuple[List[Tuple[int, int]], int]:
args = []
stack = [i]
i += 1
arg_start = i
while stack:
token = tokens[i]
if len(stack) == 1 and token.src == ',':
args.append((arg_start, i))
arg_start = i + 1
elif token.src in BRACES:
stack.append(i)
elif token.src == BRACES[tokens[stack[-1]].src]:
stack.pop()
# if we're at the end, append that argument
if not stack and tokens_to_src(tokens[arg_start:i]).strip():
args.append((arg_start, i))
i += 1
return args, i
def _get_tmpl(mapping: Dict[str, str], node: NameOrAttr) -> str:
if isinstance(node, ast.Name):
return mapping[node.id]
else:
return mapping[node.attr]
def _arg_str(tokens: List[Token], start: int, end: int) -> str:
return tokens_to_src(tokens[start:end]).strip()
def _replace_call(
tokens: List[Token],
start: int,
end: int,
args: List[Tuple[int, int]],
tmpl: str,
) -> None:
arg_strs = [_arg_str(tokens, *arg) for arg in args]
start_rest = args[0][1] + 1
while (
start_rest < end and
tokens[start_rest].name in {'COMMENT', UNIMPORTANT_WS}
):
start_rest += 1
rest = tokens_to_src(tokens[start_rest:end - 1])
src = tmpl.format(args=arg_strs, rest=rest)
tokens[start:end] = [Token('CODE', src)]
def _replace_yield(tokens: List[Token], i: int) -> None:
in_token = _find_token(tokens, i, 'in')
colon = _find_block_start(tokens, i)
block = Block.find(tokens, i, trim_end=True)
container = tokens_to_src(tokens[in_token + 1:colon]).strip()
tokens[i:block.end] = [Token('CODE', f'yield from {container}\n')]
def _fix_py3_plus(
contents_text: str,
min_version: MinVersion,
keep_mock: bool = False,
) -> str:
try:
ast_obj = ast_parse(contents_text)
except SyntaxError:
return contents_text
visitor = FindPy3Plus(keep_mock)
visitor.visit(ast_obj)
if not any((
visitor.bases_to_remove,
visitor.encode_calls,
visitor.if_py2_blocks_else,
visitor.if_py3_blocks,
visitor.if_py3_blocks_else,
visitor.metaclass_type_assignments,
visitor.native_literals,
visitor.io_open_calls,
visitor.open_mode_calls,
visitor.mock_mock,
visitor.mock_absolute_imports,
visitor.mock_relative_imports,
visitor.os_error_alias_calls,
visitor.os_error_alias_simple,
visitor.os_error_alias_excepts,
visitor.no_arg_decorators,
visitor.six_add_metaclass,
visitor.six_b,
visitor.six_calls,
visitor.six_iter,
visitor.six_raise_from,
visitor.six_reraise,
visitor.six_remove_decorators,
visitor.six_simple,
visitor.six_type_ctx,
visitor.six_with_metaclass,
visitor.super_calls,
visitor.yield_from_fors,
)):
return contents_text
try:
tokens = src_to_tokens(contents_text)
except tokenize.TokenError: # pragma: no cover (bpo-2180)
return contents_text
_fixup_dedent_tokens(tokens)
def _replace(i: int, mapping: Dict[str, str], node: NameOrAttr) -> None:
new_token = Token('CODE', _get_tmpl(mapping, node))
if isinstance(node, ast.Name):
tokens[i] = new_token
else:
j = i
while tokens[j].src != node.attr:
# timid: if we see a parenthesis here, skip it
if tokens[j].src == ')':
return
j += 1
tokens[i:j + 1] = [new_token]
for i, token in reversed_enumerate(tokens):
if not token.src:
continue
elif token.offset in visitor.bases_to_remove:
_remove_base_class(tokens, i)
elif token.offset in visitor.if_py3_blocks:
if tokens[i].src == 'if':
if_block = Block.find(tokens, i)
if_block.dedent(tokens)
del tokens[if_block.start:if_block.block]
else:
if_block = Block.find(tokens, _find_elif(tokens, i))
if_block.replace_condition(tokens, [Token('NAME', 'else')])
elif token.offset in visitor.if_py2_blocks_else:
if tokens[i].src == 'if':
if_block, else_block = _find_if_else_block(tokens, i)
else_block.dedent(tokens)
del tokens[if_block.start:else_block.block]
else:
j = _find_elif(tokens, i)
if_block, else_block = _find_if_else_block(tokens, j)
del tokens[if_block.start:else_block.start]
elif token.offset in visitor.if_py3_blocks_else:
if tokens[i].src == 'if':
if_block, else_block = _find_if_else_block(tokens, i)
if_block.dedent(tokens)
del tokens[if_block.end:else_block.end]
del tokens[if_block.start:if_block.block]
else:
j = _find_elif(tokens, i)
if_block, else_block = _find_if_else_block(tokens, j)
del tokens[if_block.end:else_block.end]
if_block.replace_condition(tokens, [Token('NAME', 'else')])
elif token.offset in visitor.metaclass_type_assignments:
j = _find_end(tokens, i)
del tokens[i:j + 1]
elif token.offset in visitor.native_literals:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
if any(tok.name == 'NL' for tok in tokens[i:end]):
continue
if func_args:
_replace_call(tokens, i, end, func_args, '{args[0]}')
else:
tokens[i:end] = [token._replace(name='STRING', src="''")]
elif token.offset in visitor.six_type_ctx:
_replace(i, SIX_TYPE_CTX_ATTRS, visitor.six_type_ctx[token.offset])
elif token.offset in visitor.six_simple:
_replace(i, SIX_SIMPLE_ATTRS, visitor.six_simple[token.offset])
elif token.offset in visitor.six_remove_decorators:
_remove_decorator(tokens, i)
elif token.offset in visitor.six_b:
j = _find_open_paren(tokens, i)
if (
tokens[j + 1].name == 'STRING' and
_is_ascii(tokens[j + 1].src) and
tokens[j + 2].src == ')'
):
func_args, end = _parse_call_args(tokens, j)
_replace_call(tokens, i, end, func_args, SIX_B_TMPL)
elif token.offset in visitor.six_iter:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
call = visitor.six_iter[token.offset]
assert isinstance(call.func, (ast.Name, ast.Attribute))
template = f'iter({_get_tmpl(SIX_CALLS, call.func)})'
_replace_call(tokens, i, end, func_args, template)
elif token.offset in visitor.six_calls:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
call = visitor.six_calls[token.offset]
assert isinstance(call.func, (ast.Name, ast.Attribute))
template = _get_tmpl(SIX_CALLS, call.func)
_replace_call(tokens, i, end, func_args, template)
elif token.offset in visitor.six_raise_from:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
_replace_call(tokens, i, end, func_args, RAISE_FROM_TMPL)
elif token.offset in visitor.six_reraise:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
if len(func_args) == 1:
tmpl = RERAISE_TMPL
elif len(func_args) == 2:
tmpl = RERAISE_2_TMPL
else:
tmpl = RERAISE_3_TMPL
_replace_call(tokens, i, end, func_args, tmpl)
elif token.offset in visitor.six_add_metaclass:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
metaclass = f'metaclass={_arg_str(tokens, *func_args[0])}'
# insert `metaclass={args[0]}` into `class:`
# search forward for the `class` token
j = i + 1
while tokens[j].src != 'class':
j += 1
class_token = j
# then search forward for a `:` token, not inside a brace
j = _find_block_start(tokens, j)
last_paren = -1
for k in range(class_token, j):
if tokens[k].src == ')':
last_paren = k
if last_paren == -1:
tokens.insert(j, Token('CODE', f'({metaclass})'))
else:
insert = last_paren - 1
while tokens[insert].name in NON_CODING_TOKENS:
insert -= 1
if tokens[insert].src == '(': # no bases
src = metaclass
elif tokens[insert].src != ',':
src = f', {metaclass}'
else:
src = f' {metaclass},'
tokens.insert(insert + 1, Token('CODE', src))
_remove_decorator(tokens, i)
elif token.offset in visitor.six_with_metaclass:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
if len(func_args) == 1:
tmpl = WITH_METACLASS_NO_BASES_TMPL
elif len(func_args) == 2:
base = _arg_str(tokens, *func_args[1])
if base == 'object':
tmpl = WITH_METACLASS_NO_BASES_TMPL
else:
tmpl = WITH_METACLASS_BASES_TMPL
else:
tmpl = WITH_METACLASS_BASES_TMPL
_replace_call(tokens, i, end, func_args, tmpl)
elif token.offset in visitor.super_calls:
i = _find_open_paren(tokens, i)
call = visitor.super_calls[token.offset]
victims = _victims(tokens, i, call, gen=False)
del tokens[victims.starts[0] + 1:victims.ends[-1]]
elif token.offset in visitor.encode_calls:
i = _find_open_paren(tokens, i + 1)
call = visitor.encode_calls[token.offset]
victims = _victims(tokens, i, call, gen=False)
del tokens[victims.starts[0] + 1:victims.ends[-1]]
elif token.offset in visitor.io_open_calls:
j = _find_open_paren(tokens, i)
tokens[i:j] = [token._replace(name='NAME', src='open')]
elif token.offset in visitor.mock_mock:
j = _find_token(tokens, i + 1, 'mock')
del tokens[i + 1:j + 1]
elif token.offset in visitor.mock_absolute_imports:
j = _find_token(tokens, i, 'mock')
if (
j + 2 < len(tokens) and
tokens[j + 1].src == '.' and
tokens[j + 2].src == 'mock'
):
j += 2
src = 'from unittest import mock'
tokens[i:j + 1] = [tokens[j]._replace(name='NAME', src=src)]
elif token.offset in visitor.mock_relative_imports:
j = _find_token(tokens, i, 'mock')
if (
j + 2 < len(tokens) and
tokens[j + 1].src == '.' and
tokens[j + 2].src == 'mock'
):
k = j + 2
else:
k = j
src = 'unittest.mock'
tokens[j:k + 1] = [tokens[j]._replace(name='NAME', src=src)]
elif token.offset in visitor.open_mode_calls:
j = _find_open_paren(tokens, i)
func_args, end = _parse_call_args(tokens, j)
mode = tokens_to_src(tokens[slice(*func_args[1])])
mode_stripped = mode.strip().strip('"\'')
if mode_stripped in U_MODE_REMOVE:
del tokens[func_args[0][1]:func_args[1][1]]
elif mode_stripped in U_MODE_REPLACE_R:
new_mode = mode.replace('U', 'r')
tokens[slice(*func_args[1])] = [Token('SRC', new_mode)]
elif mode_stripped in U_MODE_REMOVE_U:
new_mode = mode.replace('U', '')
tokens[slice(*func_args[1])] = [Token('SRC', new_mode)]
else:
raise AssertionError(f'unreachable: {mode!r}')
elif token.offset in visitor.os_error_alias_calls:
j = _find_open_paren(tokens, i)
tokens[i:j] = [token._replace(name='NAME', src='OSError')]
elif token.offset in visitor.os_error_alias_simple:
node = visitor.os_error_alias_simple[token.offset]
_replace(i, collections.defaultdict(lambda: 'OSError'), node)
elif token.offset in visitor.os_error_alias_excepts:
line, utf8_byte_offset = token.line, token.utf8_byte_offset
# find all the arg strs in the tuple
except_index = i
while tokens[except_index].src != 'except':
except_index -= 1
start = _find_open_paren(tokens, except_index)
func_args, end = _parse_call_args(tokens, start)
# save the exceptions and remove the block
arg_strs = [_arg_str(tokens, *arg) for arg in func_args]
del tokens[start:end]
# rewrite the block without dupes
args = []
for arg in arg_strs:
left, part, right = arg.partition('.')
if (
left in visitor.OS_ERROR_ALIAS_MODULES and
part == '.' and
right == 'error'
):
args.append('OSError')
elif (
left in visitor.OS_ERROR_ALIASES and
part == right == ''
):
args.append('OSError')
elif (
left == 'error' and
part == right == '' and
(
'error' in visitor._from_imports['mmap'] or
'error' in visitor._from_imports['select'] or
'error' in visitor._from_imports['socket']
)
):
args.append('OSError')
else:
args.append(arg)
unique_args = tuple(collections.OrderedDict.fromkeys(args))
if len(unique_args) > 1:
joined = '({})'.format(', '.join(unique_args))
elif tokens[start - 1].name != 'UNIMPORTANT_WS':
joined = ' {}'.format(unique_args[0])
else:
joined = unique_args[0]
new = Token('CODE', joined, line, utf8_byte_offset)
tokens.insert(start, new)
visitor.os_error_alias_excepts.discard(token.offset)
elif token.offset in visitor.yield_from_fors:
_replace_yield(tokens, i)
elif (
min_version >= (3, 8) and
token.offset in visitor.no_arg_decorators
):
i = _find_open_paren(tokens, i)
j = _find_token(tokens, i, ')')
del tokens[i:j + 1]
return tokens_to_src(tokens)
def _simple_arg(arg: ast.expr) -> bool:
return (
isinstance(arg, ast.Name) or
(isinstance(arg, ast.Attribute) and _simple_arg(arg.value)) or
(
isinstance(arg, ast.Call) and
_simple_arg(arg.func) and
not arg.args and not arg.keywords
)
)
def _starargs(call: ast.Call) -> bool:
return (
any(k.arg is None for k in call.keywords) or
any(isinstance(a, ast.Starred) for a in call.args)
)
def _format_params(call: ast.Call) -> Dict[str, str]:
params = {}
for i, arg in enumerate(call.args):
params[str(i)] = _unparse(arg)
for kwd in call.keywords:
# kwd.arg can't be None here because we exclude starargs
assert kwd.arg is not None
params[kwd.arg] = _unparse(kwd.value)
return params
class FindPy36Plus(ast.NodeVisitor):
def __init__(self) -> None:
self.fstrings: Dict[Offset, ast.Call] = {}
self.named_tuples: Dict[Offset, ast.Call] = {}
self.dict_typed_dicts: Dict[Offset, ast.Call] = {}
self.kw_typed_dicts: Dict[Offset, ast.Call] = {}
self._from_imports: Dict[str, Set[str]] = collections.defaultdict(set)
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
if node.level == 0 and node.module in {'typing', 'typing_extensions'}:
for name in node.names:
if not name.asname:
self._from_imports[node.module].add(name.name)
self.generic_visit(node)
def _is_attr(self, node: ast.AST, mods: Set[str], name: str) -> bool:
return (
(
isinstance(node, ast.Name) and
node.id == name and
any(name in self._from_imports[mod] for mod in mods)
) or
(
isinstance(node, ast.Attribute) and
node.attr == name and
isinstance(node.value, ast.Name) and
node.value.id in mods
)
)
def _parse(self, node: ast.Call) -> Optional[Tuple[DotFormatPart, ...]]:
if not (
isinstance(node.func, ast.Attribute) and
isinstance(node.func.value, ast.Str) and
node.func.attr == 'format' and
all(_simple_arg(arg) for arg in node.args) and
all(_simple_arg(k.value) for k in node.keywords) and
not _starargs(node)
):
return None
try:
return parse_format(node.func.value.s)
except ValueError:
return None
def visit_Call(self, node: ast.Call) -> None:
parsed = self._parse(node)
if parsed is not None:
params = _format_params(node)
seen: Set[str] = set()
i = 0
for _, name, spec, _ in parsed:
# timid: difficult to rewrite correctly
if spec is not None and '{' in spec:
break
if name is not None:
candidate, _, _ = name.partition('.')
# timid: could make the f-string longer
if candidate and candidate in seen:
break
# timid: bracketed
elif '[' in name:
break
seen.add(candidate)
key = candidate or str(i)
# their .format() call is broken currently
if key not in params:
break
if not candidate:
i += 1
else:
self.fstrings[_ast_to_offset(node)] = node
self.generic_visit(node)
def visit_Assign(self, node: ast.Assign) -> None:
if (
# NT = ...("NT", ...)
len(node.targets) == 1 and
isinstance(node.targets[0], ast.Name) and
isinstance(node.value, ast.Call) and
len(node.value.args) >= 1 and
isinstance(node.value.args[0], ast.Str) and
node.targets[0].id == node.value.args[0].s and
not _starargs(node.value)
):
if (
self._is_attr(
node.value.func, {'typing'}, 'NamedTuple',
) and
len(node.value.args) == 2 and
not node.value.keywords and
isinstance(node.value.args[1], (ast.List, ast.Tuple)) and
len(node.value.args[1].elts) > 0 and
all(
isinstance(tup, ast.Tuple) and
len(tup.elts) == 2 and
isinstance(tup.elts[0], ast.Str) and
tup.elts[0].s.isidentifier() and
tup.elts[0].s not in _KEYWORDS
for tup in node.value.args[1].elts
)
):
self.named_tuples[_ast_to_offset(node)] = node.value
elif (
self._is_attr(
node.value.func,
{'typing', 'typing_extensions'},
'TypedDict',
) and
len(node.value.args) == 1 and
len(node.value.keywords) > 0
):
self.kw_typed_dicts[_ast_to_offset(node)] = node.value
elif (
self._is_attr(
node.value.func,
{'typing', 'typing_extensions'},
'TypedDict',
) and
len(node.value.args) == 2 and
not node.value.keywords and
isinstance(node.value.args[1], ast.Dict) and
node.value.args[1].keys and
all(
isinstance(k, ast.Str) and
k.s.isidentifier() and
k.s not in _KEYWORDS
for k in node.value.args[1].keys
)
):
self.dict_typed_dicts[_ast_to_offset(node)] = node.value
self.generic_visit(node)
def _unparse(node: ast.expr) -> str:
if isinstance(node, ast.Name):
return node.id
elif isinstance(node, ast.Attribute):
return ''.join((_unparse(node.value), '.', node.attr))
elif isinstance(node, ast.Call):
return '{}()'.format(_unparse(node.func))
elif isinstance(node, ast.Subscript):
if sys.version_info >= (3, 9): # pragma: no cover (py39+)
node_slice: ast.expr = node.slice
elif isinstance(node.slice, ast.Index): # pragma: no cover (<py39)
node_slice = node.slice.value
else:
raise AssertionError(f'expected Slice: {ast.dump(node)}')
if isinstance(node_slice, ast.Tuple):
if len(node_slice.elts) == 1:
slice_s = f'{_unparse(node_slice.elts[0])},'
else:
slice_s = ', '.join(_unparse(elt) for elt in node_slice.elts)
else:
slice_s = _unparse(node_slice)
return '{}[{}]'.format(_unparse(node.value), slice_s)
elif isinstance(node, ast.Str):
return repr(node.s)
elif isinstance(node, ast.Ellipsis):
return '...'
elif isinstance(node, ast.List):
return '[{}]'.format(', '.join(_unparse(elt) for elt in node.elts))
elif isinstance(node, ast.NameConstant):
return repr(node.value)
else:
raise NotImplementedError(ast.dump(node))
def _to_fstring(src: str, call: ast.Call) -> str:
params = _format_params(call)
parts = []
i = 0
for s, name, spec, conv in parse_format('f' + src):
if name is not None:
k, dot, rest = name.partition('.')
name = ''.join((params[k or str(i)], dot, rest))
if not k: # named and auto params can be in different orders
i += 1
parts.append((s, name, spec, conv))
return unparse_parsed_string(parts)
def _replace_typed_class(
tokens: List[Token],
i: int,
call: ast.Call,
types: Dict[str, ast.expr],
) -> None:
if i > 0 and tokens[i - 1].name in {'INDENT', UNIMPORTANT_WS}:
indent = f'{tokens[i - 1].src}{" " * 4}'
else:
indent = ' ' * 4
# NT = NamedTuple("nt", [("a", int)])
# ^i ^end
end = i + 1
while end < len(tokens) and tokens[end].name != 'NEWLINE':
end += 1
attrs = '\n'.join(f'{indent}{k}: {_unparse(v)}' for k, v in types.items())
src = f'class {tokens[i].src}({_unparse(call.func)}):\n{attrs}'
tokens[i:end] = [Token('CODE', src)]
def _fix_py36_plus(contents_text: str) -> str:
try:
ast_obj = ast_parse(contents_text)
except SyntaxError:
return contents_text
visitor = FindPy36Plus()
visitor.visit(ast_obj)
if not any((
visitor.fstrings,
visitor.named_tuples,
visitor.dict_typed_dicts,
visitor.kw_typed_dicts,
)):
return contents_text
try:
tokens = src_to_tokens(contents_text)
except tokenize.TokenError: # pragma: no cover (bpo-2180)
return contents_text
for i, token in reversed_enumerate(tokens):
if token.offset in visitor.fstrings:
node = visitor.fstrings[token.offset]
# TODO: handle \N escape sequences
if r'\N' in token.src:
continue
paren = i + 3
if tokens_to_src(tokens[i + 1:paren + 1]) != '.format(':
continue
# we don't actually care about arg position, so we pass `node`
victims = _victims(tokens, paren, node, gen=False)
end = victims.ends[-1]
# if it spans more than one line, bail
if tokens[end].line != token.line:
continue
tokens[i] = token._replace(src=_to_fstring(token.src, node))
del tokens[i + 1:end + 1]
elif token.offset in visitor.named_tuples and token.name == 'NAME':
call = visitor.named_tuples[token.offset]
types: Dict[str, ast.expr] = {
tup.elts[0].s: tup.elts[1] # type: ignore # (checked above)
for tup in call.args[1].elts # type: ignore # (checked above)
}
_replace_typed_class(tokens, i, call, types)
elif token.offset in visitor.kw_typed_dicts and token.name == 'NAME':
call = visitor.kw_typed_dicts[token.offset]
types = {
arg.arg: arg.value # type: ignore # (checked above)
for arg in call.keywords
}
_replace_typed_class(tokens, i, call, types)
elif token.offset in visitor.dict_typed_dicts and token.name == 'NAME':
call = visitor.dict_typed_dicts[token.offset]
types = {
k.s: v # type: ignore # (checked above)
for k, v in zip(
call.args[1].keys, # type: ignore # (checked above)
call.args[1].values, # type: ignore # (checked above)
)
}
_replace_typed_class(tokens, i, call, types)
return tokens_to_src(tokens)
def _fix_file(filename: str, args: argparse.Namespace) -> int:
if filename == '-':
contents_bytes = sys.stdin.buffer.read()
else:
with open(filename, 'rb') as fb:
contents_bytes = fb.read()
try:
contents_text_orig = contents_text = contents_bytes.decode()
except UnicodeDecodeError:
print(f'{filename} is non-utf-8 (not supported)')
return 1
contents_text = _fix_py2_compatible(contents_text)
contents_text = _fix_tokens(contents_text, min_version=args.min_version)
if not args.keep_percent_format:
contents_text = _fix_percent_format(contents_text)
if args.min_version >= (3,):
contents_text = _fix_py3_plus(
contents_text, args.min_version, args.keep_mock,
)
if args.min_version >= (3, 6):
contents_text = _fix_py36_plus(contents_text)
if filename == '-':
print(contents_text, end='')
elif contents_text != contents_text_orig:
print(f'Rewriting {filename}', file=sys.stderr)
with open(filename, 'w', encoding='UTF-8', newline='') as f:
f.write(contents_text)
if args.exit_zero_even_if_changed:
return 0
else:
return contents_text != contents_text_orig
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*')
parser.add_argument('--exit-zero-even-if-changed', action='store_true')
parser.add_argument('--keep-percent-format', action='store_true')
parser.add_argument('--keep-mock', action='store_true')
parser.add_argument(
'--py3-plus', '--py3-only',
action='store_const', dest='min_version', default=(2, 7), const=(3,),
)
parser.add_argument(
'--py36-plus',
action='store_const', dest='min_version', const=(3, 6),
)
parser.add_argument(
'--py37-plus',
action='store_const', dest='min_version', const=(3, 7),
)
parser.add_argument(
'--py38-plus',
action='store_const', dest='min_version', const=(3, 8),
)
args = parser.parse_args(argv)
ret = 0
for filename in args.filenames:
ret |= _fix_file(filename, args)
return ret
if __name__ == '__main__':
exit(main())
|
from __future__ import annotations
import re
import enum
import asyncio
import warnings
from io import BytesIO
from typing import Any, List, Optional
from asyncio import TimeoutError
import PIL
import aiohttp
import discord
from PIL.Image import DecompressionBombWarning
from discord.ext import commands
from pink.errors import PINKError
from pink.context import Context
from pink.regexes import ID_REGEX, EMOTE_REGEX, CLEAN_URL_REGEX
warnings.simplefilter("error", DecompressionBombWarning)
class ImageType(enum.Enum):
EMOTE = 0
EMOJI = 1
USER = 2
URL = 3
ATTACHMENT = 4
EMBED = 5
class FetchedImage:
__slots__ = ("bytes",)
def __init__(self, data: bytes):
self.bytes = data
async def to_pil_image(
self, ctx: Context, *, max_dimensions: int = 10000
) -> PIL.Image:
"""Returns Pillow image created from bytes. Should be closed manually"""
try:
img = PIL.Image.open(BytesIO(self.bytes))
except PIL.Image.DecompressionBombError:
raise PINKError(
f"failed to open image, exceeds **{PIL.Image.MAX_IMAGE_PIXELS}** pixel limit"
)
except OSError as e:
raise PINKError(f"failed to open image: {e}", formatted=False)
else:
if sum(img.size) > max_dimensions:
# TODO: clean up close calls? Pillow seem to stop leaking memory
img.close()
raise PINKError(f"Image is too large: **{img.size}pix**")
return img
def __repr__(self) -> str:
return f"<{type(self).__name__} bytes={len(self.bytes)}>"
class Image:
DEFAULT_STATIC_FORMAT = "png"
DEFAULT_ANIMATED_FORMAT = "gif"
STATIC_FORMATS = (
DEFAULT_STATIC_FORMAT,
"jpg",
"jpeg",
"webp",
)
ANIMATED_FORMATS = (DEFAULT_ANIMATED_FORMAT,)
__slots__ = (
"type",
"url",
"fetched",
"is_spoiler",
)
def __init__(
self,
kind: ImageType,
url: str,
data: Optional[bytes] = None,
is_spoiler: bool = False,
):
self.type = kind
self.url = url
self.is_spoiler = is_spoiler
self.fetched = FetchedImage(data) if data else None
@classmethod
async def convert(cls, ctx: Context, argument: str) -> Image:
return await cls.from_pattern(ctx, argument)
@classmethod
async def from_pattern(cls, ctx: Context, argument: str) -> Image:
return await cls._from_pattern(ctx, argument, allow_animated=True)
@classmethod
async def _from_reference(
cls,
ctx: Context,
reference: discord.MessageReference,
*,
allow_static: bool = True,
allow_animated: bool = False,
) -> Image:
if (resolved := reference.resolved) is None:
resolved = await ctx.channel.fetch_message(reference.message_id)
if isinstance(resolved, discord.Message): # and not discord.DeletedMessage
if (
img := cls.from_message(
ctx,
resolved,
allow_static=allow_static,
allow_animated=allow_animated,
)
) is not None:
return img
raise commands.BadArgument("No images found in referenced message")
raise commands.BadArgument(
f"Unable to fetch referenced message {ctx.channel.id}-{ctx.message.id}",
)
@classmethod
async def _from_pattern(
cls,
ctx: Context,
argument: str,
*,
allow_static: bool = True,
allow_animated: bool = False,
) -> Image:
if not (allow_static or allow_animated):
raise ValueError("Either animated or static image type should be allowed")
# if there is a referenced message, it is more important than message content
# for these reasons:
# - it takes more efdort to reply to message than to attach file/paste url
# - if this was a mistake, it's easier for user to use command again relying on
# from_history to fetch previous message rather than replying to message
# again
#
# this implementation is a bit of a mess, there is an `argument` parameter, but
# we assume that ctx.message is target message in from_history anyway
if (reference := ctx.message.reference) is not None:
return await cls._from_reference(
ctx,
reference,
allow_static=allow_static,
allow_animated=allow_animated,
)
if argument == "~":
return await cls.from_history(ctx)
# match up to 50 previous messages using one or multiple ^'s
if re.fullmatch(r"\^{1,50}", argument):
msgs = await ctx.channel.history(
before=ctx.message.created_at, limit=50
).flatten()
message = msgs[len(argument) - 1]
if not (
image := cls.from_message(
ctx,
message,
allow_static=allow_static,
allow_animated=allow_animated,
)
):
raise commands.BadArgument(
f"Nothing found in message <{message.jump_url}>"
)
return image
def pick_format(target_animated: bool) -> Optional[str]:
if allow_static and allow_animated:
return (
cls.DEFAULT_ANIMATED_FORMAT
if target_animated
else cls.DEFAULT_STATIC_FORMAT
)
if allow_animated and target_animated:
return cls.DEFAULT_ANIMATED_FORMAT
if allow_static:
return cls.DEFAULT_STATIC_FORMAT
# only static allowed, target is animated
return None
# check if pattern is emote
if emote_match := EMOTE_REGEX.fullmatch(argument):
emote_id = int(emote_match["id"])
is_animated = emote_match["animated"] != ""
if (emote_format := pick_format(is_animated)) is None:
raise commands.BadArgument(
"Static images are not allowed, static emote provided"
)
if emote := ctx.bot.get_emoji(emote_id):
return Image(
kind=ImageType.EMOTE,
url=str(emote.url_as(format=emote_format)),
)
return Image(
kind=ImageType.EMOTE,
url=f"https://cdn.discordapp.com/emojis/{emote_id}.{emote_format}",
)
# check if pattern is id that points to emote
if id_match := ID_REGEX.fullmatch(argument):
if emote := ctx.bot.get_emoji(int(id_match.string)):
if (emote_format := pick_format(emote.animated)) is None:
raise commands.BadArgument(
"Static images are not allowed, static emote provided"
)
return Image(
kind=ImageType.EMOTE,
url=str(emote.url_as(format=emote_format)),
)
# check if pattern is emoji
# thanks NotSoSuper and cake for the CDN
# thanks discord for this nonsense
pattern_no_selector_16 = argument.rstrip("\N{VARIATION SELECTOR-16}")
code = "-".join(map(lambda c: f"{ord(c):x}", pattern_no_selector_16))
emote_url = f"https://cdn.notsobot.com/twemoji/512x512/{code}.png"
async with ctx.session.get(
emote_url, timeout=aiohttp.ClientTimeout(total=5)
) as r:
if r.status == 200:
return Image(
kind=ImageType.EMOTE,
url=emote_url,
data=await r.read(),
)
# check if pattern is user mention
try:
# TODO: case insensitive or fuzzy because this is trash
user = await commands.UserConverter().convert(ctx, argument)
except commands.UserNotFound:
pass
else:
if (avatar_format := pick_format(user.is_avatar_animated())) is None:
raise commands.BadArgument(
f"Static images are not allowed, {user} has static avatar",
)
return Image(
kind=ImageType.USER,
url=str(user.avatar_url_as(format=avatar_format)),
)
# check if pattern is url
argument = CLEAN_URL_REGEX.sub("", argument)
if not argument.startswith(("http://", "https://")):
raise commands.BadArgument(
f"Unable to match custom emote, emoji or user with `{argument}`\n"
f"If input is image url, it should begin with http or https"
)
return Image(kind=ImageType.URL, url=argument)
@classmethod
async def from_history(
cls,
ctx: Context,
) -> Image:
return await cls._from_history(ctx, allow_animated=True)
@classmethod
def _check_extension(
cls,
url: str,
*,
allow_static: bool = True,
allow_animated: bool = False,
) -> Optional[str]:
extension = url.rpartition(".")[-1].lower()
if extension in cls.STATIC_FORMATS and allow_static:
return extension
elif extension in cls.ANIMATED_FORMATS and allow_animated:
return extension
return None
@classmethod
def from_message(
cls,
ctx: Context,
msg: discord.Message,
*,
allow_static: bool = True,
allow_animated: bool = False,
) -> Optional[Image]:
# check attachments (files uploaded to discord)
for attachment in msg.attachments:
if (
cls._check_extension(
attachment.filename,
allow_static=allow_static,
allow_animated=allow_animated,
)
is None
):
continue
return Image(
kind=ImageType.ATTACHMENT,
url=attachment.url,
is_spoiler=attachment.is_spoiler(),
)
# check embeds (user posted url / bot posted rich embed)
for embed in msg.embeds:
if embed.image:
if (
cls._check_extension(
embed.image.url,
allow_static=allow_static,
allow_animated=allow_animated,
)
is not None
):
return Image(
kind=ImageType.EMBED,
url=embed.image.url,
)
# bot condition because we do not want image from
# rich embed thumbnail
if not embed.thumbnail or (msg.author.bot and embed.type == "rich"):
continue
# avoid case when image embed was created from url that is
# used as argument or flag
if msg.id == ctx.message.id:
if embed.thumbnail.url in msg.content:
continue
if (
cls._check_extension(
embed.thumbnail.url,
allow_static=allow_static,
allow_animated=allow_animated,
)
is None
):
continue
return Image(
kind=ImageType.EMBED,
url=embed.thumbnail.url,
)
return None
@classmethod
async def _from_history(
cls,
ctx: Context,
*,
allow_static: bool = True,
allow_animated: bool = False,
) -> Image:
if not (allow_static or allow_animated):
raise ValueError("Either animated or static image type should be allowed")
# referenced message is checked second time (first in from_pattern), but
# a) it should be in cache by this time
# b) usually it is not checked if user does not provide input
if (reference := ctx.message.reference) is not None:
return await cls._from_reference(
ctx,
reference,
allow_static=allow_static,
allow_animated=allow_animated,
)
# check channel history for attachments
#
# command can be invoked by message edit, but we still want
# to check messages before created_at
history = await ctx.channel.history(
limit=200, before=ctx.message.created_at
).flatten()
for msg in [ctx.message] + history:
if (
img := cls.from_message(
ctx, msg, allow_static=allow_static, allow_animated=allow_animated
)
) is not None:
return img
raise commands.BadArgument("Nothing found in latest 200 messages")
async def fetch(
self,
ctx: Context,
*,
url: Optional[str] = None,
**kwargs: Any,
) -> FetchedImage:
if url is None:
url = self.url
if url == self.url and self.fetched is not None:
return self.fetched
else:
image_bytes = await self._fetch(ctx, url, **kwargs)
fetched = FetchedImage(image_bytes)
if url == self.url:
self.fetched = fetched
return fetched
@classmethod
async def _fetch(
cls,
ctx: Context,
url: str,
*,
allow_static: bool = True,
allow_animated: bool = False,
timeout: int = 10,
max_content_length: int = 8000000,
) -> bytes:
try:
async with ctx.session.get(url, timeout=timeout) as r:
if r.status != 200:
raise PINKError(f"bad status code: **{r.status}**")
if (r.content_length or 0) > max_content_length:
raise PINKError("content is too big", formatted=False)
allowed_extensions: List[str] = []
if allow_static:
allowed_extensions.extend(cls.STATIC_FORMATS)
if allow_animated:
allowed_extensions.extend(cls.ANIMATED_FORMATS)
if r.content_type.rpartition("/")[-1].lower() not in allowed_extensions:
raise PINKError(
f'unknown content type: **{r.content_type}**, expected one of **{', '.join(allowed_extensions)}**'
)
return await r.read()
except PINKError:
raise
except (Exception, asyncio.TimeoutError) as e:
error = "Download error: "
if isinstance(e, TimeoutError):
error += f"timeout reached: **{timeout}s**"
else:
error += str(e)
raise commands.BadArgument(error, e)
async def to_pil_image(self, ctx: Context) -> PIL.Image:
fetched = await self.fetch(ctx)
return await fetched.to_pil_image(ctx)
def __repr__(self) -> str:
return f"<{type(self).__name__} url={self.url} type={self.type.name}>"
class StaticImage(Image):
@classmethod
async def from_pattern(cls, ctx: Context, argument: str) -> Image:
return await cls._from_pattern(ctx, argument)
@classmethod
async def from_history(
cls,
ctx: Context,
) -> Image:
return await cls._from_history(ctx)
class AnimatedImage(Image):
@classmethod
async def from_pattern(cls, ctx: Context, argument: str) -> Image:
return await cls._from_pattern(
ctx, argument, allow_static=False, allow_animated=True
)
@classmethod
async def from_history(
cls,
ctx: Context,
) -> Image:
return await cls._from_history(ctx, allow_static=False, allow_animated=True)
| from __future__ import annotations
import re
import enum
import asyncio
import warnings
from io import BytesIO
from typing import Any, List, Optional
from asyncio import TimeoutError
import PIL
import aiohttp
import discord
from PIL.Image import DecompressionBombWarning
from discord.ext import commands
from pink.errors import PINKError
from pink.context import Context
from pink.regexes import ID_REGEX, EMOTE_REGEX, CLEAN_URL_REGEX
warnings.simplefilter("error", DecompressionBombWarning)
class ImageType(enum.Enum):
EMOTE = 0
EMOJI = 1
USER = 2
URL = 3
ATTACHMENT = 4
EMBED = 5
class FetchedImage:
__slots__ = ("bytes",)
def __init__(self, data: bytes):
self.bytes = data
async def to_pil_image(
self, ctx: Context, *, max_dimensions: int = 10000
) -> PIL.Image:
"""Returns Pillow image created from bytes. Should be closed manually"""
try:
img = PIL.Image.open(BytesIO(self.bytes))
except PIL.Image.DecompressionBombError:
raise PINKError(
f"failed to open image, exceeds **{PIL.Image.MAX_IMAGE_PIXELS}** pixel limit"
)
except OSError as e:
raise PINKError(f"failed to open image: {e}", formatted=False)
else:
if sum(img.size) > max_dimensions:
# TODO: clean up close calls? Pillow seem to stop leaking memory
img.close()
raise PINKError(f"Image is too large: **{img.size}pix**")
return img
def __repr__(self) -> str:
return f"<{type(self).__name__} bytes={len(self.bytes)}>"
class Image:
DEFAULT_STATIC_FORMAT = "png"
DEFAULT_ANIMATED_FORMAT = "gif"
STATIC_FORMATS = (
DEFAULT_STATIC_FORMAT,
"jpg",
"jpeg",
"webp",
)
ANIMATED_FORMATS = (DEFAULT_ANIMATED_FORMAT,)
__slots__ = (
"type",
"url",
"fetched",
"is_spoiler",
)
def __init__(
self,
kind: ImageType,
url: str,
data: Optional[bytes] = None,
is_spoiler: bool = False,
):
self.type = kind
self.url = url
self.is_spoiler = is_spoiler
self.fetched = FetchedImage(data) if data else None
@classmethod
async def convert(cls, ctx: Context, argument: str) -> Image:
return await cls.from_pattern(ctx, argument)
@classmethod
async def from_pattern(cls, ctx: Context, argument: str) -> Image:
return await cls._from_pattern(ctx, argument, allow_animated=True)
@classmethod
async def _from_reference(
cls,
ctx: Context,
reference: discord.MessageReference,
*,
allow_static: bool = True,
allow_animated: bool = False,
) -> Image:
if (resolved := reference.resolved) is None:
resolved = await ctx.channel.fetch_message(reference.message_id)
if isinstance(resolved, discord.Message): # and not discord.DeletedMessage
if (
img := cls.from_message(
ctx,
resolved,
allow_static=allow_static,
allow_animated=allow_animated,
)
) is not None:
return img
raise commands.BadArgument("No images found in referenced message")
raise commands.BadArgument(
f"Unable to fetch referenced message {ctx.channel.id}-{ctx.message.id}",
)
@classmethod
async def _from_pattern(
cls,
ctx: Context,
argument: str,
*,
allow_static: bool = True,
allow_animated: bool = False,
) -> Image:
if not (allow_static or allow_animated):
raise ValueError("Either animated or static image type should be allowed")
# if there is a referenced message, it is more important than message content
# for these reasons:
# - it takes more efdort to reply to message than to attach file/paste url
# - if this was a mistake, it's easier for user to use command again relying on
# from_history to fetch previous message rather than replying to message
# again
#
# this implementation is a bit of a mess, there is an `argument` parameter, but
# we assume that ctx.message is target message in from_history anyway
if (reference := ctx.message.reference) is not None:
return await cls._from_reference(
ctx,
reference,
allow_static=allow_static,
allow_animated=allow_animated,
)
if argument == "~":
return await cls.from_history(ctx)
# match up to 50 previous messages using one or multiple ^'s
if re.fullmatch(r"\^{1,50}", argument):
msgs = await ctx.channel.history(
before=ctx.message.created_at, limit=50
).flatten()
message = msgs[len(argument) - 1]
if not (
image := cls.from_message(
ctx,
message,
allow_static=allow_static,
allow_animated=allow_animated,
)
):
raise commands.BadArgument(
f"Nothing found in message <{message.jump_url}>"
)
return image
def pick_format(target_animated: bool) -> Optional[str]:
if allow_static and allow_animated:
return (
cls.DEFAULT_ANIMATED_FORMAT
if target_animated
else cls.DEFAULT_STATIC_FORMAT
)
if allow_animated and target_animated:
return cls.DEFAULT_ANIMATED_FORMAT
if allow_static:
return cls.DEFAULT_STATIC_FORMAT
# only static allowed, target is animated
return None
# check if pattern is emote
if emote_match := EMOTE_REGEX.fullmatch(argument):
emote_id = int(emote_match["id"])
is_animated = emote_match["animated"] != ""
if (emote_format := pick_format(is_animated)) is None:
raise commands.BadArgument(
"Static images are not allowed, static emote provided"
)
if emote := ctx.bot.get_emoji(emote_id):
return Image(
kind=ImageType.EMOTE,
url=str(emote.url_as(format=emote_format)),
)
return Image(
kind=ImageType.EMOTE,
url=f"https://cdn.discordapp.com/emojis/{emote_id}.{emote_format}",
)
# check if pattern is id that points to emote
if id_match := ID_REGEX.fullmatch(argument):
if emote := ctx.bot.get_emoji(int(id_match.string)):
if (emote_format := pick_format(emote.animated)) is None:
raise commands.BadArgument(
"Static images are not allowed, static emote provided"
)
return Image(
kind=ImageType.EMOTE,
url=str(emote.url_as(format=emote_format)),
)
# check if pattern is emoji
# thanks NotSoSuper and cake for the CDN
# thanks discord for this nonsense
pattern_no_selector_16 = argument.rstrip("\N{VARIATION SELECTOR-16}")
code = "-".join(map(lambda c: f"{ord(c):x}", pattern_no_selector_16))
emote_url = f"https://cdn.notsobot.com/twemoji/512x512/{code}.png"
async with ctx.session.get(
emote_url, timeout=aiohttp.ClientTimeout(total=5)
) as r:
if r.status == 200:
return Image(
kind=ImageType.EMOTE,
url=emote_url,
data=await r.read(),
)
# check if pattern is user mention
try:
# TODO: case insensitive or fuzzy because this is trash
user = await commands.UserConverter().convert(ctx, argument)
except commands.UserNotFound:
pass
else:
if (avatar_format := pick_format(user.is_avatar_animated())) is None:
raise commands.BadArgument(
f"Static images are not allowed, {user} has static avatar",
)
return Image(
kind=ImageType.USER,
url=str(user.avatar_url_as(format=avatar_format)),
)
# check if pattern is url
argument = CLEAN_URL_REGEX.sub("", argument)
if not argument.startswith(("http://", "https://")):
raise commands.BadArgument(
f"Unable to match custom emote, emoji or user with `{argument}`\n"
f"If input is image url, it should begin with http or https"
)
return Image(kind=ImageType.URL, url=argument)
@classmethod
async def from_history(
cls,
ctx: Context,
) -> Image:
return await cls._from_history(ctx, allow_animated=True)
@classmethod
def _check_extension(
cls,
url: str,
*,
allow_static: bool = True,
allow_animated: bool = False,
) -> Optional[str]:
extension = url.rpartition(".")[-1].lower()
if extension in cls.STATIC_FORMATS and allow_static:
return extension
elif extension in cls.ANIMATED_FORMATS and allow_animated:
return extension
return None
@classmethod
def from_message(
cls,
ctx: Context,
msg: discord.Message,
*,
allow_static: bool = True,
allow_animated: bool = False,
) -> Optional[Image]:
# check attachments (files uploaded to discord)
for attachment in msg.attachments:
if (
cls._check_extension(
attachment.filename,
allow_static=allow_static,
allow_animated=allow_animated,
)
is None
):
continue
return Image(
kind=ImageType.ATTACHMENT,
url=attachment.url,
is_spoiler=attachment.is_spoiler(),
)
# check embeds (user posted url / bot posted rich embed)
for embed in msg.embeds:
if embed.image:
if (
cls._check_extension(
embed.image.url,
allow_static=allow_static,
allow_animated=allow_animated,
)
is not None
):
return Image(
kind=ImageType.EMBED,
url=embed.image.url,
)
# bot condition because we do not want image from
# rich embed thumbnail
if not embed.thumbnail or (msg.author.bot and embed.type == "rich"):
continue
# avoid case when image embed was created from url that is
# used as argument or flag
if msg.id == ctx.message.id:
if embed.thumbnail.url in msg.content:
continue
if (
cls._check_extension(
embed.thumbnail.url,
allow_static=allow_static,
allow_animated=allow_animated,
)
is None
):
continue
return Image(
kind=ImageType.EMBED,
url=embed.thumbnail.url,
)
return None
@classmethod
async def _from_history(
cls,
ctx: Context,
*,
allow_static: bool = True,
allow_animated: bool = False,
) -> Image:
if not (allow_static or allow_animated):
raise ValueError("Either animated or static image type should be allowed")
# referenced message is checked second time (first in from_pattern), but
# a) it should be in cache by this time
# b) usually it is not checked if user does not provide input
if (reference := ctx.message.reference) is not None:
return await cls._from_reference(
ctx,
reference,
allow_static=allow_static,
allow_animated=allow_animated,
)
# check channel history for attachments
#
# command can be invoked by message edit, but we still want
# to check messages before created_at
history = await ctx.channel.history(
limit=200, before=ctx.message.created_at
).flatten()
for msg in [ctx.message] + history:
if (
img := cls.from_message(
ctx, msg, allow_static=allow_static, allow_animated=allow_animated
)
) is not None:
return img
raise commands.BadArgument("Nothing found in latest 200 messages")
async def fetch(
self,
ctx: Context,
*,
url: Optional[str] = None,
**kwargs: Any,
) -> FetchedImage:
if url is None:
url = self.url
if url == self.url and self.fetched is not None:
return self.fetched
else:
image_bytes = await self._fetch(ctx, url, **kwargs)
fetched = FetchedImage(image_bytes)
if url == self.url:
self.fetched = fetched
return fetched
@classmethod
async def _fetch(
cls,
ctx: Context,
url: str,
*,
allow_static: bool = True,
allow_animated: bool = False,
timeout: int = 10,
max_content_length: int = 8000000,
) -> bytes:
try:
async with ctx.session.get(url, timeout=timeout) as r:
if r.status != 200:
raise PINKError(f"bad status code: **{r.status}**")
if (r.content_length or 0) > max_content_length:
raise PINKError("content is too big", formatted=False)
allowed_extensions: List[str] = []
if allow_static:
allowed_extensions.extend(cls.STATIC_FORMATS)
if allow_animated:
allowed_extensions.extend(cls.ANIMATED_FORMATS)
if r.content_type.rpartition("/")[-1].lower() not in allowed_extensions:
raise PINKError(
f'unknown content type: **{r.content_type}**, expected one of **{", ".join(allowed_extensions)}**'
)
return await r.read()
except PINKError:
raise
except (Exception, asyncio.TimeoutError) as e:
error = "Download error: "
if isinstance(e, TimeoutError):
error += f"timeout reached: **{timeout}s**"
else:
error += str(e)
raise commands.BadArgument(error, e)
async def to_pil_image(self, ctx: Context) -> PIL.Image:
fetched = await self.fetch(ctx)
return await fetched.to_pil_image(ctx)
def __repr__(self) -> str:
return f"<{type(self).__name__} url={self.url} type={self.type.name}>"
class StaticImage(Image):
@classmethod
async def from_pattern(cls, ctx: Context, argument: str) -> Image:
return await cls._from_pattern(ctx, argument)
@classmethod
async def from_history(
cls,
ctx: Context,
) -> Image:
return await cls._from_history(ctx)
class AnimatedImage(Image):
@classmethod
async def from_pattern(cls, ctx: Context, argument: str) -> Image:
return await cls._from_pattern(
ctx, argument, allow_static=False, allow_animated=True
)
@classmethod
async def from_history(
cls,
ctx: Context,
) -> Image:
return await cls._from_history(ctx, allow_static=False, allow_animated=True)
|
"""General utility functions."""
import datetime as dt
import logging as lg
import sys
import unicodedata
from pathlib import Path
from . import _version
from . import settings
def citation():
"""
Print the OSMnx package's citation information.
Boeing, G. 2017. OSMnx: New Methods for Acquiring, Constructing, Analyzing,
and Visualizing Complex Street Networks. Computers, Environment and Urban
Systems, 65(126-139). https://doi.org/10.1016/j.compenvurbsys.2017.05.004
Returns
-------
None
"""
cite = (
"Citation:\n\n"
"Boeing, G. 2017. OSMnx: New Methods for Acquiring, "
"Constructing, Analyzing, and Visualizing Complex Street "
"Networks. Computers, Environment and Urban Systems, 65(126-139). "
"https://doi.org/10.1016/j.compenvurbsys.2017.05.004\n\n"
"BibTeX entry for LaTeX users:\n\n"
"@article{boeing_osmnx_2017,\n"
" title = {{OSMnx}: {New} {Methods} for {Acquiring}, "
"{Constructing}, {Analyzing}, and {Visualizing} {Complex} "
"{Street} {Networks}},\n"
" volume = {65},\n"
" doi = {10.1016/j.compenvurbsys.2017.05.004},\n"
" number = {126-139},\n"
" journal = {Computers, Environment and Urban Systems},\n"
" author = {Boeing, Geoff},\n"
" year = {2017}\n"
"}"
)
print(cite)
def ts(style="datetime", template=None):
"""
Get current timestamp as string.
Parameters
----------
style : string {"datetime", "date", "time"}
format the timestamp with this built-in template
template : string
if not None, format the timestamp with this template instead of one of
the built-in styles
Returns
-------
ts : string
the string timestamp
"""
if template is None:
if style == "datetime":
template = "{:%Y-%m-%d %H:%M:%S}"
elif style == "date":
template = "{:%Y-%m-%d}"
elif style == "time":
template = "{:%H:%M:%S}"
else: # pragma: no cover
raise ValueError(f'unrecognized timestamp style "{style}"')
ts = template.format(dt.datetime.now())
return ts
def config(
all_oneway=settings.all_oneway,
bidirectional_network_types=settings.bidirectional_network_types,
cache_folder=settings.cache_folder,
cache_only_mode=settings.cache_only_mode,
data_folder=settings.data_folder,
default_accept_language=settings.default_accept_language,
default_access=settings.default_access,
default_crs=settings.default_crs,
default_referer=settings.default_referer,
default_user_agent=settings.default_user_agent,
elevation_provider=settings.elevation_provider,
imgs_folder=settings.imgs_folder,
log_console=settings.log_console,
log_file=settings.log_file,
log_filename=settings.log_filename,
log_level=settings.log_level,
log_name=settings.log_name,
logs_folder=settings.logs_folder,
max_query_area_size=settings.max_query_area_size,
memory=settings.memory,
nominatim_endpoint=settings.nominatim_endpoint,
nominatim_key=settings.nominatim_key,
osm_xml_node_attrs=settings.osm_xml_node_attrs,
osm_xml_node_tags=settings.osm_xml_node_tags,
osm_xml_way_attrs=settings.osm_xml_way_attrs,
osm_xml_way_tags=settings.osm_xml_way_tags,
overpass_endpoint=settings.overpass_endpoint,
overpass_settings=settings.overpass_settings,
timeout=settings.timeout,
use_cache=settings.use_cache,
useful_tags_node=settings.useful_tags_node,
useful_tags_way=settings.useful_tags_way,
):
"""
Configure OSMnx by setting the default global settings' values.
Any parameters not passed by the caller are (re-)set to their original
default values.
Parameters
----------
all_oneway : bool
Only use if specifically saving to .osm XML file with save_graph_xml
function. if True, forces all ways to be loaded as oneway ways,
preserving the original order of nodes stored in the OSM way XML.
This also retains original OSM string values for oneway attribute
values, rather than converting them to a True/False bool.
bidirectional_network_types : list
network types for which a fully bidirectional graph will be created
cache_folder : string or pathlib.Path
path to folder in which to save/load HTTP response cache
data_folder : string or pathlib.Path
path to folder in which to save/load graph files by default
cache_only_mode : bool
If True, download network data from Overpass then raise a
CacheOnlyModeInterrupt error for user to catch. This prevents graph
building from taking place and instead just saves OSM response data to
cache. Useful for sequentially caching lots of raw data (as you can
only query Overpass one request at a time) then using the cache to
quickly build many graphs simultaneously with multiprocessing.
default_accept_language : string
HTTP header accept-language
default_access : string
default filter for OSM "access" key
default_crs : string
default coordinate reference system to set when creating graphs
default_referer : string
HTTP header referer
default_user_agent : string
HTTP header user-agent
elevation_provider : string {"google", "airmap"}
the API provider to use for adding node elevations
imgs_folder : string or pathlib.Path
path to folder in which to save plot images by default
log_file : bool
if True, save log output to a file in logs_folder
log_filename : string
name of the log file, without file extension
log_console : bool
if True, print log output to the console (terminal window)
log_level : int
one of Python's logger.level constants
log_name : string
name of the logger
logs_folder : string or pathlib.Path
path to folder in which to save log files
max_query_area_size : int
maximum area for any part of the geometry in meters: any polygon
bigger than this will get divided up for multiple queries to API
(default 50km x 50km)
memory : int
Overpass server memory allocation size for the query, in bytes. If
None, server will use its default allocation size. Use with caution.
nominatim_endpoint : string
the API endpoint to use for nominatim queries
nominatim_key : string
your API key, if you are using an endpoint that requires one
osm_xml_node_attrs : list
node attributes for saving .osm XML files with save_graph_xml function
osm_xml_node_tags : list
node tags for saving .osm XML files with save_graph_xml function
osm_xml_way_attrs : list
edge attributes for saving .osm XML files with save_graph_xml function
osm_xml_way_tags : list
edge tags for for saving .osm XML files with save_graph_xml function
overpass_endpoint : string
the API endpoint to use for overpass queries
overpass_settings : string
Settings string for overpass queries. For example, to query historical
OSM data as of a certain date:
``'[out:json][timeout:90][date:"2019-10-28T19:20:00Z"]'``.
Use with caution.
timeout : int
the timeout interval for the HTTP request and for API to use while
running the query
use_cache : bool
if True, cache HTTP responses locally instead of calling API
repeatedly for the same request
useful_tags_node : list
OSM "node" tags to add as graph node attributes, when present
useful_tags_way : list
OSM "way" tags to add as graph edge attributes, when present
Returns
-------
None
"""
# set each global setting to the argument value
settings.all_oneway = all_oneway
settings.bidirectional_network_types = bidirectional_network_types
settings.cache_folder = cache_folder
settings.cache_only_mode = cache_only_mode
settings.data_folder = data_folder
settings.default_accept_language = default_accept_language
settings.default_access = default_access
settings.default_crs = default_crs
settings.default_referer = default_referer
settings.default_user_agent = default_user_agent
settings.elevation_provider = elevation_provider
settings.imgs_folder = imgs_folder
settings.log_console = log_console
settings.log_file = log_file
settings.log_filename = log_filename
settings.log_level = log_level
settings.log_name = log_name
settings.logs_folder = logs_folder
settings.max_query_area_size = max_query_area_size
settings.memory = memory
settings.nominatim_endpoint = nominatim_endpoint
settings.nominatim_key = nominatim_key
settings.osm_xml_node_attrs = osm_xml_node_attrs
settings.osm_xml_node_tags = osm_xml_node_tags
settings.osm_xml_way_attrs = osm_xml_way_attrs
settings.osm_xml_way_tags = osm_xml_way_tags
settings.overpass_endpoint = overpass_endpoint
settings.overpass_settings = overpass_settings
settings.timeout = timeout
settings.use_cache = use_cache
settings.useful_tags_node = useful_tags_node
settings.useful_tags_way = useful_tags_way
log(f"Configured OSMnx {_version.__version__}")
log(f"HTTP response caching is {"on" if settings.use_cache else "off"}")
def log(message, level=None, name=None, filename=None):
"""
Write a message to the logger.
This logs to file and/or prints to the console (terminal), depending on
the current configuration of settings.log_file and settings.log_console.
Parameters
----------
message : string
the message to log
level : int
one of Python's logger.level constants
name : string
name of the logger
filename : string
name of the log file, without file extension
Returns
-------
None
"""
if level is None:
level = settings.log_level
if name is None:
name = settings.log_name
if filename is None:
filename = settings.log_filename
# if logging to file is turned on
if settings.log_file:
# get the current logger (or create a new one, if none), then log
# message at requested level
logger = _get_logger(level=level, name=name, filename=filename)
if level == lg.DEBUG:
logger.debug(message)
elif level == lg.INFO:
logger.info(message)
elif level == lg.WARNING:
logger.warning(message)
elif level == lg.ERROR:
logger.error(message)
# if logging to console, convert message to ascii and print to console
if settings.log_console:
# capture current stdout, then switch it to the console, print the
# message, then switch back to what had been the stdout. this prevents
# logging to notebook in jupyter: instead, it goes to terminal
standard_out = sys.stdout
sys.stdout = sys.__stdout__
# prepend timestamp
message = f"{ts()} {message}"
# convert to ascii so it doesn't break windows terminals
message = (
unicodedata.normalize("NFKD", str(message)).encode("ascii", errors="replace").decode()
)
print(message)
sys.stdout = standard_out
def _get_logger(level, name, filename):
"""
Create a logger or return the current one if already instantiated.
Parameters
----------
level : int
one of Python's logger.level constants
name : string
name of the logger
filename : string
name of the log file, without file extension
Returns
-------
logger : logging.logger
"""
logger = lg.getLogger(name)
# if a logger with this name is not already set up
if not getattr(logger, "handler_set", None):
# get today's date and construct a log filename
log_filename = Path(settings.logs_folder) / f'{filename}_{ts(style='date')}.log'
# if the logs folder does not already exist, create it
log_filename.parent.mkdir(parents=True, exist_ok=True)
# create file handler and log formatter and set them up
handler = lg.FileHandler(log_filename, encoding="utf-8")
formatter = lg.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(level)
logger.handler_set = True
return logger
| """General utility functions."""
import datetime as dt
import logging as lg
import sys
import unicodedata
from pathlib import Path
from . import _version
from . import settings
def citation():
"""
Print the OSMnx package's citation information.
Boeing, G. 2017. OSMnx: New Methods for Acquiring, Constructing, Analyzing,
and Visualizing Complex Street Networks. Computers, Environment and Urban
Systems, 65(126-139). https://doi.org/10.1016/j.compenvurbsys.2017.05.004
Returns
-------
None
"""
cite = (
"Citation:\n\n"
"Boeing, G. 2017. OSMnx: New Methods for Acquiring, "
"Constructing, Analyzing, and Visualizing Complex Street "
"Networks. Computers, Environment and Urban Systems, 65(126-139). "
"https://doi.org/10.1016/j.compenvurbsys.2017.05.004\n\n"
"BibTeX entry for LaTeX users:\n\n"
"@article{boeing_osmnx_2017,\n"
" title = {{OSMnx}: {New} {Methods} for {Acquiring}, "
"{Constructing}, {Analyzing}, and {Visualizing} {Complex} "
"{Street} {Networks}},\n"
" volume = {65},\n"
" doi = {10.1016/j.compenvurbsys.2017.05.004},\n"
" number = {126-139},\n"
" journal = {Computers, Environment and Urban Systems},\n"
" author = {Boeing, Geoff},\n"
" year = {2017}\n"
"}"
)
print(cite)
def ts(style="datetime", template=None):
"""
Get current timestamp as string.
Parameters
----------
style : string {"datetime", "date", "time"}
format the timestamp with this built-in template
template : string
if not None, format the timestamp with this template instead of one of
the built-in styles
Returns
-------
ts : string
the string timestamp
"""
if template is None:
if style == "datetime":
template = "{:%Y-%m-%d %H:%M:%S}"
elif style == "date":
template = "{:%Y-%m-%d}"
elif style == "time":
template = "{:%H:%M:%S}"
else: # pragma: no cover
raise ValueError(f'unrecognized timestamp style "{style}"')
ts = template.format(dt.datetime.now())
return ts
def config(
all_oneway=settings.all_oneway,
bidirectional_network_types=settings.bidirectional_network_types,
cache_folder=settings.cache_folder,
cache_only_mode=settings.cache_only_mode,
data_folder=settings.data_folder,
default_accept_language=settings.default_accept_language,
default_access=settings.default_access,
default_crs=settings.default_crs,
default_referer=settings.default_referer,
default_user_agent=settings.default_user_agent,
elevation_provider=settings.elevation_provider,
imgs_folder=settings.imgs_folder,
log_console=settings.log_console,
log_file=settings.log_file,
log_filename=settings.log_filename,
log_level=settings.log_level,
log_name=settings.log_name,
logs_folder=settings.logs_folder,
max_query_area_size=settings.max_query_area_size,
memory=settings.memory,
nominatim_endpoint=settings.nominatim_endpoint,
nominatim_key=settings.nominatim_key,
osm_xml_node_attrs=settings.osm_xml_node_attrs,
osm_xml_node_tags=settings.osm_xml_node_tags,
osm_xml_way_attrs=settings.osm_xml_way_attrs,
osm_xml_way_tags=settings.osm_xml_way_tags,
overpass_endpoint=settings.overpass_endpoint,
overpass_settings=settings.overpass_settings,
timeout=settings.timeout,
use_cache=settings.use_cache,
useful_tags_node=settings.useful_tags_node,
useful_tags_way=settings.useful_tags_way,
):
"""
Configure OSMnx by setting the default global settings' values.
Any parameters not passed by the caller are (re-)set to their original
default values.
Parameters
----------
all_oneway : bool
Only use if specifically saving to .osm XML file with save_graph_xml
function. if True, forces all ways to be loaded as oneway ways,
preserving the original order of nodes stored in the OSM way XML.
This also retains original OSM string values for oneway attribute
values, rather than converting them to a True/False bool.
bidirectional_network_types : list
network types for which a fully bidirectional graph will be created
cache_folder : string or pathlib.Path
path to folder in which to save/load HTTP response cache
data_folder : string or pathlib.Path
path to folder in which to save/load graph files by default
cache_only_mode : bool
If True, download network data from Overpass then raise a
CacheOnlyModeInterrupt error for user to catch. This prevents graph
building from taking place and instead just saves OSM response data to
cache. Useful for sequentially caching lots of raw data (as you can
only query Overpass one request at a time) then using the cache to
quickly build many graphs simultaneously with multiprocessing.
default_accept_language : string
HTTP header accept-language
default_access : string
default filter for OSM "access" key
default_crs : string
default coordinate reference system to set when creating graphs
default_referer : string
HTTP header referer
default_user_agent : string
HTTP header user-agent
elevation_provider : string {"google", "airmap"}
the API provider to use for adding node elevations
imgs_folder : string or pathlib.Path
path to folder in which to save plot images by default
log_file : bool
if True, save log output to a file in logs_folder
log_filename : string
name of the log file, without file extension
log_console : bool
if True, print log output to the console (terminal window)
log_level : int
one of Python's logger.level constants
log_name : string
name of the logger
logs_folder : string or pathlib.Path
path to folder in which to save log files
max_query_area_size : int
maximum area for any part of the geometry in meters: any polygon
bigger than this will get divided up for multiple queries to API
(default 50km x 50km)
memory : int
Overpass server memory allocation size for the query, in bytes. If
None, server will use its default allocation size. Use with caution.
nominatim_endpoint : string
the API endpoint to use for nominatim queries
nominatim_key : string
your API key, if you are using an endpoint that requires one
osm_xml_node_attrs : list
node attributes for saving .osm XML files with save_graph_xml function
osm_xml_node_tags : list
node tags for saving .osm XML files with save_graph_xml function
osm_xml_way_attrs : list
edge attributes for saving .osm XML files with save_graph_xml function
osm_xml_way_tags : list
edge tags for for saving .osm XML files with save_graph_xml function
overpass_endpoint : string
the API endpoint to use for overpass queries
overpass_settings : string
Settings string for overpass queries. For example, to query historical
OSM data as of a certain date:
``'[out:json][timeout:90][date:"2019-10-28T19:20:00Z"]'``.
Use with caution.
timeout : int
the timeout interval for the HTTP request and for API to use while
running the query
use_cache : bool
if True, cache HTTP responses locally instead of calling API
repeatedly for the same request
useful_tags_node : list
OSM "node" tags to add as graph node attributes, when present
useful_tags_way : list
OSM "way" tags to add as graph edge attributes, when present
Returns
-------
None
"""
# set each global setting to the argument value
settings.all_oneway = all_oneway
settings.bidirectional_network_types = bidirectional_network_types
settings.cache_folder = cache_folder
settings.cache_only_mode = cache_only_mode
settings.data_folder = data_folder
settings.default_accept_language = default_accept_language
settings.default_access = default_access
settings.default_crs = default_crs
settings.default_referer = default_referer
settings.default_user_agent = default_user_agent
settings.elevation_provider = elevation_provider
settings.imgs_folder = imgs_folder
settings.log_console = log_console
settings.log_file = log_file
settings.log_filename = log_filename
settings.log_level = log_level
settings.log_name = log_name
settings.logs_folder = logs_folder
settings.max_query_area_size = max_query_area_size
settings.memory = memory
settings.nominatim_endpoint = nominatim_endpoint
settings.nominatim_key = nominatim_key
settings.osm_xml_node_attrs = osm_xml_node_attrs
settings.osm_xml_node_tags = osm_xml_node_tags
settings.osm_xml_way_attrs = osm_xml_way_attrs
settings.osm_xml_way_tags = osm_xml_way_tags
settings.overpass_endpoint = overpass_endpoint
settings.overpass_settings = overpass_settings
settings.timeout = timeout
settings.use_cache = use_cache
settings.useful_tags_node = useful_tags_node
settings.useful_tags_way = useful_tags_way
log(f"Configured OSMnx {_version.__version__}")
log(f"HTTP response caching is {'on' if settings.use_cache else 'off'}")
def log(message, level=None, name=None, filename=None):
"""
Write a message to the logger.
This logs to file and/or prints to the console (terminal), depending on
the current configuration of settings.log_file and settings.log_console.
Parameters
----------
message : string
the message to log
level : int
one of Python's logger.level constants
name : string
name of the logger
filename : string
name of the log file, without file extension
Returns
-------
None
"""
if level is None:
level = settings.log_level
if name is None:
name = settings.log_name
if filename is None:
filename = settings.log_filename
# if logging to file is turned on
if settings.log_file:
# get the current logger (or create a new one, if none), then log
# message at requested level
logger = _get_logger(level=level, name=name, filename=filename)
if level == lg.DEBUG:
logger.debug(message)
elif level == lg.INFO:
logger.info(message)
elif level == lg.WARNING:
logger.warning(message)
elif level == lg.ERROR:
logger.error(message)
# if logging to console, convert message to ascii and print to console
if settings.log_console:
# capture current stdout, then switch it to the console, print the
# message, then switch back to what had been the stdout. this prevents
# logging to notebook in jupyter: instead, it goes to terminal
standard_out = sys.stdout
sys.stdout = sys.__stdout__
# prepend timestamp
message = f"{ts()} {message}"
# convert to ascii so it doesn't break windows terminals
message = (
unicodedata.normalize("NFKD", str(message)).encode("ascii", errors="replace").decode()
)
print(message)
sys.stdout = standard_out
def _get_logger(level, name, filename):
"""
Create a logger or return the current one if already instantiated.
Parameters
----------
level : int
one of Python's logger.level constants
name : string
name of the logger
filename : string
name of the log file, without file extension
Returns
-------
logger : logging.logger
"""
logger = lg.getLogger(name)
# if a logger with this name is not already set up
if not getattr(logger, "handler_set", None):
# get today's date and construct a log filename
log_filename = Path(settings.logs_folder) / f'{filename}_{ts(style="date")}.log'
# if the logs folder does not already exist, create it
log_filename.parent.mkdir(parents=True, exist_ok=True)
# create file handler and log formatter and set them up
handler = lg.FileHandler(log_filename, encoding="utf-8")
formatter = lg.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(level)
logger.handler_set = True
return logger
|
import asyncio
import datetime
import functools
import json
import re
import textwrap
import urllib
from collections import namedtuple
from io import BytesIO
import aiohttp
import discord
from bs4 import BeautifulSoup
from html2text import html2text as h2t
from redbot.core import commands
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import humanize_number, pagify
from redbot.vendored.discord.ext import menus
# TODO Add optional way to use from google search api
nsfwcheck = lambda ctx: (not ctx.guild) or ctx.channel.is_nsfw()
class Google(commands.Cog):
"""
A Simple google search with image support as well
A fair bit of querying stuff is taken from Kowlin's cog - https://github.com/Kowlin/refactored-cogs
"""
def __init__(self, bot: Red) -> None:
self.bot = bot
self.options = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
}
self.link_regex = re.compile(
r"https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/\/=]*(?:\.png|\.jpe?g|\.gif))"
)
self.cookies = None
@commands.group(invoke_without_command=True)
@commands.bot_has_permissions(embed_links=True, add_reactions=True)
async def google(self, ctx, *, query: str = None):
"""Search in google from discord"""
if not query:
await ctx.send("Please enter something to search")
else:
isnsfw = nsfwcheck(ctx)
async with ctx.typing():
response, kwargs = await self.get_result(query, nsfw=isnsfw)
pages = []
groups = [response[n : n + 3] for n in range(0, len(response), 3)]
for num, group in enumerate(groups, 1):
emb = discord.Embed(
title="Google Search: {}".format(
query[:44] + "\N{HORIZONTAL ELLIPSIS}" if len(query) > 45 else query
),
color=await ctx.embed_color(),
)
for result in group:
desc = (
f"[{result.url[:60]}]({result.url})\n" if result.url else ""
) + f"{result.desc}"[:1024]
emb.add_field(
name=f"{result.title}",
value=desc or "Nothing",
inline=False,
)
emb.description = f"Page {num} of {len(groups)}"
emb.set_footer(
text=f"Safe Search: {not isnsfw} | " + kwargs["stats"].replace("\n", " ")
)
if "thumbnail" in kwargs:
emb.set_thumbnail(url=kwargs["thumbnail"])
if "image" in kwargs and num == 1:
emb.set_image(url=kwargs["image"])
pages.append(emb)
if pages:
await ResultMenu(source=Source(pages, per_page=1)).start(ctx)
else:
await ctx.send("No result")
@google.command()
async def autofill(self, ctx, *, query: str):
"""Responds with a list of the Google Autofill results for a particular query."""
# This “API” is a bit of a hack; it was only meant for use by
# Google’s own products. and hence it is undocumented.
# Attribution: https://shreyaschand.com/blog/2013/01/03/google-autocomplete-api/
base_url = "https://suggestqueries.google.com/complete/search"
params = {"client": "firefox", "hl": "en", "q": query}
async with ctx.typing():
try:
async with aiohttp.ClientSession() as session:
async with session.get(base_url, params=params) as response:
if response.status != 200:
return await ctx.send(f"https://http.cat/{response.status}")
data = json.loads(await response.read())
except asyncio.TimeoutError:
return await ctx.send("Operation timed out.")
if not data[1]:
return await ctx.send("Could not find any results.")
await ctx.send("\n".join(data[1]))
@google.command(aliases=["books"])
async def book(self, ctx, *, query: str):
"""Search for a book or magazine on Google Books.
This command requires an API key.
To get an API key, you'll first require to enable the API at:
https://console.cloud.google.com/flows/enableapi?apiid=books.googleapis.com
Once you have enabled the API, you can find out how to acquire the API key at:
https://developers.google.com/books/docs/v1/using#APIKey
Once you get API key, set it in your redbot instance using:
```
[p]set api googlebooks api_key <your_api_key>
```
There are special keywords you can specify in the search terms to search in particular fields.
You can read more on that in detail over at:
https://developers.google.com/books/docs/v1/using#PerformingSearch
"""
api_key = (await ctx.bot.get_shared_api_tokens("googlebooks")).get("api_key")
if not api_key:
return await ctx.send_help()
async with ctx.typing():
base_url = "https://www.googleapis.com/books/v1/volumes"
params = {
"apiKey": api_key,
"q": query,
"printType": "all",
"maxResults": 40,
"orderBy": "relevance",
}
try:
async with aiohttp.ClientSession() as session:
async with session.get(base_url, params=params) as response:
if response.status != 200:
return await ctx.send(f"https://http.cat/{response.status}")
data = await response.json()
except aiohttp.TimeoutError:
return await ctx.send("Operation timed out.")
if len(data.get("items")) == 0:
return await ctx.send("No results.")
pages = []
for i, info in enumerate(data.get("items")):
embed = discord.Embed(colour=await ctx.embed_color())
embed.title = info.get("volumeInfo").get("title")
embed.url = info.get("volumeInfo").get("canonicalVolumeLink")
embed.description = info.get("volumeInfo").get("description", "No summary.")[:2000]
embed.set_author(
name="Google Books",
url="https://books.google.com/",
icon_url="https://i.imgur.com/N3oHABo.png",
)
if info.get("volumeInfo").get("imageLinks"):
embed.set_thumbnail(
url=info.get("volumeInfo").get("imageLinks").get("thumbnail")
)
embed.add_field(
name="Published Date",
value=info.get("volumeInfo").get("publishedDate", "Unknown"),
)
if info.get("volumeInfo").get("authors"):
embed.add_field(
name="Authors",
value=", ".join(info.get("volumeInfo").get("authors")),
)
embed.add_field(
name="Publisher",
value=info.get("volumeInfo").get("publisher", "Unknown"),
)
if info.get("volumeInfo").get("pageCount"):
embed.add_field(
name="Page Count",
value=humanize_number(info.get("volumeInfo").get("pageCount")),
)
embed.add_field(
name="Web Reader Link",
value=f"[Click here!]({info.get("accessInfo").get("webReaderLink")})",
)
if info.get("volumeInfo").get("categories"):
embed.add_field(
name="Category",
value=", ".join(info.get("volumeInfo").get("categories")),
)
if info.get("saleInfo").get("retailPrice"):
currency_format = (
f"[{info.get("saleInfo").get("retailPrice").get("amount")} "
f"{info.get("saleInfo").get("retailPrice").get("currencyCode")}]"
f"({info.get("saleInfo").get("buyLink")} 'Click to buy on Google Books!')"
)
embed.add_field(
name="Retail Price",
value=currency_format,
)
epub_available = (
"✅" if info.get("accessInfo").get("epub").get("isAvailable") else "❌"
)
pdf_available = (
"✅" if info.get("accessInfo").get("pdf").get("isAvailable") else "❌"
)
if info.get("accessInfo").get("epub").get("downloadLink"):
epub_available += (
" [`Download Link`]"
f"({info.get("accessInfo").get("epub").get("downloadLink")})"
)
if info.get("accessInfo").get("pdf").get("downloadLink"):
pdf_available += (
" [`Download Link`]"
f"({info.get("accessInfo").get("pdf").get("downloadLink")})"
)
embed.add_field(name="EPUB available?", value=epub_available)
embed.add_field(name="PDF available?", value=pdf_available)
viewablility = (
f"{info.get("accessInfo").get("viewability").replace("_", " ").title()}"
)
embed.add_field(name="Viewablility", value=viewablility)
embed.set_footer(text=f"Page {i + 1} of {len(data.get("items"))}")
pages.append(embed)
if len(pages) == 1:
await ctx.send(embed=pages[0])
else:
await ResultMenu(source=Source(pages, per_page=1)).start(ctx)
@google.command()
async def doodle(self, ctx, month: int = None, year: int = None):
"""Responds with Google doodles of the current month.
Or doodles of specific month/year if `month` and `year` values are provided.
"""
month = datetime.datetime.now(datetime.timezone.utc).month if not month else month
year = datetime.datetime.now(datetime.timezone.utc).year if not year else year
async with ctx.typing():
base_url = f"https://www.google.com/doodles/json/{year}/{month}"
try:
async with aiohttp.ClientSession() as session:
async with session.get(base_url) as response:
if response.status != 200:
return await ctx.send(f"https://http.cat/{response.status}")
output = await response.json()
except asyncio.TimeoutError:
return await ctx.send("Operation timed out.")
if not output:
return await ctx.send("Could not find any results.")
pages = []
for data in output:
em = discord.Embed(colour=await ctx.embed_color())
em.title = data.get("title", "Doodle title missing")
img_url = data.get("high_res_url")
if img_url and not img_url.startswith("https:"):
img_url = "https:" + data.get("high_res_url")
if not img_url:
img_url = "https:" + data.get("url")
em.set_image(url=img_url)
date = "-".join([str(x) for x in data.get("run_date_array")[::-1]])
em.set_footer(text=f"{data.get("share_text")}\nDoodle published on: {date}")
pages.append(em)
if len(pages) == 1:
return await ctx.send(embed=pages[0])
else:
await ResultMenu(source=Source(pages, per_page=1)).start(ctx)
@google.command(aliases=["img"])
async def image(self, ctx, *, query: str = None):
"""Search google images from discord"""
if not query:
await ctx.send("Please enter some image name to search")
else:
isnsfw = nsfwcheck(ctx)
async with ctx.typing():
response = await self.get_result(query, images=True, nsfw=isnsfw)
size = len(tuple(response))
pages = [
discord.Embed(
title=f"Pages: {i}/{size}",
color=await ctx.embed_color(),
description="Some images might not be visible.",
)
.set_image(url=j)
.set_footer(text=f"Safe Search: {not isnsfw}")
for i, j in enumerate(response, 1)
]
if pages:
await ResultMenu(source=Source(pages, per_page=1)).start(ctx)
else:
await ctx.send("No result")
@google.command(aliases=["rev"])
async def reverse(self, ctx, *, url: str = None):
"""Attach or paste the url of an image to reverse search, or reply to a message which has the image/embed with the image"""
isnsfw = nsfwcheck(ctx)
query = None
def reply(ctx):
# Helper reply grabber
if hasattr(ctx.message, "reference") and ctx.message.reference != None:
msg = ctx.message.reference.resolved
if isinstance(msg, discord.Message):
return msg
def get_url(msg_obj, check=False):
# Helper get potential url, if check is True then returns none if nothing is found in embeds
if msg_obj.embeds:
emb = msg_obj.embeds[0].to_dict()
if "image" in emb:
return emb["image"]["url"]
elif "thumbnail" in emb:
return emb["thumbnail"]["url"]
if msg_obj.attachments:
return msg_obj.attachments[0].url
else:
return None if check else msg_obj.content.lstrip("<").rstrip(">")
def check_url(url: str):
# Helper function to check if valid url or not
return url.startswith("http") and " " not in url
if resp := reply(ctx):
query = get_url(resp)
# TODO More work on this to shorten code.
if not query or not check_url(query):
if query := get_url(ctx.message, check=True):
pass
elif url is None:
return await ctx.send_help()
else:
query = url.lstrip("<").rstrip(">")
# Big brain url parsing
if not check_url(query):
return await ctx.send_help()
if not query or not query.startswith("http") or " " in query:
return await ctx.send_help()
encoded = {
"image_url": query,
"encoded_image": None,
"image_content": None,
"filename": None,
"hl": "en",
}
async with ctx.typing():
async with aiohttp.ClientSession() as session:
async with session.get(
"https://www.google.com/searchbyimage?" + urllib.parse.urlencode(encoded),
headers=self.options,
cookies=self.cookies,
) as resp:
text = await resp.read()
redir_url = resp.url
prep = functools.partial(self.reverse_search, text)
result, (response, kwargs) = await self.bot.loop.run_in_executor(None, prep)
pages = []
if response:
groups = [response[n : n + 3] for n in range(0, len(response), 3)]
for num, group in enumerate(groups, 1):
emb = discord.Embed(
title="Google Reverse Image Search",
description="[`"
+ (result or "Nothing significant found")
+ f"`]({redir_url})",
color=await ctx.embed_color(),
)
for i in group:
desc = (f"[{i.url[:60]}]({i.url})\n" if i.url else "") + f"{i.desc}"[:1024]
emb.add_field(
name=f"{i.title}",
value=desc or "Nothing",
inline=False,
)
emb.set_footer(
text=f"Safe Search: {not isnsfw} | "
+ kwargs["stats"].replace("\n", " ")
+ f"| Page: {num}/{len(groups)}"
)
emb.set_thumbnail(url=encoded["image_url"])
pages.append(emb)
if pages:
await ResultMenu(source=Source(pages, per_page=1)).start(ctx)
else:
await ctx.send(
embed=discord.Embed(
title="Google Reverse Image Search",
description="[`" + ("Nothing significant found") + f"`]({redir_url})",
color=await ctx.embed_color(),
).set_thumbnail(url=encoded["image_url"])
)
@commands.is_owner()
@google.command(hidden=True)
async def debug(self, ctx, *, url):
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.options, cookies=self.cookies) as resp:
text = await resp.text()
f = BytesIO(bytes(text, "utf-8"))
await ctx.send(file=discord.File(f, filename="filename.html"))
f.close()
async def get_result(self, query, images=False, nsfw=False):
"""Fetch the data"""
# TODO make this fetching a little better
encoded = urllib.parse.quote_plus(query, encoding="utf-8", errors="replace")
async def get_html(url, encoded):
async with aiohttp.ClientSession() as session:
async with session.get(
url + encoded, headers=self.options, cookies=self.cookies
) as resp:
self.cookies = resp.cookies
return await resp.text()
if not nsfw:
encoded += "&safe=active"
if not images:
url = "https://www.google.com/search?q="
text = await get_html(url, encoded)
prep = functools.partial(self.parser_text, text)
else:
# TYSM fixator, for the non-js query url
url = "https://www.google.com/search?tbm=isch&q="
text = await get_html(url, encoded)
prep = functools.partial(self.parser_image, text)
return await self.bot.loop.run_in_executor(None, prep)
def reverse_search(self, text):
soup = BeautifulSoup(text, features="html.parser")
if check := soup.find("div", class_="card-section"):
if "The URL doesn't refer" in check.text:
return check.text, (None, None)
if res := soup.find("input", class_="gLFyf gsfi"):
return res["value"], (self.parser_text(text, soup=soup, cards=False) or (None, None))
def parser_text(self, text, soup=None, cards: bool = True):
"""My bad logic for scraping"""
if not soup:
soup = BeautifulSoup(text, features="html.parser")
s = namedtuple("searchres", "url title desc")
final = []
kwargs = {"stats": h2t(str(soup.find("div", id="result-stats")))}
def get_card():
"""Getting cards if present, here started the pain"""
# common card
if card := soup.find("div", class_="g mnr-c g-blk"):
if desc := card.find("span", class_="hgKElc"):
final.append(s(None, "Google Info Card:", h2t(str(desc))))
return
# another webpull card: what is the language JetBrains made? TODO fix this, depends on too many classes as of now
if card := soup.find("div", class_="kp-blk c2xzTb"):
if head := card.find("div", class_="Z0LcW XcVN5d AZCkJd"):
if desc := card.find("div", class_="iKJnec"):
final.append(s(None, f"Answer: {head.text}", h2t(str(desc))))
return
# calculator card
if card := soup.find("div", class_="tyYmIf"):
if question := card.find("span", class_="vUGUtc"):
if answer := card.find("span", class_="qv3Wpe"):
tmp = h2t(str(question)).strip("\n")
final.append(
s(None, "Google Calculator:", f"**{tmp}** {h2t(str(answer))}")
)
return
# sidepage card
if card := soup.find("div", class_="liYKde g VjDLd"):
if thumbnail := card.find("g-img", attrs={"data-lpage": True}):
kwargs["thumbnail"] = thumbnail["data-lpage"]
if title := soup.find("div", class_="SPZz6b"):
if desc := card.find("div", class_="kno-rdesc"):
if remove := desc.find(class_="Uo8X3b"):
remove.decompose()
desc = (
textwrap.shorten(
h2t(str(desc)), 1024, placeholder="\N{HORIZONTAL ELLIPSIS}"
)
+ "\n"
)
if more_info := card.findAll("div", class_="Z1hOCe"):
for thing in more_info:
tmp = thing.findAll("span")
if len(tmp) == 2:
desc2 = f"\n **{tmp[0].text}**`{tmp[1].text.lstrip(":")}`"
# More jack advises :D
MAX = 1024
MAX_LEN = MAX - len(desc2)
if len(desc) > MAX_LEN:
desc = (
next(
pagify(
desc,
delims=[" ", "\n"],
page_length=MAX_LEN - 1,
shorten_by=0,
)
)
+ "\N{HORIZONTAL ELLIPSIS}"
)
desc = desc + desc2
final.append(
s(
None,
"Google Featured Card: "
+ h2t(str(title)).replace("\n", " ").replace("#", ""),
desc,
)
)
return
# time cards and unit conversions and moar-_- WORK ON THIS, THIS IS BAD STUFF 100
if card := soup.find("div", class_="vk_c"):
if conversion := card.findAll("div", class_="rpnBye"):
if len(conversion) != 2:
return
tmp = tuple(
map(
lambda thing: (
thing.input["value"],
thing.findAll("option", selected=True)[0].text,
),
conversion,
)
)
final.append(
s(
None,
"Unit Conversion v1:",
"`" + " ".join(tmp[0]) + " is equal to " + " ".join(tmp[1]) + "`",
)
)
return
elif card.find("div", "lu_map_section"):
if img := re.search(r"\((.*)\)", h2t(str(card)).replace("\n", "")):
kwargs["image"] = "https://www.google.com" + img[1]
return
else:
# time card
if tail := card.find("table", class_="d8WIHd"):
tail.decompose()
tmp = h2t(str(card)).replace("\n\n", "\n").split("\n")
final.append(s(None, tmp[0], "\n".join(tmp[1:])))
return
# translator cards
if card := soup.find("div", class_="tw-src-ltr"):
langs = soup.find("div", class_="pcCUmf")
src_lang = "**" + langs.find("span", class_="source-language").text + "**"
dest_lang = "**" + langs.find("span", class_="target-language").text + "**"
final_text = ""
if source := card.find("div", id="KnM9nf"):
final_text += (src_lang + "\n`" + source.find("pre").text) + "`\n"
if dest := card.find("div", id="kAz1tf"):
final_text += dest_lang + "\n`" + dest.find("pre").text.strip("\n") + "`"
final.append(s(None, "Google Translator", final_text))
return
# Unit conversions
if card := soup.find("div", class_="nRbRnb"):
final_text = "\N{ZWSP}\n**"
if source := card.find("div", class_="vk_sh c8Zgcf"):
final_text += "`" + h2t(str(source)).strip("\n")
if dest := card.find("div", class_="dDoNo ikb4Bb vk_bk gsrt gzfeS"):
final_text += " " + h2t(str(dest)).strip("\n") + "`**"
if time := card.find("div", class_="hqAUc"):
if remove := time.find("select"):
remove.decompose()
tmp = h2t(str(time)).replace("\n", " ").split("·")
final_text += (
"\n"
+ (f"`{tmp[0].strip()}` ·{tmp[1]}" if len(tmp) == 2 else "·".join(tmp))
+ "\n\N{ZWSP}"
)
final.append(s(None, "Unit Conversion", final_text))
return
# Definition cards
if card := soup.find("div", class_="KIy09e"):
final_text = ""
if word := card.find("div", class_="DgZBFd XcVN5d frCXef"):
if sup := word.find("sup"):
sup.decompose()
final_text += "`" + word.text + "`"
if pronounciate := card.find("div", class_="S23sjd g30o5d"):
final_text += " | " + pronounciate.text
if type_ := card.find("div", class_="pgRvse vdBwhd ePtbIe"):
final_text += " | " + type_.text + "\n\n"
if definition := card.find("div", class_="L1jWkf h3TRxf"):
for text in definition.findAll("div")[:2]:
tmp = h2t(str(text))
if tmp.count("\n") < 5:
final_text += "`" + tmp.strip("\n").replace("\n", " ") + "`" + "\n"
final.append(s(None, "Definition", final_text))
return
# single answer card
if card := soup.find("div", class_="ayRjaf"):
final.append(
s(
None,
h2t(str(card.find("div", class_="zCubwf"))).replace("\n", ""),
h2t(str(card.find("span").find("span"))).strip("\n") + "\n\N{ZWSP}",
)
)
return
# another single card?
if card := soup.find("div", class_="sXLaOe"):
final.append(s(None, "Single Answer Card:", card.text))
return
if cards:
get_card()
for res in soup.findAll("div", class_="g"):
if name := res.find("div", class_="yuRUbf"):
url = name.a["href"]
if title := name.find("h3", "LC20lb DKV0Md"):
title = title.text
else:
title = url
else:
url = None
title = None
if desc := res.find("div", class_="IsZvec"):
if remove := desc.find("span", class_="f"):
remove.decompose()
desc = h2t(str(desc.find("span", class_="aCOpRe")))
else:
desc = "Not found"
if title:
final.append(s(url, title, desc.replace("\n", " ")))
return final, kwargs
def parser_image(self, html):
# first 2 are google static logo images
return self.link_regex.findall(html)[2:]
# Dpy menus
class Source(menus.ListPageSource):
async def format_page(self, menu, embeds):
return embeds
# Thanks fixator https://github.com/fixator10/Fixator10-Cogs/blob/V3.leveler_abc/leveler/menus/top.py
class ResultMenu(menus.MenuPages, inherit_buttons=False):
def __init__(self, **kwargs):
super().__init__(
**kwargs,
timeout=60,
clear_reactions_after=True,
delete_message_after=True,
)
def _skip_double_triangle_buttons(self):
return super()._skip_double_triangle_buttons()
async def finalize(self, timed_out):
"""|coro|
A coroutine that is called when the menu loop has completed
its run. This is useful if some asynchronous clean-up is
required after the fact.
Parameters
--------------
timed_out: :class:`bool`
Whether the menu completed due to timing out.
"""
if timed_out and self.delete_message_after:
self.delete_message_after = False
@menus.button(
"\N{BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}\ufe0f",
position=menus.First(0),
skip_if=_skip_double_triangle_buttons,
)
async def go_to_first_page(self, payload):
"""go to the first page"""
await self.show_page(0)
@menus.button("\N{BLACK LEFT-POINTING TRIANGLE}\ufe0f", position=menus.First(1))
async def go_to_previous_page(self, payload):
"""go to the previous page"""
if self.current_page == 0:
await self.show_page(self._source.get_max_pages() - 1)
else:
await self.show_checked_page(self.current_page - 1)
@menus.button("\N{BLACK RIGHT-POINTING TRIANGLE}\ufe0f", position=menus.Last(0))
async def go_to_next_page(self, payload):
"""go to the next page"""
if self.current_page == self._source.get_max_pages() - 1:
await self.show_page(0)
else:
await self.show_checked_page(self.current_page + 1)
@menus.button(
"\N{BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}\ufe0f",
position=menus.Last(1),
skip_if=_skip_double_triangle_buttons,
)
async def go_to_last_page(self, payload):
"""go to the last page"""
# The call here is safe because it's guarded by skip_if
await self.show_page(self._source.get_max_pages() - 1)
@menus.button("\N{CROSS MARK}", position=menus.First(2))
async def stop_pages(self, payload) -> None:
self.stop()
| import asyncio
import datetime
import functools
import json
import re
import textwrap
import urllib
from collections import namedtuple
from io import BytesIO
import aiohttp
import discord
from bs4 import BeautifulSoup
from html2text import html2text as h2t
from redbot.core import commands
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import humanize_number, pagify
from redbot.vendored.discord.ext import menus
# TODO Add optional way to use from google search api
nsfwcheck = lambda ctx: (not ctx.guild) or ctx.channel.is_nsfw()
class Google(commands.Cog):
"""
A Simple google search with image support as well
A fair bit of querying stuff is taken from Kowlin's cog - https://github.com/Kowlin/refactored-cogs
"""
def __init__(self, bot: Red) -> None:
self.bot = bot
self.options = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
}
self.link_regex = re.compile(
r"https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/\/=]*(?:\.png|\.jpe?g|\.gif))"
)
self.cookies = None
@commands.group(invoke_without_command=True)
@commands.bot_has_permissions(embed_links=True, add_reactions=True)
async def google(self, ctx, *, query: str = None):
"""Search in google from discord"""
if not query:
await ctx.send("Please enter something to search")
else:
isnsfw = nsfwcheck(ctx)
async with ctx.typing():
response, kwargs = await self.get_result(query, nsfw=isnsfw)
pages = []
groups = [response[n : n + 3] for n in range(0, len(response), 3)]
for num, group in enumerate(groups, 1):
emb = discord.Embed(
title="Google Search: {}".format(
query[:44] + "\N{HORIZONTAL ELLIPSIS}" if len(query) > 45 else query
),
color=await ctx.embed_color(),
)
for result in group:
desc = (
f"[{result.url[:60]}]({result.url})\n" if result.url else ""
) + f"{result.desc}"[:1024]
emb.add_field(
name=f"{result.title}",
value=desc or "Nothing",
inline=False,
)
emb.description = f"Page {num} of {len(groups)}"
emb.set_footer(
text=f"Safe Search: {not isnsfw} | " + kwargs["stats"].replace("\n", " ")
)
if "thumbnail" in kwargs:
emb.set_thumbnail(url=kwargs["thumbnail"])
if "image" in kwargs and num == 1:
emb.set_image(url=kwargs["image"])
pages.append(emb)
if pages:
await ResultMenu(source=Source(pages, per_page=1)).start(ctx)
else:
await ctx.send("No result")
@google.command()
async def autofill(self, ctx, *, query: str):
"""Responds with a list of the Google Autofill results for a particular query."""
# This “API” is a bit of a hack; it was only meant for use by
# Google’s own products. and hence it is undocumented.
# Attribution: https://shreyaschand.com/blog/2013/01/03/google-autocomplete-api/
base_url = "https://suggestqueries.google.com/complete/search"
params = {"client": "firefox", "hl": "en", "q": query}
async with ctx.typing():
try:
async with aiohttp.ClientSession() as session:
async with session.get(base_url, params=params) as response:
if response.status != 200:
return await ctx.send(f"https://http.cat/{response.status}")
data = json.loads(await response.read())
except asyncio.TimeoutError:
return await ctx.send("Operation timed out.")
if not data[1]:
return await ctx.send("Could not find any results.")
await ctx.send("\n".join(data[1]))
@google.command(aliases=["books"])
async def book(self, ctx, *, query: str):
"""Search for a book or magazine on Google Books.
This command requires an API key.
To get an API key, you'll first require to enable the API at:
https://console.cloud.google.com/flows/enableapi?apiid=books.googleapis.com
Once you have enabled the API, you can find out how to acquire the API key at:
https://developers.google.com/books/docs/v1/using#APIKey
Once you get API key, set it in your redbot instance using:
```
[p]set api googlebooks api_key <your_api_key>
```
There are special keywords you can specify in the search terms to search in particular fields.
You can read more on that in detail over at:
https://developers.google.com/books/docs/v1/using#PerformingSearch
"""
api_key = (await ctx.bot.get_shared_api_tokens("googlebooks")).get("api_key")
if not api_key:
return await ctx.send_help()
async with ctx.typing():
base_url = "https://www.googleapis.com/books/v1/volumes"
params = {
"apiKey": api_key,
"q": query,
"printType": "all",
"maxResults": 40,
"orderBy": "relevance",
}
try:
async with aiohttp.ClientSession() as session:
async with session.get(base_url, params=params) as response:
if response.status != 200:
return await ctx.send(f"https://http.cat/{response.status}")
data = await response.json()
except aiohttp.TimeoutError:
return await ctx.send("Operation timed out.")
if len(data.get("items")) == 0:
return await ctx.send("No results.")
pages = []
for i, info in enumerate(data.get("items")):
embed = discord.Embed(colour=await ctx.embed_color())
embed.title = info.get("volumeInfo").get("title")
embed.url = info.get("volumeInfo").get("canonicalVolumeLink")
embed.description = info.get("volumeInfo").get("description", "No summary.")[:2000]
embed.set_author(
name="Google Books",
url="https://books.google.com/",
icon_url="https://i.imgur.com/N3oHABo.png",
)
if info.get("volumeInfo").get("imageLinks"):
embed.set_thumbnail(
url=info.get("volumeInfo").get("imageLinks").get("thumbnail")
)
embed.add_field(
name="Published Date",
value=info.get("volumeInfo").get("publishedDate", "Unknown"),
)
if info.get("volumeInfo").get("authors"):
embed.add_field(
name="Authors",
value=", ".join(info.get("volumeInfo").get("authors")),
)
embed.add_field(
name="Publisher",
value=info.get("volumeInfo").get("publisher", "Unknown"),
)
if info.get("volumeInfo").get("pageCount"):
embed.add_field(
name="Page Count",
value=humanize_number(info.get("volumeInfo").get("pageCount")),
)
embed.add_field(
name="Web Reader Link",
value=f"[Click here!]({info.get('accessInfo').get('webReaderLink')})",
)
if info.get("volumeInfo").get("categories"):
embed.add_field(
name="Category",
value=", ".join(info.get("volumeInfo").get("categories")),
)
if info.get("saleInfo").get("retailPrice"):
currency_format = (
f"[{info.get('saleInfo').get('retailPrice').get('amount')} "
f"{info.get('saleInfo').get('retailPrice').get('currencyCode')}]"
f"({info.get('saleInfo').get('buyLink')} 'Click to buy on Google Books!')"
)
embed.add_field(
name="Retail Price",
value=currency_format,
)
epub_available = (
"✅" if info.get("accessInfo").get("epub").get("isAvailable") else "❌"
)
pdf_available = (
"✅" if info.get("accessInfo").get("pdf").get("isAvailable") else "❌"
)
if info.get("accessInfo").get("epub").get("downloadLink"):
epub_available += (
" [`Download Link`]"
f"({info.get('accessInfo').get('epub').get('downloadLink')})"
)
if info.get("accessInfo").get("pdf").get("downloadLink"):
pdf_available += (
" [`Download Link`]"
f"({info.get('accessInfo').get('pdf').get('downloadLink')})"
)
embed.add_field(name="EPUB available?", value=epub_available)
embed.add_field(name="PDF available?", value=pdf_available)
viewablility = (
f"{info.get('accessInfo').get('viewability').replace('_', ' ').title()}"
)
embed.add_field(name="Viewablility", value=viewablility)
embed.set_footer(text=f"Page {i + 1} of {len(data.get('items'))}")
pages.append(embed)
if len(pages) == 1:
await ctx.send(embed=pages[0])
else:
await ResultMenu(source=Source(pages, per_page=1)).start(ctx)
@google.command()
async def doodle(self, ctx, month: int = None, year: int = None):
"""Responds with Google doodles of the current month.
Or doodles of specific month/year if `month` and `year` values are provided.
"""
month = datetime.datetime.now(datetime.timezone.utc).month if not month else month
year = datetime.datetime.now(datetime.timezone.utc).year if not year else year
async with ctx.typing():
base_url = f"https://www.google.com/doodles/json/{year}/{month}"
try:
async with aiohttp.ClientSession() as session:
async with session.get(base_url) as response:
if response.status != 200:
return await ctx.send(f"https://http.cat/{response.status}")
output = await response.json()
except asyncio.TimeoutError:
return await ctx.send("Operation timed out.")
if not output:
return await ctx.send("Could not find any results.")
pages = []
for data in output:
em = discord.Embed(colour=await ctx.embed_color())
em.title = data.get("title", "Doodle title missing")
img_url = data.get("high_res_url")
if img_url and not img_url.startswith("https:"):
img_url = "https:" + data.get("high_res_url")
if not img_url:
img_url = "https:" + data.get("url")
em.set_image(url=img_url)
date = "-".join([str(x) for x in data.get("run_date_array")[::-1]])
em.set_footer(text=f"{data.get('share_text')}\nDoodle published on: {date}")
pages.append(em)
if len(pages) == 1:
return await ctx.send(embed=pages[0])
else:
await ResultMenu(source=Source(pages, per_page=1)).start(ctx)
@google.command(aliases=["img"])
async def image(self, ctx, *, query: str = None):
"""Search google images from discord"""
if not query:
await ctx.send("Please enter some image name to search")
else:
isnsfw = nsfwcheck(ctx)
async with ctx.typing():
response = await self.get_result(query, images=True, nsfw=isnsfw)
size = len(tuple(response))
pages = [
discord.Embed(
title=f"Pages: {i}/{size}",
color=await ctx.embed_color(),
description="Some images might not be visible.",
)
.set_image(url=j)
.set_footer(text=f"Safe Search: {not isnsfw}")
for i, j in enumerate(response, 1)
]
if pages:
await ResultMenu(source=Source(pages, per_page=1)).start(ctx)
else:
await ctx.send("No result")
@google.command(aliases=["rev"])
async def reverse(self, ctx, *, url: str = None):
"""Attach or paste the url of an image to reverse search, or reply to a message which has the image/embed with the image"""
isnsfw = nsfwcheck(ctx)
query = None
def reply(ctx):
# Helper reply grabber
if hasattr(ctx.message, "reference") and ctx.message.reference != None:
msg = ctx.message.reference.resolved
if isinstance(msg, discord.Message):
return msg
def get_url(msg_obj, check=False):
# Helper get potential url, if check is True then returns none if nothing is found in embeds
if msg_obj.embeds:
emb = msg_obj.embeds[0].to_dict()
if "image" in emb:
return emb["image"]["url"]
elif "thumbnail" in emb:
return emb["thumbnail"]["url"]
if msg_obj.attachments:
return msg_obj.attachments[0].url
else:
return None if check else msg_obj.content.lstrip("<").rstrip(">")
def check_url(url: str):
# Helper function to check if valid url or not
return url.startswith("http") and " " not in url
if resp := reply(ctx):
query = get_url(resp)
# TODO More work on this to shorten code.
if not query or not check_url(query):
if query := get_url(ctx.message, check=True):
pass
elif url is None:
return await ctx.send_help()
else:
query = url.lstrip("<").rstrip(">")
# Big brain url parsing
if not check_url(query):
return await ctx.send_help()
if not query or not query.startswith("http") or " " in query:
return await ctx.send_help()
encoded = {
"image_url": query,
"encoded_image": None,
"image_content": None,
"filename": None,
"hl": "en",
}
async with ctx.typing():
async with aiohttp.ClientSession() as session:
async with session.get(
"https://www.google.com/searchbyimage?" + urllib.parse.urlencode(encoded),
headers=self.options,
cookies=self.cookies,
) as resp:
text = await resp.read()
redir_url = resp.url
prep = functools.partial(self.reverse_search, text)
result, (response, kwargs) = await self.bot.loop.run_in_executor(None, prep)
pages = []
if response:
groups = [response[n : n + 3] for n in range(0, len(response), 3)]
for num, group in enumerate(groups, 1):
emb = discord.Embed(
title="Google Reverse Image Search",
description="[`"
+ (result or "Nothing significant found")
+ f"`]({redir_url})",
color=await ctx.embed_color(),
)
for i in group:
desc = (f"[{i.url[:60]}]({i.url})\n" if i.url else "") + f"{i.desc}"[:1024]
emb.add_field(
name=f"{i.title}",
value=desc or "Nothing",
inline=False,
)
emb.set_footer(
text=f"Safe Search: {not isnsfw} | "
+ kwargs["stats"].replace("\n", " ")
+ f"| Page: {num}/{len(groups)}"
)
emb.set_thumbnail(url=encoded["image_url"])
pages.append(emb)
if pages:
await ResultMenu(source=Source(pages, per_page=1)).start(ctx)
else:
await ctx.send(
embed=discord.Embed(
title="Google Reverse Image Search",
description="[`" + ("Nothing significant found") + f"`]({redir_url})",
color=await ctx.embed_color(),
).set_thumbnail(url=encoded["image_url"])
)
@commands.is_owner()
@google.command(hidden=True)
async def debug(self, ctx, *, url):
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.options, cookies=self.cookies) as resp:
text = await resp.text()
f = BytesIO(bytes(text, "utf-8"))
await ctx.send(file=discord.File(f, filename="filename.html"))
f.close()
async def get_result(self, query, images=False, nsfw=False):
"""Fetch the data"""
# TODO make this fetching a little better
encoded = urllib.parse.quote_plus(query, encoding="utf-8", errors="replace")
async def get_html(url, encoded):
async with aiohttp.ClientSession() as session:
async with session.get(
url + encoded, headers=self.options, cookies=self.cookies
) as resp:
self.cookies = resp.cookies
return await resp.text()
if not nsfw:
encoded += "&safe=active"
if not images:
url = "https://www.google.com/search?q="
text = await get_html(url, encoded)
prep = functools.partial(self.parser_text, text)
else:
# TYSM fixator, for the non-js query url
url = "https://www.google.com/search?tbm=isch&q="
text = await get_html(url, encoded)
prep = functools.partial(self.parser_image, text)
return await self.bot.loop.run_in_executor(None, prep)
def reverse_search(self, text):
soup = BeautifulSoup(text, features="html.parser")
if check := soup.find("div", class_="card-section"):
if "The URL doesn't refer" in check.text:
return check.text, (None, None)
if res := soup.find("input", class_="gLFyf gsfi"):
return res["value"], (self.parser_text(text, soup=soup, cards=False) or (None, None))
def parser_text(self, text, soup=None, cards: bool = True):
"""My bad logic for scraping"""
if not soup:
soup = BeautifulSoup(text, features="html.parser")
s = namedtuple("searchres", "url title desc")
final = []
kwargs = {"stats": h2t(str(soup.find("div", id="result-stats")))}
def get_card():
"""Getting cards if present, here started the pain"""
# common card
if card := soup.find("div", class_="g mnr-c g-blk"):
if desc := card.find("span", class_="hgKElc"):
final.append(s(None, "Google Info Card:", h2t(str(desc))))
return
# another webpull card: what is the language JetBrains made? TODO fix this, depends on too many classes as of now
if card := soup.find("div", class_="kp-blk c2xzTb"):
if head := card.find("div", class_="Z0LcW XcVN5d AZCkJd"):
if desc := card.find("div", class_="iKJnec"):
final.append(s(None, f"Answer: {head.text}", h2t(str(desc))))
return
# calculator card
if card := soup.find("div", class_="tyYmIf"):
if question := card.find("span", class_="vUGUtc"):
if answer := card.find("span", class_="qv3Wpe"):
tmp = h2t(str(question)).strip("\n")
final.append(
s(None, "Google Calculator:", f"**{tmp}** {h2t(str(answer))}")
)
return
# sidepage card
if card := soup.find("div", class_="liYKde g VjDLd"):
if thumbnail := card.find("g-img", attrs={"data-lpage": True}):
kwargs["thumbnail"] = thumbnail["data-lpage"]
if title := soup.find("div", class_="SPZz6b"):
if desc := card.find("div", class_="kno-rdesc"):
if remove := desc.find(class_="Uo8X3b"):
remove.decompose()
desc = (
textwrap.shorten(
h2t(str(desc)), 1024, placeholder="\N{HORIZONTAL ELLIPSIS}"
)
+ "\n"
)
if more_info := card.findAll("div", class_="Z1hOCe"):
for thing in more_info:
tmp = thing.findAll("span")
if len(tmp) == 2:
desc2 = f"\n **{tmp[0].text}**`{tmp[1].text.lstrip(':')}`"
# More jack advises :D
MAX = 1024
MAX_LEN = MAX - len(desc2)
if len(desc) > MAX_LEN:
desc = (
next(
pagify(
desc,
delims=[" ", "\n"],
page_length=MAX_LEN - 1,
shorten_by=0,
)
)
+ "\N{HORIZONTAL ELLIPSIS}"
)
desc = desc + desc2
final.append(
s(
None,
"Google Featured Card: "
+ h2t(str(title)).replace("\n", " ").replace("#", ""),
desc,
)
)
return
# time cards and unit conversions and moar-_- WORK ON THIS, THIS IS BAD STUFF 100
if card := soup.find("div", class_="vk_c"):
if conversion := card.findAll("div", class_="rpnBye"):
if len(conversion) != 2:
return
tmp = tuple(
map(
lambda thing: (
thing.input["value"],
thing.findAll("option", selected=True)[0].text,
),
conversion,
)
)
final.append(
s(
None,
"Unit Conversion v1:",
"`" + " ".join(tmp[0]) + " is equal to " + " ".join(tmp[1]) + "`",
)
)
return
elif card.find("div", "lu_map_section"):
if img := re.search(r"\((.*)\)", h2t(str(card)).replace("\n", "")):
kwargs["image"] = "https://www.google.com" + img[1]
return
else:
# time card
if tail := card.find("table", class_="d8WIHd"):
tail.decompose()
tmp = h2t(str(card)).replace("\n\n", "\n").split("\n")
final.append(s(None, tmp[0], "\n".join(tmp[1:])))
return
# translator cards
if card := soup.find("div", class_="tw-src-ltr"):
langs = soup.find("div", class_="pcCUmf")
src_lang = "**" + langs.find("span", class_="source-language").text + "**"
dest_lang = "**" + langs.find("span", class_="target-language").text + "**"
final_text = ""
if source := card.find("div", id="KnM9nf"):
final_text += (src_lang + "\n`" + source.find("pre").text) + "`\n"
if dest := card.find("div", id="kAz1tf"):
final_text += dest_lang + "\n`" + dest.find("pre").text.strip("\n") + "`"
final.append(s(None, "Google Translator", final_text))
return
# Unit conversions
if card := soup.find("div", class_="nRbRnb"):
final_text = "\N{ZWSP}\n**"
if source := card.find("div", class_="vk_sh c8Zgcf"):
final_text += "`" + h2t(str(source)).strip("\n")
if dest := card.find("div", class_="dDoNo ikb4Bb vk_bk gsrt gzfeS"):
final_text += " " + h2t(str(dest)).strip("\n") + "`**"
if time := card.find("div", class_="hqAUc"):
if remove := time.find("select"):
remove.decompose()
tmp = h2t(str(time)).replace("\n", " ").split("·")
final_text += (
"\n"
+ (f"`{tmp[0].strip()}` ·{tmp[1]}" if len(tmp) == 2 else "·".join(tmp))
+ "\n\N{ZWSP}"
)
final.append(s(None, "Unit Conversion", final_text))
return
# Definition cards
if card := soup.find("div", class_="KIy09e"):
final_text = ""
if word := card.find("div", class_="DgZBFd XcVN5d frCXef"):
if sup := word.find("sup"):
sup.decompose()
final_text += "`" + word.text + "`"
if pronounciate := card.find("div", class_="S23sjd g30o5d"):
final_text += " | " + pronounciate.text
if type_ := card.find("div", class_="pgRvse vdBwhd ePtbIe"):
final_text += " | " + type_.text + "\n\n"
if definition := card.find("div", class_="L1jWkf h3TRxf"):
for text in definition.findAll("div")[:2]:
tmp = h2t(str(text))
if tmp.count("\n") < 5:
final_text += "`" + tmp.strip("\n").replace("\n", " ") + "`" + "\n"
final.append(s(None, "Definition", final_text))
return
# single answer card
if card := soup.find("div", class_="ayRjaf"):
final.append(
s(
None,
h2t(str(card.find("div", class_="zCubwf"))).replace("\n", ""),
h2t(str(card.find("span").find("span"))).strip("\n") + "\n\N{ZWSP}",
)
)
return
# another single card?
if card := soup.find("div", class_="sXLaOe"):
final.append(s(None, "Single Answer Card:", card.text))
return
if cards:
get_card()
for res in soup.findAll("div", class_="g"):
if name := res.find("div", class_="yuRUbf"):
url = name.a["href"]
if title := name.find("h3", "LC20lb DKV0Md"):
title = title.text
else:
title = url
else:
url = None
title = None
if desc := res.find("div", class_="IsZvec"):
if remove := desc.find("span", class_="f"):
remove.decompose()
desc = h2t(str(desc.find("span", class_="aCOpRe")))
else:
desc = "Not found"
if title:
final.append(s(url, title, desc.replace("\n", " ")))
return final, kwargs
def parser_image(self, html):
# first 2 are google static logo images
return self.link_regex.findall(html)[2:]
# Dpy menus
class Source(menus.ListPageSource):
async def format_page(self, menu, embeds):
return embeds
# Thanks fixator https://github.com/fixator10/Fixator10-Cogs/blob/V3.leveler_abc/leveler/menus/top.py
class ResultMenu(menus.MenuPages, inherit_buttons=False):
def __init__(self, **kwargs):
super().__init__(
**kwargs,
timeout=60,
clear_reactions_after=True,
delete_message_after=True,
)
def _skip_double_triangle_buttons(self):
return super()._skip_double_triangle_buttons()
async def finalize(self, timed_out):
"""|coro|
A coroutine that is called when the menu loop has completed
its run. This is useful if some asynchronous clean-up is
required after the fact.
Parameters
--------------
timed_out: :class:`bool`
Whether the menu completed due to timing out.
"""
if timed_out and self.delete_message_after:
self.delete_message_after = False
@menus.button(
"\N{BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}\ufe0f",
position=menus.First(0),
skip_if=_skip_double_triangle_buttons,
)
async def go_to_first_page(self, payload):
"""go to the first page"""
await self.show_page(0)
@menus.button("\N{BLACK LEFT-POINTING TRIANGLE}\ufe0f", position=menus.First(1))
async def go_to_previous_page(self, payload):
"""go to the previous page"""
if self.current_page == 0:
await self.show_page(self._source.get_max_pages() - 1)
else:
await self.show_checked_page(self.current_page - 1)
@menus.button("\N{BLACK RIGHT-POINTING TRIANGLE}\ufe0f", position=menus.Last(0))
async def go_to_next_page(self, payload):
"""go to the next page"""
if self.current_page == self._source.get_max_pages() - 1:
await self.show_page(0)
else:
await self.show_checked_page(self.current_page + 1)
@menus.button(
"\N{BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}\ufe0f",
position=menus.Last(1),
skip_if=_skip_double_triangle_buttons,
)
async def go_to_last_page(self, payload):
"""go to the last page"""
# The call here is safe because it's guarded by skip_if
await self.show_page(self._source.get_max_pages() - 1)
@menus.button("\N{CROSS MARK}", position=menus.First(2))
async def stop_pages(self, payload) -> None:
self.stop()
|
import constants
from models.worker_spec import (
args_list_from_spec_params
)
def update_all_deployments(api, apps_api_instance, spec, status, namespace):
worker_deployment = update_worker_deployment(
apps_api_instance, spec, status, namespace
)
flower_deployment = update_flower_deployment(
apps_api_instance, spec, status, namespace
)
flower_svc = update_flower_service(
api, spec, status, namespace
)
children = [
{
'name': worker_deployment.metadata.name,
'replicas': worker_deployment.spec.replicas,
'kind': constants.DEPLOYMENT_KIND,
'type': constants.WORKER_TYPE
},
{
'name': flower_deployment.metadata.name,
'replicas': flower_deployment.spec.replicas,
'kind': constants.DEPLOYMENT_KIND,
'type': constants.FLOWER_TYPE
},
{
'name': flower_svc.metadata.name,
'spec': flower_svc.spec.to_dict(),
'kind': constants.SERVICE_KIND,
'type': constants.FLOWER_TYPE
}
]
return {
'children': children,
'children_count': len(children),
'status': constants.STATUS_UPDATED
}
def get_curr_deployment_from_handler_status(handler_name, status, child_type):
"""
Get current deployment name from handler's status
@param: handler_name - which handler to get from
@param: child_type - worker or flower
@returns: current deployment name
"""
for child in status.get(handler_name).get('children'):
if child.get('type') == child_type and child.get('kind') == constants.DEPLOYMENT_KIND: # NOQA
return child.get('name')
return None
def get_curr_deployment_name(status, child_type):
"""
Get current deployment name from parent's status
@param: child_type - worker or flower
@returns: current deployment name
"""
if status.get('update_fn'):
return get_curr_deployment_from_handler_status('update_fn', status, child_type)
return get_curr_deployment_from_handler_status('create_fn', status, child_type)
def update_worker_deployment(apps_api_instance, spec, status, namespace):
worker_spec = spec['workerSpec']
worker_spec_dict = {
'args': args_list_from_spec_params(
celery_app=spec['common']['celeryApp'],
queues=worker_spec['queues'],
loglevel=worker_spec['logLevel'],
concurrency=worker_spec['concurrency']
),
'command': ["celery"],
'image': spec['common']['image'],
'name': f"{spec["common"]["appName"]}-celery-worker",
'resources': worker_spec['resources']
}
# JSON way of submitting spec to deploy/patch
patch_body = {
"spec": {
"replicas": worker_spec['numOfWorkers'],
"template": {
"spec": {
"containers": [
worker_spec_dict
]
}
}
}
}
worker_deployment_name = get_curr_deployment_name(
status, constants.WORKER_TYPE
)
return apps_api_instance.patch_namespaced_deployment(
worker_deployment_name, namespace, patch_body
)
def update_flower_deployment(apps_api_instance, spec, status, namespace):
flower_spec = spec['flowerSpec']
flower_spec_dict = {
'args': [spec['common']['celeryApp']],
'command': ['flower'],
'image': spec['common']['image'],
'name': f"{spec["common"]["appName"]}-flower",
'ports': [
{"containerPort": 5555}
],
'resources': flower_spec['resources']
}
# JSON way of submitting spec to deploy/patch
patch_body = {
"spec": {
"replicas": flower_spec['replicas'],
"template": {
"spec": {
"containers": [
flower_spec_dict
]
}
}
}
}
flower_deployment_name = get_curr_deployment_name(
status, constants.FLOWER_TYPE
)
return apps_api_instance.patch_namespaced_deployment(
flower_deployment_name, namespace, patch_body
)
def update_flower_service(api, spec, status, namespace):
# Only app_name change will affect flower service
patch_body = {
"spec": {
"selector": {
"run": f"{spec["common"]["appName"]}-flower"
}
}
}
flower_svc_name = get_curr_deployment_name(
status, constants.FLOWER_TYPE
) # flower svc is named same as flower deployment
return api.patch_namespaced_service(
flower_svc_name, namespace, patch_body
)
| import constants
from models.worker_spec import (
args_list_from_spec_params
)
def update_all_deployments(api, apps_api_instance, spec, status, namespace):
worker_deployment = update_worker_deployment(
apps_api_instance, spec, status, namespace
)
flower_deployment = update_flower_deployment(
apps_api_instance, spec, status, namespace
)
flower_svc = update_flower_service(
api, spec, status, namespace
)
children = [
{
'name': worker_deployment.metadata.name,
'replicas': worker_deployment.spec.replicas,
'kind': constants.DEPLOYMENT_KIND,
'type': constants.WORKER_TYPE
},
{
'name': flower_deployment.metadata.name,
'replicas': flower_deployment.spec.replicas,
'kind': constants.DEPLOYMENT_KIND,
'type': constants.FLOWER_TYPE
},
{
'name': flower_svc.metadata.name,
'spec': flower_svc.spec.to_dict(),
'kind': constants.SERVICE_KIND,
'type': constants.FLOWER_TYPE
}
]
return {
'children': children,
'children_count': len(children),
'status': constants.STATUS_UPDATED
}
def get_curr_deployment_from_handler_status(handler_name, status, child_type):
"""
Get current deployment name from handler's status
@param: handler_name - which handler to get from
@param: child_type - worker or flower
@returns: current deployment name
"""
for child in status.get(handler_name).get('children'):
if child.get('type') == child_type and child.get('kind') == constants.DEPLOYMENT_KIND: # NOQA
return child.get('name')
return None
def get_curr_deployment_name(status, child_type):
"""
Get current deployment name from parent's status
@param: child_type - worker or flower
@returns: current deployment name
"""
if status.get('update_fn'):
return get_curr_deployment_from_handler_status('update_fn', status, child_type)
return get_curr_deployment_from_handler_status('create_fn', status, child_type)
def update_worker_deployment(apps_api_instance, spec, status, namespace):
worker_spec = spec['workerSpec']
worker_spec_dict = {
'args': args_list_from_spec_params(
celery_app=spec['common']['celeryApp'],
queues=worker_spec['queues'],
loglevel=worker_spec['logLevel'],
concurrency=worker_spec['concurrency']
),
'command': ["celery"],
'image': spec['common']['image'],
'name': f"{spec['common']['appName']}-celery-worker",
'resources': worker_spec['resources']
}
# JSON way of submitting spec to deploy/patch
patch_body = {
"spec": {
"replicas": worker_spec['numOfWorkers'],
"template": {
"spec": {
"containers": [
worker_spec_dict
]
}
}
}
}
worker_deployment_name = get_curr_deployment_name(
status, constants.WORKER_TYPE
)
return apps_api_instance.patch_namespaced_deployment(
worker_deployment_name, namespace, patch_body
)
def update_flower_deployment(apps_api_instance, spec, status, namespace):
flower_spec = spec['flowerSpec']
flower_spec_dict = {
'args': [spec['common']['celeryApp']],
'command': ['flower'],
'image': spec['common']['image'],
'name': f"{spec['common']['appName']}-flower",
'ports': [
{"containerPort": 5555}
],
'resources': flower_spec['resources']
}
# JSON way of submitting spec to deploy/patch
patch_body = {
"spec": {
"replicas": flower_spec['replicas'],
"template": {
"spec": {
"containers": [
flower_spec_dict
]
}
}
}
}
flower_deployment_name = get_curr_deployment_name(
status, constants.FLOWER_TYPE
)
return apps_api_instance.patch_namespaced_deployment(
flower_deployment_name, namespace, patch_body
)
def update_flower_service(api, spec, status, namespace):
# Only app_name change will affect flower service
patch_body = {
"spec": {
"selector": {
"run": f"{spec['common']['appName']}-flower"
}
}
}
flower_svc_name = get_curr_deployment_name(
status, constants.FLOWER_TYPE
) # flower svc is named same as flower deployment
return api.patch_namespaced_service(
flower_svc_name, namespace, patch_body
)
|
from flask import render_template, url_for, flash, redirect, request
from website import app, db, login_manager
from website.forms import LinkForm, EditForm, LoginForm
from website.models import Link, User
import json
import re
from flask_login import LoginManager, login_user, current_user, logout_user, login_required
from better_profanity import profanity
@login_manager.user_loader
def user_loader(username):
user = User()
user.id = username
return user
@app.route('/home', methods=['GET'])
@app.route('/', methods=['GET'])
def home():
return render_template('home.html')
@app.route('/about', methods=['GET'])
def about():
with open('config.json') as f:
data = json.load(f)
return render_template('about.html', domain=data['domain'])
@app.route('/rickrolled', methods=['GET'])
def rickrolled():
return render_template('rickrolled.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = LoginForm()
with open('config.json') as f:
data = json.load(f)
if form.validate_on_submit():
if form.password.data == data['password']:
user = User()
user.id = "Rick"
login_user(user, remember=True)
flash('Successfully logged in!', 'success')
return redirect(url_for('home'))
else:
flash('Incorrect password!', 'danger')
return render_template('login.html', form=form, data=data)
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('home'))
@app.route('/admin', methods=['GET'])
@login_required
def admin():
links = Link.query.all()
links.reverse()
totClicks = sum([link.clicks for link in links])
with open('config.json') as f:
data = json.load(f)
return render_template('admin.html', links=links, domain=data['domain'], totClicks=totClicks)
@app.route('/new', methods=['GET', 'POST'])
def new():
form = LinkForm()
if form.validate_on_submit():
link = Link(link=form.link.data, title=form.title.data, name = form.name.data, desc=form.desc.data, image=form.image.data, url='https://www.youtube.com/watch?v=dQw4w9WgXcQ')
with open('bad-words.txt', 'r') as f:
wordlist = [i.strip() for i in f.readlines()]
profanity.load_censor_words()
profanity.add_censor_words(wordlist)
if profanity.contains_profanity(f'{link.link} {link.title} {link.name} {link.desc}'):
flash('NOTE: EXCESSIVE PROFANITY IS NOT PERMITTED ON THIS PLATFORM. CONTINUED EXCESSIVE PROFANITY MAY RESULT IN AN IP BAN FROM THIS PLATFORM', 'danger')
link.link = profanity.censor(link.link, 'X')
link.title = profanity.censor(link.title, 'X')
link.name = profanity.censor(link.name, 'X')
link.desc = profanity.censor(link.desc, 'X')
link.link = link.link.replace(' ','-')
link.link = re.sub(r'[^a-zA-Z0-9-]', '-', link.link)
# ensure uniqueness of link
existinglink = Link.query.filter_by(link=link.link).first()
while existinglink:
link.link = link.link + 'X'
existinglink = Link.query.filter_by(link=link.link).first()
db.session.add(link)
db.session.commit()
# getting config details
with open('config.json') as f:
data = json.load(f)
flash(f"Created link {data["domain"]}/l/{link.link}", 'success')
return redirect(url_for('home'))
return render_template('new.html', form=form, legend='New Link')
@app.route('/l/<link_url>/edit', methods=['GET', 'POST'])
@login_required
def edit(link_url):
link = Link.query.filter_by(link=link_url).first()
form = EditForm()
if form.validate_on_submit():
link.link = form.link.data
link.link = link.link.replace(' ','-')
link.link = re.sub(r'[^a-zA-Z0-9-]', '-', link.link)
link.url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
link.title = form.title.data
link.name = form.name.data
link.desc = form.desc.data
link.image = form.image.data
db.session.commit()
flash('Successfully updated link!', 'success')
return redirect(url_for('home'))
elif request.method == 'GET':
form.link.data = link.link
form.title.data = link.title
form.name.data = link.name
form.desc.data = link.desc
form.image.data = link.image
return render_template('new.html', form=form, legend='Update Link')
@app.route('/l/<link_url>', methods=['GET'])
def redir(link_url):
link = Link.query.filter_by(link=link_url).first()
if not link:
return '<h1>Either you manually typed an incorrect link or the link you clicked was removed for exsessive profanity.</h1>'
link.clicks +=1
db.session.commit()
return render_template('redir.html', title=link.title, name=link.name, desc=link.desc, image=link.image, url=link.url)
@app.route('/l/<link_url>/delete', methods=['GET','POST'])
@login_required
def delete(link_url):
link = Link.query.filter_by(link=link_url).first()
db.session.delete(link)
db.session.commit()
flash('Successfully deleted link!', 'success')
return redirect(url_for('home')) | from flask import render_template, url_for, flash, redirect, request
from website import app, db, login_manager
from website.forms import LinkForm, EditForm, LoginForm
from website.models import Link, User
import json
import re
from flask_login import LoginManager, login_user, current_user, logout_user, login_required
from better_profanity import profanity
@login_manager.user_loader
def user_loader(username):
user = User()
user.id = username
return user
@app.route('/home', methods=['GET'])
@app.route('/', methods=['GET'])
def home():
return render_template('home.html')
@app.route('/about', methods=['GET'])
def about():
with open('config.json') as f:
data = json.load(f)
return render_template('about.html', domain=data['domain'])
@app.route('/rickrolled', methods=['GET'])
def rickrolled():
return render_template('rickrolled.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = LoginForm()
with open('config.json') as f:
data = json.load(f)
if form.validate_on_submit():
if form.password.data == data['password']:
user = User()
user.id = "Rick"
login_user(user, remember=True)
flash('Successfully logged in!', 'success')
return redirect(url_for('home'))
else:
flash('Incorrect password!', 'danger')
return render_template('login.html', form=form, data=data)
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('home'))
@app.route('/admin', methods=['GET'])
@login_required
def admin():
links = Link.query.all()
links.reverse()
totClicks = sum([link.clicks for link in links])
with open('config.json') as f:
data = json.load(f)
return render_template('admin.html', links=links, domain=data['domain'], totClicks=totClicks)
@app.route('/new', methods=['GET', 'POST'])
def new():
form = LinkForm()
if form.validate_on_submit():
link = Link(link=form.link.data, title=form.title.data, name = form.name.data, desc=form.desc.data, image=form.image.data, url='https://www.youtube.com/watch?v=dQw4w9WgXcQ')
with open('bad-words.txt', 'r') as f:
wordlist = [i.strip() for i in f.readlines()]
profanity.load_censor_words()
profanity.add_censor_words(wordlist)
if profanity.contains_profanity(f'{link.link} {link.title} {link.name} {link.desc}'):
flash('NOTE: EXCESSIVE PROFANITY IS NOT PERMITTED ON THIS PLATFORM. CONTINUED EXCESSIVE PROFANITY MAY RESULT IN AN IP BAN FROM THIS PLATFORM', 'danger')
link.link = profanity.censor(link.link, 'X')
link.title = profanity.censor(link.title, 'X')
link.name = profanity.censor(link.name, 'X')
link.desc = profanity.censor(link.desc, 'X')
link.link = link.link.replace(' ','-')
link.link = re.sub(r'[^a-zA-Z0-9-]', '-', link.link)
# ensure uniqueness of link
existinglink = Link.query.filter_by(link=link.link).first()
while existinglink:
link.link = link.link + 'X'
existinglink = Link.query.filter_by(link=link.link).first()
db.session.add(link)
db.session.commit()
# getting config details
with open('config.json') as f:
data = json.load(f)
flash(f"Created link {data['domain']}/l/{link.link}", 'success')
return redirect(url_for('home'))
return render_template('new.html', form=form, legend='New Link')
@app.route('/l/<link_url>/edit', methods=['GET', 'POST'])
@login_required
def edit(link_url):
link = Link.query.filter_by(link=link_url).first()
form = EditForm()
if form.validate_on_submit():
link.link = form.link.data
link.link = link.link.replace(' ','-')
link.link = re.sub(r'[^a-zA-Z0-9-]', '-', link.link)
link.url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
link.title = form.title.data
link.name = form.name.data
link.desc = form.desc.data
link.image = form.image.data
db.session.commit()
flash('Successfully updated link!', 'success')
return redirect(url_for('home'))
elif request.method == 'GET':
form.link.data = link.link
form.title.data = link.title
form.name.data = link.name
form.desc.data = link.desc
form.image.data = link.image
return render_template('new.html', form=form, legend='Update Link')
@app.route('/l/<link_url>', methods=['GET'])
def redir(link_url):
link = Link.query.filter_by(link=link_url).first()
if not link:
return '<h1>Either you manually typed an incorrect link or the link you clicked was removed for exsessive profanity.</h1>'
link.clicks +=1
db.session.commit()
return render_template('redir.html', title=link.title, name=link.name, desc=link.desc, image=link.image, url=link.url)
@app.route('/l/<link_url>/delete', methods=['GET','POST'])
@login_required
def delete(link_url):
link = Link.query.filter_by(link=link_url).first()
db.session.delete(link)
db.session.commit()
flash('Successfully deleted link!', 'success')
return redirect(url_for('home')) |
import numpy as np
import os
import json
import collections
import cv2
import tensorflow as tf
from config import CONFIG
CONFIG = CONFIG()
#from prepare_img_features import model_config_dict
model_config_dict = {'mobilenet_v2': {'model': tf.keras.applications.MobileNetV2,
'features_shape': 1280,
'input_shape': (224, 224),
'attention_features_shape': 49},
'inception_v3': {'model': tf.keras.applications.InceptionV3,
'features_shape': 2048,
'input_shape': (299, 299),
'attention_features_shape': 64}
}
seed = 42
np.random.seed(seed)
def organise_data():
"""This function returns a flattened list of img, caption pairs. This is necessary since
there are multiple captions per image. The work has been taken and altered from Tensorflow
Image Captioning tutorial."""
with open(CONFIG.ANNOTATION_FILE, 'r') as f:
annotations = json.load(f)
# Group all captions together having the same image ID.
image_path_to_caption = collections.defaultdict(list)
for val in annotations['annotations']:
caption = f"<start> {val["caption"]} <end>"
image_path = os.path.join(CONFIG.IMAGES_DIR,f'COCO_train2014_' + '%012d.jpg' % (val['image_id']))
image_path_to_caption[image_path].append(caption)
image_paths = list(image_path_to_caption.keys())
np.random.shuffle(image_paths)
# Select the first e.g. 6000 image_paths from the shuffled set.
# Approximately each image id has 5 captions associated with it, so that will
# lead to 30,000 examples.
train_image_paths = image_paths[:CONFIG.NUMBER_OF_IMAGES]
print('The number of captions in this training set is: ', len(train_image_paths))
train_captions = []
img_name_vector = []
for image_path in train_image_paths:
caption_list = image_path_to_caption[image_path]
train_captions.extend(caption_list)
img_name_vector.extend([image_path] * len(caption_list))
assert len(train_captions) == len(img_name_vector)
#caption_filename_tuple = list(zip(train_captions, img_name_vector))
return train_captions, img_name_vector
def calc_max_length(tensor):
"""Find the maximum length of any caption in our dataset"""
return max(len(t) for t in tensor)
# Load the numpy files
def map_func(img_name, caption):
img_name_file_only = img_name.decode('utf-8').split('/')[-1]
cached_features_to_load = os.path.join(CONFIG.CACHE_DIR_ROOT, f'{CONFIG.CNN_BACKBONE}_features', img_name_file_only + '.npy')
img_tensor = np.load(cached_features_to_load)
return img_tensor, caption
def map_func_including_cnn(img_name, caption):
img_name_file_only = img_name.decode('utf-8').split('/')[-1]
path_to_file = os.path.join(CONFIG.IMAGES_DIR, img_name_file_only)
img_tensor, _ = load_image(path_to_file)
return img_tensor, caption
def load_image(image_path):
img = tf.io.read_file(image_path)
img = tf.image.decode_jpeg(img, channels=3)
img = tf.image.resize(img, model_config_dict[CONFIG.CNN_BACKBONE]['input_shape'])
img = tf.keras.applications.imagenet_utils.preprocess_input(img)
return img, image_path
| import numpy as np
import os
import json
import collections
import cv2
import tensorflow as tf
from config import CONFIG
CONFIG = CONFIG()
#from prepare_img_features import model_config_dict
model_config_dict = {'mobilenet_v2': {'model': tf.keras.applications.MobileNetV2,
'features_shape': 1280,
'input_shape': (224, 224),
'attention_features_shape': 49},
'inception_v3': {'model': tf.keras.applications.InceptionV3,
'features_shape': 2048,
'input_shape': (299, 299),
'attention_features_shape': 64}
}
seed = 42
np.random.seed(seed)
def organise_data():
"""This function returns a flattened list of img, caption pairs. This is necessary since
there are multiple captions per image. The work has been taken and altered from Tensorflow
Image Captioning tutorial."""
with open(CONFIG.ANNOTATION_FILE, 'r') as f:
annotations = json.load(f)
# Group all captions together having the same image ID.
image_path_to_caption = collections.defaultdict(list)
for val in annotations['annotations']:
caption = f"<start> {val['caption']} <end>"
image_path = os.path.join(CONFIG.IMAGES_DIR,f'COCO_train2014_' + '%012d.jpg' % (val['image_id']))
image_path_to_caption[image_path].append(caption)
image_paths = list(image_path_to_caption.keys())
np.random.shuffle(image_paths)
# Select the first e.g. 6000 image_paths from the shuffled set.
# Approximately each image id has 5 captions associated with it, so that will
# lead to 30,000 examples.
train_image_paths = image_paths[:CONFIG.NUMBER_OF_IMAGES]
print('The number of captions in this training set is: ', len(train_image_paths))
train_captions = []
img_name_vector = []
for image_path in train_image_paths:
caption_list = image_path_to_caption[image_path]
train_captions.extend(caption_list)
img_name_vector.extend([image_path] * len(caption_list))
assert len(train_captions) == len(img_name_vector)
#caption_filename_tuple = list(zip(train_captions, img_name_vector))
return train_captions, img_name_vector
def calc_max_length(tensor):
"""Find the maximum length of any caption in our dataset"""
return max(len(t) for t in tensor)
# Load the numpy files
def map_func(img_name, caption):
img_name_file_only = img_name.decode('utf-8').split('/')[-1]
cached_features_to_load = os.path.join(CONFIG.CACHE_DIR_ROOT, f'{CONFIG.CNN_BACKBONE}_features', img_name_file_only + '.npy')
img_tensor = np.load(cached_features_to_load)
return img_tensor, caption
def map_func_including_cnn(img_name, caption):
img_name_file_only = img_name.decode('utf-8').split('/')[-1]
path_to_file = os.path.join(CONFIG.IMAGES_DIR, img_name_file_only)
img_tensor, _ = load_image(path_to_file)
return img_tensor, caption
def load_image(image_path):
img = tf.io.read_file(image_path)
img = tf.image.decode_jpeg(img, channels=3)
img = tf.image.resize(img, model_config_dict[CONFIG.CNN_BACKBONE]['input_shape'])
img = tf.keras.applications.imagenet_utils.preprocess_input(img)
return img, image_path
|
import random, RouteFinder, Board,moveLogic,bestReply
from typing import Dict
def getMove(head: Dict[str, int], coOrd: Dict[str, int]):
if head["x"] == (coOrd["x"] + 1):
return "left"
if head["x"] == (coOrd["x"] - 1):
return "right"
if head["y"] == (coOrd["y"] + 1):
return "down"
if head["y"] == (coOrd["y"] - 1):
return "up"
return "error"
def choose_move(data: dict) -> str:
Board.resetGameBoard()
Board.resetFood()
height = data["board"]["height"]
width = data["board"]["width"]
snakes = data["board"]["snakes"]
food = data["board"]["food"]
my_head = data["you"]["head"]
for snake in snakes:
if snake["id"] == data["you"]["id"]:
mySnake = snake
Board.initialiseBoard(width, height)
Board.fillGameBoard(snakes, food, height)
food = RouteFinder.findClosestFood(food, my_head)[0]
possible_moves = ["up", "down", "left", "right"]
possible_moves = moveLogic.avoid_other_snakes(my_head, snakes, possible_moves)
possible_moves = moveLogic.avoid_walls(my_head, width, height, possible_moves)
possible_moves = moveLogic.checkForHeadCollision(mySnake,snakes,possible_moves,Board.getBoard())
index = 0
for s in snakes:
if s["id"] == data["you"]["id"]:
snakes.pop(index)
index += 1
snakes.insert(0,mySnake)
pinf = float('inf')
ninf = float('-inf')
boardCopy = Board.getBoard()[:]
move = random.choice(possible_moves)
if data['turn'] > 5:
if len (possible_moves) > 1:
result = (bestReply.BRS(ninf,pinf,2,"Max",boardCopy,snakes,"initial",mySnake))
if result[1] in possible_moves:
print(result)
move = result[1]
else:
print("Broken")
print(result)
print(possible_moves)
move = random.choice(possible_moves)
if data["you"]["health"] < 25:
path = RouteFinder.bfsForFood(food, my_head, possible_moves,boardCopy)
if path != []:
move = getMove(my_head, path[1])
if (not move in possible_moves):
move = random.choice(possible_moves)
print(
f"{data["game"]["id"]} MOVE {data["turn"]}: {move} picked from all valid options in {possible_moves}"
)
return move | import random, RouteFinder, Board,moveLogic,bestReply
from typing import Dict
def getMove(head: Dict[str, int], coOrd: Dict[str, int]):
if head["x"] == (coOrd["x"] + 1):
return "left"
if head["x"] == (coOrd["x"] - 1):
return "right"
if head["y"] == (coOrd["y"] + 1):
return "down"
if head["y"] == (coOrd["y"] - 1):
return "up"
return "error"
def choose_move(data: dict) -> str:
Board.resetGameBoard()
Board.resetFood()
height = data["board"]["height"]
width = data["board"]["width"]
snakes = data["board"]["snakes"]
food = data["board"]["food"]
my_head = data["you"]["head"]
for snake in snakes:
if snake["id"] == data["you"]["id"]:
mySnake = snake
Board.initialiseBoard(width, height)
Board.fillGameBoard(snakes, food, height)
food = RouteFinder.findClosestFood(food, my_head)[0]
possible_moves = ["up", "down", "left", "right"]
possible_moves = moveLogic.avoid_other_snakes(my_head, snakes, possible_moves)
possible_moves = moveLogic.avoid_walls(my_head, width, height, possible_moves)
possible_moves = moveLogic.checkForHeadCollision(mySnake,snakes,possible_moves,Board.getBoard())
index = 0
for s in snakes:
if s["id"] == data["you"]["id"]:
snakes.pop(index)
index += 1
snakes.insert(0,mySnake)
pinf = float('inf')
ninf = float('-inf')
boardCopy = Board.getBoard()[:]
move = random.choice(possible_moves)
if data['turn'] > 5:
if len (possible_moves) > 1:
result = (bestReply.BRS(ninf,pinf,2,"Max",boardCopy,snakes,"initial",mySnake))
if result[1] in possible_moves:
print(result)
move = result[1]
else:
print("Broken")
print(result)
print(possible_moves)
move = random.choice(possible_moves)
if data["you"]["health"] < 25:
path = RouteFinder.bfsForFood(food, my_head, possible_moves,boardCopy)
if path != []:
move = getMove(my_head, path[1])
if (not move in possible_moves):
move = random.choice(possible_moves)
print(
f"{data['game']['id']} MOVE {data['turn']}: {move} picked from all valid options in {possible_moves}"
)
return move |
from hikari import Member,Embed, GatewayGuild, GuildReactionAddEvent, GuildMessageCreateEvent
from lightbulb import Plugin, Context, SlashCommand, command, option, implements, guild_only
from core.cd import Cooldown
cd = Cooldown(1, 60)
plugin = Plugin("Niveaux")
plugin.add_checks(guild_only)
def get_progress_bar(level: int, xp: int, n: int, short: bool = False):
needed = 5 * ((level - 1) ** 2) + (50 * (level - 1)) + 100
progress = (
needed - int(5 / 6 * level * (2 * level ** 2 + 27 * level + 91) - xp)
if xp
else 0
)
p = int((progress / needed) * n) or 1
if short:
progress = f"{round(progress/1000, 1)}k" if int(progress / 1000) else progress
needed = f"{round(needed/1000, 1)}k" if int(needed / 1000) else needed
return f"{"🟩"*p}{"⬛" * (n-p)} {progress} / {needed}"
def get_page(guild: GatewayGuild, entries: dict):
field1, field2, field3 = "", "", ""
for user_id, entry in entries.items():
member = guild.get_member(user_id)
if not member:
continue
level, xp = entry["level"], entry["xp"]
bar = get_progress_bar(level + 1, xp, 5, True)
xp = f"{round(xp / 1000, 1)}k" if int(xp / 1000) else xp
field1 += f"**{entry["pos"]}.** {member.display_name}\n"
field2 += f"{level} ({xp})\n"
field3 += f"{bar}\n"
return ("Noms", field1), ("Niveau", field2), ("Progrès", field3)
@plugin.command()
@option("membre", "Le membre dont tu veux voir le rang", Member, default=None)
@command("rank", "Afficher le niveau d'un membre")
@implements(SlashCommand)
async def rank(ctx: Context):
guild = ctx.get_guild()
member = ctx.options.membre or ctx.member
data = await plugin.bot.db.fetch_leaderboard(guild.id)
data = {
entry["_id"]: entry["guilds"][0] | {"pos": i + 1}
for i, entry in enumerate(sorted(data, reverse=True, key=lambda e: e['guilds'][0]["xp"]))
}
embed = Embed(color=0x3498DB)
embed.set_author(name=f"Progression de {member.display_name}", icon=member.avatar_url)
xp, lvl = data[member.id]["xp"], data[member.id]["level"] + 1
bar = get_progress_bar(lvl, xp, 13)
embed.add_field(name=f"Niveau {lvl-1} • Rang {data[member.id]["pos"]}", value=bar)
await ctx.respond(embed=embed)
@plugin.command()
@command("levels", description="Afficher le classement du serveur")
@implements(SlashCommand)
async def levels(ctx: Context):
guild = ctx.get_guild()
embed = (
Embed(color=0x3498DB)
.set_author(name="Classement du serveur", icon=guild.icon_url)
.set_footer(text="Page 1")
)
data = await plugin.bot.db.fetch_leaderboard(guild.id)
data = list(sorted(data, reverse=True, key=lambda e: e['guilds'][0]['xp']))
data = {
entry["_id"]: entry["guilds"][0] | {"pos": i + 1}
for i, entry in enumerate(data[:10])
}
for field in get_page(guild, data):
embed.add_field(name=field[0], value=field[1], inline=True)
resp = await ctx.respond(embed=embed)
message = await resp.message()
for emoji in ["◀️", "▶️"]:
await message.add_reaction(emoji)
@plugin.listener(GuildReactionAddEvent)
async def on_reaction_add(event):
guild, member = plugin.bot.cache.get_guild(event.guild_id), event.member
if member.is_bot:
return
message = plugin.bot.cache.get_message(event.message_id)
if (
not message
or not message.embeds
or not message.embeds[0].author
or message.embeds[0].author.name != "Classement du serveur"
):
return
data = await plugin.bot.db.fetch_leaderboard(guild.id)
data = list(sorted(data, reverse=True, key=lambda e: e['guilds'][0]['xp']))
embed, total = message.embeds[0], len(data) // 10 + (len(data) % 10 > 0)
inc = -1 if event.emoji_name == "◀️" else 1
page = (int(embed.footer.text.split()[-1]) + inc) % total or total
a, b = (1, 10) if page == 1 else (page * 10 - 9, page * 10)
data = {
entry["_id"]: entry["guilds"][0] | {"pos": i + a}
for i, entry in enumerate(data[a-1:b])
}
for i, field in enumerate(get_page(guild, data)):
embed.edit_field(i, field[0], field[1])
embed.set_footer(text=f"Page {page}")
await message.edit(embed=embed)
await message.remove_reaction(event.emoji_name, user=member.id)
@plugin.listener(GuildMessageCreateEvent)
async def on_message(event):
guild, member = plugin.bot.cache.get_guild(event.guild_id), event.member
if not guild or not member or member.is_bot or member.id == 689154823941390507:
return
if not cd.update_cooldown(member, guild):
return
entry = await plugin.bot.db.fetch_member(guild.id, member.id)
if not entry:
return
xp, lvl = entry["guilds"][0]["xp"], entry["guilds"][0]["level"] + 1
next_lvl = 5 / 6 * lvl * (2 * lvl ** 2 + 27 * lvl + 91)
await plugin.bot.db.update_member_xp(guild.id, member.id, xp, next_lvl)
if next_lvl > xp:
return
settings = await plugin.bot.db.fetch_settings(guild.id)
if settings["channel"] is None:
return
channel = guild.get_channel(settings["channel"])
if channel:
embed = Embed(color=0xF1C40F, description=f"🆙 {event.message.author.mention} vient de monter niveau **{lvl}**.")
await channel.send(embed=embed)
def load(bot):
bot.add_plugin(plugin)
| from hikari import Member,Embed, GatewayGuild, GuildReactionAddEvent, GuildMessageCreateEvent
from lightbulb import Plugin, Context, SlashCommand, command, option, implements, guild_only
from core.cd import Cooldown
cd = Cooldown(1, 60)
plugin = Plugin("Niveaux")
plugin.add_checks(guild_only)
def get_progress_bar(level: int, xp: int, n: int, short: bool = False):
needed = 5 * ((level - 1) ** 2) + (50 * (level - 1)) + 100
progress = (
needed - int(5 / 6 * level * (2 * level ** 2 + 27 * level + 91) - xp)
if xp
else 0
)
p = int((progress / needed) * n) or 1
if short:
progress = f"{round(progress/1000, 1)}k" if int(progress / 1000) else progress
needed = f"{round(needed/1000, 1)}k" if int(needed / 1000) else needed
return f"{'🟩'*p}{'⬛' * (n-p)} {progress} / {needed}"
def get_page(guild: GatewayGuild, entries: dict):
field1, field2, field3 = "", "", ""
for user_id, entry in entries.items():
member = guild.get_member(user_id)
if not member:
continue
level, xp = entry["level"], entry["xp"]
bar = get_progress_bar(level + 1, xp, 5, True)
xp = f"{round(xp / 1000, 1)}k" if int(xp / 1000) else xp
field1 += f"**{entry['pos']}.** {member.display_name}\n"
field2 += f"{level} ({xp})\n"
field3 += f"{bar}\n"
return ("Noms", field1), ("Niveau", field2), ("Progrès", field3)
@plugin.command()
@option("membre", "Le membre dont tu veux voir le rang", Member, default=None)
@command("rank", "Afficher le niveau d'un membre")
@implements(SlashCommand)
async def rank(ctx: Context):
guild = ctx.get_guild()
member = ctx.options.membre or ctx.member
data = await plugin.bot.db.fetch_leaderboard(guild.id)
data = {
entry["_id"]: entry["guilds"][0] | {"pos": i + 1}
for i, entry in enumerate(sorted(data, reverse=True, key=lambda e: e['guilds'][0]["xp"]))
}
embed = Embed(color=0x3498DB)
embed.set_author(name=f"Progression de {member.display_name}", icon=member.avatar_url)
xp, lvl = data[member.id]["xp"], data[member.id]["level"] + 1
bar = get_progress_bar(lvl, xp, 13)
embed.add_field(name=f"Niveau {lvl-1} • Rang {data[member.id]['pos']}", value=bar)
await ctx.respond(embed=embed)
@plugin.command()
@command("levels", description="Afficher le classement du serveur")
@implements(SlashCommand)
async def levels(ctx: Context):
guild = ctx.get_guild()
embed = (
Embed(color=0x3498DB)
.set_author(name="Classement du serveur", icon=guild.icon_url)
.set_footer(text="Page 1")
)
data = await plugin.bot.db.fetch_leaderboard(guild.id)
data = list(sorted(data, reverse=True, key=lambda e: e['guilds'][0]['xp']))
data = {
entry["_id"]: entry["guilds"][0] | {"pos": i + 1}
for i, entry in enumerate(data[:10])
}
for field in get_page(guild, data):
embed.add_field(name=field[0], value=field[1], inline=True)
resp = await ctx.respond(embed=embed)
message = await resp.message()
for emoji in ["◀️", "▶️"]:
await message.add_reaction(emoji)
@plugin.listener(GuildReactionAddEvent)
async def on_reaction_add(event):
guild, member = plugin.bot.cache.get_guild(event.guild_id), event.member
if member.is_bot:
return
message = plugin.bot.cache.get_message(event.message_id)
if (
not message
or not message.embeds
or not message.embeds[0].author
or message.embeds[0].author.name != "Classement du serveur"
):
return
data = await plugin.bot.db.fetch_leaderboard(guild.id)
data = list(sorted(data, reverse=True, key=lambda e: e['guilds'][0]['xp']))
embed, total = message.embeds[0], len(data) // 10 + (len(data) % 10 > 0)
inc = -1 if event.emoji_name == "◀️" else 1
page = (int(embed.footer.text.split()[-1]) + inc) % total or total
a, b = (1, 10) if page == 1 else (page * 10 - 9, page * 10)
data = {
entry["_id"]: entry["guilds"][0] | {"pos": i + a}
for i, entry in enumerate(data[a-1:b])
}
for i, field in enumerate(get_page(guild, data)):
embed.edit_field(i, field[0], field[1])
embed.set_footer(text=f"Page {page}")
await message.edit(embed=embed)
await message.remove_reaction(event.emoji_name, user=member.id)
@plugin.listener(GuildMessageCreateEvent)
async def on_message(event):
guild, member = plugin.bot.cache.get_guild(event.guild_id), event.member
if not guild or not member or member.is_bot or member.id == 689154823941390507:
return
if not cd.update_cooldown(member, guild):
return
entry = await plugin.bot.db.fetch_member(guild.id, member.id)
if not entry:
return
xp, lvl = entry["guilds"][0]["xp"], entry["guilds"][0]["level"] + 1
next_lvl = 5 / 6 * lvl * (2 * lvl ** 2 + 27 * lvl + 91)
await plugin.bot.db.update_member_xp(guild.id, member.id, xp, next_lvl)
if next_lvl > xp:
return
settings = await plugin.bot.db.fetch_settings(guild.id)
if settings["channel"] is None:
return
channel = guild.get_channel(settings["channel"])
if channel:
embed = Embed(color=0xF1C40F, description=f"🆙 {event.message.author.mention} vient de monter niveau **{lvl}**.")
await channel.send(embed=embed)
def load(bot):
bot.add_plugin(plugin)
|
# Copyright 2020 Google, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import base64
import requests
import time
import json
from flask import Flask, request
#from cloudevents.http import from_http
from google.cloud import bigquery
from google.oauth2 import service_account
project_id = "dataops-319100"
app = Flask(__name__)
version = "1.0"
# Construct a BigQuery client object.
client = bigquery.Client()
# TODO(developer): Set table_id to the ID of the table to create.
table_id="dataops-319100.dwh.wikipedia_pageviews_2021"
job_config = bigquery.LoadJobConfig(
schema=[
bigquery.SchemaField("datehour", "TIMESTAMP"),
bigquery.SchemaField("wiki", "STRING"),
bigquery.SchemaField("title", "STRING"),
bigquery.SchemaField("views", "INTEGER"),
],
skip_leading_rows=1,
# The source format defaults to CSV, so the line below is optional.
source_format=bigquery.SourceFormat.CSV,
)
@app.route('/', methods=['POST'])
def index():
data = request.get_json()
if not data:
msg = 'no Pub/Sub message received'
print(f'error: {msg}')
return f'Bad Request: {msg}', 400
if not isinstance(data, dict) or 'message' not in data:
msg = 'invalid Pub/Sub message format'
print(f'error: {msg}')
return f'Bad Request: {msg}', 400
pubsub_message = data['message']
name = 'World'
if isinstance(pubsub_message, dict) and 'data' in pubsub_message:
name = base64.b64decode(pubsub_message['data']).decode('utf-8').strip()
resp = f"Hello, {name}! ID: {request.headers.get("ce-id")}"
#print(resp)
print("data message:",data['message'])
if 'attributes' in data['message']:
url = "gs://"+data['message']['attributes']['bucketId']+"/"+data['message']['attributes']['objectId']
print("New file to add to BQ:",url)
print("event type:",data['message']['attributes']['eventType'])
if data['message']['attributes']['eventType'] == "OBJECT_FINALIZE":
#before loading clear the staging table
query_job = client.query(
"""
TRUNCATE TABLE `dataops-319100.dwh.wikipedia_pageviews_2021`
"""
)
#results = query_job.result() # Waits for job to complete.
#load new data from csv file into BQ table
load_job = client.load_table_from_uri(
url, table_id, job_config=job_config
) # Make an API request.
load_job.result() # Waits for the job to complete.
destination_table = client.get_table(table_id) # Make an API request.
print("Loaded {} rows.".format(destination_table.num_rows))
#after loading the csv file into BQ - calling dataform API to perform the transformation
base_url='https://api.dataform.co/v1/project/5709626575159296/run'
secret = os.environ.get("df_token")
headers={'Authorization': 'Bearer ' + secret}
run_create_request={"environmentName": "", "scheduleName": ""}
response = requests.post(base_url, data=json.dumps(run_create_request), headers=headers)
run_url = base_url + '/' + response.json()['id']
response = requests.get(run_url, headers=headers)
while response.json()['status'] == 'RUNNING':
time.sleep(10)
response = requests.get(run_url, headers=headers)
print(response.json())
return (resp, 204)
else:
msg = 'not a create object message'
print(f'error: {msg}')
return f'Bad Request: {msg}', 400
else:
return f'Not the right message: {msg}', 400
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080))) | # Copyright 2020 Google, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import base64
import requests
import time
import json
from flask import Flask, request
#from cloudevents.http import from_http
from google.cloud import bigquery
from google.oauth2 import service_account
project_id = "dataops-319100"
app = Flask(__name__)
version = "1.0"
# Construct a BigQuery client object.
client = bigquery.Client()
# TODO(developer): Set table_id to the ID of the table to create.
table_id="dataops-319100.dwh.wikipedia_pageviews_2021"
job_config = bigquery.LoadJobConfig(
schema=[
bigquery.SchemaField("datehour", "TIMESTAMP"),
bigquery.SchemaField("wiki", "STRING"),
bigquery.SchemaField("title", "STRING"),
bigquery.SchemaField("views", "INTEGER"),
],
skip_leading_rows=1,
# The source format defaults to CSV, so the line below is optional.
source_format=bigquery.SourceFormat.CSV,
)
@app.route('/', methods=['POST'])
def index():
data = request.get_json()
if not data:
msg = 'no Pub/Sub message received'
print(f'error: {msg}')
return f'Bad Request: {msg}', 400
if not isinstance(data, dict) or 'message' not in data:
msg = 'invalid Pub/Sub message format'
print(f'error: {msg}')
return f'Bad Request: {msg}', 400
pubsub_message = data['message']
name = 'World'
if isinstance(pubsub_message, dict) and 'data' in pubsub_message:
name = base64.b64decode(pubsub_message['data']).decode('utf-8').strip()
resp = f"Hello, {name}! ID: {request.headers.get('ce-id')}"
#print(resp)
print("data message:",data['message'])
if 'attributes' in data['message']:
url = "gs://"+data['message']['attributes']['bucketId']+"/"+data['message']['attributes']['objectId']
print("New file to add to BQ:",url)
print("event type:",data['message']['attributes']['eventType'])
if data['message']['attributes']['eventType'] == "OBJECT_FINALIZE":
#before loading clear the staging table
query_job = client.query(
"""
TRUNCATE TABLE `dataops-319100.dwh.wikipedia_pageviews_2021`
"""
)
#results = query_job.result() # Waits for job to complete.
#load new data from csv file into BQ table
load_job = client.load_table_from_uri(
url, table_id, job_config=job_config
) # Make an API request.
load_job.result() # Waits for the job to complete.
destination_table = client.get_table(table_id) # Make an API request.
print("Loaded {} rows.".format(destination_table.num_rows))
#after loading the csv file into BQ - calling dataform API to perform the transformation
base_url='https://api.dataform.co/v1/project/5709626575159296/run'
secret = os.environ.get("df_token")
headers={'Authorization': 'Bearer ' + secret}
run_create_request={"environmentName": "", "scheduleName": ""}
response = requests.post(base_url, data=json.dumps(run_create_request), headers=headers)
run_url = base_url + '/' + response.json()['id']
response = requests.get(run_url, headers=headers)
while response.json()['status'] == 'RUNNING':
time.sleep(10)
response = requests.get(run_url, headers=headers)
print(response.json())
return (resp, 204)
else:
msg = 'not a create object message'
print(f'error: {msg}')
return f'Bad Request: {msg}', 400
else:
return f'Not the right message: {msg}', 400
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080))) |
"""Irrigation Unlimited Coordinator and sub classes"""
from datetime import datetime, time, timedelta
from types import MappingProxyType
from typing import OrderedDict
import homeassistant
from homeassistant.core import HomeAssistant, CALLBACK_TYPE
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_time_interval
import homeassistant.helpers.sun as sun
import homeassistant.util.dt as dt
import logging
import uuid
import time as tm
from homeassistant.const import (
CONF_AFTER,
CONF_BEFORE,
CONF_DELAY,
CONF_ENTITY_ID,
CONF_NAME,
CONF_REPEAT,
CONF_WEEKDAY,
CONF_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
WEEKDAYS,
ATTR_ENTITY_ID,
)
from .const import (
CONF_ACTUAL,
CONF_ALL_ZONES_CONFIG,
CONF_DAY,
CONF_DECREASE,
CONF_INCREASE,
CONF_INDEX,
CONF_OUTPUT_EVENTS,
CONF_PERCENTAGE,
CONF_REFRESH_INTERVAL,
CONF_RESET,
CONF_RESULTS,
CONF_SEQUENCES,
CONF_SEQUENCE_ID,
CONF_SHOW_LOG,
CONF_AUTOPLAY,
DEFAULT_GRANULATITY,
DEFAULT_REFRESH_INTERVAL,
DEFAULT_TEST_SPEED,
CONF_DURATION,
CONF_ENABLED,
CONF_GRANULARITY,
CONF_TIME,
CONF_SUN,
CONF_PREAMBLE,
CONF_POSTAMBLE,
CONF_TESTING,
CONF_SPEED,
CONF_TIMES,
CONF_START,
CONF_END,
CONF_CONTROLLERS,
CONF_SCHEDULES,
CONF_ZONES,
CONF_MINIMUM,
CONF_MAXIMUM,
CONF_MONTH,
MONTHS,
CONF_ODD,
CONF_EVEN,
CONF_SHOW,
CONF_CONFIG,
CONF_TIMELINE,
CONF_ZONE_ID,
CONF_FUTURE_SPAN,
SERVICE_CANCEL,
SERVICE_DISABLE,
SERVICE_ENABLE,
SERVICE_TOGGLE,
SERVICE_MANUAL_RUN,
SERVICE_TIME_ADJUST,
STATUS_BLOCKED,
STATUS_PAUSED,
STATUS_DISABLED,
STATUS_INITIALISING,
)
_LOGGER: logging.Logger = logging.getLogger(__package__)
# Useful time manipulation routine
def time_to_timedelta(offset: time) -> timedelta:
"""Create a timedelta from a time object"""
return datetime.combine(datetime.min, offset) - datetime.min
# These routines truncate dates, times and deltas to the internal
# granularity. This should be no more than 1 minute and realisticly
# no less than 1 second i.e. 1 >= GRANULARITY <= 60
# The current boundaries are whole minutes (60 seconds).
SYSTEM_GRANULARITY: int = DEFAULT_GRANULATITY # Granularity in seconds
def reset_granularity() -> None:
global SYSTEM_GRANULARITY
SYSTEM_GRANULARITY = DEFAULT_GRANULATITY
return
def granularity_time() -> timedelta:
"""Return the system granularity as a timedelta"""
return timedelta(seconds=SYSTEM_GRANULARITY)
def wash_td(delta: timedelta, granularity: int = None) -> timedelta:
"""Truncate the supplied timedelta to internal boundaries"""
if delta is not None:
if granularity is None:
granularity = SYSTEM_GRANULARITY
whole_seconds = int(delta.total_seconds())
rounded_seconds = int(whole_seconds / granularity) * granularity
return timedelta(seconds=rounded_seconds)
else:
return None
def wash_dt(date: datetime, granularity: int = None) -> datetime:
"""Truncate the supplied datetime to internal boundaries"""
if date is not None:
if granularity is None:
granularity = SYSTEM_GRANULARITY
rounded_seconds = int(date.second / granularity) * granularity
d = date.replace(second=rounded_seconds, microsecond=0)
return d
else:
return None
def wash_t(time: time, granularity: int = None) -> time:
"""Truncate the supplied time to internal boundaries"""
if time is not None:
if granularity is None:
granularity = SYSTEM_GRANULARITY
utc = dt.utcnow()
d = utc.combine(utc.date(), time)
rounded_seconds = int(d.second / granularity) * granularity
t = d.replace(second=rounded_seconds, microsecond=0)
return t.timetz()
else:
return None
def round_td(delta: timedelta, granularity: int = None) -> timedelta:
"""Round the supplied timedelta to internal boundaries"""
if delta is not None:
if granularity is None:
granularity = SYSTEM_GRANULARITY
rounded_seconds = (
int((delta.total_seconds() + granularity / 2) / granularity) * granularity
)
return timedelta(seconds=rounded_seconds)
else:
return None
class IUBase:
"""Irrigation Unlimited base class"""
def __init__(self, index: int) -> None:
# Private variables
self._id: int = uuid.uuid4().int
self._index: int = index
return
def __eq__(self, other) -> bool:
if isinstance(other, IUBase):
return self.id == other.id
else:
return False
@property
def id(self) -> str:
"""Return our unique id"""
return self._id
@property
def index(self) -> int:
return self._index
class IUAdjustment:
"""Irrigation Unlimited class to handle run time adjustment"""
def __init__(self) -> None:
self.clear()
return
def __str__(self) -> str:
"""Return the adjustment as a string notation"""
if self._method is None:
s = "None"
elif self._method == CONF_ACTUAL:
s = f"={self._time_adjustment}"
elif self._method == CONF_PERCENTAGE:
s = f"%{self._time_adjustment}"
elif self._method == CONF_INCREASE:
s = f"+{self._time_adjustment}"
elif self._method == CONF_DECREASE:
s = f"-{self._time_adjustment}"
else:
s = str(self._time_adjustment)
return s
@property
def has_adjustment(self) -> bool:
return self._method != None
def clear(self) -> None:
self._method: str = None
self._time_adjustment = None
self._minimum: timedelta = None
self._maximum: timedelta = None
return
def load(self, data: MappingProxyType) -> bool:
"""Read the adjustment configuration. Return true if anything has changed"""
# Save current settings
old_method = self._method
old_time_adjustment = self._time_adjustment
old_minimum = self._minimum
old_maximum = self._maximum
if CONF_ACTUAL in data:
self._method = CONF_ACTUAL
self._time_adjustment = wash_td(data.get(CONF_ACTUAL))
elif CONF_PERCENTAGE in data:
self._method = CONF_PERCENTAGE
self._time_adjustment = data.get(CONF_PERCENTAGE)
elif CONF_INCREASE in data:
self._method = CONF_INCREASE
self._time_adjustment = wash_td(data.get(CONF_INCREASE))
elif CONF_DECREASE in data:
self._method = CONF_DECREASE
self._time_adjustment = wash_td(data.get(CONF_DECREASE))
elif CONF_RESET in data:
self._method = None
self._time_adjustment = None
self._minimum = wash_td(data.get(CONF_MINIMUM, None))
if self._minimum is not None:
self._minimum = max(self._minimum, granularity_time()) # Set floor
self._maximum = wash_td(data.get(CONF_MAXIMUM, None))
return (
self._method != old_method
or self._time_adjustment != old_time_adjustment
or self._minimum != old_minimum
or self._maximum != old_maximum
)
def adjust(self, time: timedelta) -> timedelta:
"""Return the adjusted time"""
new_time: timedelta
if self._method is None:
new_time = time
elif self._method == CONF_ACTUAL:
new_time = self._time_adjustment
elif self._method == CONF_PERCENTAGE:
new_time = round_td(time * self._time_adjustment / 100)
elif self._method == CONF_INCREASE:
new_time = time + self._time_adjustment
elif self._method == CONF_DECREASE:
new_time = time - self._time_adjustment
else:
new_time = time
if self._minimum is not None:
new_time = max(new_time, self._minimum)
if self._maximum is not None:
new_time = min(new_time, self._maximum)
return new_time
class IUSchedule(IUBase):
"""Irrigation Unlimited Schedule class. Schedules are not actual
points in time but describe a future event i.e. next Monday"""
def __init__(
self,
hass: HomeAssistant,
schedule_index: int,
) -> None:
super().__init__(schedule_index)
# Passed parameters
self._hass = hass
# Config parameters
self._time = None
self._duration: timedelta = None
self._name: str = None
self._weekdays: list[int] = None
self._months: list[int] = None
# Private variables
self._dirty: bool = True
return
@property
def name(self) -> str:
"""Return the friendly name of this schedule"""
return self._name
@property
def is_setup(self) -> bool:
"""Return true is this schedule is setup"""
return True
@property
def run_time(self) -> timedelta:
"""Return the duration"""
return self._duration
def clear(self) -> None:
"""Reset this schedule"""
self._dirty = True
return
def load(self, config: OrderedDict) -> "IUSchedule":
"""Load schedule data from config"""
self.clear()
self._time = config[CONF_TIME]
self._duration = wash_td(config.get(CONF_DURATION, None))
self._name = config.get(CONF_NAME, f"Schedule {self.index + 1}")
if CONF_WEEKDAY in config:
self._weekdays = []
for i in config[CONF_WEEKDAY]:
self._weekdays.append(WEEKDAYS.index(i))
else:
self._weekdays = None
if CONF_MONTH in config:
self._months = []
for i in config[CONF_MONTH]:
self._months.append(MONTHS.index(i) + 1)
else:
self._months = None
self._days = config.get(CONF_DAY, None)
return self
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict[CONF_TIME] = self._time
dict[CONF_DURATION] = self._duration
dict[CONF_NAME] = self._name
if self._weekdays is not None:
dict[CONF_WEEKDAY] = []
for item in self._weekdays:
dict[CONF_WEEKDAY].append(WEEKDAYS[item])
if self._months is not None:
dict[CONF_MONTH] = []
for item in self._months:
dict[CONF_MONTH].append(MONTHS[item - 1])
if self._days is not None:
dict[CONF_DAY] = self._days
return dict
def get_next_run(self, atime: datetime, ftime: datetime) -> datetime:
"""
Determine the next start time. Date processing in this routine
is done in local time and returned as UTC
"""
local_time = dt.as_local(atime)
final_time = dt.as_local(ftime)
next_run: datetime = None
while True:
if next_run is None:
next_run = local_time # Initialise on first pass
else:
next_run += timedelta(days=1) # Advance to next day
# Sanity check. Note: Astral events like sunrise might take months i.e. Antarctica winter
if next_run > final_time:
return None
# DOW filter
if self._weekdays is not None and next_run.weekday() not in self._weekdays:
continue
# Month filter
if self._months is not None and next_run.month not in self._months:
continue
# Day filter
if self._days is not None:
if self._days == CONF_ODD:
if next_run.day % 2 == 0:
continue
elif self._days == CONF_EVEN:
if next_run.day % 2 != 0:
continue
elif next_run.day not in self._days:
continue
if isinstance(self._time, time):
next_run = datetime.combine(
next_run.date(), self._time, next_run.tzinfo
)
elif isinstance(self._time, dict) and CONF_SUN in self._time:
se = sun.get_astral_event_date(
self._hass, self._time[CONF_SUN], next_run
)
if se is None:
continue # Astral event did not occur today
next_run = dt.as_local(se)
if CONF_AFTER in self._time:
next_run += self._time[CONF_AFTER]
if CONF_BEFORE in self._time:
next_run -= self._time[CONF_BEFORE]
else: # Some weird error happened
return None
next_run = wash_dt(next_run)
if next_run >= local_time:
break
return dt.as_utc(next_run)
class IURun(IUBase):
"""Irrigation Unlimited Run class. A run is an actual point
in time. If schedule is None then it is a manual run.
"""
def __init__(
self,
start_time: datetime,
duration: timedelta,
zone: "IUZone",
schedule: "IUSchedule",
sequence_run: "IUSequenceRun",
) -> None:
super().__init__(None)
# Passed parameters
self._start_time: datetime = start_time
self._duration: timedelta = duration
self._zone = zone
self._schedule = schedule
self._sequence_run = sequence_run
# Private variables
self._end_time: datetime = self._start_time + self._duration
self._remaining_time: timedelta = self._end_time - self._start_time
self._percent_complete: int = 0
return
@property
def start_time(self) -> datetime:
return self._start_time
@property
def duration(self) -> timedelta:
return self._duration
@property
def zone(self) -> "IUSchedule":
return self._zone
@property
def schedule(self) -> "IUSchedule":
"""Return the schedule"""
return self._schedule
@property
def end_time(self) -> datetime:
return self._end_time
@property
def time_remaining(self) -> timedelta:
return self._remaining_time
@property
def percent_complete(self) -> float:
return self._percent_complete
@property
def is_sequence(self) -> bool:
return self._sequence_run is not None
@property
def sequence_run(self) -> "IUSequenceRun":
return self._sequence_run
@property
def sequence(self) -> "IUSequence":
if self.is_sequence:
return self._sequence_run.sequence
else:
return None
@property
def sequence_zone(self) -> "IUSequenceZone":
if self.is_sequence:
return self._sequence_run.sequence_zone(self)
else:
return None
@property
def sequence_id(self) -> int:
if self.is_sequence:
return self._sequence_run._id
else:
return None
@property
def sequence_running(self) -> bool:
return self.is_sequence and self._sequence_run.running
@sequence_running.setter
def sequence_running(self, value: bool) -> None:
"""Flag sequence is now running"""
if self.is_sequence:
self.sequence_run.running = value
return
@property
def crumbs(self) -> str:
return self._crumbs()
def _crumbs(self) -> str:
def get_index(object: IUBase) -> int:
if object is not None:
return object.index + 1
else:
return 0
if self.is_sequence:
sidx = self.sequence_run.run_index(self) + 1
else:
sidx = 0
return f"{get_index(self._zone)}.{get_index(self._schedule)}.{get_index(self.sequence)}.{get_index(self.sequence_zone)}.{sidx}"
def is_manual(self) -> bool:
"""Check if this is a manual run"""
return self._schedule is None
def is_running(self, time: datetime) -> bool:
"""Check if this schedule is running"""
return (time >= self._start_time) and (time < self._end_time)
def is_expired(self, time: datetime) -> bool:
"""Check if this schedule is expired"""
return time >= self._end_time
def is_future(self, time: datetime) -> bool:
"""Check schedule is in the future"""
return self._start_time > time
def is_valid(self, time: datetime) -> bool:
"""Return true if run is valid. Should be
running or in the future.
"""
return self.is_running(time) and not self.is_future(time)
def sequence_start(self, time: datetime) -> bool:
"""Check if sequence is about to start but not yet flagged"""
result = (
self.is_sequence
and self.is_running(time)
and not self._sequence_run.running
)
if result:
self._sequence_run.running = True
return result
def update_time_remaining(self, time: datetime) -> bool:
if self.is_running(time):
self._remaining_time = self._end_time - time
total_duration: timedelta = self._end_time - self._start_time
time_elapsed: timedelta = time - self._start_time
self._percent_complete = int((time_elapsed / total_duration) * 100)
return True
else:
return False
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict["start"] = self._start_time
dict["end"] = self._end_time
return dict
class IURunQueue(list):
DAYS_SPAN: int = 3
RQ_STATUS_CLEARED: int = 0x01
RQ_STATUS_EXTENDED: int = 0x02
RQ_STATUS_REDUCED: int = 0x04
RQ_STATUS_SORTED: int = 0x08
RQ_STATUS_UPDATED: int = 0x10
RQ_STATUS_CANCELED: int = 0x20
RQ_STATUS_CHANGED: int = 0x40
def __init__(self) -> None:
# Private variables
self._current_run: IURun = None
self._next_run: IURun = None
self._sorted: bool = False
self._cancel_request: bool = False
self._future_span = wash_td(timedelta(days=self.DAYS_SPAN))
return
@property
def current_run(self) -> IURun:
return self._current_run
@property
def next_run(self) -> IURun:
return self._next_run
@property
def in_sequence(self) -> bool:
return self._in_sequence()
def _in_sequence(self) -> bool:
for run in self:
if run.sequence_running:
return True
return False
def add(
self,
start_time: datetime,
duration: timedelta,
zone: "IUZone",
schedule: "IUSchedule",
sequence_run: "IUSequenceRun",
) -> IURun:
run = IURun(start_time, duration, zone, schedule, sequence_run)
self.append(run)
self._sorted = False
return run
def cancel(self) -> None:
"""Flag the current run to be cancelled"""
self._cancel_request = True
return
def clear_all(self) -> bool:
modified: bool = False
if len(self) > 0:
self._current_run = None
super().clear()
modified = True
return modified
def clear(self, time: datetime) -> bool:
"""Clear out the queue except for manual or running schedules"""
modified: bool = False
if len(self) > 0:
i = len(self) - 1
while i >= 0:
item: IURun = self[i]
if not (
item.is_running(time) or item.is_manual() or item.sequence_running
):
self.pop(i)
modified = True
i -= 1
if modified:
self._next_run = None
self._sorted = True
return modified
def find_last_index(self, id: int) -> int:
"""Return the index of the run that finishes last in the queue.
This routine does not require the list to be sorted."""
result: int = None
last_time: datetime = None
for i, run in enumerate(self):
if run.schedule is not None and run.schedule.id == id:
if last_time is None or run.end_time > last_time:
last_time = run.end_time
result = i
return result
def find_last_run(self, id: int) -> IURun:
i = self.find_last_index(id)
if i is not None:
return self[i]
else:
return None
def find_last_date(self, id: int) -> datetime:
"""Find the last time in the queue for the supplied id"""
run = self.find_last_run(id)
if run is not None:
return run.end_time
else:
return None
def find_manual(self) -> IURun:
for run in self:
if run.is_manual():
return run
return None
def last_time(self, time: datetime) -> datetime:
return time + self._future_span
def load(self, config: OrderedDict, all_zones: OrderedDict):
if all_zones is not None:
self._future_span = wash_td(
all_zones.get(CONF_FUTURE_SPAN, self._future_span)
)
self._future_span = wash_td(config.get(CONF_FUTURE_SPAN, self._future_span))
self._future_span = max(self._future_span, timedelta(hours=12))
return self
def sorter(self, run: IURun) -> datetime:
"""Sort call back routine. Items are sorted
by start_time."""
if run.is_manual():
return datetime.min.replace(tzinfo=dt.UTC) # Always put manual run at head
else:
return run.start_time
def sort(self) -> bool:
"""Sort the run queue."""
modified: bool = False
if not self._sorted:
super().sort(key=self.sorter)
self._current_run = None
self._next_run = None
self._sorted = True
modified = True
return modified
def remove_expired(self, time: datetime) -> bool:
"""Remove any expired runs from the queue"""
modified: bool = False
i = len(self) - 1
while i >= 0:
run: IURun = self[i]
if run.is_expired(time):
self._current_run = None
self._next_run = None
self.pop(i)
modified = True
i -= 1
return modified
def remove_current(self) -> bool:
"""Remove the current run or upcoming manual run"""
modified: bool = False
if self._current_run is not None or (
self._next_run is not None and self._next_run.is_manual()
):
if len(self) > 0:
self.pop(0)
self._current_run = None
self._next_run = None
modified = True
return modified
def update_queue(self, time: datetime) -> int:
"""Update the run queue. Sort the queue, remove expired runs
and set current and next runs.
Returns a bit field of changes to queue.
"""
status: int = 0
if self.sort():
status |= self.RQ_STATUS_SORTED
if self._cancel_request:
if self.remove_current():
status |= self.RQ_STATUS_CANCELED
self._cancel_request = False
if self.remove_expired(time):
status |= self.RQ_STATUS_REDUCED
# Try to find a running schedule
if self._current_run is None and len(self) > 0 and self[0].is_running(time):
self._current_run = self[0]
self._next_run = None
status |= self.RQ_STATUS_UPDATED
# Try to find the next schedule
if self._next_run is None:
if self._current_run is None:
if len(self) >= 1:
self._next_run = self[0]
status |= self.RQ_STATUS_UPDATED
else:
if len(self) >= 2:
self._next_run = self[1]
status |= self.RQ_STATUS_UPDATED
for run in self:
if run.sequence_start(time):
status |= self.RQ_STATUS_CHANGED
return status
def update_sensor(self, time: datetime) -> bool:
if self._current_run is not None:
return self._current_run.update_time_remaining(time)
else:
return False
def as_list(self) -> list:
l = []
for run in self:
l.append(run.as_dict())
return l
class IUScheduleQueue(IURunQueue):
"""Class to hold the upcoming schedules to run"""
def __init__(self) -> None:
super().__init__()
# Config variables
self._minimum: timedelta = None
self._maximum: timedelta = None
return
def add(
self,
start_time: datetime,
duration: timedelta,
zone: "IUZone",
schedule: "IUSchedule",
sequence_run: "IUSequenceRun",
) -> IURun:
if self._minimum is not None:
duration = max(duration, self._minimum)
if self._maximum is not None:
duration = min(duration, self._maximum)
return super().add(start_time, duration, zone, schedule, sequence_run)
def add_schedule(
self,
zone: "IUZone",
schedule: IUSchedule,
start_time: datetime,
adjustment: IUAdjustment,
) -> IURun:
"""Add a new schedule run to the queue"""
duration = schedule.run_time
if adjustment is not None:
duration = adjustment.adjust(duration)
return self.add(start_time, duration, zone, schedule, None)
def add_manual(
self, start_time: datetime, duration: timedelta, zone: "IUZone"
) -> IURun:
"""Add a manual run to the queue. Cancel any existing
manual or running schedule"""
if self._current_run is not None:
self.pop(0)
# Remove any existing manual schedules
while True:
run = self.find_manual()
if run is None:
break
else:
self.remove(run)
self._current_run = None
self._next_run = None
duration = max(duration, granularity_time())
return self.add(start_time, duration, zone, None, None)
def merge_one(
self,
time: datetime,
zone: "IUZone",
schedule: IUSchedule,
adjustment: IUAdjustment,
) -> bool:
modified: bool = False
# See if schedule already exists in run queue. If so get
# the finish time of the last entry.
next_time = self.find_last_date(schedule.id)
if next_time is not None:
next_time += granularity_time()
else:
next_time = time
next_run = schedule.get_next_run(next_time, self.last_time(time))
if next_run is not None:
self.add_schedule(zone, schedule, next_run, adjustment)
modified = True
return modified
def merge_fill(
self,
time: datetime,
zone: "IUZone",
schedule: IUSchedule,
adjustment: IUAdjustment,
) -> bool:
"""Merge the schedule into the run queue. Add as many until the span is
reached. Return True if the schedule was added."""
modified: bool = False
while self.merge_one(time, zone, schedule, adjustment):
modified = True
return modified
def load(self, config: OrderedDict, all_zones: OrderedDict) -> "IUScheduleQueue":
super().load(config, all_zones)
if all_zones is not None:
self._minimum = wash_td(all_zones.get(CONF_MINIMUM, self._minimum))
self._maximum = wash_td(all_zones.get(CONF_MAXIMUM, self._maximum))
self._minimum = wash_td(config.get(CONF_MINIMUM, self._minimum))
self._maximum = wash_td(config.get(CONF_MAXIMUM, self._maximum))
return self
def update_queue(
self,
time: datetime,
) -> int:
return super().update_queue(time)
class IUZone(IUBase):
"""Irrigation Unlimited Zone class"""
def __init__(
self,
hass: HomeAssistant,
coordinator: "IUCoordinator",
controller: "IUController",
zone_index: int,
) -> None:
super().__init__(zone_index)
# Passed parameters
self._hass = hass
self._coordinator = coordinator
self._controller = controller
# Config parameters
self._zone_id: str = None
self._is_enabled: bool = True
self._name: str = None
self._switch_entity_id: str = None
self._show_config: bool = False
self._show_timeline: bool = False
# Private variables
self._initialised: bool = False
self._schedules: list[IUSchedule] = []
self._run_queue = IUScheduleQueue()
self._adjustment = IUAdjustment()
self._zone_sensor: Entity = None
self._is_on: bool = False
self._sensor_update_required: bool = False
self._sensor_last_update: datetime = None
self._dirty: bool = True
return
@property
def schedules(self) -> "list[IUSchedule]":
return self._schedules
@property
def runs(self) -> IUScheduleQueue:
return self._run_queue
@property
def adjustment(self) -> IUAdjustment:
return self._adjustment
@property
def zone_id(self) -> str:
return self._zone_id
@property
def name(self) -> str:
if self._name is not None:
return self._name
else:
return f"Zone {self._index + 1}"
@property
def is_on(self) -> bool:
return self._is_on
@property
def is_setup(self) -> bool:
return self._is_setup()
@property
def enabled(self) -> bool:
"""Return true if this zone is enabled"""
return self._is_enabled
@enabled.setter
def enabled(self, value: bool) -> None:
"""Enable/disable zone"""
if value != self._is_enabled:
self._is_enabled = value
self._dirty = True
self.request_update()
return
@property
def zone_sensor(self) -> Entity:
return self._zone_sensor
@zone_sensor.setter
def zone_sensor(self, value: Entity) -> None:
self._zone_sensor = value
return
@property
def status(self) -> str:
return self._status()
@property
def show_config(self) -> bool:
return self._show_config
@property
def show_timeline(self) -> bool:
return self._show_timeline
def _is_setup(self) -> bool:
"""Check if this object is setup"""
if not self._initialised:
self._initialised = self._zone_sensor is not None
if self._initialised:
for schedule in self._schedules:
self._initialised = self._initialised and schedule.is_setup
return self._initialised
def _status(self) -> str:
"""Return status of zone"""
if self._initialised:
if self._controller.enabled:
if self._is_enabled:
if self._is_on:
return STATE_ON
else:
return STATE_OFF
else:
return STATUS_DISABLED
else:
return STATUS_BLOCKED
else:
return STATUS_INITIALISING
def service_adjust_time(self, data: MappingProxyType, time: datetime) -> bool:
"""Adjust the scheduled run times. Return true if adjustment changed"""
result = self._adjustment.load(data)
if result:
self._run_queue.clear(time)
return result
def service_manual_run(self, data: MappingProxyType, time: datetime) -> None:
"""Add a manual run."""
if self._is_enabled and self._controller.enabled:
ns = wash_dt(time + granularity_time())
if self._controller.preamble is not None:
ns = ns + self._controller.preamble
self._run_queue.add_manual(ns, wash_td(data[CONF_TIME]), self)
return
def service_cancel(self, data: MappingProxyType, time: datetime) -> None:
"""Cancel the current running schedule"""
self._run_queue.cancel()
return
def add(self, schedule: IUSchedule) -> IUSchedule:
"""Add a new schedule to the zone"""
self._schedules.append(schedule)
return schedule
def find_add(
self, coordinator: "IUCoordinator", controller: "IUController", index: int
) -> IUSchedule:
if index >= len(self._schedules):
return self.add(IUSchedule(self._hass, index))
else:
return self._schedules[index]
def clear_run_queue(self) -> None:
"""Clear out the run queue"""
self._run_queue.clear_all()
return
def clear(self) -> None:
"""Reset this zone"""
self._schedules.clear()
self.clear_run_queue()
self._adjustment = IUAdjustment()
self._is_on = False
return
def load(self, config: OrderedDict, all_zones: OrderedDict) -> "IUZone":
"""Load zone data from the configuration"""
self.clear()
self._zone_id = config.get(CONF_ID, str(self.index + 1))
self._is_enabled = config.get(CONF_ENABLED, True)
self._name = config.get(CONF_NAME, None)
self._switch_entity_id = config.get(CONF_ENTITY_ID)
self._run_queue.load(config, all_zones)
if all_zones is not None and CONF_SHOW in all_zones:
self._show_config = all_zones[CONF_SHOW].get(CONF_CONFIG, self._show_config)
self._show_timeline = all_zones[CONF_SHOW].get(
CONF_TIMELINE, self._show_timeline
)
if CONF_SHOW in config:
self._show_config = config[CONF_SHOW].get(CONF_CONFIG, self._show_config)
self._show_timeline = config[CONF_SHOW].get(
CONF_TIMELINE, self._show_timeline
)
if CONF_SCHEDULES in config:
for si, schedule_config in enumerate(config[CONF_SCHEDULES]):
self.find_add(self._coordinator, self._controller, si).load(
schedule_config
)
self._dirty = True
return self
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict[CONF_INDEX] = self._index
dict[CONF_NAME] = self.name
dict[CONF_SCHEDULES] = []
for schedule in self._schedules:
dict[CONF_SCHEDULES].append(schedule.as_dict())
return dict
def muster(self, time: datetime) -> int:
status: int = 0
if self._dirty:
self._run_queue.clear_all()
status |= IURunQueue.RQ_STATUS_CLEARED
self._dirty = False
return status
def muster_schedules(self, time: datetime) -> int:
"""Calculate run times for this zone"""
status: int = 0
for schedule in self._schedules:
if self._run_queue.merge_fill(time, self, schedule, self._adjustment):
status |= IURunQueue.RQ_STATUS_EXTENDED
if status != 0:
self.request_update()
return status
def check_run(self, time: datetime, parent_enabled: bool) -> bool:
"""Update the run status"""
is_running: bool = False
state_changed: bool = False
is_running = (
parent_enabled
and self._is_enabled
and self._run_queue.current_run is not None
and self._run_queue.current_run.is_running(time)
)
state_changed = is_running ^ self._is_on
if state_changed:
self._is_on = not self._is_on
self.request_update()
return state_changed
def request_update(self) -> None:
"""Flag the sensor needs an update"""
self._sensor_update_required = True
return
def update_sensor(self, time: datetime, do_on: bool) -> bool:
"""Lazy sensor updater"""
updated: bool = False
do_update: bool = False
if self._zone_sensor is not None:
if do_on == False:
updated |= self._run_queue.update_sensor(time)
if not self._is_on:
do_update = self._sensor_update_required
else:
if self._is_on:
# If we are running then update sensor according to refresh_interval
if self._run_queue.current_run is not None:
do_update = (
self._sensor_last_update is None
or time - self._sensor_last_update
>= self._coordinator.refresh_interval
)
do_update = do_update or self._sensor_update_required
else:
do_update = False
if do_update:
self._zone_sensor.schedule_update_ha_state()
self._sensor_update_required = False
self._sensor_last_update = time
updated = True
return updated
def call_switch(self, service_type: str) -> None:
if self._switch_entity_id is not None:
self._hass.async_create_task(
self._hass.services.async_call(
homeassistant.core.DOMAIN,
service_type,
{ATTR_ENTITY_ID: self._switch_entity_id},
)
)
return
class IUZoneQueue(IURunQueue):
"""Class to hold the upcoming zones to run"""
def add_zone(
self,
start_time: datetime,
duration: timedelta,
zone: IUZone,
schedule: IUSchedule,
sequence_run: "IUSequenceRun",
preamble: timedelta,
postamble: timedelta,
) -> IURun:
"""Add a new master run to the queue"""
if preamble is not None:
start_time -= preamble
duration += preamble
if postamble is not None:
duration += postamble
run = self.find_run(start_time, duration, zone, schedule, sequence_run)
if run is None:
run = self.add(start_time, duration, zone, schedule, sequence_run)
return run
def find_run(
self,
start_time: datetime,
duration: timedelta,
zone: IUZone,
schedule: IUSchedule,
sequence_run: "IUSequenceRun",
) -> IURun:
for run in self:
if (
start_time == run.start_time
and zone == run.zone
and run.schedule is not None
and schedule is not None
and run.schedule == schedule
):
return run
return None
def rebuild_schedule(
self,
time: datetime,
zones: "list[IUZone]",
preamble: timedelta,
postamble: timedelta,
all: bool,
) -> int:
"""Create a superset of all the zones."""
status: int = 0
if all:
self.clear_all()
else:
self.clear(time)
for zone in zones:
for run in zone.runs:
self.add_zone(
run.start_time,
run.duration,
run.zone,
run.schedule,
run.sequence_run,
preamble,
postamble,
)
status |= IURunQueue.RQ_STATUS_EXTENDED | IURunQueue.RQ_STATUS_REDUCED
status |= self.update_queue(time)
return status
class IUSequenceZone(IUBase):
"""Irrigation Unlimited Sequence Zone class"""
def __init__(
self,
hass: HomeAssistant,
coordinator: "IUCoordinator",
controller: "IUController",
sequence: "IUSequence",
zone_index: int,
) -> None:
super().__init__(zone_index)
# Passed parameters
self._hass = hass
self._coordinator = coordinator
self._controller = controller
self._sequence = sequence
# Config parameters
self._zone_ids: list[str] = None
self._delay: timedelta = None
self._duration: timedelta = None
self._repeat: int = None
# Private variables
return
@property
def zone_ids(self) -> "list[str]":
return self._zone_ids
@property
def duration(self) -> timedelta:
return self._duration
@property
def delay(self) -> timedelta:
return self._delay
@property
def repeat(self) -> int:
return self._repeat
def clear(self) -> None:
"""Reset this sequence zone"""
return
def load(self, config: OrderedDict) -> "IUSequenceZone":
"""Load sequence zone data from the configuration"""
self.clear()
self._zone_ids = config[CONF_ZONE_ID]
self._delay = wash_td(config.get(CONF_DELAY))
self._duration = wash_td(config.get(CONF_DURATION))
self._repeat = config.get(CONF_REPEAT, 1)
return self
class IUSequence(IUBase):
"""Irrigation Unlimited Sequence class"""
def __init__(
self,
hass: HomeAssistant,
coordinator: "IUCoordinator",
controller: "IUController",
sequence_index: int,
) -> None:
super().__init__(sequence_index)
# Passed parameters
self._hass = hass
self._coordinator = coordinator
self._controller = controller
# Config parameters
self._name: str = None
self._delay: timedelta = None
self._duration: timedelta = None
self._repeat: int = None
# Private variables
self._schedules: list[IUSchedule] = []
self._zones: list[IUSequenceZone] = []
self._adjustment = IUAdjustment()
return
@property
def schedules(self) -> "list[IUSchedule]":
return self._schedules
@property
def zones(self) -> "list[IUSequenceZone]":
return self._zones
@property
def delay(self) -> timedelta:
return self._delay
@property
def duration(self) -> timedelta:
return self._duration
@property
def repeat(self) -> int:
return self._repeat
@property
def adjustment(self) -> IUAdjustment:
return self._adjustment
@property
def has_adjustment(self) -> bool:
return self._adjustment.has_adjustment
def zone_duration(self, zone: IUSequenceZone) -> timedelta:
"""Return the duration for the specified zone"""
if zone.duration is not None:
duration = zone.duration
else:
duration = self._duration
if duration is None:
duration = granularity_time()
return duration
def zone_delay(self, zone: IUSequenceZone) -> timedelta:
"""Return the delay for the specified zone"""
if zone.delay is not None:
delay = zone.delay
else:
delay = self._delay
if delay is None:
delay = timedelta(0)
return delay
def total_duration(self) -> timedelta:
"""Return the total duration for all the zones"""
duration = timedelta(0)
for zone in self._zones:
duration += self.zone_duration(zone) * zone.repeat
duration *= self._repeat
return duration
def total_delay(self) -> timedelta:
"""Return the total delay for all the zones"""
delay = timedelta(0)
for zone in self._zones:
delay += self.zone_delay(zone) * zone.repeat
delay *= self._repeat
delay -= self.zone_delay(zone)
return delay
def total_time(self) -> timedelta:
"""Return the total time for the sequence"""
return self.total_duration() + self.total_delay()
def duration_multiplier(self, total_time: timedelta) -> float:
"""Given a new total run time, calculate how much to shrink or expand each
zone duration. Final time will be approximate as the new durations must
be rounded to internal boundaries"""
total_duration = self.total_duration()
if total_time is not None and total_duration != 0:
return (total_time - self.total_delay()) / total_duration
else:
return 1.0
def clear(self) -> None:
"""Reset this sequence"""
self._schedules.clear()
self._zones.clear()
self._adjustment.clear()
return
def add_schedule(self, schedule: IUSchedule) -> IUSchedule:
"""Add a new schedule to the sequence"""
self._schedules.append(schedule)
return schedule
def find_add_schedule(
self, coordinator: "IUCoordinator", controller: "IUController", index: int
) -> IUSchedule:
if index >= len(self._schedules):
return self.add_schedule(IUSchedule(self._hass, index))
else:
return self._schedules[index]
def add_zone(self, zone: IUSequenceZone) -> IUSequenceZone:
"""Add a new zone to the sequence"""
self._zones.append(zone)
return zone
def find_add_zone(
self, coordinator: "IUCoordinator", controller: "IUController", index: int
) -> IUSequenceZone:
if index >= len(self._zones):
return self.add_zone(
IUSequenceZone(self._hass, coordinator, controller, self, index)
)
else:
return self._zones[index]
def zone_ids(self) -> str:
for sequence_zone in self._zones:
for zone_id in sequence_zone.zone_ids:
yield zone_id
def load(self, config: OrderedDict) -> "IUSequence":
"""Load sequence data from the configuration"""
self.clear()
self._name = config.get(CONF_NAME, f"Run {self.index + 1}")
self._delay = wash_td(config.get(CONF_DELAY))
self._duration = wash_td(config.get(CONF_DURATION))
self._repeat = config.get(CONF_REPEAT, 1)
for si, schedule_config in enumerate(config[CONF_SCHEDULES]):
self.find_add_schedule(self._coordinator, self._controller, si).load(
schedule_config
)
for zi, zone_config in enumerate(config[CONF_ZONES]):
self.find_add_zone(self._coordinator, self._controller, zi).load(
zone_config
)
return self
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict[CONF_INDEX] = self._index
dict[CONF_NAME] = self._name
return dict
class IUSequenceRun(IUBase):
"""Irrigation Unlimited sequence run manager class"""
def __init__(self, sequence: IUSequence) -> None:
super().__init__(None)
# Passed parameters
self._sequence = sequence
# Private variables
self._runs: OrderedDict = {}
self._running = False
return
@property
def sequence(self) -> IUSequence:
return self._sequence
@property
def running(self) -> bool:
return self._running
@running.setter
def running(self, value: bool) -> None:
"""Flag sequence is now running"""
self._running = value
return
def add(self, run: IURun, sequence_zone: IUSequenceZone) -> None:
self._runs[run.id] = sequence_zone
return
def run_index(self, run: IURun) -> int:
return list(self._runs.keys()).index(run.id)
def sequence_zone(self, run: IURun) -> IUSequenceZone:
return self._runs.get(run.id, None)
class IUController(IUBase):
"""Irrigation Unlimited Controller (Master) class"""
def __init__(
self, hass: HomeAssistant, coordinator: "IUCoordinator", controller_index: int
) -> None:
# Passed parameters
super().__init__(controller_index)
self._hass = hass
self._coordinator = coordinator # Parent
# Config parameters
self._is_enabled: bool = True
self._name: str = None
self._switch_entity_id: str = None
self._preamble: timedelta = None
self._postamble: timedelta = None
# Private variables
self._initialised: bool = False
self._zones: list[IUZone] = []
self._sequences: list[IUSequence] = []
self._run_queue = IUZoneQueue()
self._master_sensor: Entity = None
self._is_on: bool = False
self._sensor_update_required: bool = False
self._sensor_last_update: datetime = None
self._dirty: bool = True
return
@property
def zones(self) -> "list[IUZone]":
return self._zones
@property
def runs(self) -> IUZoneQueue:
return self._run_queue
@property
def name(self) -> str:
return self._name
@property
def is_on(self) -> bool:
return self._is_on
@property
def is_setup(self) -> bool:
return self._is_setup()
@property
def enabled(self) -> bool:
"""Return true is this zone is on"""
return self._is_enabled
@enabled.setter
def enabled(self, value: bool) -> None:
"""Enable/disable this controller"""
if value != self._is_enabled:
self._is_enabled = value
self._dirty = True
self.request_update()
self.notify_children()
return
@property
def master_sensor(self) -> Entity:
return self._master_sensor
@master_sensor.setter
def master_sensor(self, value: Entity) -> None:
self._master_sensor = value
return
@property
def preamble(self) -> timedelta:
return self._preamble
@property
def status(self) -> str:
return self._status()
@property
def is_paused(self) -> bool:
return self._run_queue.in_sequence
def _status(self) -> str:
"""Return status of the controller"""
if self._initialised:
if self._is_enabled:
if self._is_on:
return STATE_ON
else:
if self._run_queue.in_sequence:
return STATUS_PAUSED
else:
return STATE_OFF
else:
return STATUS_DISABLED
else:
return STATUS_INITIALISING
def _is_setup(self) -> bool:
if not self._initialised:
self._initialised = self._master_sensor is not None
if self._initialised:
for zone in self._zones:
self._initialised = self._initialised and zone.is_setup
return self._initialised
def add_zone(self, zone: IUZone) -> IUZone:
"""Add a new zone to the controller"""
self._zones.append(zone)
return zone
def find_add_zone(
self, coordinator: "IUCoordinator", controller: "IUController", index: int
) -> IUZone:
if index >= len(self._zones):
return self.add_zone(IUZone(self._hass, coordinator, controller, index))
else:
return self._zones[index]
def add_sequence(self, sequence: IUSequence) -> IUSequence:
"""Add a new sequence to the controller"""
self._sequences.append(sequence)
return sequence
def find_sequence(self, index: int) -> IUSequence:
if index >= 0 and index < len(self._sequences):
return self._sequences[index]
else:
return None
def find_add_sequence(
self, coordinator: "IUCoordinator", controller: "IUController", index: int
) -> IUSequence:
if index >= len(self._sequences):
return self.add_sequence(
IUSequence(self._hass, coordinator, controller, index)
)
else:
return self._sequences[index]
def find_zone_by_zone_id(self, zone_id: str) -> IUZone:
for zone in self._zones:
if zone.zone_id == zone_id:
return zone
return None
def clear(self) -> None:
# Don't clear zones
# self._zones.clear()
self._sequences.clear()
self._is_on = False
return
def notify_children(self) -> None:
for zone in self._zones:
zone.request_update()
return
def load(self, config: OrderedDict) -> "IUController":
"""Load config data for the controller"""
self.clear()
self._is_enabled = config.get(CONF_ENABLED, True)
self._name = config.get(CONF_NAME, f"Controller {self.index + 1}")
self._switch_entity_id = config.get(CONF_ENTITY_ID)
self._preamble = wash_td(config.get(CONF_PREAMBLE))
self._postamble = wash_td(config.get(CONF_POSTAMBLE))
all_zones = config.get(CONF_ALL_ZONES_CONFIG)
for zi, zone_config in enumerate(config[CONF_ZONES]):
self.find_add_zone(self._coordinator, self, zi).load(zone_config, all_zones)
if CONF_SEQUENCES in config:
for qi, sequence_config in enumerate(config[CONF_SEQUENCES]):
self.find_add_sequence(self._coordinator, self, qi).load(
sequence_config
)
self._dirty = True
return self
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict[CONF_INDEX] = self._index
dict[CONF_NAME] = self._name
dict[CONF_ZONES] = []
for zone in self._zones:
dict[CONF_ZONES].append(zone.as_dict())
dict[CONF_SEQUENCES] = []
for sequence in self._sequences:
dict[CONF_SEQUENCES].append(sequence.as_dict())
return dict
def muster_sequence(
self,
time: datetime,
sequence: IUSequence,
schedule: IUSchedule,
total_duration: timedelta = None,
) -> int:
def init_run_time(
time: datetime, schedule: IUSchedule, zone: IUZone
) -> datetime:
if schedule is not None:
next_time = zone.runs.find_last_date(schedule.id)
if next_time is not None:
next_time += granularity_time()
else:
next_time = time
next_run = schedule.get_next_run(next_time, zone.runs.last_time(time))
else:
next_run = time + granularity_time()
return next_run
def calc_multiplier(
total_duration: timedelta, sequence: IUSequence, schedule: IUSchedule
) -> float:
"""Calculate the multiplier"""
if total_duration is None:
if schedule is not None and schedule.run_time is not None:
total_duration = schedule.run_time
else:
total_duration = sequence.total_time()
if schedule is not None and sequence.has_adjustment:
total_delay = sequence.total_delay()
total_duration = (
sequence.adjustment.adjust(total_duration - total_delay)
+ total_delay
)
if total_duration < total_delay:
total_duration = total_delay # Make run time 0
return sequence.duration_multiplier(total_duration)
duration_multiplier = calc_multiplier(total_duration, sequence, schedule)
status: int = 0
next_run: datetime = None
sequence_run: IUSequenceRun = None
for i in range(sequence.repeat): # pylint: disable=unused-variable
for sequence_zone in sequence.zones:
duration = round_td(
sequence.zone_duration(sequence_zone) * duration_multiplier
)
duration_max = timedelta(0)
delay = sequence.zone_delay(sequence_zone)
for zone in (
self.find_zone_by_zone_id(zone_id)
for zone_id in sequence_zone.zone_ids
):
if zone is not None and zone.enabled:
# Initialise on first pass
if next_run is None:
next_run = init_run_time(time, schedule, zone)
if next_run is None:
return status # Exit if queue is full
sequence_run = IUSequenceRun(sequence)
# Don't adjust manual run and no adjustment on adjustment
if schedule is not None and not sequence.has_adjustment:
duration_adjusted = zone.adjustment.adjust(duration)
else:
duration_adjusted = duration
zone_run_time = next_run
for j in range( # pylint: disable=unused-variable
sequence_zone.repeat
):
run = zone.runs.add(
zone_run_time,
duration_adjusted,
zone,
schedule,
sequence_run,
)
sequence_run.add(run, sequence_zone)
zone_run_time += run.duration + delay
zone.request_update()
duration_max = max(duration_max, zone_run_time - next_run)
status |= IURunQueue.RQ_STATUS_EXTENDED
next_run += duration_max
return status
def muster(self, time: datetime, force: bool) -> int:
"""Calculate run times for this controller. This is where most of the hard yakka
is done."""
status: int = 0
if self._dirty or force:
self._run_queue.clear_all()
for zone in self._zones:
zone.clear_run_queue()
status |= IURunQueue.RQ_STATUS_CLEARED
zone_status: int = 0
# Handle initialisation
for zone in self._zones:
zone_status |= zone.muster(time)
# Process sequence schedules
for sequence in self._sequences:
for schedule in sequence.schedules:
while True:
sequence_status = self.muster_sequence(
time, sequence, schedule, None
)
zone_status |= sequence_status
if sequence_status & IURunQueue.RQ_STATUS_EXTENDED == 0:
break
# Process zone schedules
for zone in self._zones:
if zone.enabled:
zone_status |= zone.muster_schedules(time)
# Post processing
for zone in self._zones:
zone_status |= zone.runs.update_queue(time)
if (
zone_status
& (
IURunQueue.RQ_STATUS_CLEARED
| IURunQueue.RQ_STATUS_EXTENDED
| IURunQueue.RQ_STATUS_SORTED
| IURunQueue.RQ_STATUS_CANCELED
| IURunQueue.RQ_STATUS_CHANGED
)
!= 0
):
all = bool(
zone_status
& (IURunQueue.RQ_STATUS_CLEARED | IURunQueue.RQ_STATUS_CANCELED)
)
status |= self._run_queue.rebuild_schedule(
time, self._zones, self._preamble, self._postamble, all
)
else:
status |= self._run_queue.update_queue(time)
if status != 0:
self.request_update()
self._dirty = False
return status | zone_status
def check_run(self, time: datetime) -> bool:
"""Check the run status and update sensors. Return flag
if anything has changed."""
zones_changed: list[int] = []
is_running: bool = False
state_changed: bool = False
# Gather zones that have changed status
for zone in self._zones:
if zone.check_run(time, self._is_enabled):
zones_changed.append(zone.index)
# Handle off zones before master
for zone in (self._zones[i] for i in zones_changed):
if not zone.is_on:
zone.call_switch(SERVICE_TURN_OFF)
self._coordinator.status_changed(time, self, zone, zone.is_on)
# Check if master has changed and update
is_running = self._is_enabled and self._run_queue.current_run is not None
state_changed = is_running ^ self._is_on
if state_changed:
self._is_on = not self._is_on
self.request_update()
self.call_switch(SERVICE_TURN_ON if self._is_on else SERVICE_TURN_OFF)
self._coordinator.status_changed(time, self, None, self._is_on)
# Handle on zones after master
for zone in (self._zones[i] for i in zones_changed):
if zone.is_on:
zone.call_switch(SERVICE_TURN_ON)
self._coordinator.status_changed(time, self, zone, zone.is_on)
return state_changed
def request_update(self) -> None:
"""Flag the sensor needs an update. The actual update is done
in update_sensor"""
self._sensor_update_required = True
return
def update_sensor(self, time: datetime) -> None:
"""Lazy sensor updater."""
self._run_queue.update_sensor(time)
for zone in self._zones:
zone.update_sensor(time, False)
if self._master_sensor is not None:
do_update: bool = self._sensor_update_required
# If we are running then update sensor according to refresh_interval
if self._run_queue.current_run is not None:
do_update = (
do_update
or self._sensor_last_update is None
or time - self._sensor_last_update
>= self._coordinator.refresh_interval
)
if do_update:
self._master_sensor.schedule_update_ha_state()
self._sensor_update_required = False
self._sensor_last_update = time
for zone in self._zones:
zone.update_sensor(time, True)
return
def call_switch(self, service_type: str) -> None:
"""Update the linked entity if enabled"""
if self._switch_entity_id is not None:
self._hass.async_create_task(
self._hass.services.async_call(
homeassistant.core.DOMAIN,
service_type,
{ATTR_ENTITY_ID: self._switch_entity_id},
)
)
return
def service_adjust_time(self, data: MappingProxyType, time: datetime) -> None:
sequence_id = data.get(CONF_SEQUENCE_ID, None)
if sequence_id is None:
zl: list[int] = data.get(CONF_ZONES, None)
for zone in self._zones:
if zl is None or zone.index + 1 in zl:
zone.service_adjust_time(data, time)
else:
sequence = self.find_sequence(sequence_id - 1)
if sequence is not None:
if sequence.adjustment.load(data):
for zone_id in sequence.zone_ids():
zone = self.find_zone_by_zone_id(zone_id)
if zone is not None:
zone.runs.clear(time)
return
def service_manual_run(self, data: MappingProxyType, time: datetime) -> None:
sequence_id = data.get(CONF_SEQUENCE_ID, None)
if sequence_id is None:
zl: list[int] = data.get(CONF_ZONES, None)
for zone in self._zones:
if zl is None or zone.index + 1 in zl:
zone.service_manual_run(data, time)
else:
sequence = self.find_sequence(sequence_id - 1)
if sequence is not None:
self.muster_sequence(time, sequence, None, wash_td(data[CONF_TIME]))
return
def service_cancel(self, data: MappingProxyType, time: datetime) -> None:
zl: list[int] = data.get(CONF_ZONES, None)
for zone in self._zones:
if zl is None or zone.index + 1 in zl:
zone.service_cancel(data, time)
return
class IUEvent:
def __init__(self) -> None:
# Private variables
self._time: datetime = None
self._controller: IUController = None
self._zone: IUZone = None
self._state: bool = None
self._crumbs: str = None
return
def __eq__(self, other: "IUEvent") -> bool:
return (
self._time == other._time
and self._controller == other.controller
and self._zone == other.zone
and self._state == other.state
)
@property
def time(self) -> datetime:
return self._time
@property
def controller(self) -> IUController:
return self._controller
@property
def zone(self) -> IUZone:
return self._zone
@property
def state(self) -> bool:
return self._state
@property
def time_local(self) -> str:
return self.dt2lstr()
@property
def zone_name(self) -> str:
if self._zone == 0:
return "Master"
else:
return f"Zone {self._zone}"
def load(self, config: OrderedDict) -> "IUEvent":
self._time: datetime = wash_dt(dt.as_utc(config["t"]))
self._controller: int = config["c"]
self._zone: int = config["z"]
self._state: bool = config["s"]
return self
def load2(
self, time: datetime, controller: int, zone: int, state: bool, crumbs: str
):
self._time = time
self._controller = controller
self._zone = zone
self._state = state
self._crumbs = crumbs
return self
def dt2lstr(self) -> str:
"""Format the passed datetime into local time"""
return datetime.strftime(dt.as_local(self._time), "%Y-%m-%d %H:%M:%S")
def as_str(self) -> str:
return f"{{t: "{self.time_local}", c: {self._controller}, z: {self._zone}, s: {1 if self._state else 0}}}"
def as_dict(self):
return {
"t": self._time,
"c": self._controller,
"z": self._zone,
"s": self._state,
}
def write_log(self) -> None:
"""Output the status of master or zone"""
zm = f"{self.zone_name} is {STATE_ON if self._state else STATE_OFF}"
if self._zone != 0 and self._state:
zm = zm + f" [{self._crumbs}]"
_LOGGER.debug(
f"[{self.time_local}] Controller {self._controller} %s",
zm,
)
return
class IUTest(IUBase):
def __init__(self, test_index: int, speed: float) -> None:
# Passed parameters
super().__init__(test_index)
self._speed = speed
# Config parameters
self._name: str = None
self._start: datetime = None
self._end: datetime = None
self._results: list[IUEvent] = []
# Private variables
self._current_result: int = 0
self._events: int = 0
self._checks: int = 0
self._errors: int = 0
self._perf_mon: int = 0
self._delta: timedelta = None
self._test_time: float = 0
return
@property
def name(self) -> str:
return self._name
@property
def start(self) -> datetime:
return self._start
@property
def events(self) -> int:
return self._events
@property
def checks(self) -> int:
return self._checks
@property
def errors(self) -> int:
return self._errors
@property
def test_time(self) -> float:
return self._test_time
@property
def virtual_duration(self) -> timedelta:
return (self._end - self._start) / self._speed
@property
def current_result(self) -> int:
return self._current_result
@property
def total_results(self) -> int:
return len(self._results)
def is_finished(self, time) -> bool:
return self.virtual_time(time) > self._end
def next_result(self) -> IUEvent:
if self._current_result < len(self._results):
r = self._results[self._current_result]
self._current_result += 1
return r
else:
return None
def check_result(self, result: IUEvent, event: IUEvent) -> bool:
self._events += 1
if result is not None:
self._checks += 1
if result != event:
self._errors += 1
return False
else:
return False
return True
def clear(self) -> None:
self._results.clear()
return
def load(self, config: OrderedDict):
self.clear()
self._start = wash_dt(dt.as_utc(config[CONF_START]))
self._end = wash_dt(dt.as_utc(config[CONF_END]))
self._name = config.get(CONF_NAME, None)
if CONF_RESULTS in config:
for r in config[CONF_RESULTS]:
self._results.append(IUEvent().load(r))
return self
def begin(self, time: datetime) -> None:
self._delta = time - self._start
self._perf_mon = tm.perf_counter()
self._current_result = 0
self._events = 0
self._checks = 0
self._errors = 0
self._test_time = 0
return
def end(self) -> None:
self._test_time = tm.perf_counter() - self._perf_mon
return
def virtual_time(self, time: datetime) -> datetime:
"""Return the virtual clock. For testing we can speed
up time. This routine will return a virtual time based
on the real time and the duration from start. It is in
effect a test warp speed"""
vt: datetime = time - self._delta
actual_duration: float = (vt - self._start).total_seconds()
virtual_duration: float = actual_duration * self._speed
return self._start + timedelta(seconds=virtual_duration)
class IUTester:
"""Irrigation Unlimited testing class"""
def __init__(self) -> None:
self._tests: list[IUTest] = []
self.load(None)
return
@property
def enabled(self) -> bool:
return self._enabled
@property
def speed(self) -> float:
return self._speed
@property
def is_testing(self) -> bool:
return self._is_testing()
@property
def tests(self) -> "list[IUTest]":
return self._tests
@property
def current_test(self) -> IUTest:
if self._running_test is not None and self._running_test < len(self._tests):
return self._tests[self._running_test]
else:
return None
@property
def last_test(self) -> IUTest:
if self._last_test is not None and self._last_test < len(self._tests):
return self._tests[self._last_test]
else:
return None
@property
def total_events(self) -> int:
result: int = 0
for test in self._tests:
result += test.events
return result
@property
def total_checks(self) -> int:
result: int = 0
for test in self._tests:
result += test.checks
return result
@property
def total_errors(self) -> int:
result: int = 0
for test in self._tests:
result += test.errors
return result
@property
def total_time(self) -> float:
result: float = 0
for test in self._tests:
result += test.test_time
return result
@property
def total_tests(self) -> int:
return len(self._tests)
@property
def total_virtual_duration(self) -> timedelta:
result = timedelta(0)
for test in self._tests:
result += test.virtual_duration
return result
@property
def total_results(self) -> int:
result: int = 0
for test in self._tests:
result += test.total_results
return result
def start_test(self, test_no: int, time: datetime) -> IUTest:
if test_no > 0 and test_no <= len(self._tests):
self._running_test = test_no - 1 # 0-based
ct = self._tests[self._running_test]
ct.begin(time)
if self._show_log:
_LOGGER.info(
"Running test %d from %s to %s",
self._running_test + 1,
dt.as_local(ct._start).strftime("%c"),
dt.as_local(ct._end).strftime("%c"),
)
self._test_initialised = False
else:
self._running_test = None
return self.current_test
def end_test(self, time: datetime) -> None:
ct = self.current_test
if ct is not None:
ct.end()
if self._show_log:
_LOGGER.info("Test %d completed", self._running_test + 1)
self._last_test = self._running_test
self._running_test = None
return
def next_test(self, time: datetime) -> IUTest:
current = self._running_test # This is 0-based
self.end_test(time)
return self.start_test(current + 2, time) # This takes 1-based
def _is_testing(self) -> bool:
return self._enabled and self._running_test is not None
def clear(self) -> None:
# Private variables
self._tests.clear()
self._test_initialised = False
self._running_test: int = None
self._last_test: int = None
self._autoplay_initialised: bool = False
return
def load(self, config: OrderedDict) -> "IUTester":
"""Load config data for the tester"""
# Config parameters
self.clear()
if config is None:
config = {}
self._enabled: bool = config.get(CONF_ENABLED, False)
self._speed: float = config.get(CONF_SPEED, DEFAULT_TEST_SPEED)
self._output_events: bool = config.get(CONF_OUTPUT_EVENTS, False)
self._show_log: bool = config.get(CONF_SHOW_LOG, True)
self._autoplay: bool = config.get(CONF_AUTOPLAY, True)
if CONF_TIMES in config:
for ti, test in enumerate(config[CONF_TIMES]):
self._tests.append(IUTest(ti, self._speed).load(test))
return self
def poll_test(self, time: datetime, poll_func) -> None:
if self._autoplay and not self._autoplay_initialised:
self.start_test(1, time)
self._autoplay_initialised = True
ct = self.current_test
if ct is not None:
if not self._test_initialised:
poll_func(ct._start, True)
self._test_initialised = True
elif ct.is_finished(time): # End of current test
if self._autoplay:
ct = self.next_test(time)
if ct is not None:
poll_func(ct.start, True)
else: # All tests finished
if self._show_log:
_LOGGER.info(
"All tests completed (Idle); checks: %d, errors: %d",
self.total_checks,
self.total_errors,
)
poll_func(time, True)
else: # End single test
self.end_test(time)
poll_func(time, True)
else: # Continue existing test
poll_func(ct.virtual_time(time))
else: # Out of tests to run
poll_func(time)
return
def entity_state_changed(self, event: IUEvent) -> None:
"""Called when an entity has changed state"""
def check_state(event: IUEvent):
"""Check the event against the next result"""
ct = self.current_test
if ct is not None:
r = ct.next_result()
if not ct.check_result(r, event):
if self._show_log:
_LOGGER.error(
"(%d) Event <> result %s <> %s",
ct.current_result,
event.as_str(),
r.as_str() if r is not None else "None",
)
if self._show_log:
event.write_log()
if self._is_testing():
if self._output_events:
print(event.as_str())
check_state(event)
return
class IUCoordinator:
"""Irrigation Unimited Coordinator class"""
def __init__(self, hass: HomeAssistant) -> None:
# Passed parameters
self._hass = hass
# Config parameters
self._refresh_interval: timedelta = None
# Private variables
self._controllers: list[IUController] = []
self._is_on: bool = False
self._sensor_update_required: bool = False
self._sensor_last_update: datetime = None
self._dirty: bool = True
self._component: Entity = None
self._initialised: bool = False
self._last_tick: datetime = None
self._last_muster: datetime = None
self._muster_required: bool = False
self._remove_listener: CALLBACK_TYPE = None
self._tester = IUTester()
return
@property
def controllers(self) -> "list[IUController]":
return self._controllers
@property
def tester(self) -> IUTester:
return self._tester
@property
def is_setup(self) -> bool:
return self._is_setup()
@property
def component(self) -> Entity:
return self._component
@component.setter
def component(self, value: Entity) -> None:
self._component = value
return
@property
def refresh_interval(self) -> timedelta:
return self._refresh_interval
def _is_setup(self) -> bool:
"""Wait for sensors to be setup"""
all_setup: bool = self._hass.is_running and self._component is not None
for controller in self._controllers:
all_setup = all_setup and controller.is_setup
return all_setup
def add(self, controller: IUController) -> IUController:
"""Add a new controller to the system"""
self._controllers.append(controller)
return controller
def find_add(self, coordinator: "IUCoordinator", index: int) -> IUController:
if index >= len(self._controllers):
return self.add(IUController(self._hass, coordinator, index))
else:
return self._controllers[index]
def clear(self) -> None:
# Don't clear controllers
# self._controllers.clear()
self._is_on: bool = False
return
def load(self, config: OrderedDict) -> "IUCoordinator":
"""Load config data for the system"""
self.clear()
global SYSTEM_GRANULARITY
SYSTEM_GRANULARITY = config.get(CONF_GRANULARITY, DEFAULT_GRANULATITY)
self._refresh_interval = timedelta(
seconds=config.get(CONF_REFRESH_INTERVAL, DEFAULT_REFRESH_INTERVAL)
)
for ci, controller_config in enumerate(config[CONF_CONTROLLERS]):
self.find_add(self, ci).load(controller_config)
self._tester = IUTester().load(config.get(CONF_TESTING))
self._dirty = True
self._muster_required = True
return self
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict[CONF_CONTROLLERS] = []
for controller in self._controllers:
dict[CONF_CONTROLLERS].append(controller.as_dict())
return dict
def muster(self, time: datetime, force: bool) -> int:
"""Calculate run times for system"""
status: int = 0
for controller in self._controllers:
status |= controller.muster(time, force)
self._dirty = False
return status
def check_run(self, time: datetime) -> bool:
"""Update run status"""
is_running: bool = False
for controller in self._controllers:
is_running = is_running or controller.check_run(time)
return is_running
def request_update(self) -> None:
"""Flag the sensor needs an update. The actual update is done
in update_sensor"""
self._sensor_update_required = True
return
def update_sensor(self, time: datetime) -> None:
"""Update home assistant sensors if required"""
for controller in self._controllers:
controller.update_sensor(time)
if self._component is not None and self._sensor_update_required:
self._component.schedule_update_ha_state()
self._sensor_update_required = False
self._sensor_last_update = time
return
def poll(self, time: datetime, force: bool = False) -> None:
"""Poll the system for changes, updates and refreshes"""
wtime: datetime = wash_dt(time)
if (wtime != self._last_muster) or self._muster_required:
if self.muster(wtime, force) != 0:
self.check_run(wtime)
self._muster_required = False
self._last_muster = wtime
self.update_sensor(wash_dt(time, 1))
return
def poll_main(self, time: datetime, force: bool = False) -> None:
if self._tester.enabled:
self._tester.poll_test(time, self.poll)
else:
self.poll(time, force)
return
def timer(self, time: datetime) -> None:
self._last_tick = time
if self._initialised:
self.poll_main(time)
else:
self._initialised = self.is_setup
if self._initialised:
self.request_update()
self.poll_main(time)
return
async def _async_timer(self, time: datetime) -> None:
"""Timer callback"""
self.timer(time)
return
def track_interval(self) -> timedelta:
track_time = SYSTEM_GRANULARITY / self._tester.speed
track_time *= 0.95 # Run clock slightly ahead of required to avoid skipping
return min(timedelta(seconds=track_time), self._refresh_interval)
def start(self) -> None:
"""Start the system up"""
self.stop()
self._remove_listener = async_track_time_interval(
self._hass, self._async_timer, self.track_interval()
)
return
def stop(self) -> None:
if self._remove_listener is not None:
self._remove_listener()
self._remove_listener = None
return
def register_entity(
self, controller: IUController, zone: IUZone, entity: Entity
) -> None:
if controller is None:
self._component = entity
elif zone is None:
controller.master_sensor = entity
else:
zone.zone_sensor = entity
return
def deregister_entity(
self, controller: IUController, zone: IUZone, entity: Entity
) -> None:
if controller is None:
self._component = None
elif zone is None:
controller.master_sensor = None
else:
zone.zone_sensor = None
return
def service_time(self) -> datetime:
"""Return a time midway between last and next future tick"""
if self._last_tick is not None:
return self._last_tick + self.track_interval() / 2
else:
return dt.utcnow()
def service_call(
self,
service: str,
controller: IUController,
zone: IUZone,
data: MappingProxyType,
) -> None:
"""Entry point for all service calls."""
time = self.service_time()
if self._tester.is_testing:
time = self._tester.current_test.virtual_time(time)
time = wash_dt(time)
if service == SERVICE_ENABLE:
if zone is not None:
zone.enabled = True
else:
controller.enabled = True
elif service == SERVICE_DISABLE:
if zone is not None:
zone.enabled = False
else:
controller.enabled = False
elif service == SERVICE_TOGGLE:
if zone is not None:
zone.enabled = not zone.enabled
else:
controller.enabled = not controller.enabled
elif service == SERVICE_CANCEL:
if zone is not None:
zone.service_cancel(data, time)
else:
controller.service_cancel(data, time)
elif service == SERVICE_TIME_ADJUST:
if zone is not None:
zone.service_adjust_time(data, time)
else:
controller.service_adjust_time(data, time)
elif service == SERVICE_MANUAL_RUN:
if zone is not None:
zone.service_manual_run(data, time)
else:
controller.service_manual_run(data, time)
else:
return
self._muster_required = True
return
def start_test(self, test_no: int) -> datetime:
self._last_tick = None
next_time = dt.utcnow()
self._tester.start_test(test_no, next_time)
self.timer(next_time)
return next_time
def status_changed(
self, time: datetime, controller: IUController, zone: IUZone, state: bool
) -> None:
crumbs: str = ""
if zone is not None:
zone_id = zone.index + 1
if state == True:
crumbs = zone.runs.current_run.crumbs
else:
zone_id = 0
e = IUEvent().load2(time, controller.index + 1, zone_id, state, crumbs)
self._tester.entity_state_changed(e)
return
| """Irrigation Unlimited Coordinator and sub classes"""
from datetime import datetime, time, timedelta
from types import MappingProxyType
from typing import OrderedDict
import homeassistant
from homeassistant.core import HomeAssistant, CALLBACK_TYPE
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_time_interval
import homeassistant.helpers.sun as sun
import homeassistant.util.dt as dt
import logging
import uuid
import time as tm
from homeassistant.const import (
CONF_AFTER,
CONF_BEFORE,
CONF_DELAY,
CONF_ENTITY_ID,
CONF_NAME,
CONF_REPEAT,
CONF_WEEKDAY,
CONF_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
WEEKDAYS,
ATTR_ENTITY_ID,
)
from .const import (
CONF_ACTUAL,
CONF_ALL_ZONES_CONFIG,
CONF_DAY,
CONF_DECREASE,
CONF_INCREASE,
CONF_INDEX,
CONF_OUTPUT_EVENTS,
CONF_PERCENTAGE,
CONF_REFRESH_INTERVAL,
CONF_RESET,
CONF_RESULTS,
CONF_SEQUENCES,
CONF_SEQUENCE_ID,
CONF_SHOW_LOG,
CONF_AUTOPLAY,
DEFAULT_GRANULATITY,
DEFAULT_REFRESH_INTERVAL,
DEFAULT_TEST_SPEED,
CONF_DURATION,
CONF_ENABLED,
CONF_GRANULARITY,
CONF_TIME,
CONF_SUN,
CONF_PREAMBLE,
CONF_POSTAMBLE,
CONF_TESTING,
CONF_SPEED,
CONF_TIMES,
CONF_START,
CONF_END,
CONF_CONTROLLERS,
CONF_SCHEDULES,
CONF_ZONES,
CONF_MINIMUM,
CONF_MAXIMUM,
CONF_MONTH,
MONTHS,
CONF_ODD,
CONF_EVEN,
CONF_SHOW,
CONF_CONFIG,
CONF_TIMELINE,
CONF_ZONE_ID,
CONF_FUTURE_SPAN,
SERVICE_CANCEL,
SERVICE_DISABLE,
SERVICE_ENABLE,
SERVICE_TOGGLE,
SERVICE_MANUAL_RUN,
SERVICE_TIME_ADJUST,
STATUS_BLOCKED,
STATUS_PAUSED,
STATUS_DISABLED,
STATUS_INITIALISING,
)
_LOGGER: logging.Logger = logging.getLogger(__package__)
# Useful time manipulation routine
def time_to_timedelta(offset: time) -> timedelta:
"""Create a timedelta from a time object"""
return datetime.combine(datetime.min, offset) - datetime.min
# These routines truncate dates, times and deltas to the internal
# granularity. This should be no more than 1 minute and realisticly
# no less than 1 second i.e. 1 >= GRANULARITY <= 60
# The current boundaries are whole minutes (60 seconds).
SYSTEM_GRANULARITY: int = DEFAULT_GRANULATITY # Granularity in seconds
def reset_granularity() -> None:
global SYSTEM_GRANULARITY
SYSTEM_GRANULARITY = DEFAULT_GRANULATITY
return
def granularity_time() -> timedelta:
"""Return the system granularity as a timedelta"""
return timedelta(seconds=SYSTEM_GRANULARITY)
def wash_td(delta: timedelta, granularity: int = None) -> timedelta:
"""Truncate the supplied timedelta to internal boundaries"""
if delta is not None:
if granularity is None:
granularity = SYSTEM_GRANULARITY
whole_seconds = int(delta.total_seconds())
rounded_seconds = int(whole_seconds / granularity) * granularity
return timedelta(seconds=rounded_seconds)
else:
return None
def wash_dt(date: datetime, granularity: int = None) -> datetime:
"""Truncate the supplied datetime to internal boundaries"""
if date is not None:
if granularity is None:
granularity = SYSTEM_GRANULARITY
rounded_seconds = int(date.second / granularity) * granularity
d = date.replace(second=rounded_seconds, microsecond=0)
return d
else:
return None
def wash_t(time: time, granularity: int = None) -> time:
"""Truncate the supplied time to internal boundaries"""
if time is not None:
if granularity is None:
granularity = SYSTEM_GRANULARITY
utc = dt.utcnow()
d = utc.combine(utc.date(), time)
rounded_seconds = int(d.second / granularity) * granularity
t = d.replace(second=rounded_seconds, microsecond=0)
return t.timetz()
else:
return None
def round_td(delta: timedelta, granularity: int = None) -> timedelta:
"""Round the supplied timedelta to internal boundaries"""
if delta is not None:
if granularity is None:
granularity = SYSTEM_GRANULARITY
rounded_seconds = (
int((delta.total_seconds() + granularity / 2) / granularity) * granularity
)
return timedelta(seconds=rounded_seconds)
else:
return None
class IUBase:
"""Irrigation Unlimited base class"""
def __init__(self, index: int) -> None:
# Private variables
self._id: int = uuid.uuid4().int
self._index: int = index
return
def __eq__(self, other) -> bool:
if isinstance(other, IUBase):
return self.id == other.id
else:
return False
@property
def id(self) -> str:
"""Return our unique id"""
return self._id
@property
def index(self) -> int:
return self._index
class IUAdjustment:
"""Irrigation Unlimited class to handle run time adjustment"""
def __init__(self) -> None:
self.clear()
return
def __str__(self) -> str:
"""Return the adjustment as a string notation"""
if self._method is None:
s = "None"
elif self._method == CONF_ACTUAL:
s = f"={self._time_adjustment}"
elif self._method == CONF_PERCENTAGE:
s = f"%{self._time_adjustment}"
elif self._method == CONF_INCREASE:
s = f"+{self._time_adjustment}"
elif self._method == CONF_DECREASE:
s = f"-{self._time_adjustment}"
else:
s = str(self._time_adjustment)
return s
@property
def has_adjustment(self) -> bool:
return self._method != None
def clear(self) -> None:
self._method: str = None
self._time_adjustment = None
self._minimum: timedelta = None
self._maximum: timedelta = None
return
def load(self, data: MappingProxyType) -> bool:
"""Read the adjustment configuration. Return true if anything has changed"""
# Save current settings
old_method = self._method
old_time_adjustment = self._time_adjustment
old_minimum = self._minimum
old_maximum = self._maximum
if CONF_ACTUAL in data:
self._method = CONF_ACTUAL
self._time_adjustment = wash_td(data.get(CONF_ACTUAL))
elif CONF_PERCENTAGE in data:
self._method = CONF_PERCENTAGE
self._time_adjustment = data.get(CONF_PERCENTAGE)
elif CONF_INCREASE in data:
self._method = CONF_INCREASE
self._time_adjustment = wash_td(data.get(CONF_INCREASE))
elif CONF_DECREASE in data:
self._method = CONF_DECREASE
self._time_adjustment = wash_td(data.get(CONF_DECREASE))
elif CONF_RESET in data:
self._method = None
self._time_adjustment = None
self._minimum = wash_td(data.get(CONF_MINIMUM, None))
if self._minimum is not None:
self._minimum = max(self._minimum, granularity_time()) # Set floor
self._maximum = wash_td(data.get(CONF_MAXIMUM, None))
return (
self._method != old_method
or self._time_adjustment != old_time_adjustment
or self._minimum != old_minimum
or self._maximum != old_maximum
)
def adjust(self, time: timedelta) -> timedelta:
"""Return the adjusted time"""
new_time: timedelta
if self._method is None:
new_time = time
elif self._method == CONF_ACTUAL:
new_time = self._time_adjustment
elif self._method == CONF_PERCENTAGE:
new_time = round_td(time * self._time_adjustment / 100)
elif self._method == CONF_INCREASE:
new_time = time + self._time_adjustment
elif self._method == CONF_DECREASE:
new_time = time - self._time_adjustment
else:
new_time = time
if self._minimum is not None:
new_time = max(new_time, self._minimum)
if self._maximum is not None:
new_time = min(new_time, self._maximum)
return new_time
class IUSchedule(IUBase):
"""Irrigation Unlimited Schedule class. Schedules are not actual
points in time but describe a future event i.e. next Monday"""
def __init__(
self,
hass: HomeAssistant,
schedule_index: int,
) -> None:
super().__init__(schedule_index)
# Passed parameters
self._hass = hass
# Config parameters
self._time = None
self._duration: timedelta = None
self._name: str = None
self._weekdays: list[int] = None
self._months: list[int] = None
# Private variables
self._dirty: bool = True
return
@property
def name(self) -> str:
"""Return the friendly name of this schedule"""
return self._name
@property
def is_setup(self) -> bool:
"""Return true is this schedule is setup"""
return True
@property
def run_time(self) -> timedelta:
"""Return the duration"""
return self._duration
def clear(self) -> None:
"""Reset this schedule"""
self._dirty = True
return
def load(self, config: OrderedDict) -> "IUSchedule":
"""Load schedule data from config"""
self.clear()
self._time = config[CONF_TIME]
self._duration = wash_td(config.get(CONF_DURATION, None))
self._name = config.get(CONF_NAME, f"Schedule {self.index + 1}")
if CONF_WEEKDAY in config:
self._weekdays = []
for i in config[CONF_WEEKDAY]:
self._weekdays.append(WEEKDAYS.index(i))
else:
self._weekdays = None
if CONF_MONTH in config:
self._months = []
for i in config[CONF_MONTH]:
self._months.append(MONTHS.index(i) + 1)
else:
self._months = None
self._days = config.get(CONF_DAY, None)
return self
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict[CONF_TIME] = self._time
dict[CONF_DURATION] = self._duration
dict[CONF_NAME] = self._name
if self._weekdays is not None:
dict[CONF_WEEKDAY] = []
for item in self._weekdays:
dict[CONF_WEEKDAY].append(WEEKDAYS[item])
if self._months is not None:
dict[CONF_MONTH] = []
for item in self._months:
dict[CONF_MONTH].append(MONTHS[item - 1])
if self._days is not None:
dict[CONF_DAY] = self._days
return dict
def get_next_run(self, atime: datetime, ftime: datetime) -> datetime:
"""
Determine the next start time. Date processing in this routine
is done in local time and returned as UTC
"""
local_time = dt.as_local(atime)
final_time = dt.as_local(ftime)
next_run: datetime = None
while True:
if next_run is None:
next_run = local_time # Initialise on first pass
else:
next_run += timedelta(days=1) # Advance to next day
# Sanity check. Note: Astral events like sunrise might take months i.e. Antarctica winter
if next_run > final_time:
return None
# DOW filter
if self._weekdays is not None and next_run.weekday() not in self._weekdays:
continue
# Month filter
if self._months is not None and next_run.month not in self._months:
continue
# Day filter
if self._days is not None:
if self._days == CONF_ODD:
if next_run.day % 2 == 0:
continue
elif self._days == CONF_EVEN:
if next_run.day % 2 != 0:
continue
elif next_run.day not in self._days:
continue
if isinstance(self._time, time):
next_run = datetime.combine(
next_run.date(), self._time, next_run.tzinfo
)
elif isinstance(self._time, dict) and CONF_SUN in self._time:
se = sun.get_astral_event_date(
self._hass, self._time[CONF_SUN], next_run
)
if se is None:
continue # Astral event did not occur today
next_run = dt.as_local(se)
if CONF_AFTER in self._time:
next_run += self._time[CONF_AFTER]
if CONF_BEFORE in self._time:
next_run -= self._time[CONF_BEFORE]
else: # Some weird error happened
return None
next_run = wash_dt(next_run)
if next_run >= local_time:
break
return dt.as_utc(next_run)
class IURun(IUBase):
"""Irrigation Unlimited Run class. A run is an actual point
in time. If schedule is None then it is a manual run.
"""
def __init__(
self,
start_time: datetime,
duration: timedelta,
zone: "IUZone",
schedule: "IUSchedule",
sequence_run: "IUSequenceRun",
) -> None:
super().__init__(None)
# Passed parameters
self._start_time: datetime = start_time
self._duration: timedelta = duration
self._zone = zone
self._schedule = schedule
self._sequence_run = sequence_run
# Private variables
self._end_time: datetime = self._start_time + self._duration
self._remaining_time: timedelta = self._end_time - self._start_time
self._percent_complete: int = 0
return
@property
def start_time(self) -> datetime:
return self._start_time
@property
def duration(self) -> timedelta:
return self._duration
@property
def zone(self) -> "IUSchedule":
return self._zone
@property
def schedule(self) -> "IUSchedule":
"""Return the schedule"""
return self._schedule
@property
def end_time(self) -> datetime:
return self._end_time
@property
def time_remaining(self) -> timedelta:
return self._remaining_time
@property
def percent_complete(self) -> float:
return self._percent_complete
@property
def is_sequence(self) -> bool:
return self._sequence_run is not None
@property
def sequence_run(self) -> "IUSequenceRun":
return self._sequence_run
@property
def sequence(self) -> "IUSequence":
if self.is_sequence:
return self._sequence_run.sequence
else:
return None
@property
def sequence_zone(self) -> "IUSequenceZone":
if self.is_sequence:
return self._sequence_run.sequence_zone(self)
else:
return None
@property
def sequence_id(self) -> int:
if self.is_sequence:
return self._sequence_run._id
else:
return None
@property
def sequence_running(self) -> bool:
return self.is_sequence and self._sequence_run.running
@sequence_running.setter
def sequence_running(self, value: bool) -> None:
"""Flag sequence is now running"""
if self.is_sequence:
self.sequence_run.running = value
return
@property
def crumbs(self) -> str:
return self._crumbs()
def _crumbs(self) -> str:
def get_index(object: IUBase) -> int:
if object is not None:
return object.index + 1
else:
return 0
if self.is_sequence:
sidx = self.sequence_run.run_index(self) + 1
else:
sidx = 0
return f"{get_index(self._zone)}.{get_index(self._schedule)}.{get_index(self.sequence)}.{get_index(self.sequence_zone)}.{sidx}"
def is_manual(self) -> bool:
"""Check if this is a manual run"""
return self._schedule is None
def is_running(self, time: datetime) -> bool:
"""Check if this schedule is running"""
return (time >= self._start_time) and (time < self._end_time)
def is_expired(self, time: datetime) -> bool:
"""Check if this schedule is expired"""
return time >= self._end_time
def is_future(self, time: datetime) -> bool:
"""Check schedule is in the future"""
return self._start_time > time
def is_valid(self, time: datetime) -> bool:
"""Return true if run is valid. Should be
running or in the future.
"""
return self.is_running(time) and not self.is_future(time)
def sequence_start(self, time: datetime) -> bool:
"""Check if sequence is about to start but not yet flagged"""
result = (
self.is_sequence
and self.is_running(time)
and not self._sequence_run.running
)
if result:
self._sequence_run.running = True
return result
def update_time_remaining(self, time: datetime) -> bool:
if self.is_running(time):
self._remaining_time = self._end_time - time
total_duration: timedelta = self._end_time - self._start_time
time_elapsed: timedelta = time - self._start_time
self._percent_complete = int((time_elapsed / total_duration) * 100)
return True
else:
return False
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict["start"] = self._start_time
dict["end"] = self._end_time
return dict
class IURunQueue(list):
DAYS_SPAN: int = 3
RQ_STATUS_CLEARED: int = 0x01
RQ_STATUS_EXTENDED: int = 0x02
RQ_STATUS_REDUCED: int = 0x04
RQ_STATUS_SORTED: int = 0x08
RQ_STATUS_UPDATED: int = 0x10
RQ_STATUS_CANCELED: int = 0x20
RQ_STATUS_CHANGED: int = 0x40
def __init__(self) -> None:
# Private variables
self._current_run: IURun = None
self._next_run: IURun = None
self._sorted: bool = False
self._cancel_request: bool = False
self._future_span = wash_td(timedelta(days=self.DAYS_SPAN))
return
@property
def current_run(self) -> IURun:
return self._current_run
@property
def next_run(self) -> IURun:
return self._next_run
@property
def in_sequence(self) -> bool:
return self._in_sequence()
def _in_sequence(self) -> bool:
for run in self:
if run.sequence_running:
return True
return False
def add(
self,
start_time: datetime,
duration: timedelta,
zone: "IUZone",
schedule: "IUSchedule",
sequence_run: "IUSequenceRun",
) -> IURun:
run = IURun(start_time, duration, zone, schedule, sequence_run)
self.append(run)
self._sorted = False
return run
def cancel(self) -> None:
"""Flag the current run to be cancelled"""
self._cancel_request = True
return
def clear_all(self) -> bool:
modified: bool = False
if len(self) > 0:
self._current_run = None
super().clear()
modified = True
return modified
def clear(self, time: datetime) -> bool:
"""Clear out the queue except for manual or running schedules"""
modified: bool = False
if len(self) > 0:
i = len(self) - 1
while i >= 0:
item: IURun = self[i]
if not (
item.is_running(time) or item.is_manual() or item.sequence_running
):
self.pop(i)
modified = True
i -= 1
if modified:
self._next_run = None
self._sorted = True
return modified
def find_last_index(self, id: int) -> int:
"""Return the index of the run that finishes last in the queue.
This routine does not require the list to be sorted."""
result: int = None
last_time: datetime = None
for i, run in enumerate(self):
if run.schedule is not None and run.schedule.id == id:
if last_time is None or run.end_time > last_time:
last_time = run.end_time
result = i
return result
def find_last_run(self, id: int) -> IURun:
i = self.find_last_index(id)
if i is not None:
return self[i]
else:
return None
def find_last_date(self, id: int) -> datetime:
"""Find the last time in the queue for the supplied id"""
run = self.find_last_run(id)
if run is not None:
return run.end_time
else:
return None
def find_manual(self) -> IURun:
for run in self:
if run.is_manual():
return run
return None
def last_time(self, time: datetime) -> datetime:
return time + self._future_span
def load(self, config: OrderedDict, all_zones: OrderedDict):
if all_zones is not None:
self._future_span = wash_td(
all_zones.get(CONF_FUTURE_SPAN, self._future_span)
)
self._future_span = wash_td(config.get(CONF_FUTURE_SPAN, self._future_span))
self._future_span = max(self._future_span, timedelta(hours=12))
return self
def sorter(self, run: IURun) -> datetime:
"""Sort call back routine. Items are sorted
by start_time."""
if run.is_manual():
return datetime.min.replace(tzinfo=dt.UTC) # Always put manual run at head
else:
return run.start_time
def sort(self) -> bool:
"""Sort the run queue."""
modified: bool = False
if not self._sorted:
super().sort(key=self.sorter)
self._current_run = None
self._next_run = None
self._sorted = True
modified = True
return modified
def remove_expired(self, time: datetime) -> bool:
"""Remove any expired runs from the queue"""
modified: bool = False
i = len(self) - 1
while i >= 0:
run: IURun = self[i]
if run.is_expired(time):
self._current_run = None
self._next_run = None
self.pop(i)
modified = True
i -= 1
return modified
def remove_current(self) -> bool:
"""Remove the current run or upcoming manual run"""
modified: bool = False
if self._current_run is not None or (
self._next_run is not None and self._next_run.is_manual()
):
if len(self) > 0:
self.pop(0)
self._current_run = None
self._next_run = None
modified = True
return modified
def update_queue(self, time: datetime) -> int:
"""Update the run queue. Sort the queue, remove expired runs
and set current and next runs.
Returns a bit field of changes to queue.
"""
status: int = 0
if self.sort():
status |= self.RQ_STATUS_SORTED
if self._cancel_request:
if self.remove_current():
status |= self.RQ_STATUS_CANCELED
self._cancel_request = False
if self.remove_expired(time):
status |= self.RQ_STATUS_REDUCED
# Try to find a running schedule
if self._current_run is None and len(self) > 0 and self[0].is_running(time):
self._current_run = self[0]
self._next_run = None
status |= self.RQ_STATUS_UPDATED
# Try to find the next schedule
if self._next_run is None:
if self._current_run is None:
if len(self) >= 1:
self._next_run = self[0]
status |= self.RQ_STATUS_UPDATED
else:
if len(self) >= 2:
self._next_run = self[1]
status |= self.RQ_STATUS_UPDATED
for run in self:
if run.sequence_start(time):
status |= self.RQ_STATUS_CHANGED
return status
def update_sensor(self, time: datetime) -> bool:
if self._current_run is not None:
return self._current_run.update_time_remaining(time)
else:
return False
def as_list(self) -> list:
l = []
for run in self:
l.append(run.as_dict())
return l
class IUScheduleQueue(IURunQueue):
"""Class to hold the upcoming schedules to run"""
def __init__(self) -> None:
super().__init__()
# Config variables
self._minimum: timedelta = None
self._maximum: timedelta = None
return
def add(
self,
start_time: datetime,
duration: timedelta,
zone: "IUZone",
schedule: "IUSchedule",
sequence_run: "IUSequenceRun",
) -> IURun:
if self._minimum is not None:
duration = max(duration, self._minimum)
if self._maximum is not None:
duration = min(duration, self._maximum)
return super().add(start_time, duration, zone, schedule, sequence_run)
def add_schedule(
self,
zone: "IUZone",
schedule: IUSchedule,
start_time: datetime,
adjustment: IUAdjustment,
) -> IURun:
"""Add a new schedule run to the queue"""
duration = schedule.run_time
if adjustment is not None:
duration = adjustment.adjust(duration)
return self.add(start_time, duration, zone, schedule, None)
def add_manual(
self, start_time: datetime, duration: timedelta, zone: "IUZone"
) -> IURun:
"""Add a manual run to the queue. Cancel any existing
manual or running schedule"""
if self._current_run is not None:
self.pop(0)
# Remove any existing manual schedules
while True:
run = self.find_manual()
if run is None:
break
else:
self.remove(run)
self._current_run = None
self._next_run = None
duration = max(duration, granularity_time())
return self.add(start_time, duration, zone, None, None)
def merge_one(
self,
time: datetime,
zone: "IUZone",
schedule: IUSchedule,
adjustment: IUAdjustment,
) -> bool:
modified: bool = False
# See if schedule already exists in run queue. If so get
# the finish time of the last entry.
next_time = self.find_last_date(schedule.id)
if next_time is not None:
next_time += granularity_time()
else:
next_time = time
next_run = schedule.get_next_run(next_time, self.last_time(time))
if next_run is not None:
self.add_schedule(zone, schedule, next_run, adjustment)
modified = True
return modified
def merge_fill(
self,
time: datetime,
zone: "IUZone",
schedule: IUSchedule,
adjustment: IUAdjustment,
) -> bool:
"""Merge the schedule into the run queue. Add as many until the span is
reached. Return True if the schedule was added."""
modified: bool = False
while self.merge_one(time, zone, schedule, adjustment):
modified = True
return modified
def load(self, config: OrderedDict, all_zones: OrderedDict) -> "IUScheduleQueue":
super().load(config, all_zones)
if all_zones is not None:
self._minimum = wash_td(all_zones.get(CONF_MINIMUM, self._minimum))
self._maximum = wash_td(all_zones.get(CONF_MAXIMUM, self._maximum))
self._minimum = wash_td(config.get(CONF_MINIMUM, self._minimum))
self._maximum = wash_td(config.get(CONF_MAXIMUM, self._maximum))
return self
def update_queue(
self,
time: datetime,
) -> int:
return super().update_queue(time)
class IUZone(IUBase):
"""Irrigation Unlimited Zone class"""
def __init__(
self,
hass: HomeAssistant,
coordinator: "IUCoordinator",
controller: "IUController",
zone_index: int,
) -> None:
super().__init__(zone_index)
# Passed parameters
self._hass = hass
self._coordinator = coordinator
self._controller = controller
# Config parameters
self._zone_id: str = None
self._is_enabled: bool = True
self._name: str = None
self._switch_entity_id: str = None
self._show_config: bool = False
self._show_timeline: bool = False
# Private variables
self._initialised: bool = False
self._schedules: list[IUSchedule] = []
self._run_queue = IUScheduleQueue()
self._adjustment = IUAdjustment()
self._zone_sensor: Entity = None
self._is_on: bool = False
self._sensor_update_required: bool = False
self._sensor_last_update: datetime = None
self._dirty: bool = True
return
@property
def schedules(self) -> "list[IUSchedule]":
return self._schedules
@property
def runs(self) -> IUScheduleQueue:
return self._run_queue
@property
def adjustment(self) -> IUAdjustment:
return self._adjustment
@property
def zone_id(self) -> str:
return self._zone_id
@property
def name(self) -> str:
if self._name is not None:
return self._name
else:
return f"Zone {self._index + 1}"
@property
def is_on(self) -> bool:
return self._is_on
@property
def is_setup(self) -> bool:
return self._is_setup()
@property
def enabled(self) -> bool:
"""Return true if this zone is enabled"""
return self._is_enabled
@enabled.setter
def enabled(self, value: bool) -> None:
"""Enable/disable zone"""
if value != self._is_enabled:
self._is_enabled = value
self._dirty = True
self.request_update()
return
@property
def zone_sensor(self) -> Entity:
return self._zone_sensor
@zone_sensor.setter
def zone_sensor(self, value: Entity) -> None:
self._zone_sensor = value
return
@property
def status(self) -> str:
return self._status()
@property
def show_config(self) -> bool:
return self._show_config
@property
def show_timeline(self) -> bool:
return self._show_timeline
def _is_setup(self) -> bool:
"""Check if this object is setup"""
if not self._initialised:
self._initialised = self._zone_sensor is not None
if self._initialised:
for schedule in self._schedules:
self._initialised = self._initialised and schedule.is_setup
return self._initialised
def _status(self) -> str:
"""Return status of zone"""
if self._initialised:
if self._controller.enabled:
if self._is_enabled:
if self._is_on:
return STATE_ON
else:
return STATE_OFF
else:
return STATUS_DISABLED
else:
return STATUS_BLOCKED
else:
return STATUS_INITIALISING
def service_adjust_time(self, data: MappingProxyType, time: datetime) -> bool:
"""Adjust the scheduled run times. Return true if adjustment changed"""
result = self._adjustment.load(data)
if result:
self._run_queue.clear(time)
return result
def service_manual_run(self, data: MappingProxyType, time: datetime) -> None:
"""Add a manual run."""
if self._is_enabled and self._controller.enabled:
ns = wash_dt(time + granularity_time())
if self._controller.preamble is not None:
ns = ns + self._controller.preamble
self._run_queue.add_manual(ns, wash_td(data[CONF_TIME]), self)
return
def service_cancel(self, data: MappingProxyType, time: datetime) -> None:
"""Cancel the current running schedule"""
self._run_queue.cancel()
return
def add(self, schedule: IUSchedule) -> IUSchedule:
"""Add a new schedule to the zone"""
self._schedules.append(schedule)
return schedule
def find_add(
self, coordinator: "IUCoordinator", controller: "IUController", index: int
) -> IUSchedule:
if index >= len(self._schedules):
return self.add(IUSchedule(self._hass, index))
else:
return self._schedules[index]
def clear_run_queue(self) -> None:
"""Clear out the run queue"""
self._run_queue.clear_all()
return
def clear(self) -> None:
"""Reset this zone"""
self._schedules.clear()
self.clear_run_queue()
self._adjustment = IUAdjustment()
self._is_on = False
return
def load(self, config: OrderedDict, all_zones: OrderedDict) -> "IUZone":
"""Load zone data from the configuration"""
self.clear()
self._zone_id = config.get(CONF_ID, str(self.index + 1))
self._is_enabled = config.get(CONF_ENABLED, True)
self._name = config.get(CONF_NAME, None)
self._switch_entity_id = config.get(CONF_ENTITY_ID)
self._run_queue.load(config, all_zones)
if all_zones is not None and CONF_SHOW in all_zones:
self._show_config = all_zones[CONF_SHOW].get(CONF_CONFIG, self._show_config)
self._show_timeline = all_zones[CONF_SHOW].get(
CONF_TIMELINE, self._show_timeline
)
if CONF_SHOW in config:
self._show_config = config[CONF_SHOW].get(CONF_CONFIG, self._show_config)
self._show_timeline = config[CONF_SHOW].get(
CONF_TIMELINE, self._show_timeline
)
if CONF_SCHEDULES in config:
for si, schedule_config in enumerate(config[CONF_SCHEDULES]):
self.find_add(self._coordinator, self._controller, si).load(
schedule_config
)
self._dirty = True
return self
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict[CONF_INDEX] = self._index
dict[CONF_NAME] = self.name
dict[CONF_SCHEDULES] = []
for schedule in self._schedules:
dict[CONF_SCHEDULES].append(schedule.as_dict())
return dict
def muster(self, time: datetime) -> int:
status: int = 0
if self._dirty:
self._run_queue.clear_all()
status |= IURunQueue.RQ_STATUS_CLEARED
self._dirty = False
return status
def muster_schedules(self, time: datetime) -> int:
"""Calculate run times for this zone"""
status: int = 0
for schedule in self._schedules:
if self._run_queue.merge_fill(time, self, schedule, self._adjustment):
status |= IURunQueue.RQ_STATUS_EXTENDED
if status != 0:
self.request_update()
return status
def check_run(self, time: datetime, parent_enabled: bool) -> bool:
"""Update the run status"""
is_running: bool = False
state_changed: bool = False
is_running = (
parent_enabled
and self._is_enabled
and self._run_queue.current_run is not None
and self._run_queue.current_run.is_running(time)
)
state_changed = is_running ^ self._is_on
if state_changed:
self._is_on = not self._is_on
self.request_update()
return state_changed
def request_update(self) -> None:
"""Flag the sensor needs an update"""
self._sensor_update_required = True
return
def update_sensor(self, time: datetime, do_on: bool) -> bool:
"""Lazy sensor updater"""
updated: bool = False
do_update: bool = False
if self._zone_sensor is not None:
if do_on == False:
updated |= self._run_queue.update_sensor(time)
if not self._is_on:
do_update = self._sensor_update_required
else:
if self._is_on:
# If we are running then update sensor according to refresh_interval
if self._run_queue.current_run is not None:
do_update = (
self._sensor_last_update is None
or time - self._sensor_last_update
>= self._coordinator.refresh_interval
)
do_update = do_update or self._sensor_update_required
else:
do_update = False
if do_update:
self._zone_sensor.schedule_update_ha_state()
self._sensor_update_required = False
self._sensor_last_update = time
updated = True
return updated
def call_switch(self, service_type: str) -> None:
if self._switch_entity_id is not None:
self._hass.async_create_task(
self._hass.services.async_call(
homeassistant.core.DOMAIN,
service_type,
{ATTR_ENTITY_ID: self._switch_entity_id},
)
)
return
class IUZoneQueue(IURunQueue):
"""Class to hold the upcoming zones to run"""
def add_zone(
self,
start_time: datetime,
duration: timedelta,
zone: IUZone,
schedule: IUSchedule,
sequence_run: "IUSequenceRun",
preamble: timedelta,
postamble: timedelta,
) -> IURun:
"""Add a new master run to the queue"""
if preamble is not None:
start_time -= preamble
duration += preamble
if postamble is not None:
duration += postamble
run = self.find_run(start_time, duration, zone, schedule, sequence_run)
if run is None:
run = self.add(start_time, duration, zone, schedule, sequence_run)
return run
def find_run(
self,
start_time: datetime,
duration: timedelta,
zone: IUZone,
schedule: IUSchedule,
sequence_run: "IUSequenceRun",
) -> IURun:
for run in self:
if (
start_time == run.start_time
and zone == run.zone
and run.schedule is not None
and schedule is not None
and run.schedule == schedule
):
return run
return None
def rebuild_schedule(
self,
time: datetime,
zones: "list[IUZone]",
preamble: timedelta,
postamble: timedelta,
all: bool,
) -> int:
"""Create a superset of all the zones."""
status: int = 0
if all:
self.clear_all()
else:
self.clear(time)
for zone in zones:
for run in zone.runs:
self.add_zone(
run.start_time,
run.duration,
run.zone,
run.schedule,
run.sequence_run,
preamble,
postamble,
)
status |= IURunQueue.RQ_STATUS_EXTENDED | IURunQueue.RQ_STATUS_REDUCED
status |= self.update_queue(time)
return status
class IUSequenceZone(IUBase):
"""Irrigation Unlimited Sequence Zone class"""
def __init__(
self,
hass: HomeAssistant,
coordinator: "IUCoordinator",
controller: "IUController",
sequence: "IUSequence",
zone_index: int,
) -> None:
super().__init__(zone_index)
# Passed parameters
self._hass = hass
self._coordinator = coordinator
self._controller = controller
self._sequence = sequence
# Config parameters
self._zone_ids: list[str] = None
self._delay: timedelta = None
self._duration: timedelta = None
self._repeat: int = None
# Private variables
return
@property
def zone_ids(self) -> "list[str]":
return self._zone_ids
@property
def duration(self) -> timedelta:
return self._duration
@property
def delay(self) -> timedelta:
return self._delay
@property
def repeat(self) -> int:
return self._repeat
def clear(self) -> None:
"""Reset this sequence zone"""
return
def load(self, config: OrderedDict) -> "IUSequenceZone":
"""Load sequence zone data from the configuration"""
self.clear()
self._zone_ids = config[CONF_ZONE_ID]
self._delay = wash_td(config.get(CONF_DELAY))
self._duration = wash_td(config.get(CONF_DURATION))
self._repeat = config.get(CONF_REPEAT, 1)
return self
class IUSequence(IUBase):
"""Irrigation Unlimited Sequence class"""
def __init__(
self,
hass: HomeAssistant,
coordinator: "IUCoordinator",
controller: "IUController",
sequence_index: int,
) -> None:
super().__init__(sequence_index)
# Passed parameters
self._hass = hass
self._coordinator = coordinator
self._controller = controller
# Config parameters
self._name: str = None
self._delay: timedelta = None
self._duration: timedelta = None
self._repeat: int = None
# Private variables
self._schedules: list[IUSchedule] = []
self._zones: list[IUSequenceZone] = []
self._adjustment = IUAdjustment()
return
@property
def schedules(self) -> "list[IUSchedule]":
return self._schedules
@property
def zones(self) -> "list[IUSequenceZone]":
return self._zones
@property
def delay(self) -> timedelta:
return self._delay
@property
def duration(self) -> timedelta:
return self._duration
@property
def repeat(self) -> int:
return self._repeat
@property
def adjustment(self) -> IUAdjustment:
return self._adjustment
@property
def has_adjustment(self) -> bool:
return self._adjustment.has_adjustment
def zone_duration(self, zone: IUSequenceZone) -> timedelta:
"""Return the duration for the specified zone"""
if zone.duration is not None:
duration = zone.duration
else:
duration = self._duration
if duration is None:
duration = granularity_time()
return duration
def zone_delay(self, zone: IUSequenceZone) -> timedelta:
"""Return the delay for the specified zone"""
if zone.delay is not None:
delay = zone.delay
else:
delay = self._delay
if delay is None:
delay = timedelta(0)
return delay
def total_duration(self) -> timedelta:
"""Return the total duration for all the zones"""
duration = timedelta(0)
for zone in self._zones:
duration += self.zone_duration(zone) * zone.repeat
duration *= self._repeat
return duration
def total_delay(self) -> timedelta:
"""Return the total delay for all the zones"""
delay = timedelta(0)
for zone in self._zones:
delay += self.zone_delay(zone) * zone.repeat
delay *= self._repeat
delay -= self.zone_delay(zone)
return delay
def total_time(self) -> timedelta:
"""Return the total time for the sequence"""
return self.total_duration() + self.total_delay()
def duration_multiplier(self, total_time: timedelta) -> float:
"""Given a new total run time, calculate how much to shrink or expand each
zone duration. Final time will be approximate as the new durations must
be rounded to internal boundaries"""
total_duration = self.total_duration()
if total_time is not None and total_duration != 0:
return (total_time - self.total_delay()) / total_duration
else:
return 1.0
def clear(self) -> None:
"""Reset this sequence"""
self._schedules.clear()
self._zones.clear()
self._adjustment.clear()
return
def add_schedule(self, schedule: IUSchedule) -> IUSchedule:
"""Add a new schedule to the sequence"""
self._schedules.append(schedule)
return schedule
def find_add_schedule(
self, coordinator: "IUCoordinator", controller: "IUController", index: int
) -> IUSchedule:
if index >= len(self._schedules):
return self.add_schedule(IUSchedule(self._hass, index))
else:
return self._schedules[index]
def add_zone(self, zone: IUSequenceZone) -> IUSequenceZone:
"""Add a new zone to the sequence"""
self._zones.append(zone)
return zone
def find_add_zone(
self, coordinator: "IUCoordinator", controller: "IUController", index: int
) -> IUSequenceZone:
if index >= len(self._zones):
return self.add_zone(
IUSequenceZone(self._hass, coordinator, controller, self, index)
)
else:
return self._zones[index]
def zone_ids(self) -> str:
for sequence_zone in self._zones:
for zone_id in sequence_zone.zone_ids:
yield zone_id
def load(self, config: OrderedDict) -> "IUSequence":
"""Load sequence data from the configuration"""
self.clear()
self._name = config.get(CONF_NAME, f"Run {self.index + 1}")
self._delay = wash_td(config.get(CONF_DELAY))
self._duration = wash_td(config.get(CONF_DURATION))
self._repeat = config.get(CONF_REPEAT, 1)
for si, schedule_config in enumerate(config[CONF_SCHEDULES]):
self.find_add_schedule(self._coordinator, self._controller, si).load(
schedule_config
)
for zi, zone_config in enumerate(config[CONF_ZONES]):
self.find_add_zone(self._coordinator, self._controller, zi).load(
zone_config
)
return self
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict[CONF_INDEX] = self._index
dict[CONF_NAME] = self._name
return dict
class IUSequenceRun(IUBase):
"""Irrigation Unlimited sequence run manager class"""
def __init__(self, sequence: IUSequence) -> None:
super().__init__(None)
# Passed parameters
self._sequence = sequence
# Private variables
self._runs: OrderedDict = {}
self._running = False
return
@property
def sequence(self) -> IUSequence:
return self._sequence
@property
def running(self) -> bool:
return self._running
@running.setter
def running(self, value: bool) -> None:
"""Flag sequence is now running"""
self._running = value
return
def add(self, run: IURun, sequence_zone: IUSequenceZone) -> None:
self._runs[run.id] = sequence_zone
return
def run_index(self, run: IURun) -> int:
return list(self._runs.keys()).index(run.id)
def sequence_zone(self, run: IURun) -> IUSequenceZone:
return self._runs.get(run.id, None)
class IUController(IUBase):
"""Irrigation Unlimited Controller (Master) class"""
def __init__(
self, hass: HomeAssistant, coordinator: "IUCoordinator", controller_index: int
) -> None:
# Passed parameters
super().__init__(controller_index)
self._hass = hass
self._coordinator = coordinator # Parent
# Config parameters
self._is_enabled: bool = True
self._name: str = None
self._switch_entity_id: str = None
self._preamble: timedelta = None
self._postamble: timedelta = None
# Private variables
self._initialised: bool = False
self._zones: list[IUZone] = []
self._sequences: list[IUSequence] = []
self._run_queue = IUZoneQueue()
self._master_sensor: Entity = None
self._is_on: bool = False
self._sensor_update_required: bool = False
self._sensor_last_update: datetime = None
self._dirty: bool = True
return
@property
def zones(self) -> "list[IUZone]":
return self._zones
@property
def runs(self) -> IUZoneQueue:
return self._run_queue
@property
def name(self) -> str:
return self._name
@property
def is_on(self) -> bool:
return self._is_on
@property
def is_setup(self) -> bool:
return self._is_setup()
@property
def enabled(self) -> bool:
"""Return true is this zone is on"""
return self._is_enabled
@enabled.setter
def enabled(self, value: bool) -> None:
"""Enable/disable this controller"""
if value != self._is_enabled:
self._is_enabled = value
self._dirty = True
self.request_update()
self.notify_children()
return
@property
def master_sensor(self) -> Entity:
return self._master_sensor
@master_sensor.setter
def master_sensor(self, value: Entity) -> None:
self._master_sensor = value
return
@property
def preamble(self) -> timedelta:
return self._preamble
@property
def status(self) -> str:
return self._status()
@property
def is_paused(self) -> bool:
return self._run_queue.in_sequence
def _status(self) -> str:
"""Return status of the controller"""
if self._initialised:
if self._is_enabled:
if self._is_on:
return STATE_ON
else:
if self._run_queue.in_sequence:
return STATUS_PAUSED
else:
return STATE_OFF
else:
return STATUS_DISABLED
else:
return STATUS_INITIALISING
def _is_setup(self) -> bool:
if not self._initialised:
self._initialised = self._master_sensor is not None
if self._initialised:
for zone in self._zones:
self._initialised = self._initialised and zone.is_setup
return self._initialised
def add_zone(self, zone: IUZone) -> IUZone:
"""Add a new zone to the controller"""
self._zones.append(zone)
return zone
def find_add_zone(
self, coordinator: "IUCoordinator", controller: "IUController", index: int
) -> IUZone:
if index >= len(self._zones):
return self.add_zone(IUZone(self._hass, coordinator, controller, index))
else:
return self._zones[index]
def add_sequence(self, sequence: IUSequence) -> IUSequence:
"""Add a new sequence to the controller"""
self._sequences.append(sequence)
return sequence
def find_sequence(self, index: int) -> IUSequence:
if index >= 0 and index < len(self._sequences):
return self._sequences[index]
else:
return None
def find_add_sequence(
self, coordinator: "IUCoordinator", controller: "IUController", index: int
) -> IUSequence:
if index >= len(self._sequences):
return self.add_sequence(
IUSequence(self._hass, coordinator, controller, index)
)
else:
return self._sequences[index]
def find_zone_by_zone_id(self, zone_id: str) -> IUZone:
for zone in self._zones:
if zone.zone_id == zone_id:
return zone
return None
def clear(self) -> None:
# Don't clear zones
# self._zones.clear()
self._sequences.clear()
self._is_on = False
return
def notify_children(self) -> None:
for zone in self._zones:
zone.request_update()
return
def load(self, config: OrderedDict) -> "IUController":
"""Load config data for the controller"""
self.clear()
self._is_enabled = config.get(CONF_ENABLED, True)
self._name = config.get(CONF_NAME, f"Controller {self.index + 1}")
self._switch_entity_id = config.get(CONF_ENTITY_ID)
self._preamble = wash_td(config.get(CONF_PREAMBLE))
self._postamble = wash_td(config.get(CONF_POSTAMBLE))
all_zones = config.get(CONF_ALL_ZONES_CONFIG)
for zi, zone_config in enumerate(config[CONF_ZONES]):
self.find_add_zone(self._coordinator, self, zi).load(zone_config, all_zones)
if CONF_SEQUENCES in config:
for qi, sequence_config in enumerate(config[CONF_SEQUENCES]):
self.find_add_sequence(self._coordinator, self, qi).load(
sequence_config
)
self._dirty = True
return self
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict[CONF_INDEX] = self._index
dict[CONF_NAME] = self._name
dict[CONF_ZONES] = []
for zone in self._zones:
dict[CONF_ZONES].append(zone.as_dict())
dict[CONF_SEQUENCES] = []
for sequence in self._sequences:
dict[CONF_SEQUENCES].append(sequence.as_dict())
return dict
def muster_sequence(
self,
time: datetime,
sequence: IUSequence,
schedule: IUSchedule,
total_duration: timedelta = None,
) -> int:
def init_run_time(
time: datetime, schedule: IUSchedule, zone: IUZone
) -> datetime:
if schedule is not None:
next_time = zone.runs.find_last_date(schedule.id)
if next_time is not None:
next_time += granularity_time()
else:
next_time = time
next_run = schedule.get_next_run(next_time, zone.runs.last_time(time))
else:
next_run = time + granularity_time()
return next_run
def calc_multiplier(
total_duration: timedelta, sequence: IUSequence, schedule: IUSchedule
) -> float:
"""Calculate the multiplier"""
if total_duration is None:
if schedule is not None and schedule.run_time is not None:
total_duration = schedule.run_time
else:
total_duration = sequence.total_time()
if schedule is not None and sequence.has_adjustment:
total_delay = sequence.total_delay()
total_duration = (
sequence.adjustment.adjust(total_duration - total_delay)
+ total_delay
)
if total_duration < total_delay:
total_duration = total_delay # Make run time 0
return sequence.duration_multiplier(total_duration)
duration_multiplier = calc_multiplier(total_duration, sequence, schedule)
status: int = 0
next_run: datetime = None
sequence_run: IUSequenceRun = None
for i in range(sequence.repeat): # pylint: disable=unused-variable
for sequence_zone in sequence.zones:
duration = round_td(
sequence.zone_duration(sequence_zone) * duration_multiplier
)
duration_max = timedelta(0)
delay = sequence.zone_delay(sequence_zone)
for zone in (
self.find_zone_by_zone_id(zone_id)
for zone_id in sequence_zone.zone_ids
):
if zone is not None and zone.enabled:
# Initialise on first pass
if next_run is None:
next_run = init_run_time(time, schedule, zone)
if next_run is None:
return status # Exit if queue is full
sequence_run = IUSequenceRun(sequence)
# Don't adjust manual run and no adjustment on adjustment
if schedule is not None and not sequence.has_adjustment:
duration_adjusted = zone.adjustment.adjust(duration)
else:
duration_adjusted = duration
zone_run_time = next_run
for j in range( # pylint: disable=unused-variable
sequence_zone.repeat
):
run = zone.runs.add(
zone_run_time,
duration_adjusted,
zone,
schedule,
sequence_run,
)
sequence_run.add(run, sequence_zone)
zone_run_time += run.duration + delay
zone.request_update()
duration_max = max(duration_max, zone_run_time - next_run)
status |= IURunQueue.RQ_STATUS_EXTENDED
next_run += duration_max
return status
def muster(self, time: datetime, force: bool) -> int:
"""Calculate run times for this controller. This is where most of the hard yakka
is done."""
status: int = 0
if self._dirty or force:
self._run_queue.clear_all()
for zone in self._zones:
zone.clear_run_queue()
status |= IURunQueue.RQ_STATUS_CLEARED
zone_status: int = 0
# Handle initialisation
for zone in self._zones:
zone_status |= zone.muster(time)
# Process sequence schedules
for sequence in self._sequences:
for schedule in sequence.schedules:
while True:
sequence_status = self.muster_sequence(
time, sequence, schedule, None
)
zone_status |= sequence_status
if sequence_status & IURunQueue.RQ_STATUS_EXTENDED == 0:
break
# Process zone schedules
for zone in self._zones:
if zone.enabled:
zone_status |= zone.muster_schedules(time)
# Post processing
for zone in self._zones:
zone_status |= zone.runs.update_queue(time)
if (
zone_status
& (
IURunQueue.RQ_STATUS_CLEARED
| IURunQueue.RQ_STATUS_EXTENDED
| IURunQueue.RQ_STATUS_SORTED
| IURunQueue.RQ_STATUS_CANCELED
| IURunQueue.RQ_STATUS_CHANGED
)
!= 0
):
all = bool(
zone_status
& (IURunQueue.RQ_STATUS_CLEARED | IURunQueue.RQ_STATUS_CANCELED)
)
status |= self._run_queue.rebuild_schedule(
time, self._zones, self._preamble, self._postamble, all
)
else:
status |= self._run_queue.update_queue(time)
if status != 0:
self.request_update()
self._dirty = False
return status | zone_status
def check_run(self, time: datetime) -> bool:
"""Check the run status and update sensors. Return flag
if anything has changed."""
zones_changed: list[int] = []
is_running: bool = False
state_changed: bool = False
# Gather zones that have changed status
for zone in self._zones:
if zone.check_run(time, self._is_enabled):
zones_changed.append(zone.index)
# Handle off zones before master
for zone in (self._zones[i] for i in zones_changed):
if not zone.is_on:
zone.call_switch(SERVICE_TURN_OFF)
self._coordinator.status_changed(time, self, zone, zone.is_on)
# Check if master has changed and update
is_running = self._is_enabled and self._run_queue.current_run is not None
state_changed = is_running ^ self._is_on
if state_changed:
self._is_on = not self._is_on
self.request_update()
self.call_switch(SERVICE_TURN_ON if self._is_on else SERVICE_TURN_OFF)
self._coordinator.status_changed(time, self, None, self._is_on)
# Handle on zones after master
for zone in (self._zones[i] for i in zones_changed):
if zone.is_on:
zone.call_switch(SERVICE_TURN_ON)
self._coordinator.status_changed(time, self, zone, zone.is_on)
return state_changed
def request_update(self) -> None:
"""Flag the sensor needs an update. The actual update is done
in update_sensor"""
self._sensor_update_required = True
return
def update_sensor(self, time: datetime) -> None:
"""Lazy sensor updater."""
self._run_queue.update_sensor(time)
for zone in self._zones:
zone.update_sensor(time, False)
if self._master_sensor is not None:
do_update: bool = self._sensor_update_required
# If we are running then update sensor according to refresh_interval
if self._run_queue.current_run is not None:
do_update = (
do_update
or self._sensor_last_update is None
or time - self._sensor_last_update
>= self._coordinator.refresh_interval
)
if do_update:
self._master_sensor.schedule_update_ha_state()
self._sensor_update_required = False
self._sensor_last_update = time
for zone in self._zones:
zone.update_sensor(time, True)
return
def call_switch(self, service_type: str) -> None:
"""Update the linked entity if enabled"""
if self._switch_entity_id is not None:
self._hass.async_create_task(
self._hass.services.async_call(
homeassistant.core.DOMAIN,
service_type,
{ATTR_ENTITY_ID: self._switch_entity_id},
)
)
return
def service_adjust_time(self, data: MappingProxyType, time: datetime) -> None:
sequence_id = data.get(CONF_SEQUENCE_ID, None)
if sequence_id is None:
zl: list[int] = data.get(CONF_ZONES, None)
for zone in self._zones:
if zl is None or zone.index + 1 in zl:
zone.service_adjust_time(data, time)
else:
sequence = self.find_sequence(sequence_id - 1)
if sequence is not None:
if sequence.adjustment.load(data):
for zone_id in sequence.zone_ids():
zone = self.find_zone_by_zone_id(zone_id)
if zone is not None:
zone.runs.clear(time)
return
def service_manual_run(self, data: MappingProxyType, time: datetime) -> None:
sequence_id = data.get(CONF_SEQUENCE_ID, None)
if sequence_id is None:
zl: list[int] = data.get(CONF_ZONES, None)
for zone in self._zones:
if zl is None or zone.index + 1 in zl:
zone.service_manual_run(data, time)
else:
sequence = self.find_sequence(sequence_id - 1)
if sequence is not None:
self.muster_sequence(time, sequence, None, wash_td(data[CONF_TIME]))
return
def service_cancel(self, data: MappingProxyType, time: datetime) -> None:
zl: list[int] = data.get(CONF_ZONES, None)
for zone in self._zones:
if zl is None or zone.index + 1 in zl:
zone.service_cancel(data, time)
return
class IUEvent:
def __init__(self) -> None:
# Private variables
self._time: datetime = None
self._controller: IUController = None
self._zone: IUZone = None
self._state: bool = None
self._crumbs: str = None
return
def __eq__(self, other: "IUEvent") -> bool:
return (
self._time == other._time
and self._controller == other.controller
and self._zone == other.zone
and self._state == other.state
)
@property
def time(self) -> datetime:
return self._time
@property
def controller(self) -> IUController:
return self._controller
@property
def zone(self) -> IUZone:
return self._zone
@property
def state(self) -> bool:
return self._state
@property
def time_local(self) -> str:
return self.dt2lstr()
@property
def zone_name(self) -> str:
if self._zone == 0:
return "Master"
else:
return f"Zone {self._zone}"
def load(self, config: OrderedDict) -> "IUEvent":
self._time: datetime = wash_dt(dt.as_utc(config["t"]))
self._controller: int = config["c"]
self._zone: int = config["z"]
self._state: bool = config["s"]
return self
def load2(
self, time: datetime, controller: int, zone: int, state: bool, crumbs: str
):
self._time = time
self._controller = controller
self._zone = zone
self._state = state
self._crumbs = crumbs
return self
def dt2lstr(self) -> str:
"""Format the passed datetime into local time"""
return datetime.strftime(dt.as_local(self._time), "%Y-%m-%d %H:%M:%S")
def as_str(self) -> str:
return f"{{t: '{self.time_local}', c: {self._controller}, z: {self._zone}, s: {1 if self._state else 0}}}"
def as_dict(self):
return {
"t": self._time,
"c": self._controller,
"z": self._zone,
"s": self._state,
}
def write_log(self) -> None:
"""Output the status of master or zone"""
zm = f"{self.zone_name} is {STATE_ON if self._state else STATE_OFF}"
if self._zone != 0 and self._state:
zm = zm + f" [{self._crumbs}]"
_LOGGER.debug(
f"[{self.time_local}] Controller {self._controller} %s",
zm,
)
return
class IUTest(IUBase):
def __init__(self, test_index: int, speed: float) -> None:
# Passed parameters
super().__init__(test_index)
self._speed = speed
# Config parameters
self._name: str = None
self._start: datetime = None
self._end: datetime = None
self._results: list[IUEvent] = []
# Private variables
self._current_result: int = 0
self._events: int = 0
self._checks: int = 0
self._errors: int = 0
self._perf_mon: int = 0
self._delta: timedelta = None
self._test_time: float = 0
return
@property
def name(self) -> str:
return self._name
@property
def start(self) -> datetime:
return self._start
@property
def events(self) -> int:
return self._events
@property
def checks(self) -> int:
return self._checks
@property
def errors(self) -> int:
return self._errors
@property
def test_time(self) -> float:
return self._test_time
@property
def virtual_duration(self) -> timedelta:
return (self._end - self._start) / self._speed
@property
def current_result(self) -> int:
return self._current_result
@property
def total_results(self) -> int:
return len(self._results)
def is_finished(self, time) -> bool:
return self.virtual_time(time) > self._end
def next_result(self) -> IUEvent:
if self._current_result < len(self._results):
r = self._results[self._current_result]
self._current_result += 1
return r
else:
return None
def check_result(self, result: IUEvent, event: IUEvent) -> bool:
self._events += 1
if result is not None:
self._checks += 1
if result != event:
self._errors += 1
return False
else:
return False
return True
def clear(self) -> None:
self._results.clear()
return
def load(self, config: OrderedDict):
self.clear()
self._start = wash_dt(dt.as_utc(config[CONF_START]))
self._end = wash_dt(dt.as_utc(config[CONF_END]))
self._name = config.get(CONF_NAME, None)
if CONF_RESULTS in config:
for r in config[CONF_RESULTS]:
self._results.append(IUEvent().load(r))
return self
def begin(self, time: datetime) -> None:
self._delta = time - self._start
self._perf_mon = tm.perf_counter()
self._current_result = 0
self._events = 0
self._checks = 0
self._errors = 0
self._test_time = 0
return
def end(self) -> None:
self._test_time = tm.perf_counter() - self._perf_mon
return
def virtual_time(self, time: datetime) -> datetime:
"""Return the virtual clock. For testing we can speed
up time. This routine will return a virtual time based
on the real time and the duration from start. It is in
effect a test warp speed"""
vt: datetime = time - self._delta
actual_duration: float = (vt - self._start).total_seconds()
virtual_duration: float = actual_duration * self._speed
return self._start + timedelta(seconds=virtual_duration)
class IUTester:
"""Irrigation Unlimited testing class"""
def __init__(self) -> None:
self._tests: list[IUTest] = []
self.load(None)
return
@property
def enabled(self) -> bool:
return self._enabled
@property
def speed(self) -> float:
return self._speed
@property
def is_testing(self) -> bool:
return self._is_testing()
@property
def tests(self) -> "list[IUTest]":
return self._tests
@property
def current_test(self) -> IUTest:
if self._running_test is not None and self._running_test < len(self._tests):
return self._tests[self._running_test]
else:
return None
@property
def last_test(self) -> IUTest:
if self._last_test is not None and self._last_test < len(self._tests):
return self._tests[self._last_test]
else:
return None
@property
def total_events(self) -> int:
result: int = 0
for test in self._tests:
result += test.events
return result
@property
def total_checks(self) -> int:
result: int = 0
for test in self._tests:
result += test.checks
return result
@property
def total_errors(self) -> int:
result: int = 0
for test in self._tests:
result += test.errors
return result
@property
def total_time(self) -> float:
result: float = 0
for test in self._tests:
result += test.test_time
return result
@property
def total_tests(self) -> int:
return len(self._tests)
@property
def total_virtual_duration(self) -> timedelta:
result = timedelta(0)
for test in self._tests:
result += test.virtual_duration
return result
@property
def total_results(self) -> int:
result: int = 0
for test in self._tests:
result += test.total_results
return result
def start_test(self, test_no: int, time: datetime) -> IUTest:
if test_no > 0 and test_no <= len(self._tests):
self._running_test = test_no - 1 # 0-based
ct = self._tests[self._running_test]
ct.begin(time)
if self._show_log:
_LOGGER.info(
"Running test %d from %s to %s",
self._running_test + 1,
dt.as_local(ct._start).strftime("%c"),
dt.as_local(ct._end).strftime("%c"),
)
self._test_initialised = False
else:
self._running_test = None
return self.current_test
def end_test(self, time: datetime) -> None:
ct = self.current_test
if ct is not None:
ct.end()
if self._show_log:
_LOGGER.info("Test %d completed", self._running_test + 1)
self._last_test = self._running_test
self._running_test = None
return
def next_test(self, time: datetime) -> IUTest:
current = self._running_test # This is 0-based
self.end_test(time)
return self.start_test(current + 2, time) # This takes 1-based
def _is_testing(self) -> bool:
return self._enabled and self._running_test is not None
def clear(self) -> None:
# Private variables
self._tests.clear()
self._test_initialised = False
self._running_test: int = None
self._last_test: int = None
self._autoplay_initialised: bool = False
return
def load(self, config: OrderedDict) -> "IUTester":
"""Load config data for the tester"""
# Config parameters
self.clear()
if config is None:
config = {}
self._enabled: bool = config.get(CONF_ENABLED, False)
self._speed: float = config.get(CONF_SPEED, DEFAULT_TEST_SPEED)
self._output_events: bool = config.get(CONF_OUTPUT_EVENTS, False)
self._show_log: bool = config.get(CONF_SHOW_LOG, True)
self._autoplay: bool = config.get(CONF_AUTOPLAY, True)
if CONF_TIMES in config:
for ti, test in enumerate(config[CONF_TIMES]):
self._tests.append(IUTest(ti, self._speed).load(test))
return self
def poll_test(self, time: datetime, poll_func) -> None:
if self._autoplay and not self._autoplay_initialised:
self.start_test(1, time)
self._autoplay_initialised = True
ct = self.current_test
if ct is not None:
if not self._test_initialised:
poll_func(ct._start, True)
self._test_initialised = True
elif ct.is_finished(time): # End of current test
if self._autoplay:
ct = self.next_test(time)
if ct is not None:
poll_func(ct.start, True)
else: # All tests finished
if self._show_log:
_LOGGER.info(
"All tests completed (Idle); checks: %d, errors: %d",
self.total_checks,
self.total_errors,
)
poll_func(time, True)
else: # End single test
self.end_test(time)
poll_func(time, True)
else: # Continue existing test
poll_func(ct.virtual_time(time))
else: # Out of tests to run
poll_func(time)
return
def entity_state_changed(self, event: IUEvent) -> None:
"""Called when an entity has changed state"""
def check_state(event: IUEvent):
"""Check the event against the next result"""
ct = self.current_test
if ct is not None:
r = ct.next_result()
if not ct.check_result(r, event):
if self._show_log:
_LOGGER.error(
"(%d) Event <> result %s <> %s",
ct.current_result,
event.as_str(),
r.as_str() if r is not None else "None",
)
if self._show_log:
event.write_log()
if self._is_testing():
if self._output_events:
print(event.as_str())
check_state(event)
return
class IUCoordinator:
"""Irrigation Unimited Coordinator class"""
def __init__(self, hass: HomeAssistant) -> None:
# Passed parameters
self._hass = hass
# Config parameters
self._refresh_interval: timedelta = None
# Private variables
self._controllers: list[IUController] = []
self._is_on: bool = False
self._sensor_update_required: bool = False
self._sensor_last_update: datetime = None
self._dirty: bool = True
self._component: Entity = None
self._initialised: bool = False
self._last_tick: datetime = None
self._last_muster: datetime = None
self._muster_required: bool = False
self._remove_listener: CALLBACK_TYPE = None
self._tester = IUTester()
return
@property
def controllers(self) -> "list[IUController]":
return self._controllers
@property
def tester(self) -> IUTester:
return self._tester
@property
def is_setup(self) -> bool:
return self._is_setup()
@property
def component(self) -> Entity:
return self._component
@component.setter
def component(self, value: Entity) -> None:
self._component = value
return
@property
def refresh_interval(self) -> timedelta:
return self._refresh_interval
def _is_setup(self) -> bool:
"""Wait for sensors to be setup"""
all_setup: bool = self._hass.is_running and self._component is not None
for controller in self._controllers:
all_setup = all_setup and controller.is_setup
return all_setup
def add(self, controller: IUController) -> IUController:
"""Add a new controller to the system"""
self._controllers.append(controller)
return controller
def find_add(self, coordinator: "IUCoordinator", index: int) -> IUController:
if index >= len(self._controllers):
return self.add(IUController(self._hass, coordinator, index))
else:
return self._controllers[index]
def clear(self) -> None:
# Don't clear controllers
# self._controllers.clear()
self._is_on: bool = False
return
def load(self, config: OrderedDict) -> "IUCoordinator":
"""Load config data for the system"""
self.clear()
global SYSTEM_GRANULARITY
SYSTEM_GRANULARITY = config.get(CONF_GRANULARITY, DEFAULT_GRANULATITY)
self._refresh_interval = timedelta(
seconds=config.get(CONF_REFRESH_INTERVAL, DEFAULT_REFRESH_INTERVAL)
)
for ci, controller_config in enumerate(config[CONF_CONTROLLERS]):
self.find_add(self, ci).load(controller_config)
self._tester = IUTester().load(config.get(CONF_TESTING))
self._dirty = True
self._muster_required = True
return self
def as_dict(self) -> OrderedDict:
dict = OrderedDict()
dict[CONF_CONTROLLERS] = []
for controller in self._controllers:
dict[CONF_CONTROLLERS].append(controller.as_dict())
return dict
def muster(self, time: datetime, force: bool) -> int:
"""Calculate run times for system"""
status: int = 0
for controller in self._controllers:
status |= controller.muster(time, force)
self._dirty = False
return status
def check_run(self, time: datetime) -> bool:
"""Update run status"""
is_running: bool = False
for controller in self._controllers:
is_running = is_running or controller.check_run(time)
return is_running
def request_update(self) -> None:
"""Flag the sensor needs an update. The actual update is done
in update_sensor"""
self._sensor_update_required = True
return
def update_sensor(self, time: datetime) -> None:
"""Update home assistant sensors if required"""
for controller in self._controllers:
controller.update_sensor(time)
if self._component is not None and self._sensor_update_required:
self._component.schedule_update_ha_state()
self._sensor_update_required = False
self._sensor_last_update = time
return
def poll(self, time: datetime, force: bool = False) -> None:
"""Poll the system for changes, updates and refreshes"""
wtime: datetime = wash_dt(time)
if (wtime != self._last_muster) or self._muster_required:
if self.muster(wtime, force) != 0:
self.check_run(wtime)
self._muster_required = False
self._last_muster = wtime
self.update_sensor(wash_dt(time, 1))
return
def poll_main(self, time: datetime, force: bool = False) -> None:
if self._tester.enabled:
self._tester.poll_test(time, self.poll)
else:
self.poll(time, force)
return
def timer(self, time: datetime) -> None:
self._last_tick = time
if self._initialised:
self.poll_main(time)
else:
self._initialised = self.is_setup
if self._initialised:
self.request_update()
self.poll_main(time)
return
async def _async_timer(self, time: datetime) -> None:
"""Timer callback"""
self.timer(time)
return
def track_interval(self) -> timedelta:
track_time = SYSTEM_GRANULARITY / self._tester.speed
track_time *= 0.95 # Run clock slightly ahead of required to avoid skipping
return min(timedelta(seconds=track_time), self._refresh_interval)
def start(self) -> None:
"""Start the system up"""
self.stop()
self._remove_listener = async_track_time_interval(
self._hass, self._async_timer, self.track_interval()
)
return
def stop(self) -> None:
if self._remove_listener is not None:
self._remove_listener()
self._remove_listener = None
return
def register_entity(
self, controller: IUController, zone: IUZone, entity: Entity
) -> None:
if controller is None:
self._component = entity
elif zone is None:
controller.master_sensor = entity
else:
zone.zone_sensor = entity
return
def deregister_entity(
self, controller: IUController, zone: IUZone, entity: Entity
) -> None:
if controller is None:
self._component = None
elif zone is None:
controller.master_sensor = None
else:
zone.zone_sensor = None
return
def service_time(self) -> datetime:
"""Return a time midway between last and next future tick"""
if self._last_tick is not None:
return self._last_tick + self.track_interval() / 2
else:
return dt.utcnow()
def service_call(
self,
service: str,
controller: IUController,
zone: IUZone,
data: MappingProxyType,
) -> None:
"""Entry point for all service calls."""
time = self.service_time()
if self._tester.is_testing:
time = self._tester.current_test.virtual_time(time)
time = wash_dt(time)
if service == SERVICE_ENABLE:
if zone is not None:
zone.enabled = True
else:
controller.enabled = True
elif service == SERVICE_DISABLE:
if zone is not None:
zone.enabled = False
else:
controller.enabled = False
elif service == SERVICE_TOGGLE:
if zone is not None:
zone.enabled = not zone.enabled
else:
controller.enabled = not controller.enabled
elif service == SERVICE_CANCEL:
if zone is not None:
zone.service_cancel(data, time)
else:
controller.service_cancel(data, time)
elif service == SERVICE_TIME_ADJUST:
if zone is not None:
zone.service_adjust_time(data, time)
else:
controller.service_adjust_time(data, time)
elif service == SERVICE_MANUAL_RUN:
if zone is not None:
zone.service_manual_run(data, time)
else:
controller.service_manual_run(data, time)
else:
return
self._muster_required = True
return
def start_test(self, test_no: int) -> datetime:
self._last_tick = None
next_time = dt.utcnow()
self._tester.start_test(test_no, next_time)
self.timer(next_time)
return next_time
def status_changed(
self, time: datetime, controller: IUController, zone: IUZone, state: bool
) -> None:
crumbs: str = ""
if zone is not None:
zone_id = zone.index + 1
if state == True:
crumbs = zone.runs.current_run.crumbs
else:
zone_id = 0
e = IUEvent().load2(time, controller.index + 1, zone_id, state, crumbs)
self._tester.entity_state_changed(e)
return
|
# -*- coding: utf-8 -*-
import argparse
import os
import shutil
from github import Github
MD_HEAD = """## ssh 的博客
大家好,我是 ssh,现在在字节跳动的 Web Infra 担任前端工程师,微信:**[sshsunlight](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/017d568dc1d14cd883cc3238350a39ec~tplv-k3u1fbpfcp-watermark.image)**,欢迎找我交个朋友。
我会在公众号「前端从进阶到入院」每日更新精心挑选的技术文章(标准就是我自己看了也会有收获),欢迎大家一起成长。

"""
BACKUP_DIR = "src/pages"
ANCHOR_NUMBER = 5
TOP_ISSUES_LABELS = ["Top"]
TODO_ISSUES_LABELS = ["TODO"]
def get_me(user):
return user.get_user().login
def isMe(issue, me):
return issue.user.login == me
def format_time(time):
return str(time)[:10]
def login(token):
return Github(token)
def get_repo(user: Github, repo: str):
return user.get_repo(repo)
def parse_TODO(issue):
body = issue.body.splitlines()
todo_undone = [l for l in body if l.startswith("- [ ] ")]
todo_done = [l for l in body if l.startswith("- [x] ")]
# just add info all done
if not todo_undone:
return f"[{issue.title}]({issue.html_url}) all done", []
return (
f"[{issue.title}]({issue.html_url})--{len(todo_undone)} jobs to do--{len(todo_done)} jobs done",
todo_done + todo_undone,
)
def get_top_issues(repo):
return repo.get_issues(labels=TOP_ISSUES_LABELS)
def get_todo_issues(repo):
return repo.get_issues(labels=TODO_ISSUES_LABELS)
def get_repo_labels(repo):
return [l for l in repo.get_labels()]
def get_issues_from_label(repo, label):
return repo.get_issues(labels=(label,))
def add_issue_info(issue, md):
time = format_time(issue.created_at)
md.write(f"- [{issue.title}]({issue.html_url})--{time}\n")
def add_md_todo(repo, md, me):
todo_issues = list(get_todo_issues(repo))
if not TODO_ISSUES_LABELS or not todo_issues:
return
with open(md, "a+", encoding="utf-8") as md:
md.write("## TODO\n")
for issue in todo_issues:
if isMe(issue, me):
todo_title, todo_list = parse_TODO(issue)
md.write("TODO list from " + todo_title + "\n")
for t in todo_list:
md.write(t + "\n")
# new line
md.write("\n")
def add_md_top(repo, md, me):
top_issues = list(get_top_issues(repo))
if not TOP_ISSUES_LABELS or not top_issues:
return
with open(md, "a+", encoding="utf-8") as md:
md.write("## 置顶文章\n")
for issue in top_issues:
if isMe(issue, me):
add_issue_info(issue, md)
def add_md_recent(repo, md, me):
new_last_issues = repo.get_issues()[:10]
with open(md, "a+", encoding="utf-8") as md:
# one the issue that only one issue and delete (pyGitHub raise an exception)
try:
md.write("## 最近更新\n")
for issue in new_last_issues:
if isMe(issue, me):
add_issue_info(issue, md)
except:
return
def add_md_header(md):
with open(md, "w", encoding="utf-8") as md:
md.write(MD_HEAD)
def add_md_label(repo, md, me):
labels = get_repo_labels(repo)
with open(md, "a+", encoding="utf-8") as md:
for label in labels:
# we don't need add top label again
if label.name in TOP_ISSUES_LABELS:
continue
# we don't need add todo label again
if label.name in TODO_ISSUES_LABELS:
continue
issues = get_issues_from_label(repo, label)
if issues.totalCount:
md.write("## " + label.name + "\n")
issues = sorted(
issues, key=lambda x: x.created_at, reverse=True)
i = 0
for issue in issues:
if not issue:
continue
if isMe(issue, me):
if i == ANCHOR_NUMBER:
md.write("<details><summary>显示更多</summary>\n")
md.write("\n")
add_issue_info(issue, md)
i += 1
if i > ANCHOR_NUMBER:
md.write("</details>\n")
md.write("\n")
def get_to_generate_issues(repo, dir_name, me, issue_number=None):
to_generate_issues = [
i
for i in list(repo.get_issues())
if isMe(i, me)
]
if issue_number:
to_generate_issues.append(repo.get_issue(int(issue_number)))
return to_generate_issues
def main(token, repo_name="blogs", issue_number=None, dir_name=BACKUP_DIR):
user = login(token)
me = get_me(user)
repo = get_repo(user, repo_name)
add_md_header("README.md")
# add to readme one by one, change order here
for func in [add_md_top, add_md_recent, add_md_label, add_md_todo]:
func(repo, "README.md", me)
to_generate_issues = get_to_generate_issues(
repo, dir_name, me, issue_number)
# save md files to backup folder
for issue in to_generate_issues:
save_issue(issue, me, dir_name)
def save_issue(issue, me, dir_name=BACKUP_DIR):
md_dir = os.path.join(
dir_name, str(issue.id)
)
if not os.path.exists(md_dir):
os.makedirs(md_dir)
md_name = os.path.join(md_dir, "index.md")
with open(md_name, "w") as f:
f.write('---\n')
f.write(f"title: '{issue.title}'\n")
f.write(f"date: '{issue.created_at.strftime("%Y-%m-%d")}'\n")
f.write("spoiler: ''\n")
f.write('---\n\n')
f.write(issue.body)
print(os.path.abspath(BACKUP_DIR))
shutil.rmtree(os.path.abspath(BACKUP_DIR))
os.makedirs(BACKUP_DIR)
parser = argparse.ArgumentParser()
parser.add_argument("github_token", help="github_token")
parser.add_argument("repo_name", help="repo_name")
parser.add_argument("--issue_number", help="issue_number",
default=None, required=False)
options = parser.parse_args()
main(options.github_token, options.repo_name, options.issue_number)
| # -*- coding: utf-8 -*-
import argparse
import os
import shutil
from github import Github
MD_HEAD = """## ssh 的博客
大家好,我是 ssh,现在在字节跳动的 Web Infra 担任前端工程师,微信:**[sshsunlight](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/017d568dc1d14cd883cc3238350a39ec~tplv-k3u1fbpfcp-watermark.image)**,欢迎找我交个朋友。
我会在公众号「前端从进阶到入院」每日更新精心挑选的技术文章(标准就是我自己看了也会有收获),欢迎大家一起成长。

"""
BACKUP_DIR = "src/pages"
ANCHOR_NUMBER = 5
TOP_ISSUES_LABELS = ["Top"]
TODO_ISSUES_LABELS = ["TODO"]
def get_me(user):
return user.get_user().login
def isMe(issue, me):
return issue.user.login == me
def format_time(time):
return str(time)[:10]
def login(token):
return Github(token)
def get_repo(user: Github, repo: str):
return user.get_repo(repo)
def parse_TODO(issue):
body = issue.body.splitlines()
todo_undone = [l for l in body if l.startswith("- [ ] ")]
todo_done = [l for l in body if l.startswith("- [x] ")]
# just add info all done
if not todo_undone:
return f"[{issue.title}]({issue.html_url}) all done", []
return (
f"[{issue.title}]({issue.html_url})--{len(todo_undone)} jobs to do--{len(todo_done)} jobs done",
todo_done + todo_undone,
)
def get_top_issues(repo):
return repo.get_issues(labels=TOP_ISSUES_LABELS)
def get_todo_issues(repo):
return repo.get_issues(labels=TODO_ISSUES_LABELS)
def get_repo_labels(repo):
return [l for l in repo.get_labels()]
def get_issues_from_label(repo, label):
return repo.get_issues(labels=(label,))
def add_issue_info(issue, md):
time = format_time(issue.created_at)
md.write(f"- [{issue.title}]({issue.html_url})--{time}\n")
def add_md_todo(repo, md, me):
todo_issues = list(get_todo_issues(repo))
if not TODO_ISSUES_LABELS or not todo_issues:
return
with open(md, "a+", encoding="utf-8") as md:
md.write("## TODO\n")
for issue in todo_issues:
if isMe(issue, me):
todo_title, todo_list = parse_TODO(issue)
md.write("TODO list from " + todo_title + "\n")
for t in todo_list:
md.write(t + "\n")
# new line
md.write("\n")
def add_md_top(repo, md, me):
top_issues = list(get_top_issues(repo))
if not TOP_ISSUES_LABELS or not top_issues:
return
with open(md, "a+", encoding="utf-8") as md:
md.write("## 置顶文章\n")
for issue in top_issues:
if isMe(issue, me):
add_issue_info(issue, md)
def add_md_recent(repo, md, me):
new_last_issues = repo.get_issues()[:10]
with open(md, "a+", encoding="utf-8") as md:
# one the issue that only one issue and delete (pyGitHub raise an exception)
try:
md.write("## 最近更新\n")
for issue in new_last_issues:
if isMe(issue, me):
add_issue_info(issue, md)
except:
return
def add_md_header(md):
with open(md, "w", encoding="utf-8") as md:
md.write(MD_HEAD)
def add_md_label(repo, md, me):
labels = get_repo_labels(repo)
with open(md, "a+", encoding="utf-8") as md:
for label in labels:
# we don't need add top label again
if label.name in TOP_ISSUES_LABELS:
continue
# we don't need add todo label again
if label.name in TODO_ISSUES_LABELS:
continue
issues = get_issues_from_label(repo, label)
if issues.totalCount:
md.write("## " + label.name + "\n")
issues = sorted(
issues, key=lambda x: x.created_at, reverse=True)
i = 0
for issue in issues:
if not issue:
continue
if isMe(issue, me):
if i == ANCHOR_NUMBER:
md.write("<details><summary>显示更多</summary>\n")
md.write("\n")
add_issue_info(issue, md)
i += 1
if i > ANCHOR_NUMBER:
md.write("</details>\n")
md.write("\n")
def get_to_generate_issues(repo, dir_name, me, issue_number=None):
to_generate_issues = [
i
for i in list(repo.get_issues())
if isMe(i, me)
]
if issue_number:
to_generate_issues.append(repo.get_issue(int(issue_number)))
return to_generate_issues
def main(token, repo_name="blogs", issue_number=None, dir_name=BACKUP_DIR):
user = login(token)
me = get_me(user)
repo = get_repo(user, repo_name)
add_md_header("README.md")
# add to readme one by one, change order here
for func in [add_md_top, add_md_recent, add_md_label, add_md_todo]:
func(repo, "README.md", me)
to_generate_issues = get_to_generate_issues(
repo, dir_name, me, issue_number)
# save md files to backup folder
for issue in to_generate_issues:
save_issue(issue, me, dir_name)
def save_issue(issue, me, dir_name=BACKUP_DIR):
md_dir = os.path.join(
dir_name, str(issue.id)
)
if not os.path.exists(md_dir):
os.makedirs(md_dir)
md_name = os.path.join(md_dir, "index.md")
with open(md_name, "w") as f:
f.write('---\n')
f.write(f"title: '{issue.title}'\n")
f.write(f"date: '{issue.created_at.strftime('%Y-%m-%d')}'\n")
f.write("spoiler: ''\n")
f.write('---\n\n')
f.write(issue.body)
print(os.path.abspath(BACKUP_DIR))
shutil.rmtree(os.path.abspath(BACKUP_DIR))
os.makedirs(BACKUP_DIR)
parser = argparse.ArgumentParser()
parser.add_argument("github_token", help="github_token")
parser.add_argument("repo_name", help="repo_name")
parser.add_argument("--issue_number", help="issue_number",
default=None, required=False)
options = parser.parse_args()
main(options.github_token, options.repo_name, options.issue_number)
|
import datetime
import MySQLdb
from itemadapter import ItemAdapter
from scrapy.exceptions import DropItem
from naver_movie.config import db_info
class NaverMoviePipeline:
def __init__(self):
self.conn = MySQLdb.connect(**db_info)
self.curs = self.conn.cursor()
def open_spider(self, spider):
spider.logger.info("Pipeline Started.")
spider.logger.info("Scrapying Start")
QUERY = """
DROP TABLE naver_movie;
CREATE TABLE IF NOT EXISTS naver_movie (
id INT PRIMARY KEY AUTO_INCREMENT,
title TEXT,
link TEXT,
rate FLOAT,
genre TEXT,
score FLOAT,
view FLOAT,
director TEXT,
actor TEXT,
crawled_time TEXT);
"""
self.curs.execute(QUERY.replace("\n", ""))
def process_item(self, item, spider):
if item.get("rate") != "0":
item["crawled_time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.curs.execute(f'INSERT INTO naver_movie (title, link, rate, genre, score, view, director, actor, crawled_time) VALUES ("{item.get('title')}", "{item.get('link')}", {item.get('rate')}, "{item.get('genre')}", {item.get('score')}, {item.get('view')}, "{item.get('director')}", "{item.get('actor')}", "{item.get('crawled_time')}");')
spider.logger.info(f'Item to DB inserted. title : {item.get('title')}')
return item
else:
raise DropItem(f'Dropped Item. title : {item.get('title')}')
def close_spider(self, spider):
spider.logger.info("Pipeline Closed.")
spider.logger.info("Scrapying Done")
self.conn.commit()
self.conn.close() | import datetime
import MySQLdb
from itemadapter import ItemAdapter
from scrapy.exceptions import DropItem
from naver_movie.config import db_info
class NaverMoviePipeline:
def __init__(self):
self.conn = MySQLdb.connect(**db_info)
self.curs = self.conn.cursor()
def open_spider(self, spider):
spider.logger.info("Pipeline Started.")
spider.logger.info("Scrapying Start")
QUERY = """
DROP TABLE naver_movie;
CREATE TABLE IF NOT EXISTS naver_movie (
id INT PRIMARY KEY AUTO_INCREMENT,
title TEXT,
link TEXT,
rate FLOAT,
genre TEXT,
score FLOAT,
view FLOAT,
director TEXT,
actor TEXT,
crawled_time TEXT);
"""
self.curs.execute(QUERY.replace("\n", ""))
def process_item(self, item, spider):
if item.get("rate") != "0":
item["crawled_time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.curs.execute(f'INSERT INTO naver_movie (title, link, rate, genre, score, view, director, actor, crawled_time) VALUES ("{item.get("title")}", "{item.get("link")}", {item.get("rate")}, "{item.get("genre")}", {item.get("score")}, {item.get("view")}, "{item.get("director")}", "{item.get("actor")}", "{item.get("crawled_time")}");')
spider.logger.info(f'Item to DB inserted. title : {item.get("title")}')
return item
else:
raise DropItem(f'Dropped Item. title : {item.get("title")}')
def close_spider(self, spider):
spider.logger.info("Pipeline Closed.")
spider.logger.info("Scrapying Done")
self.conn.commit()
self.conn.close() |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Name: _extd_ast_expr
# Purpose: Extensions of AST subclasses used in expressions
#
# Author: Michael Amrhein (michael@adrhinum.de)
#
# Copyright: (c) 2018 ff. Michael Amrhein
# License: This program is part of a larger application. For license
# details please read the file LICENSE.TXT provided together
# with the application.
# ----------------------------------------------------------------------------
"""Extensions of AST subclasses used in expressions"""
# standard library imports
import ast
from ast import AST, Expression
from copy import deepcopy
from functools import singledispatch
from itertools import chain
from typing import Optional, Set, Union
Operator = Union[ast.operator, ast.unaryop, ast.boolop, ast.cmpop]
# TODO: more documentation
# TODO: optimizations by applying boolean algebra rules
class OpBindingManager:
"""Context manager keeping track of nested operators and their binding
level.
"""
OPS = {
ast.Lambda: 1,
ast.IfExp: 1,
ast.Or: 3,
ast.And: 4,
ast.Not: 5,
ast.Eq: 6,
ast.NotEq: 6,
ast.Lt: 6,
ast.LtE: 6,
ast.Gt: 6,
ast.GtE: 6,
ast.Is: 6,
ast.IsNot: 6,
ast.In: 6,
ast.NotIn: 6,
ast.BitOr: 7,
ast.BitXor: 8,
ast.BitAnd: 9,
ast.LShift: 10,
ast.RShift: 10,
ast.Add: 11,
ast.Sub: 11,
ast.Mult: 12,
ast.Div: 12,
ast.FloorDiv: 12,
ast.Mod: 12,
ast.UAdd: 13,
ast.USub: 13,
ast.Invert: 13,
ast.Pow: 14,
ast.Starred: 20,
}
def __init__(self) -> None:
"""Initialize instance of OpBindingManager"""
self.nested_ops = []
def __call__(self, op: Operator) -> 'OpBindingManager':
"""Append nested operator."""
self.nested_ops.append((op, self.OPS[type(op)]))
return self
def __enter__(self) -> None:
"""Enter context."""
return None
def __exit__(self, exc, msg, tb) -> None:
"""Exit context."""
if exc is None:
self.nested_ops.pop()
def diff_binding(self) -> int:
"""Return the difference betweens the binding levels of the current
and the previous operator.
"""
try:
prev_op, prev_op_binding = self.nested_ops[-2]
except IndexError:
prev_op, prev_op_binding = None, 0
try:
curr_op, curr_op_binding = self.nested_ops[-1]
except IndexError:
curr_op, curr_op_binding = None, 0
# special case
if prev_op is ast.Pow and isinstance(curr_op, (ast.Invert, ast.USub)):
return 1
# print(prev_op, prev_op_binding, curr_op, curr_op_binding)
return curr_op_binding - prev_op_binding
class SourceGenerator:
"""Generates Python source code from an AST expression."""
def __init__(self) -> None:
"""Initialize instance of SourceGenerator."""
self.op_man = OpBindingManager()
self.compact = False
# helper
def parenthesize(self, src: str) -> str:
"""Return `src` embedded in parentheses."""
return f"({src})"
def wrap_expr(self, src: str, dfltChaining: bool) -> str:
"""Wrap `src` in parentheses if neccessary."""
diff_binding = self.op_man.diff_binding()
if diff_binding < 0 or diff_binding == 0 and not dfltChaining:
return self.parenthesize(src)
else:
return src
# extended dispatcher (portions copied from standard ast module)
def visit(self, node: AST, dfltChaining: bool = True) -> str:
"""Process `node` by dispatching to a handler."""
# print(node.__class__.__name__)
if node is None:
return ''
if isinstance(node, ast.Expression):
return self.visit(node.body)
# dispatch to specific or generic method
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node, dfltChaining)
def generic_visit(self, node: AST, dfltChaining: bool = True) -> str:
"""Default handler, called if no explicit visitor function exists for
a node.
"""
for field, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
self.visit(item)
elif isinstance(value, AST):
self.visit(value)
# for conveniernce
__call__ = visit
# literals
def visit_NameConstant(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s name as string."""
return str(node.value)
def visit_Num(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s number as string."""
return str(node.n)
def visit_Str(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s string representation."""
return repr(node.s)
CONV_MAP = {115: '!s', 114: '!r', 97: '!a'}
def visit_FormattedValue(self, node: AST,
dfltChaining: bool = True) -> str:
"""Return `node`s value formatted according to its format spec."""
format_spec = node.format_spec
return f"{{{self.visit(node.value)}" \
f"{self.CONV_MAP.get(node.conversion, "")}" \
f"{":"+self._nested_str(format_spec) if format_spec else ""}}}"
def _nested_str(self, node: AST) -> str:
if type(node) is ast.Str:
return node.s
if type(node) is ast.JoinedStr:
return ''.join(self._nested_str(val) for val in node.values)
return self.visit(node)
def visit_JoinedStr(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s values concatenated as string."""
return f'''f"{''.join(self._nested_str(val)
for val in node.values)}"'''
def visit_Bytes(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s bytes as string representation."""
return repr(node.s)
def visit_List(self, node: AST, dfltChaining: bool = True) -> str:
"""Return list representation of `node`s elements."""
return f"[{", ".join([self.visit(elt) for elt in node.elts])}]"
def visit_Tuple(self, node: AST, dfltChaining: bool = True) -> str:
"""Return tuple representation of `node`s elements."""
elems = (self.visit(elt) for elt in node.elts)
return f"({", ".join(elems)}{")" if len(node.elts) != 1 else ",)"}"
def visit_Set(self, node: AST, dfltChaining: bool = True) -> str:
"""Return set representation of `node`s elements."""
return '{' + ', '.join([self.visit(elt) for elt in node.elts]) + '}'
def visit_Dict(self, node: AST, dfltChaining: bool = True) -> str:
"""Return dict representation of `node`s elements."""
items = (': '.join((self.visit(key), self.visit(value)))
for key, value in zip(node.keys, node.values))
return f"{{{", ".join(items)}}}"
def visit_Ellipsis(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '...'."""
return '...'
# variables
def visit_Name(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s id."""
return node.id
def visit_Starred(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of starred expresssion."""
with self.op_man(node):
return f"*{self.visit(node.value)}"
# nested expression
def visit_Expr(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of nested expression."""
return self.visit(node.value)
# unary operators
def visit_UnaryOp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of `node`s operator and operand."""
op = node.op
with self.op_man(op):
return self.visit(op) + self.visit(node.operand)
def visit_UAdd(self, node: AST, dfltChaining: bool = True) -> str:
"""Return empty string."""
return ''
def visit_USub(self, node: AST, dfltChaining: bool = True) -> str:
"""Return minus sign."""
return '-'
def visit_Not(self, node: AST, dfltChaining: bool = True) -> str:
"""Return 'not '."""
return 'not '
def visit_Invert(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '~'."""
return '~'
# binary operators
def visit_BinOp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s operator and operands as inlined expression."""
op = node.op
with self.op_man(op):
if isinstance(op, ast.Pow):
# Pow chains right-to-left
src = self.visit(op).join((self.visit(node.left,
dfltChaining=False),
self.visit(node.right)))
else:
src = self.visit(op).join((self.visit(node.left),
self.visit(node.right,
dfltChaining=False)))
return self.wrap_expr(src, dfltChaining)
def visit_Add(self, node: AST, dfltChaining: bool = True) -> str:
"""Return plus sign."""
return '+' if self.compact else ' + '
def visit_Sub(self, node: AST, dfltChaining: bool = True) -> str:
"""Return minus sign."""
return '-' if self.compact else ' - '
def visit_Mult(self, node: AST, dfltChaining: bool = True) -> str:
"""Return multiplication sign."""
return '*' if self.compact else ' * '
def visit_Div(self, node: AST, dfltChaining: bool = True) -> str:
"""Return division sign."""
return '/' if self.compact else ' / '
def visit_FloorDiv(self, node: AST, dfltChaining: bool = True) -> str:
"""Return floor division sign."""
return '//' if self.compact else ' // '
def visit_Mod(self, node: AST, dfltChaining: bool = True) -> str:
"""Return percentage sign."""
return '%' if self.compact else ' % '
def visit_Pow(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '**'."""
return '**' if self.compact else ' ** '
def visit_LShift(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '<<'."""
return '<<' if self.compact else ' << '
def visit_RShift(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '>>'."""
return '>>' if self.compact else ' >> '
def visit_BitOr(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '|'."""
return '|' if self.compact else ' | '
def visit_BitXor(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '^'."""
return '^' if self.compact else ' ^ '
def visit_BitAnd(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '&'."""
return '&' if self.compact else ' & '
# boolean operators
def visit_BoolOp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s operator and operands as inlined expression."""
op = node.op
with self.op_man(op):
src = self.visit(op).join([self.visit(node.values[0])] +
[self.visit(val, dfltChaining=False)
for val in node.values[1:]])
return self.wrap_expr(src, dfltChaining)
def visit_And(self, node: AST, dfltChaining: bool = True) -> str:
"""Return ' and '."""
return ' and '
def visit_Or(self, node: AST, dfltChaining: bool = True) -> str:
"""Return ' or '."""
return ' or '
# comparisons
def visit_Compare(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s operators and operands as inlined expression."""
# all comparison operators have the same precedence,
# we just take the first one as representative
first_op = node.ops[0]
with self.op_man(first_op):
cmps = [' '.join((self.visit(op),
self.visit(cmp, dfltChaining=False)))
for op, cmp in zip(node.ops, node.comparators)]
src = ' '.join((self.visit(node.left), ' '.join(cmps)))
return self.wrap_expr(src, dfltChaining)
def visit_Eq(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '=='."""
return '=='
def visit_NotEq(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '!='."""
return '!='
def visit_Gt(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '>'."""
return '>'
def visit_GtE(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '>='."""
return '>='
def visit_Lt(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '<'."""
return '<'
def visit_LtE(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '<='."""
return '<='
def visit_Is(self, node: AST, dfltChaining: bool = True) -> str:
"""Return 'is'."""
return 'is'
def visit_IsNot(self, node: AST, dfltChaining: bool = True) -> str:
"""Return 'is not'."""
return 'is not'
def visit_In(self, node: AST, dfltChaining: bool = True) -> str:
"""Return 'in'."""
return 'in'
def visit_NotIn(self, node: AST, dfltChaining: bool = True) -> str:
"""Return 'not in'."""
return 'not in'
# call
def visit_keyword(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of `node` as keyword arg."""
arg = node.arg
if arg is None:
return f"**{self.visit(node.value)}"
else:
return f"{arg}={self.visit(node.value)}"
def visit_Call(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as function call."""
args = node.args
try:
kwds = node.keywords
except AttributeError:
kwds = []
self.compact = True
args_src = (self.visit(arg) for arg in args)
kwds_src = (self.visit(kwd) for kwd in kwds)
param_src = ', '.join(chain(args_src, kwds_src))
src = f"{self.visit(node.func)}({param_src})"
self.compact = False
return src
# lambda
def visit_arguments(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as argument list."""
args = node.args
dflts = node.defaults
vararg = node.vararg
kwargs = node.kwonlyargs
kwdflts = node.kw_defaults
kwarg = node.kwarg
self.compact = True
n_args_without_dflt = len(args) - len(dflts)
args_src = (arg.arg for arg in args[:n_args_without_dflt])
dflts_src = (f"{arg.arg}={self.visit(dflt)}"
for arg, dflt in zip(args[n_args_without_dflt:], dflts))
vararg_src = (f"*{vararg.arg}",) if vararg else ()
kwargs_src = ((f"{kw.arg}={self.visit(dflt)}"
if dflt is not None else f"{kw.arg}")
for kw, dflt in zip(kwargs, kwdflts))
kwarg_src = (f"**{kwarg.arg}",) if kwarg else ()
src = ', '.join(chain(args_src, dflts_src, vararg_src,
kwargs_src, kwarg_src))
self.compact = False
return src
def visit_Lambda(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as lambda expression."""
with self.op_man(node):
src = f"lambda {self.visit(node.args)}: {self.visit(node.body)}"
return self.wrap_expr(src, dfltChaining)
# … if … else …
def visit_IfExp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as ... if ... else ... expression."""
with self.op_man(node):
src = " if ".join((self.visit(node.body, dfltChaining=False),
" else ".join((self.visit(node.test),
self.visit(node.orelse)))))
return self.wrap_expr(src, dfltChaining)
# attribute access
def visit_Attribute(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as attribute access."""
return '.'.join((self.visit(node.value), node.attr))
# subscripting
def visit_Subscript(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as subscript access."""
return f"{self.visit(node.value)}[{self.visit(node.slice)}]"
def visit_Index(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of `node`s value."""
return self.visit(node.value)
def visit_Slice(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as slice."""
elems = [self.visit(node.lower), self.visit(node.upper)]
if node.step is not None:
elems.append(self.visit(node.step))
return ':'.join(elems)
def visit_ExtSlice(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as extended slice."""
return ', '.join((self.visit(dim) for dim in node.dims))
# comprehensions
def visit_comprehension(self, node: AST,
dfltChaining: bool = True) -> str:
"""Return `node`s representation as comprehension."""
target = node.target
try:
elts = target.elts # we have a tuple of names
except AttributeError:
names = self.visit(target)
else:
names = ', '.join(self.visit(elt) for elt in elts)
src = f"for {names} in {self.visit(node.iter)}"
if node.ifs:
src += f" {" ".join("if " + self.visit(if_) for if_ in node.ifs)}"
return src
def visit_ListComp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as list comprehension."""
return f"[{self.visit(node.elt)} " \
f"{" ".join(self.visit(gen) for gen in node.generators)}]"
def visit_SetComp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as set comprehension."""
return f"{{{self.visit(node.elt)} " \
f"{" ".join(self.visit(gen) for gen in node.generators)}}}"
def visit_DictComp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as dict comprehension."""
return f"{{{self.visit(node.key)}: {self.visit(node.value)} " \
f"{" ".join(self.visit(gen) for gen in node.generators)}}}"
def visit_GeneratorExp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as generator expression."""
return f"({self.visit(node.elt)} " \
f"{" ".join(self.visit(gen) for gen in node.generators)})"
def src2ast(src: str) -> Expression:
"""Return ast.Expression created from source code given in `src`."""
try:
return ast.parse(src, mode='eval')
except SyntaxError:
raise ValueError("Not a valid expression.") from None
def ast2src(expr: Expression) -> str:
"""Return source code equivalent to `expr`."""
return SourceGenerator().visit(expr)
def names(expr: AST) -> Set[str]:
"""Names of globals in `expr`."""
nodes = [node for node in ast.walk(expr) if isinstance(node, ast.Name)]
loaded = {node.id for node in nodes if isinstance(node.ctx, ast.Load)}
stored = {node.id for node in nodes if isinstance(node.ctx, ast.Store)}
return loaded - stored
class _NameReplacer(ast.NodeTransformer):
def __init__(self, old_name: str, new_name: str) -> None:
self._old_name = old_name
self._new_name = new_name
def visit_Name(self, node: AST) -> Optional[AST]:
if node.id == self._old_name:
return ast.copy_location(ast.Name(id=self._new_name,
ctx=ast.Load()), node)
return node
def replace_name(expr: AST, old_name: str, new_name: str) -> AST:
"""Replace all Name nodes named `old_name` with nodes named `new_name`."""
return _NameReplacer(old_name, new_name).visit(deepcopy(expr))
@singledispatch
def _negate(node: ast.expr) -> ast.expr:
return ast.UnaryOp(ast.Not(), node)
@_negate.register(ast.UnaryOp)
def _negate_unary_op(node: ast.UnaryOp) -> ast.expr:
if isinstance(node.op, ast.Not):
return node.operand
return _negate.dispatch(ast.expr)(node)
class _InversCmpOp:
CPM2INVERS = {
ast.Eq: ast.NotEq,
ast.NotEq: ast.Eq,
ast.Lt: ast.GtE,
ast.LtE: ast.Gt,
ast.Gt: ast.LtE,
ast.GtE: ast.Lt,
ast.Is: ast.IsNot,
ast.IsNot: ast.Is,
ast.In: ast.NotIn,
ast.NotIn: ast.In,
}
def __new__(self, op: ast.cmpop) -> ast.cmpop:
return self.CPM2INVERS[type(op)]()
@_negate.register(ast.Compare)
def _negate_compare(node: ast.Compare) -> ast.Compare:
return ast.Compare(node.left,
[_InversCmpOp(op) for op in node.ops],
node.comparators)
@_negate.register(ast.BoolOp)
def _negate_bool_op(node: ast.BoolOp) -> ast.BoolOp:
return _negate.dispatch(ast.expr)(node)
def Negation(expr: Expression) -> Expression:
"""Return expression which is the negation of `expr`."""
expr = Expression(_negate(expr.body))
return ast.fix_missing_locations(expr)
def Conjunction(expr1: Expression, expr2: Expression) -> Expression:
"""Return expression which is the conjunction of `expr1` and `expr2`."""
expr = Expression(ast.BoolOp(ast.And(), [expr1.body, expr2.body]))
return ast.fix_missing_locations(expr)
def Disjunction(expr1: Expression, expr2: Expression) -> Expression:
"""Return expression which is the disjunction of `expr1` and `expr2`."""
expr = Expression(ast.BoolOp(ast.Or(), [expr1.body, expr2.body]))
return ast.fix_missing_locations(expr)
def Contradiction(expr1: Expression, expr2: Expression) -> Expression:
"""Return expression which is the contradiction of `expr1` and `expr2`."""
expr = Disjunction(Conjunction(expr1, Negation(expr2)),
Conjunction(Negation(expr1), expr2))
return ast.fix_missing_locations(expr)
| # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Name: _extd_ast_expr
# Purpose: Extensions of AST subclasses used in expressions
#
# Author: Michael Amrhein (michael@adrhinum.de)
#
# Copyright: (c) 2018 ff. Michael Amrhein
# License: This program is part of a larger application. For license
# details please read the file LICENSE.TXT provided together
# with the application.
# ----------------------------------------------------------------------------
"""Extensions of AST subclasses used in expressions"""
# standard library imports
import ast
from ast import AST, Expression
from copy import deepcopy
from functools import singledispatch
from itertools import chain
from typing import Optional, Set, Union
Operator = Union[ast.operator, ast.unaryop, ast.boolop, ast.cmpop]
# TODO: more documentation
# TODO: optimizations by applying boolean algebra rules
class OpBindingManager:
"""Context manager keeping track of nested operators and their binding
level.
"""
OPS = {
ast.Lambda: 1,
ast.IfExp: 1,
ast.Or: 3,
ast.And: 4,
ast.Not: 5,
ast.Eq: 6,
ast.NotEq: 6,
ast.Lt: 6,
ast.LtE: 6,
ast.Gt: 6,
ast.GtE: 6,
ast.Is: 6,
ast.IsNot: 6,
ast.In: 6,
ast.NotIn: 6,
ast.BitOr: 7,
ast.BitXor: 8,
ast.BitAnd: 9,
ast.LShift: 10,
ast.RShift: 10,
ast.Add: 11,
ast.Sub: 11,
ast.Mult: 12,
ast.Div: 12,
ast.FloorDiv: 12,
ast.Mod: 12,
ast.UAdd: 13,
ast.USub: 13,
ast.Invert: 13,
ast.Pow: 14,
ast.Starred: 20,
}
def __init__(self) -> None:
"""Initialize instance of OpBindingManager"""
self.nested_ops = []
def __call__(self, op: Operator) -> 'OpBindingManager':
"""Append nested operator."""
self.nested_ops.append((op, self.OPS[type(op)]))
return self
def __enter__(self) -> None:
"""Enter context."""
return None
def __exit__(self, exc, msg, tb) -> None:
"""Exit context."""
if exc is None:
self.nested_ops.pop()
def diff_binding(self) -> int:
"""Return the difference betweens the binding levels of the current
and the previous operator.
"""
try:
prev_op, prev_op_binding = self.nested_ops[-2]
except IndexError:
prev_op, prev_op_binding = None, 0
try:
curr_op, curr_op_binding = self.nested_ops[-1]
except IndexError:
curr_op, curr_op_binding = None, 0
# special case
if prev_op is ast.Pow and isinstance(curr_op, (ast.Invert, ast.USub)):
return 1
# print(prev_op, prev_op_binding, curr_op, curr_op_binding)
return curr_op_binding - prev_op_binding
class SourceGenerator:
"""Generates Python source code from an AST expression."""
def __init__(self) -> None:
"""Initialize instance of SourceGenerator."""
self.op_man = OpBindingManager()
self.compact = False
# helper
def parenthesize(self, src: str) -> str:
"""Return `src` embedded in parentheses."""
return f"({src})"
def wrap_expr(self, src: str, dfltChaining: bool) -> str:
"""Wrap `src` in parentheses if neccessary."""
diff_binding = self.op_man.diff_binding()
if diff_binding < 0 or diff_binding == 0 and not dfltChaining:
return self.parenthesize(src)
else:
return src
# extended dispatcher (portions copied from standard ast module)
def visit(self, node: AST, dfltChaining: bool = True) -> str:
"""Process `node` by dispatching to a handler."""
# print(node.__class__.__name__)
if node is None:
return ''
if isinstance(node, ast.Expression):
return self.visit(node.body)
# dispatch to specific or generic method
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node, dfltChaining)
def generic_visit(self, node: AST, dfltChaining: bool = True) -> str:
"""Default handler, called if no explicit visitor function exists for
a node.
"""
for field, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
self.visit(item)
elif isinstance(value, AST):
self.visit(value)
# for conveniernce
__call__ = visit
# literals
def visit_NameConstant(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s name as string."""
return str(node.value)
def visit_Num(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s number as string."""
return str(node.n)
def visit_Str(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s string representation."""
return repr(node.s)
CONV_MAP = {115: '!s', 114: '!r', 97: '!a'}
def visit_FormattedValue(self, node: AST,
dfltChaining: bool = True) -> str:
"""Return `node`s value formatted according to its format spec."""
format_spec = node.format_spec
return f"{{{self.visit(node.value)}" \
f"{self.CONV_MAP.get(node.conversion, '')}" \
f"{':'+self._nested_str(format_spec) if format_spec else ''}}}"
def _nested_str(self, node: AST) -> str:
if type(node) is ast.Str:
return node.s
if type(node) is ast.JoinedStr:
return ''.join(self._nested_str(val) for val in node.values)
return self.visit(node)
def visit_JoinedStr(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s values concatenated as string."""
return f'''f"{''.join(self._nested_str(val)
for val in node.values)}"'''
def visit_Bytes(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s bytes as string representation."""
return repr(node.s)
def visit_List(self, node: AST, dfltChaining: bool = True) -> str:
"""Return list representation of `node`s elements."""
return f"[{', '.join([self.visit(elt) for elt in node.elts])}]"
def visit_Tuple(self, node: AST, dfltChaining: bool = True) -> str:
"""Return tuple representation of `node`s elements."""
elems = (self.visit(elt) for elt in node.elts)
return f"({', '.join(elems)}{')' if len(node.elts) != 1 else ',)'}"
def visit_Set(self, node: AST, dfltChaining: bool = True) -> str:
"""Return set representation of `node`s elements."""
return '{' + ', '.join([self.visit(elt) for elt in node.elts]) + '}'
def visit_Dict(self, node: AST, dfltChaining: bool = True) -> str:
"""Return dict representation of `node`s elements."""
items = (': '.join((self.visit(key), self.visit(value)))
for key, value in zip(node.keys, node.values))
return f"{{{', '.join(items)}}}"
def visit_Ellipsis(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '...'."""
return '...'
# variables
def visit_Name(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s id."""
return node.id
def visit_Starred(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of starred expresssion."""
with self.op_man(node):
return f"*{self.visit(node.value)}"
# nested expression
def visit_Expr(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of nested expression."""
return self.visit(node.value)
# unary operators
def visit_UnaryOp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of `node`s operator and operand."""
op = node.op
with self.op_man(op):
return self.visit(op) + self.visit(node.operand)
def visit_UAdd(self, node: AST, dfltChaining: bool = True) -> str:
"""Return empty string."""
return ''
def visit_USub(self, node: AST, dfltChaining: bool = True) -> str:
"""Return minus sign."""
return '-'
def visit_Not(self, node: AST, dfltChaining: bool = True) -> str:
"""Return 'not '."""
return 'not '
def visit_Invert(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '~'."""
return '~'
# binary operators
def visit_BinOp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s operator and operands as inlined expression."""
op = node.op
with self.op_man(op):
if isinstance(op, ast.Pow):
# Pow chains right-to-left
src = self.visit(op).join((self.visit(node.left,
dfltChaining=False),
self.visit(node.right)))
else:
src = self.visit(op).join((self.visit(node.left),
self.visit(node.right,
dfltChaining=False)))
return self.wrap_expr(src, dfltChaining)
def visit_Add(self, node: AST, dfltChaining: bool = True) -> str:
"""Return plus sign."""
return '+' if self.compact else ' + '
def visit_Sub(self, node: AST, dfltChaining: bool = True) -> str:
"""Return minus sign."""
return '-' if self.compact else ' - '
def visit_Mult(self, node: AST, dfltChaining: bool = True) -> str:
"""Return multiplication sign."""
return '*' if self.compact else ' * '
def visit_Div(self, node: AST, dfltChaining: bool = True) -> str:
"""Return division sign."""
return '/' if self.compact else ' / '
def visit_FloorDiv(self, node: AST, dfltChaining: bool = True) -> str:
"""Return floor division sign."""
return '//' if self.compact else ' // '
def visit_Mod(self, node: AST, dfltChaining: bool = True) -> str:
"""Return percentage sign."""
return '%' if self.compact else ' % '
def visit_Pow(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '**'."""
return '**' if self.compact else ' ** '
def visit_LShift(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '<<'."""
return '<<' if self.compact else ' << '
def visit_RShift(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '>>'."""
return '>>' if self.compact else ' >> '
def visit_BitOr(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '|'."""
return '|' if self.compact else ' | '
def visit_BitXor(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '^'."""
return '^' if self.compact else ' ^ '
def visit_BitAnd(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '&'."""
return '&' if self.compact else ' & '
# boolean operators
def visit_BoolOp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s operator and operands as inlined expression."""
op = node.op
with self.op_man(op):
src = self.visit(op).join([self.visit(node.values[0])] +
[self.visit(val, dfltChaining=False)
for val in node.values[1:]])
return self.wrap_expr(src, dfltChaining)
def visit_And(self, node: AST, dfltChaining: bool = True) -> str:
"""Return ' and '."""
return ' and '
def visit_Or(self, node: AST, dfltChaining: bool = True) -> str:
"""Return ' or '."""
return ' or '
# comparisons
def visit_Compare(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s operators and operands as inlined expression."""
# all comparison operators have the same precedence,
# we just take the first one as representative
first_op = node.ops[0]
with self.op_man(first_op):
cmps = [' '.join((self.visit(op),
self.visit(cmp, dfltChaining=False)))
for op, cmp in zip(node.ops, node.comparators)]
src = ' '.join((self.visit(node.left), ' '.join(cmps)))
return self.wrap_expr(src, dfltChaining)
def visit_Eq(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '=='."""
return '=='
def visit_NotEq(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '!='."""
return '!='
def visit_Gt(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '>'."""
return '>'
def visit_GtE(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '>='."""
return '>='
def visit_Lt(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '<'."""
return '<'
def visit_LtE(self, node: AST, dfltChaining: bool = True) -> str:
"""Return '<='."""
return '<='
def visit_Is(self, node: AST, dfltChaining: bool = True) -> str:
"""Return 'is'."""
return 'is'
def visit_IsNot(self, node: AST, dfltChaining: bool = True) -> str:
"""Return 'is not'."""
return 'is not'
def visit_In(self, node: AST, dfltChaining: bool = True) -> str:
"""Return 'in'."""
return 'in'
def visit_NotIn(self, node: AST, dfltChaining: bool = True) -> str:
"""Return 'not in'."""
return 'not in'
# call
def visit_keyword(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of `node` as keyword arg."""
arg = node.arg
if arg is None:
return f"**{self.visit(node.value)}"
else:
return f"{arg}={self.visit(node.value)}"
def visit_Call(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as function call."""
args = node.args
try:
kwds = node.keywords
except AttributeError:
kwds = []
self.compact = True
args_src = (self.visit(arg) for arg in args)
kwds_src = (self.visit(kwd) for kwd in kwds)
param_src = ', '.join(chain(args_src, kwds_src))
src = f"{self.visit(node.func)}({param_src})"
self.compact = False
return src
# lambda
def visit_arguments(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as argument list."""
args = node.args
dflts = node.defaults
vararg = node.vararg
kwargs = node.kwonlyargs
kwdflts = node.kw_defaults
kwarg = node.kwarg
self.compact = True
n_args_without_dflt = len(args) - len(dflts)
args_src = (arg.arg for arg in args[:n_args_without_dflt])
dflts_src = (f"{arg.arg}={self.visit(dflt)}"
for arg, dflt in zip(args[n_args_without_dflt:], dflts))
vararg_src = (f"*{vararg.arg}",) if vararg else ()
kwargs_src = ((f"{kw.arg}={self.visit(dflt)}"
if dflt is not None else f"{kw.arg}")
for kw, dflt in zip(kwargs, kwdflts))
kwarg_src = (f"**{kwarg.arg}",) if kwarg else ()
src = ', '.join(chain(args_src, dflts_src, vararg_src,
kwargs_src, kwarg_src))
self.compact = False
return src
def visit_Lambda(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as lambda expression."""
with self.op_man(node):
src = f"lambda {self.visit(node.args)}: {self.visit(node.body)}"
return self.wrap_expr(src, dfltChaining)
# … if … else …
def visit_IfExp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as ... if ... else ... expression."""
with self.op_man(node):
src = " if ".join((self.visit(node.body, dfltChaining=False),
" else ".join((self.visit(node.test),
self.visit(node.orelse)))))
return self.wrap_expr(src, dfltChaining)
# attribute access
def visit_Attribute(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as attribute access."""
return '.'.join((self.visit(node.value), node.attr))
# subscripting
def visit_Subscript(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as subscript access."""
return f"{self.visit(node.value)}[{self.visit(node.slice)}]"
def visit_Index(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of `node`s value."""
return self.visit(node.value)
def visit_Slice(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as slice."""
elems = [self.visit(node.lower), self.visit(node.upper)]
if node.step is not None:
elems.append(self.visit(node.step))
return ':'.join(elems)
def visit_ExtSlice(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as extended slice."""
return ', '.join((self.visit(dim) for dim in node.dims))
# comprehensions
def visit_comprehension(self, node: AST,
dfltChaining: bool = True) -> str:
"""Return `node`s representation as comprehension."""
target = node.target
try:
elts = target.elts # we have a tuple of names
except AttributeError:
names = self.visit(target)
else:
names = ', '.join(self.visit(elt) for elt in elts)
src = f"for {names} in {self.visit(node.iter)}"
if node.ifs:
src += f" {' '.join('if ' + self.visit(if_) for if_ in node.ifs)}"
return src
def visit_ListComp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as list comprehension."""
return f"[{self.visit(node.elt)} " \
f"{' '.join(self.visit(gen) for gen in node.generators)}]"
def visit_SetComp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as set comprehension."""
return f"{{{self.visit(node.elt)} " \
f"{' '.join(self.visit(gen) for gen in node.generators)}}}"
def visit_DictComp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as dict comprehension."""
return f"{{{self.visit(node.key)}: {self.visit(node.value)} " \
f"{' '.join(self.visit(gen) for gen in node.generators)}}}"
def visit_GeneratorExp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as generator expression."""
return f"({self.visit(node.elt)} " \
f"{' '.join(self.visit(gen) for gen in node.generators)})"
def src2ast(src: str) -> Expression:
"""Return ast.Expression created from source code given in `src`."""
try:
return ast.parse(src, mode='eval')
except SyntaxError:
raise ValueError("Not a valid expression.") from None
def ast2src(expr: Expression) -> str:
"""Return source code equivalent to `expr`."""
return SourceGenerator().visit(expr)
def names(expr: AST) -> Set[str]:
"""Names of globals in `expr`."""
nodes = [node for node in ast.walk(expr) if isinstance(node, ast.Name)]
loaded = {node.id for node in nodes if isinstance(node.ctx, ast.Load)}
stored = {node.id for node in nodes if isinstance(node.ctx, ast.Store)}
return loaded - stored
class _NameReplacer(ast.NodeTransformer):
def __init__(self, old_name: str, new_name: str) -> None:
self._old_name = old_name
self._new_name = new_name
def visit_Name(self, node: AST) -> Optional[AST]:
if node.id == self._old_name:
return ast.copy_location(ast.Name(id=self._new_name,
ctx=ast.Load()), node)
return node
def replace_name(expr: AST, old_name: str, new_name: str) -> AST:
"""Replace all Name nodes named `old_name` with nodes named `new_name`."""
return _NameReplacer(old_name, new_name).visit(deepcopy(expr))
@singledispatch
def _negate(node: ast.expr) -> ast.expr:
return ast.UnaryOp(ast.Not(), node)
@_negate.register(ast.UnaryOp)
def _negate_unary_op(node: ast.UnaryOp) -> ast.expr:
if isinstance(node.op, ast.Not):
return node.operand
return _negate.dispatch(ast.expr)(node)
class _InversCmpOp:
CPM2INVERS = {
ast.Eq: ast.NotEq,
ast.NotEq: ast.Eq,
ast.Lt: ast.GtE,
ast.LtE: ast.Gt,
ast.Gt: ast.LtE,
ast.GtE: ast.Lt,
ast.Is: ast.IsNot,
ast.IsNot: ast.Is,
ast.In: ast.NotIn,
ast.NotIn: ast.In,
}
def __new__(self, op: ast.cmpop) -> ast.cmpop:
return self.CPM2INVERS[type(op)]()
@_negate.register(ast.Compare)
def _negate_compare(node: ast.Compare) -> ast.Compare:
return ast.Compare(node.left,
[_InversCmpOp(op) for op in node.ops],
node.comparators)
@_negate.register(ast.BoolOp)
def _negate_bool_op(node: ast.BoolOp) -> ast.BoolOp:
return _negate.dispatch(ast.expr)(node)
def Negation(expr: Expression) -> Expression:
"""Return expression which is the negation of `expr`."""
expr = Expression(_negate(expr.body))
return ast.fix_missing_locations(expr)
def Conjunction(expr1: Expression, expr2: Expression) -> Expression:
"""Return expression which is the conjunction of `expr1` and `expr2`."""
expr = Expression(ast.BoolOp(ast.And(), [expr1.body, expr2.body]))
return ast.fix_missing_locations(expr)
def Disjunction(expr1: Expression, expr2: Expression) -> Expression:
"""Return expression which is the disjunction of `expr1` and `expr2`."""
expr = Expression(ast.BoolOp(ast.Or(), [expr1.body, expr2.body]))
return ast.fix_missing_locations(expr)
def Contradiction(expr1: Expression, expr2: Expression) -> Expression:
"""Return expression which is the contradiction of `expr1` and `expr2`."""
expr = Disjunction(Conjunction(expr1, Negation(expr2)),
Conjunction(Negation(expr1), expr2))
return ast.fix_missing_locations(expr)
|
import logging
from flask import Blueprint, Markup
from flask import (request, render_template, send_file, redirect, url_for,
flash, abort)
from flask_menu import register_menu
from .. import api
from ._navbar import show_items, activate_items
from ._utils import (call, create_csv, mark_pair_viewed, mark_pair_voted,
mark_pair_skipped, filter_voted_pairs)
blueprint = Blueprint('votes', __name__)
log = logging.getLogger(__name__)
@blueprint.route("/<code>", strict_slashes=False)
@register_menu(blueprint, '.detail', "Results", order=2,
visible_when=show_items,
active_when=activate_items)
def results(code):
key, slug = _get_key(code)
if slug and code != slug:
return redirect(url_for('votes.results', code=slug))
content, status = call(api.scores.index, key=key)
if status != 200:
abort(404)
return render_template("results.html", collection=content)
@blueprint.route("/<code>", methods=['POST'])
def add_item(code):
key, _ = _get_key(code, require_unlocked=True)
name = request.form['name'].strip()
if name and key:
content, status = call(api.items.add, key=key, name=name)
if status == 200:
item = content['_objects'][-1]
flash(f"Added item: {item["name"]}", 'info')
else:
flash(content['message'], 'danger')
elif key:
flash("A name is required.", 'danger')
else:
flash("Unable to add items.", 'danger')
return redirect(url_for('votes.results', code=code))
@blueprint.route("/<code>/import", methods=['GET', 'POST'])
def bulk_import(code):
key, _code = _get_key(code, require_unlocked=True)
content, status = call(api.scores.index, key=key)
if status != 200:
abort(404)
if request.method == 'POST':
lines = request.form['items'].split('\n')
names = [line.strip() for line in lines if line.strip()]
for name in names:
content, status = call(api.items.add, key=key, name=name)
if status == 200:
item = content['_objects'][-1]
flash(f"Added item: {item["name"]}", 'info')
else:
flash(content['message'], 'danger')
return redirect(url_for('votes.results', code=code))
return render_template("import.html", collection=content)
@blueprint.route("/<code>/results.csv")
def download_results(code):
key, _ = _get_key(code)
content, status = call(api.scores.data, key=key)
assert status == 200
name = content['name'].replace(' ', '_')
filename = f"{name}_Results.csv"
path = create_csv(filename, content['data'])
return send_file(path, mimetype='text/csv', as_attachment=True,
attachment_filename=filename, cache_timeout=0)
@blueprint.route("/<code>/vote", methods=['GET', 'POST'])
@register_menu(blueprint, '.vote', "Vote", order=3,
visible_when=show_items)
def cast(code):
key, slug = _get_key(code)
if slug and code != slug:
return redirect(url_for('votes.cast', code=slug))
if request.method == 'POST':
winner = request.args.get('winner')
loser = request.args.get('loser')
skip = request.args.get('skip')
mark_pair_viewed(code, [winner, loser])
if skip:
mark_pair_skipped(code, [winner, loser])
else:
mark_pair_voted(code, [winner, loser])
content, status = call(api.votes.add, key=key,
winner=winner, loser=loser)
return redirect(url_for('votes.cast', code=code))
content, status = call(api.votes.index, key=key)
if status != 200:
abort(404)
percent, collection = filter_voted_pairs(content)
if percent is None:
percent = 100
collection['item_data'] = [{'name': "---"}] * 2
url = url_for('votes.results', code=code, _external=True)
msg = Markup(
"You have voted on every pair in this collection. "
f"Go back to the results: <a href='{url}'>{url}</a>")
flash(msg, 'warning')
return render_template("vote.html", collection=collection, percent=percent)
def _get_key(code, *, require_unlocked=False):
# TODO: considering making a separate API for this to avoid exposing details
log.debug("Looking up key from code: %s", code)
content, status = call(api.redirects.detail, start_slug=code)
if status == 200:
slug = content['end_slug']
log.debug("Found redirect %r => %r", code, slug)
return None, slug
content, status = call(api.collections.detail, key=None, code=code)
if status == 200:
key = content['key']
log.debug("Found key: %s", key)
if require_unlocked:
if content['locked']:
log.error("Invalid action on locked collection: %s", key)
return None, code
return key, None
log.warning("Unknown code: %s", code)
return None, code
| import logging
from flask import Blueprint, Markup
from flask import (request, render_template, send_file, redirect, url_for,
flash, abort)
from flask_menu import register_menu
from .. import api
from ._navbar import show_items, activate_items
from ._utils import (call, create_csv, mark_pair_viewed, mark_pair_voted,
mark_pair_skipped, filter_voted_pairs)
blueprint = Blueprint('votes', __name__)
log = logging.getLogger(__name__)
@blueprint.route("/<code>", strict_slashes=False)
@register_menu(blueprint, '.detail', "Results", order=2,
visible_when=show_items,
active_when=activate_items)
def results(code):
key, slug = _get_key(code)
if slug and code != slug:
return redirect(url_for('votes.results', code=slug))
content, status = call(api.scores.index, key=key)
if status != 200:
abort(404)
return render_template("results.html", collection=content)
@blueprint.route("/<code>", methods=['POST'])
def add_item(code):
key, _ = _get_key(code, require_unlocked=True)
name = request.form['name'].strip()
if name and key:
content, status = call(api.items.add, key=key, name=name)
if status == 200:
item = content['_objects'][-1]
flash(f"Added item: {item['name']}", 'info')
else:
flash(content['message'], 'danger')
elif key:
flash("A name is required.", 'danger')
else:
flash("Unable to add items.", 'danger')
return redirect(url_for('votes.results', code=code))
@blueprint.route("/<code>/import", methods=['GET', 'POST'])
def bulk_import(code):
key, _code = _get_key(code, require_unlocked=True)
content, status = call(api.scores.index, key=key)
if status != 200:
abort(404)
if request.method == 'POST':
lines = request.form['items'].split('\n')
names = [line.strip() for line in lines if line.strip()]
for name in names:
content, status = call(api.items.add, key=key, name=name)
if status == 200:
item = content['_objects'][-1]
flash(f"Added item: {item['name']}", 'info')
else:
flash(content['message'], 'danger')
return redirect(url_for('votes.results', code=code))
return render_template("import.html", collection=content)
@blueprint.route("/<code>/results.csv")
def download_results(code):
key, _ = _get_key(code)
content, status = call(api.scores.data, key=key)
assert status == 200
name = content['name'].replace(' ', '_')
filename = f"{name}_Results.csv"
path = create_csv(filename, content['data'])
return send_file(path, mimetype='text/csv', as_attachment=True,
attachment_filename=filename, cache_timeout=0)
@blueprint.route("/<code>/vote", methods=['GET', 'POST'])
@register_menu(blueprint, '.vote', "Vote", order=3,
visible_when=show_items)
def cast(code):
key, slug = _get_key(code)
if slug and code != slug:
return redirect(url_for('votes.cast', code=slug))
if request.method == 'POST':
winner = request.args.get('winner')
loser = request.args.get('loser')
skip = request.args.get('skip')
mark_pair_viewed(code, [winner, loser])
if skip:
mark_pair_skipped(code, [winner, loser])
else:
mark_pair_voted(code, [winner, loser])
content, status = call(api.votes.add, key=key,
winner=winner, loser=loser)
return redirect(url_for('votes.cast', code=code))
content, status = call(api.votes.index, key=key)
if status != 200:
abort(404)
percent, collection = filter_voted_pairs(content)
if percent is None:
percent = 100
collection['item_data'] = [{'name': "---"}] * 2
url = url_for('votes.results', code=code, _external=True)
msg = Markup(
"You have voted on every pair in this collection. "
f"Go back to the results: <a href='{url}'>{url}</a>")
flash(msg, 'warning')
return render_template("vote.html", collection=collection, percent=percent)
def _get_key(code, *, require_unlocked=False):
# TODO: considering making a separate API for this to avoid exposing details
log.debug("Looking up key from code: %s", code)
content, status = call(api.redirects.detail, start_slug=code)
if status == 200:
slug = content['end_slug']
log.debug("Found redirect %r => %r", code, slug)
return None, slug
content, status = call(api.collections.detail, key=None, code=code)
if status == 200:
key = content['key']
log.debug("Found key: %s", key)
if require_unlocked:
if content['locked']:
log.error("Invalid action on locked collection: %s", key)
return None, code
return key, None
log.warning("Unknown code: %s", code)
return None, code
|
""" Camera extractor functions
This module handles extraction of camera timestamps for both Bpod and FPGA.
"""
import logging
from functools import partial
import cv2
import numpy as np
import matplotlib.pyplot as plt
from oneibl.stream import VideoStreamer
import ibllib.dsp.utils as dsp
from ibllib.misc import range_str
from ibllib.plots import squares, vertical_lines
from ibllib.io.video import assert_valid_label
from brainbox.numerical import within_ranges
from ibllib.io.extractors.base import get_session_extractor_type
from ibllib.io.extractors.ephys_fpga import get_sync_fronts, get_main_probe_sync
import ibllib.io.raw_data_loaders as raw
from ibllib.io.extractors.base import (
BaseBpodTrialsExtractor,
BaseExtractor,
run_extractor_classes,
_get_task_types_json_config
)
_logger = logging.getLogger('ibllib')
def extract_camera_sync(sync, chmap=None):
"""
Extract camera timestamps from the sync matrix
:param sync: dictionary 'times', 'polarities' of fronts detected on sync trace
:param chmap: dictionary containing channel indices. Default to constant.
:return: dictionary containing camera timestamps
"""
assert(chmap)
sr = get_sync_fronts(sync, chmap['right_camera'])
sl = get_sync_fronts(sync, chmap['left_camera'])
sb = get_sync_fronts(sync, chmap['body_camera'])
return {'right': sr.times[::2],
'left': sl.times[::2],
'body': sb.times[::2]}
def get_video_length(video_path):
"""
Returns video length
:param video_path: A path to the video
:return:
"""
is_url = isinstance(video_path, str) and video_path.startswith('http')
cap = VideoStreamer(video_path).cap if is_url else cv2.VideoCapture(str(video_path))
assert cap.isOpened(), f'Failed to open video file {video_path}'
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
cap.release()
return length
class CameraTimestampsFPGA(BaseExtractor):
def __init__(self, label, session_path=None):
super().__init__(session_path)
self.label = assert_valid_label(label)
self.save_names = f'_ibl_{label}Camera.times.npy'
self.var_names = f'{label}_camera_timestamps'
self._log_level = _logger.level
_logger.setLevel(logging.DEBUG)
def __del__(self):
_logger.setLevel(self._log_level)
def _extract(self, sync=None, chmap=None, video_path=None,
display=False, extrapolate_missing=True):
"""
The raw timestamps are taken from the FPGA. These are the times of the camera's frame TTLs.
If the pin state file exists, these timestamps are aligned to the video frames using the
audio TTLs. Frames missing from the embedded frame count are removed from the timestamps
array.
If the pin state file does not exist, the left and right camera timestamps may be aligned
using the wheel data.
:param sync: dictionary 'times', 'polarities' of fronts detected on sync trace.
:param chmap: dictionary containing channel indices. Default to constant.
:param video_path: an optional path for fetching the number of frames. If None,
the video is loaded from the session path. If an int is provided this is taken to be
the total number of frames.
:param display: if True, the audio and GPIO fronts are plotted.
:param extrapolate_missing: if True, any missing timestamps at the beginning and end of
the session are extrapolated based on the median frame rate, otherwise they will be NaNs.
:return: a numpy array of camera timestamps
"""
fpga_times = extract_camera_sync(sync=sync, chmap=chmap)
count, (*_, gpio) = raw.load_embedded_frame_data(self.session_path, self.label)
if gpio is not None and gpio['indices'].size > 1:
_logger.info('Aligning to audio TTLs')
# Extract audio TTLs
audio = get_sync_fronts(sync, chmap['audio'])
_, ts = raw.load_camera_ssv_times(self.session_path, self.label)
try:
"""
NB: Some of the audio TTLs occur very close together, and are therefore not
reflected in the pin state. This function removes those. Also converts frame
times to FPGA time.
"""
gpio, audio, ts = groom_pin_state(gpio, audio, ts, display=display)
"""
The length of the count and pin state are regularly longer than the length of
the video file. Here we assert that the video is either shorter or the same
length as the arrays, and we make an assumption that the missing frames are
right at the end of the video. We therefore simply shorten the arrays to match
the length of the video.
"""
if video_path is None:
filename = f'_iblrig_{self.label}Camera.raw.mp4'
video_path = self.session_path.joinpath('raw_video_data', filename)
# Permit the video path to be the length for development and debugging purposes
length = (video_path
if isinstance(video_path, int)
else get_video_length(video_path))
_logger.debug(f'Number of video frames = {length}')
if count.size > length:
count = count[:length]
else:
assert length == count.size, 'fewer counts than frames'
raw_ts = fpga_times[self.label]
return align_with_audio(raw_ts, audio, gpio, count,
display=display,
extrapolate_missing=extrapolate_missing)
except AssertionError as ex:
_logger.critical('Failed to extract using audio: %s', ex)
# If you reach here extracting using audio TTLs was not possible
_logger.warning('Alignment by wheel data not yet implemented')
return fpga_times[self.label]
class CameraTimestampsBpod(BaseBpodTrialsExtractor):
"""
Get the camera timestamps from the Bpod
The camera events are logged only during the events not in between, so the times need
to be interpolated
"""
save_names = '_ibl_leftCamera.times.npy'
var_names = 'left_camera_timestamps'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._log_level = _logger.level
_logger.setLevel(logging.DEBUG)
def __del__(self):
_logger.setLevel(self._log_level)
def _extract(self, video_path=None, display=False, extrapolate_missing=True):
"""
The raw timestamps are taken from the Bpod. These are the times of the camera's frame TTLs.
If the pin state file exists, these timestamps are aligned to the video frames using the
audio TTLs. Frames missing from the embedded frame count are removed from the timestamps
array.
If the pin state file does not exist, the left camera timestamps may be aligned using the
wheel data.
:param video_path: an optional path for fetching the number of frames. If None,
the video is loaded from the session path. If an int is provided this is taken to be
the total number of frames.
:param display: if True, the audio and GPIO fronts are plotted.
:param extrapolate_missing: if True, any missing timestamps at the beginning and end of
the session are extrapolated based on the median frame rate, otherwise they will be NaNs.
:return: a numpy array of camera timestamps
"""
raw_ts = self._times_from_bpod()
count, (*_, gpio) = raw.load_embedded_frame_data(self.session_path, 'left')
if video_path is None:
filename = '_iblrig_leftCamera.raw.mp4'
video_path = self.session_path.joinpath('raw_video_data', filename)
# Permit the video path to be the length for development and debugging purposes
length = video_path if isinstance(video_path, int) else get_video_length(video_path)
_logger.debug(f'Number of video frames = {length}')
# Check if the GPIO is usable for extraction. GPIO is None if the file does not exist,
# is empty, or contains only one value (i.e. doesn't change)
if gpio is not None and gpio['indices'].size > 1:
_logger.info('Aligning to audio TTLs')
# Extract audio TTLs
_, audio = raw.load_bpod_fronts(self.session_path, self.bpod_trials)
_, ts = raw.load_camera_ssv_times(self.session_path, 'left')
"""
There are many audio TTLs that are for some reason missed by the GPIO. Conversely
the last GPIO doesn't often correspond to any audio TTL. These will be removed.
The drift appears to be less severe than the FPGA, so when assigning TTLs we'll take
the nearest TTL within 500ms. The go cue TTLs comprise two short pulses ~3ms apart.
We will fuse any TTLs less than 5ms apart to make assignment more accurate.
"""
try:
gpio, audio, ts = groom_pin_state(gpio, audio, ts, take='nearest',
tolerance=.5, min_diff=5e-3, display=display)
if count.size > length:
count = count[:length]
else:
assert length == count.size, 'fewer counts than frames'
return align_with_audio(raw_ts, audio, gpio, count,
extrapolate_missing, display=display)
except AssertionError as ex:
_logger.critical('Failed to extract using audio: %s', ex)
# If you reach here extracting using audio TTLs was not possible
_logger.warning('Alignment by wheel data not yet implemented')
# Extrapolate at median frame rate
n_missing = length - raw_ts.size
if n_missing > 0:
_logger.warning(f'{n_missing} fewer Bpod timestamps than frames; '
f'{'extrapolating' if extrapolate_missing else 'appending nans'}')
frate = np.median(np.diff(raw_ts))
to_app = ((np.arange(n_missing, ) + 1) / frate + raw_ts[-1]
if extrapolate_missing
else np.full(n_missing, np.nan))
raw_ts = np.r_[raw_ts, to_app] # Append the missing times
elif n_missing < 0:
_logger.warning(f'{abs(n_missing)} fewer frames than Bpod timestamps')
return raw_ts
def _times_from_bpod(self):
ntrials = len(self.bpod_trials)
cam_times = []
n_frames = 0
n_out_of_sync = 0
missed_trials = []
for ind in np.arange(ntrials):
# get upgoing and downgoing fronts
pin = np.array(self.bpod_trials[ind]['behavior_data']
['Events timestamps'].get('Port1In'))
pout = np.array(self.bpod_trials[ind]['behavior_data']
['Events timestamps'].get('Port1Out'))
# some trials at startup may not have the camera working, discard
if np.all(pin) is None:
missed_trials.append(ind)
continue
# if the trial starts in the middle of a square, discard the first downgoing front
if pout[0] < pin[0]:
pout = pout[1:]
# same if the last sample is during an upgoing front,
# always put size as it happens last
pin = pin[:pout.size]
frate = np.median(np.diff(pin))
if ind > 0:
"""
assert that the pulses have the same length and that we don't miss frames during
the trial, the refresh rate of bpod is 100us
"""
test1 = np.all(np.abs(1 - (pin - pout) / np.median(pin - pout)) < 0.1)
test2 = np.all(np.abs(np.diff(pin) - frate) <= 0.00011)
if not all([test1, test2]):
n_out_of_sync += 1
# grow a list of cam times for ech trial
cam_times.append(pin)
n_frames += pin.size
if missed_trials:
_logger.debug('trial(s) %s missing TTL events', range_str(missed_trials))
if n_out_of_sync > 0:
_logger.warning(f"{n_out_of_sync} trials with bpod camera frame times not within"
f" 10% of the expected sampling rate")
t_first_frame = np.array([c[0] for c in cam_times])
t_last_frame = np.array([c[-1] for c in cam_times])
frate = 1 / np.nanmedian(np.array([np.median(np.diff(c)) for c in cam_times]))
intertrial_duration = t_first_frame[1:] - t_last_frame[:-1]
intertrial_missed_frames = np.int32(np.round(intertrial_duration * frate)) - 1
# initialize the full times array
frame_times = np.zeros(n_frames + int(np.sum(intertrial_missed_frames)))
ii = 0
for trial, cam_time in enumerate(cam_times):
if cam_time is not None:
# populate first the recovered times within the trials
frame_times[ii: ii + cam_time.size] = cam_time
ii += cam_time.size
if trial == (len(cam_times) - 1):
break
# then extrapolate in-between
nmiss = intertrial_missed_frames[trial]
frame_times[ii: ii + nmiss] = (cam_time[-1] + intertrial_duration[trial] /
(nmiss + 1) * (np.arange(nmiss) + 1))
ii += nmiss
assert all(np.diff(frame_times) > 0) # negative diffs implies a big problem
return frame_times
def align_with_audio(timestamps, audio, pin_state, count,
extrapolate_missing=True, display=False):
"""
Groom the raw FPGA or Bpod camera timestamps using the frame embedded audio TTLs and frame
counter.
:param timestamps: An array of raw FPGA or Bpod camera timestamps
:param audio: An array of FPGA or Bpod audio TTL times
:param pin_state: An array of camera pin states
:param count: An array of frame numbers
:param extrapolate_missing: If true and the number of timestamps is fewer than the number of
frame counts, the remaining timestamps are extrapolated based on the frame rate, otherwise
they are NaNs
:param display: Plot the resulting timestamps
:return: The corrected frame timestamps
"""
# Some assertions made on the raw data
# assert count.size == pin_state.size, 'frame count and pin state size mismatch'
assert all(np.diff(count) > 0), 'frame count not strictly increasing'
assert all(np.diff(timestamps) > 0), 'FPGA/Bpod camera times not strictly increasing'
same_n_ttl = pin_state['times'].size == audio['times'].size
assert same_n_ttl, 'more audio TTLs detected on camera than TTLs sent'
"""Here we will ensure that the FPGA camera times match the number of video frames in
length. We will make the following assumptions:
1. The number of FPGA camera times is equal to or greater than the number of video frames.
2. No TTLs were missed between the camera and FPGA.
3. No pin states were missed by Bonsai.
4 No pixel count data was missed by Bonsai.
In other words the count and pin state arrays accurately reflect the number of frames
sent by the camera and should therefore be the same length, and the length of the frame
counter should match the number of saved video frames.
The missing frame timestamps are removed in three stages:
1. Remove any timestamps that occurred before video frame acquisition in Bonsai.
2. Remove any timestamps where the frame counter reported missing frames, i.e. remove the
dropped frames which occurred throughout the session.
3. Remove the trailing timestamps at the end of the session if the camera was turned off
in the wrong order.
"""
# Align on first pin state change
first_uptick = pin_state['indices'][0]
first_ttl = np.searchsorted(timestamps, audio['times'][0])
"""Here we find up to which index in the FPGA times we discard by taking the difference
between the index of the first pin state change (when the audio TTL was reported by the
camera) and the index of the first audio TTL in FPGA time. We subtract the difference
between the frame count at the first pin state change and the index to account for any
video frames that were not saved during this period (we will remove those from the
camera FPGA times later).
"""
# Minus any frames that were dropped between the start of frame acquisition and the
# first TTL
start = first_ttl - first_uptick - (count[first_uptick] - first_uptick)
# Get approximate frame rate for extrapolating timestamps (if required)
frate = round(1 / np.nanmedian(np.diff(timestamps)))
if start < 0:
n_missing = abs(start)
_logger.warning(f'{n_missing} missing FPGA/Bpod timestamp(s) at start; '
f'{'extrapolating' if extrapolate_missing else 'prepending nans'}')
to_app = (timestamps[0] - (np.arange(n_missing, 0, -1) + 1) / frate
if extrapolate_missing
else np.full(n_missing, np.nan))
timestamps = np.r_[to_app, timestamps] # Prepend the missing times
start = 0
# Remove the extraneous timestamps from the beginning and end
end = count[-1] + 1 + start
ts = timestamps[start:end]
n_missing = count[-1] - ts.size + 1
if n_missing > 0:
# if (n_missing := count[-1] - ts.size + 1) > 0: # py3.8
"""
For ephys sessions there may be fewer FPGA times than frame counts if SpikeGLX is turned
off before the video acquisition workflow. For Bpod this always occurs because Bpod
finishes before the camera workflow. For Bpod the times are already extrapolated for
these late frames."""
_logger.warning(f'{n_missing} fewer FPGA/Bpod timestamps than frame counts; '
f'{'extrapolating' if extrapolate_missing else 'appending nans'}')
to_app = ((np.arange(n_missing, ) + 1) / frate + ts[-1]
if extrapolate_missing
else np.full(n_missing, np.nan))
ts = np.r_[ts, to_app] # Append the missing times
assert ts.size >= count.size, 'fewer timestamps than frame counts'
assert ts.size == count[-1] + 1, 'more frames recorded in frame count than timestamps '
# Remove the rest of the dropped frames
ts = ts[count]
assert np.searchsorted(ts, audio['times'][0]) == first_uptick,\
'time of first audio TTL doesn\'t match after alignment'
if ts.size != count.size:
_logger.error('number of timestamps and frames don\'t match after alignment')
if display:
# Plot to check
fig, axes = plt.subplots(1, 1)
y = within_ranges(np.arange(ts.size), pin_state['indices'].reshape(-1, 2)).astype(float)
y *= 1e-5 # For scale when zoomed in
axes.plot(ts, y, marker='d', color='blue', drawstyle='steps-pre', label='GPIO')
axes.plot(ts, np.zeros_like(ts), 'kx', label='FPGA timestamps')
vertical_lines(audio['times'], ymin=0, ymax=1e-5,
color='r', linestyle=':', ax=axes, label='audio TTL')
plt.legend()
return ts
def attribute_times(arr, events, tol=.1, injective=True, take='first'):
"""
Returns the values of the first array that correspond to those of the second.
Given two arrays of timestamps, the function will return the values of the first array
that most likely correspond to the values of the second. For each of the values in the
second array, the absolute difference is taken and the index of either the first sufficiently
close value, or simply the closest one, is assigned.
If injective is True, once a value has been assigned, to a value it can't be assigned to
another. In other words there is a one-to-one mapping between the two arrays.
:param arr: An array of event times to attribute to those in `events`
:param events: An array of event times considered a subset of `arr`
:param tol: The max absolute difference between values in order to be considered a match
:param injective: If true, once a value has been assigned it will not be assigned again
:param take: If 'first' the first value within tolerance is assigned; if 'nearest' the
closest value is assigned
:returns Numpy array the same length as `values`
"""
take = take.lower()
if take not in ('first', 'nearest'):
raise ValueError('Parameter `take` must be either "first" or "nearest"')
stack = np.ma.masked_invalid(arr, copy=False)
stack.fill_value = np.inf
assigned = np.full(events.shape, -1, dtype=int) # Initialize output array
for i, x in enumerate(events):
dx = np.abs(stack.filled() - x)
if dx.min() < tol: # is any value within tolerance
idx = np.where(dx < tol)[0][0] if take == 'first' else dx.argmin()
assigned[i] = idx
stack.mask[idx] = injective # If one-to-one, remove the assigned value
return assigned
def groom_pin_state(gpio, audio, ts, tolerance=2., display=False, take='first', min_diff=0.):
"""
Align the GPIO pin state to the FPGA audio TTLs. Any audio TTLs not reflected in the pin
state are removed from the dict and the times of the detected fronts are converted to FPGA
time. At the end of this the number of GPIO fronts should equal the number of audio fronts.
Note:
- This function is ultra safe: we probably don't need assign all the ups and down fronts
separately and could potentially even align the timestamps without removing the missed fronts
- The input gpio and audio dicts may be modified by this function
- For training sessions the frame rate is only 30Hz and the TTLs tend to be broken up by
small gaps. Setting the min_diff to 5ms helps the timestamp assignment accuracy.
:param gpio: array of GPIO pin state values
:param audio: dict of FPGA audio TTLs (see ibllib.io.extractors.ephys_fpga._get_sync_fronts)
:param ts: camera frame times
:param tolerance: two pulses need to be within this many seconds to be considered related
:param take: If 'first' the first value within tolerance is assigned; if 'nearest' the
closest value is assigned
:param display: If true, the resulting timestamps are plotted against the raw audio signal
:param min_diff: Audio TTL fronts less than min_diff seconds apart will be removed
:returns: dict of GPIO FPGA front indices, polarities and FPGA aligned times
:returns: audio times and polarities sans the TTLs not detected in the frame data
:returns: frame times in FPGA time
"""
# Check that the dimensions match
if np.any(gpio['indices'] >= ts.size):
_logger.warning('GPIO events occurring beyond timestamps array length')
keep = gpio['indices'] < ts.size
gpio = {k: gpio[k][keep] for k, v in gpio.items()}
assert audio and audio['times'].size > 0, 'no audio TTLs for session'
assert audio['times'].size == audio['polarities'].size, 'audio data dimension mismatch'
# make sure that there are no 2 consecutive fall or consecutive rise events
assert np.all(np.abs(np.diff(audio['polarities'])) == 2), 'consecutive high/low audio events'
# make sure first TTL is high
assert audio['polarities'][0] == 1
# make sure audio times in order
assert np.all(np.diff(audio['times']) > 0)
# make sure raw timestamps increase
assert np.all(np.diff(ts) > 0), 'timestamps must strictly increase'
# make sure there are state changes
assert gpio['indices'].any(), 'no TTLs detected in GPIO'
# # make sure first GPIO state is high
assert gpio['polarities'][0] == 1
"""
Some audio TTLs appear to be so short that they are not recorded by the camera. These can
be as short as a few microseconds. Applying a cutoff based on framerate was unsuccessful.
Assigning each audio TTL to each pin state change is not easy because some onsets occur very
close together (sometimes < 70ms), on the order of the delay between TTL and frame time.
Also, the two clocks have some degree of drift, so the delay between audio TTL and pin state
change may be zero or even negative.
Here we split the events into audio onsets (lo->hi) and audio offsets (hi->lo). For each
uptick in the GPIO pin state, we take the first audio onset time that was within 100ms of it.
We ensure that each audio TTL is assigned only once, so a TTL that is closer to frame 3 than
frame 1 may still be assigned to frame 1.
"""
ifronts = gpio['indices'] # The pin state flips
audio_times = audio['times']
if ifronts.size != audio['times'].size:
_logger.warning('more audio TTLs than GPIO state changes, assigning timestamps')
to_remove = np.zeros(ifronts.size, dtype=bool) # unassigned GPIO fronts to remove
low2high = ifronts[gpio['polarities'] == 1]
high2low = ifronts[gpio['polarities'] == -1]
assert low2high.size >= high2low.size
# Remove and/or fuse short TTLs
if min_diff > 0:
short, = np.where(np.diff(audio['times']) < min_diff)
audio_times = np.delete(audio['times'], np.r_[short, short + 1])
_logger.debug(f'Removed {short.size * 2} fronts TLLs less than '
f'{min_diff * 1e3:.0f}ms apart')
assert audio_times.size > 0, f'all audio TTLs less than {min_diff}s'
# Onsets
ups = ts[low2high] - ts[low2high][0] # times relative to first GPIO high
onsets = audio_times[::2] - audio_times[0] # audio times relative to first onset
# assign GPIO fronts to audio onset
assigned = attribute_times(onsets, ups, tol=tolerance, take=take)
unassigned = np.setdiff1d(np.arange(onsets.size), assigned[assigned > -1])
if unassigned.size > 0:
_logger.debug(f'{unassigned.size} audio TTL rises were not detected by the camera')
# Check that all pin state upticks could be attributed to an onset TTL
missed = assigned == -1
if np.any(missed):
# if np.any(missed := assigned == -1): # py3.8
_logger.warning(f'{sum(missed)} pin state rises could '
f'not be attributed to an audio TTL')
if display:
ax = plt.subplot()
vertical_lines(ups[assigned > -1],
linestyle='-', color='g', ax=ax,
label='assigned GPIO up state')
vertical_lines(ups[missed],
linestyle='-', color='r', ax=ax,
label='unassigned GPIO up state')
vertical_lines(onsets[unassigned],
linestyle=':', color='k', ax=ax,
alpha=0.3, label='audio onset')
vertical_lines(onsets[assigned],
linestyle=':', color='b', ax=ax, label='assigned audio onset')
plt.legend()
plt.show()
# Remove the missed fronts
to_remove = np.in1d(gpio['indices'], low2high[missed])
assigned = assigned[~missed]
onsets_ = audio_times[::2][assigned]
# Offsets
downs = ts[high2low] - ts[high2low][0]
offsets = audio_times[1::2] - audio_times[1]
assigned = attribute_times(offsets, downs, tol=tolerance, take=take)
unassigned = np.setdiff1d(np.arange(onsets.size), assigned[assigned > -1])
if unassigned.size > 0:
_logger.debug(f'{unassigned.size} audio TTL falls were not detected by the camera')
# Check that all pin state downticks could be attributed to an offset TTL
missed = assigned == -1
if np.any(missed):
# if np.any(missed := assigned == -1): # py3.8
_logger.warning(f'{sum(missed)} pin state falls could '
f'not be attributed to an audio TTL')
# Remove the missed fronts
to_remove |= np.in1d(gpio['indices'], high2low[missed])
assigned = assigned[~missed]
offsets_ = audio_times[1::2][assigned]
# Audio groomed
if np.any(to_remove):
# Check for any orphaned fronts (only one pin state edge was assigned)
to_remove = np.pad(to_remove, (0, to_remove.size % 2), 'edge') # Ensure even size
# Perform xor to find GPIOs where only onset or offset is marked for removal
orphaned = to_remove.reshape(-1, 2).sum(axis=1) == 1
if orphaned.any():
"""If there are orphaned GPIO fronts (i.e. only one edge was assigned to an
audio front), remove the orphaned front its assigned audio TTL. In other words
if both edges cannot be assigned to an audio TTL, we ignore the TTL entirely.
This is a sign that the assignment was bad and extraction may fail."""
_logger.warning('Some onsets but not offsets (or vice versa) were not assigned; '
'this may be a sign of faulty wiring or clock drift')
# Find indices of GPIO upticks where only the downtick was marked for removal
orphaned_onsets, = np.where(~to_remove.reshape(-1, 2)[:, 0] & orphaned)
# The onsets_ array already has the other TTLs removed (same size as to_remove ==
# False) so subtract the number of removed elements from index.
for i, v in enumerate(orphaned_onsets):
orphaned_onsets[i] -= to_remove.reshape(-1, 2)[:v, 0].sum()
# Same for offsets...
orphaned_offsets, = np.where(~to_remove.reshape(-1, 2)[:, 1] & orphaned)
for i, v in enumerate(orphaned_offsets):
orphaned_offsets[i] -= to_remove.reshape(-1, 2)[:v, 1].sum()
# Remove orphaned audio onsets and offsets
onsets_ = np.delete(onsets_, orphaned_onsets[orphaned_onsets < onsets_.size])
offsets_ = np.delete(offsets_, orphaned_offsets[orphaned_offsets < offsets_.size])
_logger.debug(f'{orphaned.sum()} orphaned TTLs removed')
to_remove.reshape(-1, 2)[orphaned] = True
# Remove those unassigned GPIOs
gpio = {k: v[~to_remove[:v.size]] for k, v in gpio.items()}
ifronts = gpio['indices']
# Assert that we've removed discrete TTLs
# A failure means e.g. an up-going front of one TTL was missed
# but not the down-going one.
assert np.all(np.abs(np.diff(gpio['polarities'])) == 2)
assert gpio['polarities'][0] == 1
audio_ = {'times': np.empty(ifronts.size), 'polarities': gpio['polarities']}
audio_['times'][::2] = onsets_
audio_['times'][1::2] = offsets_
else:
audio_ = audio
# Align the frame times to FPGA
fcn_a2b, drift_ppm = dsp.sync_timestamps(ts[ifronts], audio_['times'])
_logger.debug(f'frame audio alignment drift = {drift_ppm:.2f}ppm')
# Add times to GPIO dict
gpio['times'] = fcn_a2b(ts[ifronts])
if display:
# Plot all the onsets and offsets
ax = plt.subplot()
# All Audio TTLS
squares(audio['times'], audio['polarities'],
ax=ax, label='audio TTLs', linestyle=':', color='k', yrange=[0, 1], alpha=0.3)
# GPIO
x = np.insert(gpio['times'], 0, 0)
y = np.arange(x.size) % 2
squares(x, y, ax=ax, label='GPIO')
y = within_ranges(np.arange(ts.size), ifronts.reshape(-1, 2)) # 0 or 1 for each frame
ax.plot(fcn_a2b(ts), y, 'kx', label='cam times')
# Assigned audio
squares(audio_['times'], audio_['polarities'],
ax=ax, label='assigned audio TTL', linestyle=':', color='g', yrange=[0, 1])
ax.legend()
plt.xlabel('FPGA time (s)')
ax.set_yticks([0, 1])
ax.set_title('GPIO - audio TTL alignment')
plt.show()
return gpio, audio_, fcn_a2b(ts)
def extract_all(session_path, session_type=None, save=True, **kwargs):
"""
For the IBL ephys task, reads ephys binary file and extract:
- video time stamps
:param session_path: '/path/to/subject/yyyy-mm-dd/001'
:param session_type: the session type to extract, i.e. 'ephys', 'training' or 'biased'. If
None the session type is inferred from the settings file.
:param save: Bool, defaults to False
:param kwargs: parameters to pass to the extractor
:return: outputs, files
"""
if session_type is None:
session_type = get_session_extractor_type(session_path)
if not session_type or session_type not in _get_task_types_json_config().values():
raise ValueError(f"Session type {session_type} has no matching extractor")
elif 'ephys' in session_type: # assume ephys == FPGA
labels = assert_valid_label(kwargs.pop('labels', ('left', 'right', 'body')))
labels = (labels,) if isinstance(labels, str) else labels # Ensure list/tuple
extractor = [partial(CameraTimestampsFPGA, label) for label in labels]
if 'sync' not in kwargs:
kwargs['sync'], kwargs['chmap'] = \
get_main_probe_sync(session_path, bin_exists=kwargs.pop('bin_exists', False))
else: # assume Bpod otherwise
assert kwargs.pop('labels', 'left'), 'only left camera is currently supported'
extractor = CameraTimestampsBpod
outputs, files = run_extractor_classes(
extractor, session_path=session_path, save=save, **kwargs)
return outputs, files
| """ Camera extractor functions
This module handles extraction of camera timestamps for both Bpod and FPGA.
"""
import logging
from functools import partial
import cv2
import numpy as np
import matplotlib.pyplot as plt
from oneibl.stream import VideoStreamer
import ibllib.dsp.utils as dsp
from ibllib.misc import range_str
from ibllib.plots import squares, vertical_lines
from ibllib.io.video import assert_valid_label
from brainbox.numerical import within_ranges
from ibllib.io.extractors.base import get_session_extractor_type
from ibllib.io.extractors.ephys_fpga import get_sync_fronts, get_main_probe_sync
import ibllib.io.raw_data_loaders as raw
from ibllib.io.extractors.base import (
BaseBpodTrialsExtractor,
BaseExtractor,
run_extractor_classes,
_get_task_types_json_config
)
_logger = logging.getLogger('ibllib')
def extract_camera_sync(sync, chmap=None):
"""
Extract camera timestamps from the sync matrix
:param sync: dictionary 'times', 'polarities' of fronts detected on sync trace
:param chmap: dictionary containing channel indices. Default to constant.
:return: dictionary containing camera timestamps
"""
assert(chmap)
sr = get_sync_fronts(sync, chmap['right_camera'])
sl = get_sync_fronts(sync, chmap['left_camera'])
sb = get_sync_fronts(sync, chmap['body_camera'])
return {'right': sr.times[::2],
'left': sl.times[::2],
'body': sb.times[::2]}
def get_video_length(video_path):
"""
Returns video length
:param video_path: A path to the video
:return:
"""
is_url = isinstance(video_path, str) and video_path.startswith('http')
cap = VideoStreamer(video_path).cap if is_url else cv2.VideoCapture(str(video_path))
assert cap.isOpened(), f'Failed to open video file {video_path}'
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
cap.release()
return length
class CameraTimestampsFPGA(BaseExtractor):
def __init__(self, label, session_path=None):
super().__init__(session_path)
self.label = assert_valid_label(label)
self.save_names = f'_ibl_{label}Camera.times.npy'
self.var_names = f'{label}_camera_timestamps'
self._log_level = _logger.level
_logger.setLevel(logging.DEBUG)
def __del__(self):
_logger.setLevel(self._log_level)
def _extract(self, sync=None, chmap=None, video_path=None,
display=False, extrapolate_missing=True):
"""
The raw timestamps are taken from the FPGA. These are the times of the camera's frame TTLs.
If the pin state file exists, these timestamps are aligned to the video frames using the
audio TTLs. Frames missing from the embedded frame count are removed from the timestamps
array.
If the pin state file does not exist, the left and right camera timestamps may be aligned
using the wheel data.
:param sync: dictionary 'times', 'polarities' of fronts detected on sync trace.
:param chmap: dictionary containing channel indices. Default to constant.
:param video_path: an optional path for fetching the number of frames. If None,
the video is loaded from the session path. If an int is provided this is taken to be
the total number of frames.
:param display: if True, the audio and GPIO fronts are plotted.
:param extrapolate_missing: if True, any missing timestamps at the beginning and end of
the session are extrapolated based on the median frame rate, otherwise they will be NaNs.
:return: a numpy array of camera timestamps
"""
fpga_times = extract_camera_sync(sync=sync, chmap=chmap)
count, (*_, gpio) = raw.load_embedded_frame_data(self.session_path, self.label)
if gpio is not None and gpio['indices'].size > 1:
_logger.info('Aligning to audio TTLs')
# Extract audio TTLs
audio = get_sync_fronts(sync, chmap['audio'])
_, ts = raw.load_camera_ssv_times(self.session_path, self.label)
try:
"""
NB: Some of the audio TTLs occur very close together, and are therefore not
reflected in the pin state. This function removes those. Also converts frame
times to FPGA time.
"""
gpio, audio, ts = groom_pin_state(gpio, audio, ts, display=display)
"""
The length of the count and pin state are regularly longer than the length of
the video file. Here we assert that the video is either shorter or the same
length as the arrays, and we make an assumption that the missing frames are
right at the end of the video. We therefore simply shorten the arrays to match
the length of the video.
"""
if video_path is None:
filename = f'_iblrig_{self.label}Camera.raw.mp4'
video_path = self.session_path.joinpath('raw_video_data', filename)
# Permit the video path to be the length for development and debugging purposes
length = (video_path
if isinstance(video_path, int)
else get_video_length(video_path))
_logger.debug(f'Number of video frames = {length}')
if count.size > length:
count = count[:length]
else:
assert length == count.size, 'fewer counts than frames'
raw_ts = fpga_times[self.label]
return align_with_audio(raw_ts, audio, gpio, count,
display=display,
extrapolate_missing=extrapolate_missing)
except AssertionError as ex:
_logger.critical('Failed to extract using audio: %s', ex)
# If you reach here extracting using audio TTLs was not possible
_logger.warning('Alignment by wheel data not yet implemented')
return fpga_times[self.label]
class CameraTimestampsBpod(BaseBpodTrialsExtractor):
"""
Get the camera timestamps from the Bpod
The camera events are logged only during the events not in between, so the times need
to be interpolated
"""
save_names = '_ibl_leftCamera.times.npy'
var_names = 'left_camera_timestamps'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._log_level = _logger.level
_logger.setLevel(logging.DEBUG)
def __del__(self):
_logger.setLevel(self._log_level)
def _extract(self, video_path=None, display=False, extrapolate_missing=True):
"""
The raw timestamps are taken from the Bpod. These are the times of the camera's frame TTLs.
If the pin state file exists, these timestamps are aligned to the video frames using the
audio TTLs. Frames missing from the embedded frame count are removed from the timestamps
array.
If the pin state file does not exist, the left camera timestamps may be aligned using the
wheel data.
:param video_path: an optional path for fetching the number of frames. If None,
the video is loaded from the session path. If an int is provided this is taken to be
the total number of frames.
:param display: if True, the audio and GPIO fronts are plotted.
:param extrapolate_missing: if True, any missing timestamps at the beginning and end of
the session are extrapolated based on the median frame rate, otherwise they will be NaNs.
:return: a numpy array of camera timestamps
"""
raw_ts = self._times_from_bpod()
count, (*_, gpio) = raw.load_embedded_frame_data(self.session_path, 'left')
if video_path is None:
filename = '_iblrig_leftCamera.raw.mp4'
video_path = self.session_path.joinpath('raw_video_data', filename)
# Permit the video path to be the length for development and debugging purposes
length = video_path if isinstance(video_path, int) else get_video_length(video_path)
_logger.debug(f'Number of video frames = {length}')
# Check if the GPIO is usable for extraction. GPIO is None if the file does not exist,
# is empty, or contains only one value (i.e. doesn't change)
if gpio is not None and gpio['indices'].size > 1:
_logger.info('Aligning to audio TTLs')
# Extract audio TTLs
_, audio = raw.load_bpod_fronts(self.session_path, self.bpod_trials)
_, ts = raw.load_camera_ssv_times(self.session_path, 'left')
"""
There are many audio TTLs that are for some reason missed by the GPIO. Conversely
the last GPIO doesn't often correspond to any audio TTL. These will be removed.
The drift appears to be less severe than the FPGA, so when assigning TTLs we'll take
the nearest TTL within 500ms. The go cue TTLs comprise two short pulses ~3ms apart.
We will fuse any TTLs less than 5ms apart to make assignment more accurate.
"""
try:
gpio, audio, ts = groom_pin_state(gpio, audio, ts, take='nearest',
tolerance=.5, min_diff=5e-3, display=display)
if count.size > length:
count = count[:length]
else:
assert length == count.size, 'fewer counts than frames'
return align_with_audio(raw_ts, audio, gpio, count,
extrapolate_missing, display=display)
except AssertionError as ex:
_logger.critical('Failed to extract using audio: %s', ex)
# If you reach here extracting using audio TTLs was not possible
_logger.warning('Alignment by wheel data not yet implemented')
# Extrapolate at median frame rate
n_missing = length - raw_ts.size
if n_missing > 0:
_logger.warning(f'{n_missing} fewer Bpod timestamps than frames; '
f'{"extrapolating" if extrapolate_missing else "appending nans"}')
frate = np.median(np.diff(raw_ts))
to_app = ((np.arange(n_missing, ) + 1) / frate + raw_ts[-1]
if extrapolate_missing
else np.full(n_missing, np.nan))
raw_ts = np.r_[raw_ts, to_app] # Append the missing times
elif n_missing < 0:
_logger.warning(f'{abs(n_missing)} fewer frames than Bpod timestamps')
return raw_ts
def _times_from_bpod(self):
ntrials = len(self.bpod_trials)
cam_times = []
n_frames = 0
n_out_of_sync = 0
missed_trials = []
for ind in np.arange(ntrials):
# get upgoing and downgoing fronts
pin = np.array(self.bpod_trials[ind]['behavior_data']
['Events timestamps'].get('Port1In'))
pout = np.array(self.bpod_trials[ind]['behavior_data']
['Events timestamps'].get('Port1Out'))
# some trials at startup may not have the camera working, discard
if np.all(pin) is None:
missed_trials.append(ind)
continue
# if the trial starts in the middle of a square, discard the first downgoing front
if pout[0] < pin[0]:
pout = pout[1:]
# same if the last sample is during an upgoing front,
# always put size as it happens last
pin = pin[:pout.size]
frate = np.median(np.diff(pin))
if ind > 0:
"""
assert that the pulses have the same length and that we don't miss frames during
the trial, the refresh rate of bpod is 100us
"""
test1 = np.all(np.abs(1 - (pin - pout) / np.median(pin - pout)) < 0.1)
test2 = np.all(np.abs(np.diff(pin) - frate) <= 0.00011)
if not all([test1, test2]):
n_out_of_sync += 1
# grow a list of cam times for ech trial
cam_times.append(pin)
n_frames += pin.size
if missed_trials:
_logger.debug('trial(s) %s missing TTL events', range_str(missed_trials))
if n_out_of_sync > 0:
_logger.warning(f"{n_out_of_sync} trials with bpod camera frame times not within"
f" 10% of the expected sampling rate")
t_first_frame = np.array([c[0] for c in cam_times])
t_last_frame = np.array([c[-1] for c in cam_times])
frate = 1 / np.nanmedian(np.array([np.median(np.diff(c)) for c in cam_times]))
intertrial_duration = t_first_frame[1:] - t_last_frame[:-1]
intertrial_missed_frames = np.int32(np.round(intertrial_duration * frate)) - 1
# initialize the full times array
frame_times = np.zeros(n_frames + int(np.sum(intertrial_missed_frames)))
ii = 0
for trial, cam_time in enumerate(cam_times):
if cam_time is not None:
# populate first the recovered times within the trials
frame_times[ii: ii + cam_time.size] = cam_time
ii += cam_time.size
if trial == (len(cam_times) - 1):
break
# then extrapolate in-between
nmiss = intertrial_missed_frames[trial]
frame_times[ii: ii + nmiss] = (cam_time[-1] + intertrial_duration[trial] /
(nmiss + 1) * (np.arange(nmiss) + 1))
ii += nmiss
assert all(np.diff(frame_times) > 0) # negative diffs implies a big problem
return frame_times
def align_with_audio(timestamps, audio, pin_state, count,
extrapolate_missing=True, display=False):
"""
Groom the raw FPGA or Bpod camera timestamps using the frame embedded audio TTLs and frame
counter.
:param timestamps: An array of raw FPGA or Bpod camera timestamps
:param audio: An array of FPGA or Bpod audio TTL times
:param pin_state: An array of camera pin states
:param count: An array of frame numbers
:param extrapolate_missing: If true and the number of timestamps is fewer than the number of
frame counts, the remaining timestamps are extrapolated based on the frame rate, otherwise
they are NaNs
:param display: Plot the resulting timestamps
:return: The corrected frame timestamps
"""
# Some assertions made on the raw data
# assert count.size == pin_state.size, 'frame count and pin state size mismatch'
assert all(np.diff(count) > 0), 'frame count not strictly increasing'
assert all(np.diff(timestamps) > 0), 'FPGA/Bpod camera times not strictly increasing'
same_n_ttl = pin_state['times'].size == audio['times'].size
assert same_n_ttl, 'more audio TTLs detected on camera than TTLs sent'
"""Here we will ensure that the FPGA camera times match the number of video frames in
length. We will make the following assumptions:
1. The number of FPGA camera times is equal to or greater than the number of video frames.
2. No TTLs were missed between the camera and FPGA.
3. No pin states were missed by Bonsai.
4 No pixel count data was missed by Bonsai.
In other words the count and pin state arrays accurately reflect the number of frames
sent by the camera and should therefore be the same length, and the length of the frame
counter should match the number of saved video frames.
The missing frame timestamps are removed in three stages:
1. Remove any timestamps that occurred before video frame acquisition in Bonsai.
2. Remove any timestamps where the frame counter reported missing frames, i.e. remove the
dropped frames which occurred throughout the session.
3. Remove the trailing timestamps at the end of the session if the camera was turned off
in the wrong order.
"""
# Align on first pin state change
first_uptick = pin_state['indices'][0]
first_ttl = np.searchsorted(timestamps, audio['times'][0])
"""Here we find up to which index in the FPGA times we discard by taking the difference
between the index of the first pin state change (when the audio TTL was reported by the
camera) and the index of the first audio TTL in FPGA time. We subtract the difference
between the frame count at the first pin state change and the index to account for any
video frames that were not saved during this period (we will remove those from the
camera FPGA times later).
"""
# Minus any frames that were dropped between the start of frame acquisition and the
# first TTL
start = first_ttl - first_uptick - (count[first_uptick] - first_uptick)
# Get approximate frame rate for extrapolating timestamps (if required)
frate = round(1 / np.nanmedian(np.diff(timestamps)))
if start < 0:
n_missing = abs(start)
_logger.warning(f'{n_missing} missing FPGA/Bpod timestamp(s) at start; '
f'{"extrapolating" if extrapolate_missing else "prepending nans"}')
to_app = (timestamps[0] - (np.arange(n_missing, 0, -1) + 1) / frate
if extrapolate_missing
else np.full(n_missing, np.nan))
timestamps = np.r_[to_app, timestamps] # Prepend the missing times
start = 0
# Remove the extraneous timestamps from the beginning and end
end = count[-1] + 1 + start
ts = timestamps[start:end]
n_missing = count[-1] - ts.size + 1
if n_missing > 0:
# if (n_missing := count[-1] - ts.size + 1) > 0: # py3.8
"""
For ephys sessions there may be fewer FPGA times than frame counts if SpikeGLX is turned
off before the video acquisition workflow. For Bpod this always occurs because Bpod
finishes before the camera workflow. For Bpod the times are already extrapolated for
these late frames."""
_logger.warning(f'{n_missing} fewer FPGA/Bpod timestamps than frame counts; '
f'{"extrapolating" if extrapolate_missing else "appending nans"}')
to_app = ((np.arange(n_missing, ) + 1) / frate + ts[-1]
if extrapolate_missing
else np.full(n_missing, np.nan))
ts = np.r_[ts, to_app] # Append the missing times
assert ts.size >= count.size, 'fewer timestamps than frame counts'
assert ts.size == count[-1] + 1, 'more frames recorded in frame count than timestamps '
# Remove the rest of the dropped frames
ts = ts[count]
assert np.searchsorted(ts, audio['times'][0]) == first_uptick,\
'time of first audio TTL doesn\'t match after alignment'
if ts.size != count.size:
_logger.error('number of timestamps and frames don\'t match after alignment')
if display:
# Plot to check
fig, axes = plt.subplots(1, 1)
y = within_ranges(np.arange(ts.size), pin_state['indices'].reshape(-1, 2)).astype(float)
y *= 1e-5 # For scale when zoomed in
axes.plot(ts, y, marker='d', color='blue', drawstyle='steps-pre', label='GPIO')
axes.plot(ts, np.zeros_like(ts), 'kx', label='FPGA timestamps')
vertical_lines(audio['times'], ymin=0, ymax=1e-5,
color='r', linestyle=':', ax=axes, label='audio TTL')
plt.legend()
return ts
def attribute_times(arr, events, tol=.1, injective=True, take='first'):
"""
Returns the values of the first array that correspond to those of the second.
Given two arrays of timestamps, the function will return the values of the first array
that most likely correspond to the values of the second. For each of the values in the
second array, the absolute difference is taken and the index of either the first sufficiently
close value, or simply the closest one, is assigned.
If injective is True, once a value has been assigned, to a value it can't be assigned to
another. In other words there is a one-to-one mapping between the two arrays.
:param arr: An array of event times to attribute to those in `events`
:param events: An array of event times considered a subset of `arr`
:param tol: The max absolute difference between values in order to be considered a match
:param injective: If true, once a value has been assigned it will not be assigned again
:param take: If 'first' the first value within tolerance is assigned; if 'nearest' the
closest value is assigned
:returns Numpy array the same length as `values`
"""
take = take.lower()
if take not in ('first', 'nearest'):
raise ValueError('Parameter `take` must be either "first" or "nearest"')
stack = np.ma.masked_invalid(arr, copy=False)
stack.fill_value = np.inf
assigned = np.full(events.shape, -1, dtype=int) # Initialize output array
for i, x in enumerate(events):
dx = np.abs(stack.filled() - x)
if dx.min() < tol: # is any value within tolerance
idx = np.where(dx < tol)[0][0] if take == 'first' else dx.argmin()
assigned[i] = idx
stack.mask[idx] = injective # If one-to-one, remove the assigned value
return assigned
def groom_pin_state(gpio, audio, ts, tolerance=2., display=False, take='first', min_diff=0.):
"""
Align the GPIO pin state to the FPGA audio TTLs. Any audio TTLs not reflected in the pin
state are removed from the dict and the times of the detected fronts are converted to FPGA
time. At the end of this the number of GPIO fronts should equal the number of audio fronts.
Note:
- This function is ultra safe: we probably don't need assign all the ups and down fronts
separately and could potentially even align the timestamps without removing the missed fronts
- The input gpio and audio dicts may be modified by this function
- For training sessions the frame rate is only 30Hz and the TTLs tend to be broken up by
small gaps. Setting the min_diff to 5ms helps the timestamp assignment accuracy.
:param gpio: array of GPIO pin state values
:param audio: dict of FPGA audio TTLs (see ibllib.io.extractors.ephys_fpga._get_sync_fronts)
:param ts: camera frame times
:param tolerance: two pulses need to be within this many seconds to be considered related
:param take: If 'first' the first value within tolerance is assigned; if 'nearest' the
closest value is assigned
:param display: If true, the resulting timestamps are plotted against the raw audio signal
:param min_diff: Audio TTL fronts less than min_diff seconds apart will be removed
:returns: dict of GPIO FPGA front indices, polarities and FPGA aligned times
:returns: audio times and polarities sans the TTLs not detected in the frame data
:returns: frame times in FPGA time
"""
# Check that the dimensions match
if np.any(gpio['indices'] >= ts.size):
_logger.warning('GPIO events occurring beyond timestamps array length')
keep = gpio['indices'] < ts.size
gpio = {k: gpio[k][keep] for k, v in gpio.items()}
assert audio and audio['times'].size > 0, 'no audio TTLs for session'
assert audio['times'].size == audio['polarities'].size, 'audio data dimension mismatch'
# make sure that there are no 2 consecutive fall or consecutive rise events
assert np.all(np.abs(np.diff(audio['polarities'])) == 2), 'consecutive high/low audio events'
# make sure first TTL is high
assert audio['polarities'][0] == 1
# make sure audio times in order
assert np.all(np.diff(audio['times']) > 0)
# make sure raw timestamps increase
assert np.all(np.diff(ts) > 0), 'timestamps must strictly increase'
# make sure there are state changes
assert gpio['indices'].any(), 'no TTLs detected in GPIO'
# # make sure first GPIO state is high
assert gpio['polarities'][0] == 1
"""
Some audio TTLs appear to be so short that they are not recorded by the camera. These can
be as short as a few microseconds. Applying a cutoff based on framerate was unsuccessful.
Assigning each audio TTL to each pin state change is not easy because some onsets occur very
close together (sometimes < 70ms), on the order of the delay between TTL and frame time.
Also, the two clocks have some degree of drift, so the delay between audio TTL and pin state
change may be zero or even negative.
Here we split the events into audio onsets (lo->hi) and audio offsets (hi->lo). For each
uptick in the GPIO pin state, we take the first audio onset time that was within 100ms of it.
We ensure that each audio TTL is assigned only once, so a TTL that is closer to frame 3 than
frame 1 may still be assigned to frame 1.
"""
ifronts = gpio['indices'] # The pin state flips
audio_times = audio['times']
if ifronts.size != audio['times'].size:
_logger.warning('more audio TTLs than GPIO state changes, assigning timestamps')
to_remove = np.zeros(ifronts.size, dtype=bool) # unassigned GPIO fronts to remove
low2high = ifronts[gpio['polarities'] == 1]
high2low = ifronts[gpio['polarities'] == -1]
assert low2high.size >= high2low.size
# Remove and/or fuse short TTLs
if min_diff > 0:
short, = np.where(np.diff(audio['times']) < min_diff)
audio_times = np.delete(audio['times'], np.r_[short, short + 1])
_logger.debug(f'Removed {short.size * 2} fronts TLLs less than '
f'{min_diff * 1e3:.0f}ms apart')
assert audio_times.size > 0, f'all audio TTLs less than {min_diff}s'
# Onsets
ups = ts[low2high] - ts[low2high][0] # times relative to first GPIO high
onsets = audio_times[::2] - audio_times[0] # audio times relative to first onset
# assign GPIO fronts to audio onset
assigned = attribute_times(onsets, ups, tol=tolerance, take=take)
unassigned = np.setdiff1d(np.arange(onsets.size), assigned[assigned > -1])
if unassigned.size > 0:
_logger.debug(f'{unassigned.size} audio TTL rises were not detected by the camera')
# Check that all pin state upticks could be attributed to an onset TTL
missed = assigned == -1
if np.any(missed):
# if np.any(missed := assigned == -1): # py3.8
_logger.warning(f'{sum(missed)} pin state rises could '
f'not be attributed to an audio TTL')
if display:
ax = plt.subplot()
vertical_lines(ups[assigned > -1],
linestyle='-', color='g', ax=ax,
label='assigned GPIO up state')
vertical_lines(ups[missed],
linestyle='-', color='r', ax=ax,
label='unassigned GPIO up state')
vertical_lines(onsets[unassigned],
linestyle=':', color='k', ax=ax,
alpha=0.3, label='audio onset')
vertical_lines(onsets[assigned],
linestyle=':', color='b', ax=ax, label='assigned audio onset')
plt.legend()
plt.show()
# Remove the missed fronts
to_remove = np.in1d(gpio['indices'], low2high[missed])
assigned = assigned[~missed]
onsets_ = audio_times[::2][assigned]
# Offsets
downs = ts[high2low] - ts[high2low][0]
offsets = audio_times[1::2] - audio_times[1]
assigned = attribute_times(offsets, downs, tol=tolerance, take=take)
unassigned = np.setdiff1d(np.arange(onsets.size), assigned[assigned > -1])
if unassigned.size > 0:
_logger.debug(f'{unassigned.size} audio TTL falls were not detected by the camera')
# Check that all pin state downticks could be attributed to an offset TTL
missed = assigned == -1
if np.any(missed):
# if np.any(missed := assigned == -1): # py3.8
_logger.warning(f'{sum(missed)} pin state falls could '
f'not be attributed to an audio TTL')
# Remove the missed fronts
to_remove |= np.in1d(gpio['indices'], high2low[missed])
assigned = assigned[~missed]
offsets_ = audio_times[1::2][assigned]
# Audio groomed
if np.any(to_remove):
# Check for any orphaned fronts (only one pin state edge was assigned)
to_remove = np.pad(to_remove, (0, to_remove.size % 2), 'edge') # Ensure even size
# Perform xor to find GPIOs where only onset or offset is marked for removal
orphaned = to_remove.reshape(-1, 2).sum(axis=1) == 1
if orphaned.any():
"""If there are orphaned GPIO fronts (i.e. only one edge was assigned to an
audio front), remove the orphaned front its assigned audio TTL. In other words
if both edges cannot be assigned to an audio TTL, we ignore the TTL entirely.
This is a sign that the assignment was bad and extraction may fail."""
_logger.warning('Some onsets but not offsets (or vice versa) were not assigned; '
'this may be a sign of faulty wiring or clock drift')
# Find indices of GPIO upticks where only the downtick was marked for removal
orphaned_onsets, = np.where(~to_remove.reshape(-1, 2)[:, 0] & orphaned)
# The onsets_ array already has the other TTLs removed (same size as to_remove ==
# False) so subtract the number of removed elements from index.
for i, v in enumerate(orphaned_onsets):
orphaned_onsets[i] -= to_remove.reshape(-1, 2)[:v, 0].sum()
# Same for offsets...
orphaned_offsets, = np.where(~to_remove.reshape(-1, 2)[:, 1] & orphaned)
for i, v in enumerate(orphaned_offsets):
orphaned_offsets[i] -= to_remove.reshape(-1, 2)[:v, 1].sum()
# Remove orphaned audio onsets and offsets
onsets_ = np.delete(onsets_, orphaned_onsets[orphaned_onsets < onsets_.size])
offsets_ = np.delete(offsets_, orphaned_offsets[orphaned_offsets < offsets_.size])
_logger.debug(f'{orphaned.sum()} orphaned TTLs removed')
to_remove.reshape(-1, 2)[orphaned] = True
# Remove those unassigned GPIOs
gpio = {k: v[~to_remove[:v.size]] for k, v in gpio.items()}
ifronts = gpio['indices']
# Assert that we've removed discrete TTLs
# A failure means e.g. an up-going front of one TTL was missed
# but not the down-going one.
assert np.all(np.abs(np.diff(gpio['polarities'])) == 2)
assert gpio['polarities'][0] == 1
audio_ = {'times': np.empty(ifronts.size), 'polarities': gpio['polarities']}
audio_['times'][::2] = onsets_
audio_['times'][1::2] = offsets_
else:
audio_ = audio
# Align the frame times to FPGA
fcn_a2b, drift_ppm = dsp.sync_timestamps(ts[ifronts], audio_['times'])
_logger.debug(f'frame audio alignment drift = {drift_ppm:.2f}ppm')
# Add times to GPIO dict
gpio['times'] = fcn_a2b(ts[ifronts])
if display:
# Plot all the onsets and offsets
ax = plt.subplot()
# All Audio TTLS
squares(audio['times'], audio['polarities'],
ax=ax, label='audio TTLs', linestyle=':', color='k', yrange=[0, 1], alpha=0.3)
# GPIO
x = np.insert(gpio['times'], 0, 0)
y = np.arange(x.size) % 2
squares(x, y, ax=ax, label='GPIO')
y = within_ranges(np.arange(ts.size), ifronts.reshape(-1, 2)) # 0 or 1 for each frame
ax.plot(fcn_a2b(ts), y, 'kx', label='cam times')
# Assigned audio
squares(audio_['times'], audio_['polarities'],
ax=ax, label='assigned audio TTL', linestyle=':', color='g', yrange=[0, 1])
ax.legend()
plt.xlabel('FPGA time (s)')
ax.set_yticks([0, 1])
ax.set_title('GPIO - audio TTL alignment')
plt.show()
return gpio, audio_, fcn_a2b(ts)
def extract_all(session_path, session_type=None, save=True, **kwargs):
"""
For the IBL ephys task, reads ephys binary file and extract:
- video time stamps
:param session_path: '/path/to/subject/yyyy-mm-dd/001'
:param session_type: the session type to extract, i.e. 'ephys', 'training' or 'biased'. If
None the session type is inferred from the settings file.
:param save: Bool, defaults to False
:param kwargs: parameters to pass to the extractor
:return: outputs, files
"""
if session_type is None:
session_type = get_session_extractor_type(session_path)
if not session_type or session_type not in _get_task_types_json_config().values():
raise ValueError(f"Session type {session_type} has no matching extractor")
elif 'ephys' in session_type: # assume ephys == FPGA
labels = assert_valid_label(kwargs.pop('labels', ('left', 'right', 'body')))
labels = (labels,) if isinstance(labels, str) else labels # Ensure list/tuple
extractor = [partial(CameraTimestampsFPGA, label) for label in labels]
if 'sync' not in kwargs:
kwargs['sync'], kwargs['chmap'] = \
get_main_probe_sync(session_path, bin_exists=kwargs.pop('bin_exists', False))
else: # assume Bpod otherwise
assert kwargs.pop('labels', 'left'), 'only left camera is currently supported'
extractor = CameraTimestampsBpod
outputs, files = run_extractor_classes(
extractor, session_path=session_path, save=save, **kwargs)
return outputs, files
|
import requests
from osbot_aws.apis.Lambda import Lambda
from gw_bot.api.API_Slack import API_Slack
from gw_bot.api.gw.API_Glasswall import API_Glasswall
from osbot_aws.helpers.Lambda_Helpers import slack_message
from osbot_utils.utils.Files import Files
class API_GW_Slack_File:
def __init__(self):
self.api_slack = API_Slack()
def file_info_form_slack(self, slack_event):
file_id = slack_event.get('file_id')
file_info = self.api_slack.files_info(file_id)
return file_info
def download_file(self, file_info):
file_url = file_info.get('file').get('url_private_download')
file_name = file_url.split('/').pop()
tmp_file = f'{Files.temp_folder('/tmp/')}/{file_name}'
headers = {'Authorization' : f"Bearer {self.api_slack.bot_token}"}
file_contents = requests.get(file_url,headers=headers)
with open(tmp_file, "wb") as fh:
fh.write(file_contents.content)
return tmp_file
def gw_scan_file(self,target_file):
(file_name, base64_data) = API_Glasswall().get_file_base_64(target_file)
payload = {'file_contents': base64_data, 'file_name': file_name}
return Lambda('gw_bot.lambdas.gw.gw_engine').invoke(payload)
def send_report_to_slack(self, file_info, gw_report):
channel = file_info.get('file').get('channels')[0]
file_name = file_info.get('file').get('name')
file_id = file_info.get('file').get('id')
text = f':two: Scan of file *{file_id}* completed, generating report' #+ \
#f'```{json.dumps(gw_report,indent=2)}```'
# f'uploaded by the user <@{file_info.get('file').get('user')}> on channel <#{channel}> ' #+ \
#channel = 'DRE51D4EM' # for now override the message to sent the value as a DM to DinisCruz
#self.api_slack.send_message(text, [], channel=channel)
slack_message(text, [], channel=channel)
from osbot_aws.apis.Lambda import Lambda
file_name = file_info.get('file').get('name')
payload = {'file_name': file_name, 'json_data': gw_report}
png_data = Lambda('osbot_browser.lambdas.gw.xml_report').invoke(payload).get('png_data')
if png_data is None:
slack_message(':red_circle: report table could not be be created', [], channel=channel)
else:
slack_message(':three: report created, sending it to Slack', [], channel=channel)
self.api_slack.upload_image_from_png_base64(png_data, channel, 'scan')
#self.api_slack.upload_file('/tmp/test_file.png', channel) | import requests
from osbot_aws.apis.Lambda import Lambda
from gw_bot.api.API_Slack import API_Slack
from gw_bot.api.gw.API_Glasswall import API_Glasswall
from osbot_aws.helpers.Lambda_Helpers import slack_message
from osbot_utils.utils.Files import Files
class API_GW_Slack_File:
def __init__(self):
self.api_slack = API_Slack()
def file_info_form_slack(self, slack_event):
file_id = slack_event.get('file_id')
file_info = self.api_slack.files_info(file_id)
return file_info
def download_file(self, file_info):
file_url = file_info.get('file').get('url_private_download')
file_name = file_url.split('/').pop()
tmp_file = f'{Files.temp_folder("/tmp/")}/{file_name}'
headers = {'Authorization' : f"Bearer {self.api_slack.bot_token}"}
file_contents = requests.get(file_url,headers=headers)
with open(tmp_file, "wb") as fh:
fh.write(file_contents.content)
return tmp_file
def gw_scan_file(self,target_file):
(file_name, base64_data) = API_Glasswall().get_file_base_64(target_file)
payload = {'file_contents': base64_data, 'file_name': file_name}
return Lambda('gw_bot.lambdas.gw.gw_engine').invoke(payload)
def send_report_to_slack(self, file_info, gw_report):
channel = file_info.get('file').get('channels')[0]
file_name = file_info.get('file').get('name')
file_id = file_info.get('file').get('id')
text = f':two: Scan of file *{file_id}* completed, generating report' #+ \
#f'```{json.dumps(gw_report,indent=2)}```'
# f'uploaded by the user <@{file_info.get("file").get("user")}> on channel <#{channel}> ' #+ \
#channel = 'DRE51D4EM' # for now override the message to sent the value as a DM to DinisCruz
#self.api_slack.send_message(text, [], channel=channel)
slack_message(text, [], channel=channel)
from osbot_aws.apis.Lambda import Lambda
file_name = file_info.get('file').get('name')
payload = {'file_name': file_name, 'json_data': gw_report}
png_data = Lambda('osbot_browser.lambdas.gw.xml_report').invoke(payload).get('png_data')
if png_data is None:
slack_message(':red_circle: report table could not be be created', [], channel=channel)
else:
slack_message(':three: report created, sending it to Slack', [], channel=channel)
self.api_slack.upload_image_from_png_base64(png_data, channel, 'scan')
#self.api_slack.upload_file('/tmp/test_file.png', channel) |
import time
import os
import subprocess
class Design(object):
def __init__(self):
self.top_name = "design" + time.strftime("%Y-%m-%d", time.localtime())
self.is_Chisel_design = False
self.rtl_input = " "
self.Chisel_input = " "
self.result_dir = "./design/"
self.lib_name = "gscl45nm"
self.lef_input = " "
self.liberty_input = " "
self.clk_name = "clk"
self.delay = 100
def Chisel2RTL(self, verbose):
"""
Compile Chisel design to single verilog file
"""
print("========== Compiling Chisel to Verilog... ==========")
chisel_dir = self.Chisel_input
output = "" if verbose else f" > {os.path.join(self.result_dir, self.top_name, self.lib_name, "reports/", "sbt.log")}"
cmd = f'sbt "runMain {self.top_name}"' + output
subprocess.run(cmd, cwd=chisel_dir, shell=True)
self.rtl_input = os.path.join(self.Chisel_input, 'generated', '%s.v'%self.top_name)
| import time
import os
import subprocess
class Design(object):
def __init__(self):
self.top_name = "design" + time.strftime("%Y-%m-%d", time.localtime())
self.is_Chisel_design = False
self.rtl_input = " "
self.Chisel_input = " "
self.result_dir = "./design/"
self.lib_name = "gscl45nm"
self.lef_input = " "
self.liberty_input = " "
self.clk_name = "clk"
self.delay = 100
def Chisel2RTL(self, verbose):
"""
Compile Chisel design to single verilog file
"""
print("========== Compiling Chisel to Verilog... ==========")
chisel_dir = self.Chisel_input
output = "" if verbose else f" > {os.path.join(self.result_dir, self.top_name, self.lib_name, 'reports/', 'sbt.log')}"
cmd = f'sbt "runMain {self.top_name}"' + output
subprocess.run(cmd, cwd=chisel_dir, shell=True)
self.rtl_input = os.path.join(self.Chisel_input, 'generated', '%s.v'%self.top_name)
|
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The circuit data structure.
Circuits consist of a list of Moments, each Moment made up of a set of
Operations. Each Operation is a Gate that acts on some Qubits, for a given
Moment the Operations must all act on distinct Qubits.
"""
from collections import defaultdict
from itertools import groupby
import math
from typing import (
AbstractSet,
Any,
Callable,
cast,
Dict,
FrozenSet,
Iterable,
Iterator,
List,
Optional,
overload,
Sequence,
Set,
Tuple,
Type,
TYPE_CHECKING,
TypeVar,
Union,
)
import abc
import html
import numpy as np
from cirq import devices, ops, protocols, qis
from cirq.circuits._bucket_priority_queue import BucketPriorityQueue
from cirq.circuits.insert_strategy import InsertStrategy
from cirq.circuits.text_diagram_drawer import TextDiagramDrawer
from cirq.circuits.qasm_output import QasmOutput
from cirq.circuits.quil_output import QuilOutput
from cirq.type_workarounds import NotImplementedType
from cirq._compat import deprecated
import cirq._version
if TYPE_CHECKING:
import cirq
T_DESIRED_GATE_TYPE = TypeVar('T_DESIRED_GATE_TYPE', bound='ops.Gate')
CIRCUIT_TYPE = TypeVar('CIRCUIT_TYPE', bound='AbstractCircuit')
INT_TYPE = Union[int, np.integer]
class AbstractCircuit(abc.ABC):
"""The base class for Circuit-like objects.
A circuit-like object must have a list of moments (which can be empty) and
a device (which may be `devices.UNCONSTRAINED_DEVICE`).
These methods return information about the circuit, and can be called on
either Circuit or FrozenCircuit objects:
* next_moment_operating_on
* prev_moment_operating_on
* next_moments_operating_on
* operation_at
* all_qubits
* all_operations
* findall_operations
* findall_operations_between
* findall_operations_until_blocked
* findall_operations_with_gate_type
* reachable_frontier_from
* has_measurements
* are_all_matches_terminal
* are_all_measurements_terminal
* unitary
* final_state_vector
* to_text_diagram
* to_text_diagram_drawer
* qid_shape
* all_measurement_keys
* to_quil
* to_qasm
* save_qasm
"""
@property
@abc.abstractmethod
def moments(self) -> Sequence['cirq.Moment']:
pass
@property
@abc.abstractmethod
def device(self) -> devices.Device:
pass
def freeze(self) -> 'cirq.FrozenCircuit':
"""Creates a FrozenCircuit from this circuit.
If 'self' is a FrozenCircuit, the original object is returned.
"""
from cirq.circuits import FrozenCircuit
if isinstance(self, FrozenCircuit):
return self
return FrozenCircuit(self, strategy=InsertStrategy.EARLIEST, device=self.device)
def unfreeze(self) -> 'cirq.Circuit':
"""Creates a Circuit from this circuit.
If 'self' is a Circuit, this returns a copy of that circuit.
"""
if isinstance(self, Circuit):
return Circuit.copy(self)
return Circuit(self, strategy=InsertStrategy.EARLIEST, device=self.device)
def __bool__(self):
return bool(self.moments)
def __eq__(self, other):
if not isinstance(other, type(self)):
return NotImplemented
return self.moments == other.moments and self.device == other.device
def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool:
"""See `cirq.protocols.SupportsApproximateEquality`."""
if not isinstance(other, type(self)):
return NotImplemented
return (
cirq.protocols.approx_eq(self.moments, other.moments, atol=atol)
and self.device == other.device
)
def __ne__(self, other) -> bool:
return not self == other
def __len__(self) -> int:
return len(self.moments)
def __iter__(self) -> Iterator['cirq.Moment']:
return iter(self.moments)
def _decompose_(self) -> 'cirq.OP_TREE':
"""See `cirq.SupportsDecompose`."""
return self.all_operations()
# pylint: disable=function-redefined
@overload
def __getitem__(self, key: int) -> 'cirq.Moment':
pass
@overload
def __getitem__(self, key: Tuple[int, 'cirq.Qid']) -> 'cirq.Operation':
pass
@overload
def __getitem__(self, key: Tuple[int, Iterable['cirq.Qid']]) -> 'cirq.Moment':
pass
@overload
def __getitem__(self: CIRCUIT_TYPE, key: slice) -> CIRCUIT_TYPE:
pass
@overload
def __getitem__(self: CIRCUIT_TYPE, key: Tuple[slice, 'cirq.Qid']) -> CIRCUIT_TYPE:
pass
@overload
def __getitem__(self: CIRCUIT_TYPE, key: Tuple[slice, Iterable['cirq.Qid']]) -> CIRCUIT_TYPE:
pass
def __getitem__(self, key):
if isinstance(key, slice):
sliced_moments = self.moments[key]
return self._with_sliced_moments(sliced_moments)
if hasattr(key, '__index__'):
return self.moments[key]
if isinstance(key, tuple):
if len(key) != 2:
raise ValueError('If key is tuple, it must be a pair.')
moment_idx, qubit_idx = key
# moment_idx - int or slice; qubit_idx - Qid or Iterable[Qid].
selected_moments = self.moments[moment_idx]
if isinstance(selected_moments, ops.Moment):
return selected_moments[qubit_idx]
if isinstance(qubit_idx, ops.Qid):
qubit_idx = [qubit_idx]
sliced_moments = [moment[qubit_idx] for moment in selected_moments]
return self._with_sliced_moments(sliced_moments)
raise TypeError('__getitem__ called with key not of type slice, int, or tuple.')
# pylint: enable=function-redefined
@abc.abstractmethod
def _with_sliced_moments(self, moments: Sequence['cirq.Moment']):
"""Helper method for constructing circuits from __getitem__."""
def __str__(self) -> str:
return self.to_text_diagram()
def __repr__(self) -> str:
cls_name = self.__class__.__name__
args = []
if self.moments:
args.append(_list_repr_with_indented_item_lines(self.moments))
if self.device != devices.UNCONSTRAINED_DEVICE:
args.append(f'device={self.device!r}')
return f'cirq.{cls_name}({', '.join(args)})'
def _repr_pretty_(self, p: Any, cycle: bool) -> None:
"""Print ASCII diagram in Jupyter."""
cls_name = self.__class__.__name__
if cycle:
# There should never be a cycle. This is just in case.
p.text(f'{cls_name}(...)')
else:
p.text(self.to_text_diagram())
def _repr_html_(self) -> str:
"""Print ASCII diagram in Jupyter notebook without wrapping lines."""
return (
'<pre style="overflow: auto; white-space: pre;">'
+ html.escape(self.to_text_diagram())
+ '</pre>'
)
def _first_moment_operating_on(
self, qubits: Iterable['cirq.Qid'], indices: Iterable[int]
) -> Optional[int]:
qubits = frozenset(qubits)
for m in indices:
if self._has_op_at(m, qubits):
return m
return None
def next_moment_operating_on(
self, qubits: Iterable['cirq.Qid'], start_moment_index: int = 0, max_distance: int = None
) -> Optional[int]:
"""Finds the index of the next moment that touches the given qubits.
Args:
qubits: We're looking for operations affecting any of these qubits.
start_moment_index: The starting point of the search.
max_distance: The number of moments (starting from the start index
and moving forward) to check. Defaults to no limit.
Returns:
None if there is no matching moment, otherwise the index of the
earliest matching moment.
Raises:
ValueError: negative max_distance.
"""
max_circuit_distance = len(self.moments) - start_moment_index
if max_distance is None:
max_distance = max_circuit_distance
elif max_distance < 0:
raise ValueError('Negative max_distance: {}'.format(max_distance))
else:
max_distance = min(max_distance, max_circuit_distance)
return self._first_moment_operating_on(
qubits, range(start_moment_index, start_moment_index + max_distance)
)
def next_moments_operating_on(
self, qubits: Iterable['cirq.Qid'], start_moment_index: int = 0
) -> Dict['cirq.Qid', int]:
"""Finds the index of the next moment that touches each qubit.
Args:
qubits: The qubits to find the next moments acting on.
start_moment_index: The starting point of the search.
Returns:
The index of the next moment that touches each qubit. If there
is no such moment, the next moment is specified as the number of
moments in the circuit. Equivalently, can be characterized as one
plus the index of the last moment after start_moment_index
(inclusive) that does *not* act on a given qubit.
"""
next_moments = {}
for q in qubits:
next_moment = self.next_moment_operating_on([q], start_moment_index)
next_moments[q] = len(self.moments) if next_moment is None else next_moment
return next_moments
def prev_moment_operating_on(
self,
qubits: Sequence['cirq.Qid'],
end_moment_index: Optional[int] = None,
max_distance: Optional[int] = None,
) -> Optional[int]:
"""Finds the index of the next moment that touches the given qubits.
Args:
qubits: We're looking for operations affecting any of these qubits.
end_moment_index: The moment index just after the starting point of
the reverse search. Defaults to the length of the list of
moments.
max_distance: The number of moments (starting just before from the
end index and moving backward) to check. Defaults to no limit.
Returns:
None if there is no matching moment, otherwise the index of the
latest matching moment.
Raises:
ValueError: negative max_distance.
"""
if end_moment_index is None:
end_moment_index = len(self.moments)
if max_distance is None:
max_distance = len(self.moments)
elif max_distance < 0:
raise ValueError('Negative max_distance: {}'.format(max_distance))
else:
max_distance = min(end_moment_index, max_distance)
# Don't bother searching indices past the end of the list.
if end_moment_index > len(self.moments):
d = end_moment_index - len(self.moments)
end_moment_index -= d
max_distance -= d
if max_distance <= 0:
return None
return self._first_moment_operating_on(
qubits, (end_moment_index - k - 1 for k in range(max_distance))
)
def reachable_frontier_from(
self,
start_frontier: Dict['cirq.Qid', int],
*,
is_blocker: Callable[['cirq.Operation'], bool] = lambda op: False,
) -> Dict['cirq.Qid', int]:
"""Determines how far can be reached into a circuit under certain rules.
The location L = (qubit, moment_index) is *reachable* if and only if:
a) There is not a blocking operation covering L.
AND
[
b1) qubit is in start frontier and moment_index =
max(start_frontier[qubit], 0).
OR
b2) There is no operation at L and prev(L) = (qubit,
moment_index-1) is reachable.
OR
b3) There is an (non-blocking) operation P covering L such that
(q', moment_index - 1) is reachable for every q' on which P
acts.
]
An operation in moment moment_index is blocking if
a) `is_blocker` returns a truthy value.
OR
b) The operation acts on a qubit not in start_frontier.
OR
c) The operation acts on a qubit q such that start_frontier[q] >
moment_index.
In other words, the reachable region extends forward through time along
each qubit in start_frontier until it hits a blocking operation. Any
location involving a qubit not in start_frontier is unreachable.
For each qubit q in `start_frontier`, the reachable locations will
correspond to a contiguous range starting at start_frontier[q] and
ending just before some index end_q. The result of this method is a
dictionary, and that dictionary maps each qubit q to its end_q.
Examples:
If start_frontier is {
cirq.LineQubit(0): 6,
cirq.LineQubit(1): 2,
cirq.LineQubit(2): 2,
} then the reachable wire locations in the following circuit are
highlighted with '█' characters:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0: ───H───@─────────────────█████████████████████─@───H───
│ │
1: ───────@─██H███@██████████████████████─@───H───@───────
│ │
2: ─────────██████@███H██─@───────@───H───@───────────────
│ │
3: ───────────────────────@───H───@───────────────────────
And the computed end_frontier is {
cirq.LineQubit(0): 11,
cirq.LineQubit(1): 9,
cirq.LineQubit(2): 6,
}
Note that the frontier indices (shown above the circuit) are
best thought of (and shown) as happening *between* moment indices.
If we specify a blocker as follows:
is_blocker=lambda: op == cirq.CZ(cirq.LineQubit(1),
cirq.LineQubit(2))
and use this start_frontier:
{
cirq.LineQubit(0): 0,
cirq.LineQubit(1): 0,
cirq.LineQubit(2): 0,
cirq.LineQubit(3): 0,
}
Then this is the reachable area:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0: ─██H███@██████████████████████████████████████─@───H───
│ │
1: ─██████@███H██─@───────────────────────@───H───@───────
│ │
2: ─█████████████─@───H───@───────@───H───@───────────────
│ │
3: ─█████████████████████─@───H───@───────────────────────
and the computed end_frontier is:
{
cirq.LineQubit(0): 11,
cirq.LineQubit(1): 3,
cirq.LineQubit(2): 3,
cirq.LineQubit(3): 5,
}
Args:
start_frontier: A starting set of reachable locations.
is_blocker: A predicate that determines if operations block
reachability. Any location covered by an operation that causes
`is_blocker` to return True is considered to be an unreachable
location.
Returns:
An end_frontier dictionary, containing an end index for each qubit q
mapped to a start index by the given `start_frontier` dictionary.
To determine if a location (q, i) was reachable, you can use
this expression:
q in start_frontier and start_frontier[q] <= i < end_frontier[q]
where i is the moment index, q is the qubit, and end_frontier is the
result of this method.
"""
active: Set['cirq.Qid'] = set()
end_frontier = {}
queue = BucketPriorityQueue[ops.Operation](drop_duplicate_entries=True)
def enqueue_next(qubit: 'cirq.Qid', moment: int) -> None:
next_moment = self.next_moment_operating_on([qubit], moment)
if next_moment is None:
end_frontier[qubit] = max(len(self), start_frontier[qubit])
if qubit in active:
active.remove(qubit)
else:
next_op = self.operation_at(qubit, next_moment)
assert next_op is not None
queue.enqueue(next_moment, next_op)
for start_qubit, start_moment in start_frontier.items():
enqueue_next(start_qubit, start_moment)
while queue:
cur_moment, cur_op = queue.dequeue()
for q in cur_op.qubits:
if (
q in start_frontier
and cur_moment >= start_frontier[q]
and q not in end_frontier
):
active.add(q)
continue_past = (
cur_op is not None and active.issuperset(cur_op.qubits) and not is_blocker(cur_op)
)
if continue_past:
for q in cur_op.qubits:
enqueue_next(q, cur_moment + 1)
else:
for q in cur_op.qubits:
if q in active:
end_frontier[q] = cur_moment
active.remove(q)
return end_frontier
def findall_operations_between(
self,
start_frontier: Dict['cirq.Qid', int],
end_frontier: Dict['cirq.Qid', int],
omit_crossing_operations: bool = False,
) -> List[Tuple[int, 'cirq.Operation']]:
"""Finds operations between the two given frontiers.
If a qubit is in `start_frontier` but not `end_frontier`, its end index
defaults to the end of the circuit. If a qubit is in `end_frontier` but
not `start_frontier`, its start index defaults to the start of the
circuit. Operations on qubits not mentioned in either frontier are not
included in the results.
Args:
start_frontier: Just before where to start searching for operations,
for each qubit of interest. Start frontier indices are
inclusive.
end_frontier: Just before where to stop searching for operations,
for each qubit of interest. End frontier indices are exclusive.
omit_crossing_operations: Determines whether or not operations that
cross from a location between the two frontiers to a location
outside the two frontiers are included or excluded. (Operations
completely inside are always included, and operations completely
outside are always excluded.)
Returns:
A list of tuples. Each tuple describes an operation found between
the two frontiers. The first item of each tuple is the index of the
moment containing the operation, and the second item is the
operation itself. The list is sorted so that the moment index
increases monotonically.
"""
result = BucketPriorityQueue[ops.Operation](drop_duplicate_entries=True)
involved_qubits = set(start_frontier.keys()) | set(end_frontier.keys())
# Note: only sorted to ensure a deterministic result ordering.
for q in sorted(involved_qubits):
for i in range(start_frontier.get(q, 0), end_frontier.get(q, len(self))):
op = self.operation_at(q, i)
if op is None:
continue
if omit_crossing_operations and not involved_qubits.issuperset(op.qubits):
continue
result.enqueue(i, op)
return list(result)
def findall_operations_until_blocked(
self,
start_frontier: Dict['cirq.Qid', int],
is_blocker: Callable[['cirq.Operation'], bool] = lambda op: False,
) -> List[Tuple[int, ops.Operation]]:
"""
Finds all operations until a blocking operation is hit.
An operation is considered blocking if
a) It is in the 'light cone' of start_frontier.
AND
(
1) is_blocker returns a truthy value.
OR
2) It acts on a blocked qubit.
)
Every qubit acted on by a blocking operation is thereafter itself
blocked.
The notion of reachability here differs from that in
reachable_frontier_from in two respects:
1) An operation is not considered blocking only because it is in a
moment before the start_frontier of one of the qubits on which it
acts.
2) Operations that act on qubits not in start_frontier are not
automatically blocking.
For every (moment_index, operation) returned:
1) moment_index >= min((start_frontier[q] for q in operation.qubits
if q in start_frontier), default=0)
2) set(operation.qubits).intersection(start_frontier)
Below are some examples, where on the left the opening parentheses show
`start_frontier` and on the right are the operations included (with
their moment indices) in the output. `F` and `T` indicate that
`is_blocker` return `False` or `True`, respectively, when applied to
the gates; `M` indicates that it doesn't matter.
─(─F───F─────── ┄(─F───F─)┄┄┄┄┄
│ │ │ │
─(─F───F───T─── => ┄(─F───F─)┄┄┄┄┄
│ ┊
───────────T─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
───M─────(─F─── ┄┄┄┄┄┄┄┄┄(─F─)┄┄
│ │ ┊ │
───M───M─(─F─── ┄┄┄┄┄┄┄┄┄(─F─)┄┄
│ => ┊
───────M───M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ ┊
───────────M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
───M─(─────M─── ┄┄┄┄┄()┄┄┄┄┄┄┄┄
│ │ ┊ ┊
───M─(─T───M─── ┄┄┄┄┄()┄┄┄┄┄┄┄┄
│ => ┊
───────T───M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ ┊
───────────M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
─(─F───F─── ┄(─F───F─)┄
│ │ => │ │
───F─(─F─── ┄(─F───F─)┄
─(─F─────────── ┄(─F─)┄┄┄┄┄┄┄┄┄
│ │
───F───F─────── ┄(─F─)┄┄┄┄┄┄┄┄┄
│ => ┊
───────F───F─── ┄┄┄┄┄┄┄┄┄(─F─)┄
│ │
─(─────────F─── ┄┄┄┄┄┄┄┄┄(─F─)┄
Args:
start_frontier: A starting set of reachable locations.
is_blocker: A predicate that determines if operations block
reachability. Any location covered by an operation that causes
`is_blocker` to return True is considered to be an unreachable
location.
Returns:
A list of tuples. Each tuple describes an operation found between
the start frontier and a blocking operation. The first item of
each tuple is the index of the moment containing the operation,
and the second item is the operation itself.
"""
op_list = [] # type: List[Tuple[int, ops.Operation]]
if not start_frontier:
return op_list
start_index = min(start_frontier.values())
blocked_qubits = set() # type: Set[cirq.Qid]
for index, moment in enumerate(self[start_index:], start_index):
active_qubits = set(q for q, s in start_frontier.items() if s <= index)
for op in moment.operations:
if is_blocker(op) or blocked_qubits.intersection(op.qubits):
blocked_qubits.update(op.qubits)
elif active_qubits.intersection(op.qubits):
op_list.append((index, op))
if blocked_qubits.issuperset(start_frontier):
break
return op_list
def operation_at(self, qubit: 'cirq.Qid', moment_index: int) -> Optional['cirq.Operation']:
"""Finds the operation on a qubit within a moment, if any.
Args:
qubit: The qubit to check for an operation on.
moment_index: The index of the moment to check for an operation
within. Allowed to be beyond the end of the circuit.
Returns:
None if there is no operation on the qubit at the given moment, or
else the operation.
"""
if not 0 <= moment_index < len(self.moments):
return None
return self.moments[moment_index].operation_at(qubit)
def findall_operations(
self, predicate: Callable[['cirq.Operation'], bool]
) -> Iterable[Tuple[int, 'cirq.Operation']]:
"""Find the locations of all operations that satisfy a given condition.
This returns an iterator of (index, operation) tuples where each
operation satisfies op_cond(operation) is truthy. The indices are
in order of the moments and then order of the ops within that moment.
Args:
predicate: A method that takes an Operation and returns a Truthy
value indicating the operation meets the find condition.
Returns:
An iterator (index, operation)'s that satisfy the op_condition.
"""
for index, moment in enumerate(self.moments):
for op in moment.operations:
if predicate(op):
yield index, op
def findall_operations_with_gate_type(
self, gate_type: Type[T_DESIRED_GATE_TYPE]
) -> Iterable[Tuple[int, ops.GateOperation, T_DESIRED_GATE_TYPE]]:
"""Find the locations of all gate operations of a given type.
Args:
gate_type: The type of gate to find, e.g. XPowGate or
MeasurementGate.
Returns:
An iterator (index, operation, gate)'s for operations with the given
gate type.
"""
result = self.findall_operations(lambda operation: isinstance(operation.gate, gate_type))
for index, op in result:
gate_op = cast(ops.GateOperation, op)
yield index, gate_op, cast(T_DESIRED_GATE_TYPE, gate_op.gate)
def has_measurements(self):
return any(self.findall_operations(protocols.is_measurement))
def are_all_measurements_terminal(self):
"""Whether all measurement gates are at the end of the circuit."""
return self.are_all_matches_terminal(protocols.is_measurement)
def are_all_matches_terminal(self, predicate: Callable[['cirq.Operation'], bool]):
"""Check whether all of the ops that satisfy a predicate are terminal.
This method will transparently descend into any CircuitOperations this
circuit contains; as a result, it will misbehave if the predicate
refers to CircuitOperations. See the tests for an example of this.
Args:
predicate: A predicate on ops.Operations which is being checked.
Returns:
Whether or not all `Operation` s in a circuit that satisfy the
given predicate are terminal. Also checks within any CircuitGates
the circuit may contain.
"""
from cirq.circuits import CircuitOperation
# TaggedOperations can wrap CircuitOperations.
def get_op_circuit(op: ops.Operation) -> Optional['cirq.FrozenCircuit']:
while isinstance(op, ops.TaggedOperation):
op = op.sub_operation
return op.circuit if isinstance(op, CircuitOperation) else None
if not all(
self.next_moment_operating_on(op.qubits, i + 1) is None
for (i, op) in self.findall_operations(predicate)
if get_op_circuit(op) is None
):
return False
for i, moment in enumerate(self.moments):
for op in moment.operations:
circuit = get_op_circuit(op)
if circuit is None:
continue
if not circuit.are_all_matches_terminal(predicate):
return False
if i < len(self.moments) - 1 and not all(
self.next_moment_operating_on(op.qubits, i + 1) is None
for _, op in circuit.findall_operations(predicate)
):
return False
return True
def _has_op_at(self, moment_index: int, qubits: Iterable['cirq.Qid']) -> bool:
return 0 <= moment_index < len(self.moments) and self.moments[moment_index].operates_on(
qubits
)
def _validate_op_tree_qids(self, op_tree: 'cirq.OP_TREE') -> None:
"""Raises an exception if any operation in `op_tree` has qids that don't
match its qid shape.
Args:
operation: The operation to validate.
Raises:
ValueError: The operation had qids that don't match its qid shape.
"""
# Cast from Iterable[Operation, Moment] because preserve_moments is
# False.
for op in cast(Iterable['cirq.Operation'], ops.flatten_op_tree(op_tree)):
if protocols.qid_shape(op) != protocols.qid_shape(op.qubits):
raise ValueError(
'Invalid operation. '
'An operation has qid shape <{!r}> but is on qids with '
'shape <{!r}>. The operation is <{!r}>.'.format(
protocols.qid_shape(op), protocols.qid_shape(op.qubits), op
)
)
def all_qubits(self) -> FrozenSet['cirq.Qid']:
"""Returns the qubits acted upon by Operations in this circuit."""
return frozenset(q for m in self.moments for q in m.qubits)
def all_operations(self) -> Iterator[ops.Operation]:
"""Iterates over the operations applied by this circuit.
Operations from earlier moments will be iterated over first. Operations
within a moment are iterated in the order they were given to the
moment's constructor.
"""
return (op for moment in self for op in moment.operations)
def qid_shape(
self, qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT
) -> Tuple[int, ...]:
qids = ops.QubitOrder.as_qubit_order(qubit_order).order_for(self.all_qubits())
return protocols.qid_shape(qids)
def all_measurement_keys(self) -> AbstractSet[str]:
return protocols.measurement_keys(self)
def _with_measurement_key_mapping_(self, key_map: Dict[str, str]):
return self._with_sliced_moments(
[protocols.with_measurement_key_mapping(moment, key_map) for moment in self.moments]
)
def _qid_shape_(self) -> Tuple[int, ...]:
return self.qid_shape()
def _has_unitary_(self) -> bool:
if not self.are_all_measurements_terminal():
return False
unitary_ops = protocols.decompose(
self.all_operations(),
keep=protocols.has_unitary,
intercepting_decomposer=_decompose_measurement_inversions,
on_stuck_raise=None,
)
return all(protocols.has_unitary(e) for e in unitary_ops)
def _unitary_(self) -> Union[np.ndarray, NotImplementedType]:
"""Converts the circuit into a unitary matrix, if possible.
If the circuit contains any non-terminal measurements, the conversion
into a unitary matrix fails (i.e. returns NotImplemented). Terminal
measurements are ignored when computing the unitary matrix. The unitary
matrix is the product of the unitary matrix of all operations in the
circuit (after expanding them to apply to the whole system).
"""
if not self._has_unitary_():
return NotImplemented
return self.unitary(ignore_terminal_measurements=True)
def unitary(
self,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
qubits_that_should_be_present: Iterable['cirq.Qid'] = (),
ignore_terminal_measurements: bool = True,
dtype: Type[np.number] = np.complex128,
) -> np.ndarray:
"""Converts the circuit into a unitary matrix, if possible.
Returns the same result as `cirq.unitary`, but provides more options.
Args:
qubit_order: Determines how qubits are ordered when passing matrices
into np.kron.
qubits_that_should_be_present: Qubits that may or may not appear
in operations within the circuit, but that should be included
regardless when generating the matrix.
ignore_terminal_measurements: When set, measurements at the end of
the circuit are ignored instead of causing the method to
fail.
dtype: The numpy dtype for the returned unitary. Defaults to
np.complex128. Specifying np.complex64 will run faster at the
cost of precision. `dtype` must be a complex np.dtype, unless
all operations in the circuit have unitary matrices with
exclusively real coefficients (e.g. an H + TOFFOLI circuit).
Returns:
A (possibly gigantic) 2d numpy array corresponding to a matrix
equivalent to the circuit's effect on a quantum state.
Raises:
ValueError: The circuit contains measurement gates that are not
ignored.
TypeError: The circuit contains gates that don't have a known
unitary matrix, e.g. gates parameterized by a Symbol.
"""
if not ignore_terminal_measurements and any(
protocols.is_measurement(op) for op in self.all_operations()
):
raise ValueError('Circuit contains a measurement.')
if not self.are_all_measurements_terminal():
raise ValueError('Circuit contains a non-terminal measurement.')
qs = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
self.all_qubits().union(qubits_that_should_be_present)
)
# Force qubits to have dimension at least 2 for backwards compatibility.
qid_shape = self.qid_shape(qubit_order=qs)
side_len = np.product(qid_shape, dtype=int)
state = qis.eye_tensor(qid_shape, dtype=dtype)
result = _apply_unitary_circuit(self, state, qs, dtype)
return result.reshape((side_len, side_len))
def final_state_vector(
self,
initial_state: 'cirq.STATE_VECTOR_LIKE' = 0,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
qubits_that_should_be_present: Iterable['cirq.Qid'] = (),
ignore_terminal_measurements: bool = True,
dtype: Type[np.number] = np.complex128,
) -> np.ndarray:
"""Left-multiplies a state vector by the circuit's unitary effect.
A circuit's "unitary effect" is the unitary matrix produced by
multiplying together all of its gates' unitary matrices. A circuit
with non-unitary gates (such as measurement or parameterized gates) does
not have a well-defined unitary effect, and the method will fail if such
operations are present.
For convenience, terminal measurements are automatically ignored
instead of causing a failure. Set the `ignore_terminal_measurements`
argument to False to disable this behavior.
This method is equivalent to left-multiplying the input state by
`cirq.unitary(circuit)` but it's computed in a more efficient
way.
Args:
initial_state: The input state for the circuit. This can be a list
of qudit values, a big endian int encoding the qudit values,
a vector of amplitudes, or a tensor of amplitudes.
When this is an int, it refers to a computational
basis state (e.g. 5 means initialize to ``|5⟩ = |...000101⟩``).
If this is a vector of amplitudes (a flat numpy array of the
correct length for the system) or a tensor of amplitudes (a
numpy array whose shape equals this circuit's `qid_shape`), it
directly specifies the initial state's amplitudes. The vector
type must be convertible to the given `dtype` argument.
qubit_order: Determines how qubits are ordered when passing matrices
into np.kron.
qubits_that_should_be_present: Qubits that may or may not appear
in operations within the circuit, but that should be included
regardless when generating the matrix.
ignore_terminal_measurements: When set, measurements at the end of
the circuit are ignored instead of causing the method to
fail.
dtype: The numpy dtype for the returned unitary. Defaults to
np.complex128. Specifying np.complex64 will run faster at the
cost of precision. `dtype` must be a complex np.dtype, unless
all operations in the circuit have unitary matrices with
exclusively real coefficients (e.g. an H + TOFFOLI circuit).
Returns:
A (possibly gigantic) numpy array storing the superposition that
came out of the circuit for the given input state.
Raises:
ValueError: The circuit contains measurement gates that are not
ignored.
TypeError: The circuit contains gates that don't have a known
unitary matrix, e.g. gates parameterized by a Symbol.
"""
if not ignore_terminal_measurements and any(
protocols.is_measurement(op) for op in self.all_operations()
):
raise ValueError('Circuit contains a measurement.')
if not self.are_all_measurements_terminal():
raise ValueError('Circuit contains a non-terminal measurement.')
qs = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
self.all_qubits().union(qubits_that_should_be_present)
)
# Force qubits to have dimension at least 2 for backwards compatibility.
qid_shape = self.qid_shape(qubit_order=qs)
state_len = np.product(qid_shape, dtype=int)
state = qis.to_valid_state_vector(initial_state, qid_shape=qid_shape, dtype=dtype).reshape(
qid_shape
)
result = _apply_unitary_circuit(self, state, qs, dtype)
return result.reshape((state_len,))
@deprecated(deadline='v0.10.0', fix='Use final_state_vector instead.')
def final_wavefunction(
self,
initial_state: 'cirq.STATE_VECTOR_LIKE' = 0,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
qubits_that_should_be_present: Iterable['cirq.Qid'] = (),
ignore_terminal_measurements: bool = True,
dtype: Type[np.number] = np.complex128,
) -> np.ndarray:
"""Deprecated. Please use `final_state_vector`."""
return self.final_state_vector(
initial_state=initial_state,
qubit_order=qubit_order,
qubits_that_should_be_present=qubits_that_should_be_present,
ignore_terminal_measurements=ignore_terminal_measurements,
dtype=dtype,
)
def to_text_diagram(
self,
*,
use_unicode_characters: bool = True,
transpose: bool = False,
include_tags: bool = True,
precision: Optional[int] = 3,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
) -> str:
"""Returns text containing a diagram describing the circuit.
Args:
use_unicode_characters: Determines if unicode characters are
allowed (as opposed to ascii-only diagrams).
transpose: Arranges qubit wires vertically instead of horizontally.
include_tags: Whether tags on TaggedOperations should be printed
precision: Number of digits to display in text diagram
qubit_order: Determines how qubits are ordered in the diagram.
Returns:
The text diagram.
"""
diagram = self.to_text_diagram_drawer(
use_unicode_characters=use_unicode_characters,
include_tags=include_tags,
precision=precision,
qubit_order=qubit_order,
transpose=transpose,
)
return diagram.render(
crossing_char=(None if use_unicode_characters else ('-' if transpose else '|')),
horizontal_spacing=1 if transpose else 3,
use_unicode_characters=use_unicode_characters,
)
def to_text_diagram_drawer(
self,
*,
use_unicode_characters: bool = True,
qubit_namer: Optional[Callable[['cirq.Qid'], str]] = None,
transpose: bool = False,
include_tags: bool = True,
draw_moment_groups: bool = True,
precision: Optional[int] = 3,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
get_circuit_diagram_info: Optional[
Callable[['cirq.Operation', 'cirq.CircuitDiagramInfoArgs'], 'cirq.CircuitDiagramInfo']
] = None,
) -> TextDiagramDrawer:
"""Returns a TextDiagramDrawer with the circuit drawn into it.
Args:
use_unicode_characters: Determines if unicode characters are
allowed (as opposed to ascii-only diagrams).
qubit_namer: Names qubits in diagram. Defaults to str.
transpose: Arranges qubit wires vertically instead of horizontally.
draw_moment_groups: Whether to draw moment symbol or not
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the diagram.
get_circuit_diagram_info: Gets circuit diagram info. Defaults to
protocol with fallback.
Returns:
The TextDiagramDrawer instance.
"""
qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(self.all_qubits())
qubit_map = {qubits[i]: i for i in range(len(qubits))}
if qubit_namer is None:
qubit_namer = lambda q: str(q) + ('' if transpose else ': ')
diagram = TextDiagramDrawer()
diagram.write(0, 0, '')
for q, i in qubit_map.items():
diagram.write(0, i, qubit_namer(q))
if any(isinstance(op.untagged, cirq.GlobalPhaseOperation) for op in self.all_operations()):
diagram.write(0, max(qubit_map.values(), default=0) + 1, 'global phase:')
moment_groups = [] # type: List[Tuple[int, int]]
for moment in self.moments:
_draw_moment_in_diagram(
moment,
use_unicode_characters,
qubit_map,
diagram,
precision,
moment_groups,
get_circuit_diagram_info,
include_tags,
)
w = diagram.width()
for i in qubit_map.values():
diagram.horizontal_line(i, 0, w)
if moment_groups and draw_moment_groups:
_draw_moment_groups_in_diagram(moment_groups, use_unicode_characters, diagram)
if transpose:
diagram = diagram.transpose()
return diagram
def _is_parameterized_(self) -> bool:
return any(protocols.is_parameterized(op) for op in self.all_operations())
def _parameter_names_(self) -> AbstractSet[str]:
return {name for op in self.all_operations() for name in protocols.parameter_names(op)}
def _qasm_(self) -> str:
return self.to_qasm()
def _to_qasm_output(
self,
header: Optional[str] = None,
precision: int = 10,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
) -> QasmOutput:
"""Returns a QASM object equivalent to the circuit.
Args:
header: A multi-line string that is placed in a comment at the top
of the QASM. Defaults to a cirq version specifier.
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the QASM
register.
"""
if header is None:
header = 'Generated from Cirq v{}'.format(cirq._version.__version__)
qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(self.all_qubits())
return QasmOutput(
operations=self.all_operations(),
qubits=qubits,
header=header,
precision=precision,
version='2.0',
)
def _to_quil_output(
self, qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT
) -> QuilOutput:
qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(self.all_qubits())
return QuilOutput(operations=self.all_operations(), qubits=qubits)
def to_qasm(
self,
header: Optional[str] = None,
precision: int = 10,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
) -> str:
"""Returns QASM equivalent to the circuit.
Args:
header: A multi-line string that is placed in a comment at the top
of the QASM. Defaults to a cirq version specifier.
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the QASM
register.
"""
return str(self._to_qasm_output(header, precision, qubit_order))
def to_quil(self, qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT) -> str:
return str(self._to_quil_output(qubit_order))
def save_qasm(
self,
file_path: Union[str, bytes, int],
header: Optional[str] = None,
precision: int = 10,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
) -> None:
"""Save a QASM file equivalent to the circuit.
Args:
file_path: The location of the file where the qasm will be written.
header: A multi-line string that is placed in a comment at the top
of the QASM. Defaults to a cirq version specifier.
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the QASM
register.
"""
self._to_qasm_output(header, precision, qubit_order).save(file_path)
def _json_dict_(self):
return protocols.obj_to_dict_helper(self, ['moments', 'device'])
@classmethod
def _from_json_dict_(cls, moments, device, **kwargs):
return cls(moments, strategy=InsertStrategy.EARLIEST, device=device)
class Circuit(AbstractCircuit):
"""A mutable list of groups of operations to apply to some qubits.
Methods returning information about the circuit (inherited from
AbstractCircuit):
* next_moment_operating_on
* prev_moment_operating_on
* next_moments_operating_on
* operation_at
* all_qubits
* all_operations
* findall_operations
* findall_operations_between
* findall_operations_until_blocked
* findall_operations_with_gate_type
* reachable_frontier_from
* has_measurements
* are_all_matches_terminal
* are_all_measurements_terminal
* unitary
* final_state_vector
* to_text_diagram
* to_text_diagram_drawer
* qid_shape
* all_measurement_keys
* to_quil
* to_qasm
* save_qasm
Methods for mutation:
* insert
* append
* insert_into_range
* clear_operations_touching
* batch_insert
* batch_remove
* batch_insert_into
* insert_at_frontier
Circuits can also be iterated over,
```
for moment in circuit:
...
```
and sliced,
* `circuit[1:3]` is a new Circuit made up of two moments, the first being
`circuit[1]` and the second being `circuit[2]`;
* `circuit[:, qubit]` is a new Circuit with the same moments, but with
only those operations which act on the given Qubit;
* `circuit[:, qubits]`, where 'qubits' is list of Qubits, is a new Circuit
with the same moments, but only with those operations which touch
any of the given qubits;
* `circuit[1:3, qubit]` is equivalent to `circuit[1:3][:, qubit]`;
* `circuit[1:3, qubits]` is equivalent to `circuit[1:3][:, qubits]`;
and concatenated,
* `circuit1 + circuit2` is a new Circuit made up of the moments in
circuit1 followed by the moments in circuit2;
and multiplied by an integer,
* `circuit * k` is a new Circuit made up of the moments in circuit repeated
k times.
and mutated,
* `circuit[1:7] = [Moment(...)]`
"""
def __init__(
self,
*contents: 'cirq.OP_TREE',
strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST,
device: 'cirq.Device' = devices.UNCONSTRAINED_DEVICE,
) -> None:
"""Initializes a circuit.
Args:
contents: The initial list of moments and operations defining the
circuit. You can also pass in operations, lists of operations,
or generally anything meeting the `cirq.OP_TREE` contract.
Non-moment entries will be inserted according to the specified
insertion strategy.
strategy: When initializing the circuit with operations and moments
from `contents`, this determines how the operations are packed
together. This option does not affect later insertions into the
circuit.
device: Hardware that the circuit should be able to run on.
"""
self._moments: List['cirq.Moment'] = []
self._device = device
self.append(contents, strategy=strategy)
@property
def device(self) -> devices.Device:
return self._device
@device.setter
def device(self, new_device: 'cirq.Device') -> None:
new_device.validate_circuit(self)
self._device = new_device
def __copy__(self) -> 'Circuit':
return self.copy()
def copy(self) -> 'Circuit':
copied_circuit = Circuit(device=self._device)
copied_circuit._moments = self._moments[:]
return copied_circuit
def _with_sliced_moments(self, moments: Sequence['cirq.Moment']) -> 'Circuit':
new_circuit = Circuit(device=self.device)
new_circuit._moments = list(moments)
return new_circuit
# pylint: disable=function-redefined
@overload
def __setitem__(self, key: int, value: 'cirq.Moment'):
pass
@overload
def __setitem__(self, key: slice, value: Iterable['cirq.Moment']):
pass
def __setitem__(self, key, value):
if isinstance(key, int):
if not isinstance(value, ops.Moment):
raise TypeError('Can only assign Moments into Circuits.')
self._device.validate_moment(value)
self._validate_op_tree_qids(value)
if isinstance(key, slice):
value = list(value)
if any(not isinstance(v, ops.Moment) for v in value):
raise TypeError('Can only assign Moments into Circuits.')
for moment in value:
self._device.validate_moment(moment)
self._validate_op_tree_qids(moment)
self._moments[key] = value
# pylint: enable=function-redefined
def __delitem__(self, key: Union[int, slice]):
del self._moments[key]
def __iadd__(self, other):
self.append(other)
return self
def __add__(self, other):
if isinstance(other, type(self)):
if (
devices.UNCONSTRAINED_DEVICE not in [self._device, other.device]
and self._device != other.device
):
raise ValueError("Can't add circuits with incompatible devices.")
elif not isinstance(other, (ops.Operation, Iterable)):
return NotImplemented
result = self.copy()
return result.__iadd__(other)
def __radd__(self, other):
# The Circuit + Circuit case is handled by __add__
if not isinstance(other, (ops.Operation, Iterable)):
return NotImplemented
# Auto wrap OP_TREE inputs into a circuit.
result = self.copy()
result._moments[:0] = Circuit(other)._moments
result._device.validate_circuit(result)
return result
# Needed for numpy to handle multiplication by np.int64 correctly.
__array_priority__ = 10000
def __imul__(self, repetitions: INT_TYPE):
if not isinstance(repetitions, (int, np.integer)):
return NotImplemented
self._moments *= int(repetitions)
return self
def __mul__(self, repetitions: INT_TYPE):
if not isinstance(repetitions, (int, np.integer)):
return NotImplemented
return Circuit(self._moments * int(repetitions), device=self._device)
def __rmul__(self, repetitions: INT_TYPE):
if not isinstance(repetitions, (int, np.integer)):
return NotImplemented
return self * int(repetitions)
def __pow__(self, exponent: int) -> 'Circuit':
"""A circuit raised to a power, only valid for exponent -1, the inverse.
This will fail if anything other than -1 is passed to the Circuit by
returning NotImplemented. Otherwise this will return the inverse
circuit, which is the circuit with its moment order reversed and for
every moment all the moment's operations are replaced by its inverse.
If any of the operations do not support inverse, NotImplemented will be
returned.
"""
if exponent != -1:
return NotImplemented
inv_moments = []
for moment in self[::-1]:
inv_moment = cirq.inverse(moment, default=NotImplemented)
if inv_moment is NotImplemented:
return NotImplemented
inv_moments.append(inv_moment)
return cirq.Circuit(inv_moments, device=self._device)
__hash__ = None # type: ignore
def with_device(
self,
new_device: 'cirq.Device',
qubit_mapping: Callable[['cirq.Qid'], 'cirq.Qid'] = lambda e: e,
) -> 'Circuit':
"""Maps the current circuit onto a new device, and validates.
Args:
new_device: The new device that the circuit should be on.
qubit_mapping: How to translate qubits from the old device into
qubits on the new device.
Returns:
The translated circuit.
"""
return Circuit(
[
ops.Moment(
operation.transform_qubits(qubit_mapping) for operation in moment.operations
)
for moment in self._moments
],
device=new_device,
)
def transform_qubits(
self, func: Callable[['cirq.Qid'], 'cirq.Qid'], *, new_device: 'cirq.Device' = None
) -> 'cirq.Circuit':
"""Returns the same circuit, but with different qubits.
Note that this method does essentially the same thing as
`cirq.Circuit.with_device`. It is included regardless because there are
also `transform_qubits` methods on `cirq.Operation` and `cirq.Moment`.
Args:
func: The function to use to turn each current qubit into a desired
new qubit.
new_device: The device to use for the new circuit, if different.
If this is not set, the new device defaults to the current
device.
Returns:
The receiving circuit but with qubits transformed by the given
function, and with an updated device (if specified).
"""
return self.with_device(
new_device=self.device if new_device is None else new_device, qubit_mapping=func
)
def _prev_moment_available(self, op: 'cirq.Operation', end_moment_index: int) -> Optional[int]:
last_available = end_moment_index
k = end_moment_index
while k > 0:
k -= 1
if not self._can_commute_past(k, op):
return last_available
if self._can_add_op_at(k, op):
last_available = k
return last_available
def _pick_or_create_inserted_op_moment_index(
self, splitter_index: int, op: 'cirq.Operation', strategy: 'cirq.InsertStrategy'
) -> int:
"""Determines and prepares where an insertion will occur.
Args:
splitter_index: The index to insert at.
op: The operation that will be inserted.
strategy: The insertion strategy.
Returns:
The index of the (possibly new) moment where the insertion should
occur.
Raises:
ValueError: Unrecognized append strategy.
"""
if strategy is InsertStrategy.NEW or strategy is InsertStrategy.NEW_THEN_INLINE:
self._moments.insert(splitter_index, ops.Moment())
return splitter_index
if strategy is InsertStrategy.INLINE:
if 0 <= splitter_index - 1 < len(self._moments) and self._can_add_op_at(
splitter_index - 1, op
):
return splitter_index - 1
return self._pick_or_create_inserted_op_moment_index(
splitter_index, op, InsertStrategy.NEW
)
if strategy is InsertStrategy.EARLIEST:
if self._can_add_op_at(splitter_index, op):
p = self._prev_moment_available(op, splitter_index)
return p or 0
return self._pick_or_create_inserted_op_moment_index(
splitter_index, op, InsertStrategy.INLINE
)
raise ValueError('Unrecognized append strategy: {}'.format(strategy))
def _can_add_op_at(self, moment_index: int, operation: 'cirq.Operation') -> bool:
if not 0 <= moment_index < len(self._moments):
return True
return self._device.can_add_operation_into_moment(operation, self._moments[moment_index])
def _can_commute_past(self, moment_index: int, operation: 'cirq.Operation') -> bool:
return not self._moments[moment_index].operates_on(operation.qubits)
def insert(
self,
index: int,
moment_or_operation_tree: Union['cirq.Operation', 'cirq.OP_TREE'],
strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST,
) -> int:
"""Inserts operations into the circuit.
Operations are inserted into the moment specified by the index and
'InsertStrategy'.
Moments within the operation tree are inserted intact.
Args:
index: The index to insert all of the operations at.
moment_or_operation_tree: The moment or operation tree to insert.
strategy: How to pick/create the moment to put operations into.
Returns:
The insertion index that will place operations just after the
operations that were inserted by this method.
Raises:
ValueError: Bad insertion strategy.
"""
moments_and_operations = list(
ops.flatten_to_ops_or_moments(
ops.transform_op_tree(
moment_or_operation_tree,
self._device.decompose_operation,
preserve_moments=True,
),
)
)
for moment_or_op in moments_and_operations:
if isinstance(moment_or_op, ops.Moment):
self._device.validate_moment(cast(ops.Moment, moment_or_op))
else:
self._device.validate_operation(cast(ops.Operation, moment_or_op))
self._validate_op_tree_qids(moment_or_op)
# limit index to 0..len(self._moments), also deal with indices smaller 0
k = max(min(index if index >= 0 else len(self._moments) + index, len(self._moments)), 0)
for moment_or_op in moments_and_operations:
if isinstance(moment_or_op, ops.Moment):
self._moments.insert(k, moment_or_op)
k += 1
else:
op = cast(ops.Operation, moment_or_op)
p = self._pick_or_create_inserted_op_moment_index(k, op, strategy)
while p >= len(self._moments):
self._moments.append(ops.Moment())
self._moments[p] = self._moments[p].with_operation(op)
self._device.validate_moment(self._moments[p])
k = max(k, p + 1)
if strategy is InsertStrategy.NEW_THEN_INLINE:
strategy = InsertStrategy.INLINE
return k
def insert_into_range(self, operations: 'cirq.OP_TREE', start: int, end: int) -> int:
"""Writes operations inline into an area of the circuit.
Args:
start: The start of the range (inclusive) to write the
given operations into.
end: The end of the range (exclusive) to write the given
operations into. If there are still operations remaining,
new moments are created to fit them.
operations: An operation or tree of operations to insert.
Returns:
An insertion index that will place operations after the operations
that were inserted by this method.
Raises:
IndexError: Bad inline_start and/or inline_end.
"""
if not 0 <= start <= end <= len(self):
raise IndexError('Bad insert indices: [{}, {})'.format(start, end))
flat_ops = list(ops.flatten_to_ops(operations))
for op in flat_ops:
self._device.validate_operation(op)
self._validate_op_tree_qids(flat_ops)
i = start
op_index = 0
while op_index < len(flat_ops):
op = flat_ops[op_index]
while i < end and not self._device.can_add_operation_into_moment(op, self._moments[i]):
i += 1
if i >= end:
break
self._moments[i] = self._moments[i].with_operation(op)
op_index += 1
if op_index >= len(flat_ops):
return end
return self.insert(end, flat_ops[op_index:])
@staticmethod
def _pick_inserted_ops_moment_indices(
operations: Sequence['cirq.Operation'],
start: int = 0,
frontier: Dict['cirq.Qid', int] = None,
) -> Tuple[Sequence[int], Dict['cirq.Qid', int]]:
"""Greedily assigns operations to moments.
Args:
operations: The operations to assign to moments.
start: The first moment to consider assignment to.
frontier: The first moment to which an operation acting on a qubit
can be assigned. Updated in place as operations are assigned.
Returns:
The frontier giving the index of the moment after the last one to
which an operation that acts on each qubit is assigned. If a
frontier was specified as an argument, this is the same object.
"""
if frontier is None:
frontier = defaultdict(lambda: 0)
moment_indices = []
for op in operations:
op_start = max(start, max(frontier[q] for q in op.qubits))
moment_indices.append(op_start)
for q in op.qubits:
frontier[q] = max(frontier[q], op_start + 1)
return moment_indices, frontier
def _push_frontier(
self,
early_frontier: Dict['cirq.Qid', int],
late_frontier: Dict['cirq.Qid', int],
update_qubits: Iterable['cirq.Qid'] = None,
) -> Tuple[int, int]:
"""Inserts moments to separate two frontiers.
After insertion n_new moments, the following holds:
for q in late_frontier:
early_frontier[q] <= late_frontier[q] + n_new
for q in update_qubits:
early_frontier[q] the identifies the same moment as before
(but whose index may have changed if this moment is after
those inserted).
Args:
early_frontier: The earlier frontier. For qubits not in the later
frontier, this is updated to account for the newly inserted
moments.
late_frontier: The later frontier. This is not modified.
update_qubits: The qubits for which to update early_frontier to
account for the newly inserted moments.
Returns:
(index at which new moments were inserted, how many new moments
were inserted) if new moments were indeed inserted. (0, 0)
otherwise.
"""
if update_qubits is None:
update_qubits = set(early_frontier).difference(late_frontier)
n_new_moments = (
max(early_frontier.get(q, 0) - late_frontier[q] for q in late_frontier)
if late_frontier
else 0
)
if n_new_moments > 0:
insert_index = min(late_frontier.values())
self._moments[insert_index:insert_index] = [ops.Moment()] * n_new_moments
for q in update_qubits:
if early_frontier.get(q, 0) > insert_index:
early_frontier[q] += n_new_moments
return insert_index, n_new_moments
return (0, 0)
def _insert_operations(
self, operations: Sequence['cirq.Operation'], insertion_indices: Sequence[int]
) -> None:
"""Inserts operations at the specified moments. Appends new moments if
necessary.
Args:
operations: The operations to insert.
insertion_indices: Where to insert them, i.e. operations[i] is
inserted into moments[insertion_indices[i].
Raises:
ValueError: operations and insert_indices have different lengths.
NB: It's on the caller to ensure that the operations won't conflict
with operations already in the moment or even each other.
"""
if len(operations) != len(insertion_indices):
raise ValueError('operations and insertion_indices must have the same length.')
self._moments += [ops.Moment() for _ in range(1 + max(insertion_indices) - len(self))]
moment_to_ops = defaultdict(list) # type: Dict[int, List['cirq.Operation']]
for op_index, moment_index in enumerate(insertion_indices):
moment_to_ops[moment_index].append(operations[op_index])
for moment_index, new_ops in moment_to_ops.items():
self._moments[moment_index] = ops.Moment(
self._moments[moment_index].operations + tuple(new_ops)
)
def zip(*circuits):
"""Combines operations from circuits in a moment-by-moment fashion.
Moment k of the resulting circuit will have all operations from moment
k of each of the given circuits.
When the given circuits have different lengths, the shorter circuits are
implicitly padded with empty moments. This differs from the behavior of
python's built-in zip function, which would instead truncate the longer
circuits.
The zipped circuits can't have overlapping operations occurring at the
same moment index.
Args:
circuits: The circuits to merge together.
Returns:
The merged circuit.
Raises:
ValueError:
The zipped circuits have overlapping operations occurring at the
same moment index.
Examples:
>>> import cirq
>>> a, b, c, d = cirq.LineQubit.range(4)
>>> circuit1 = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b))
>>> circuit2 = cirq.Circuit(cirq.X(c), cirq.Y(c), cirq.Z(c))
>>> circuit3 = cirq.Circuit(cirq.Moment(), cirq.Moment(cirq.S(d)))
>>> print(circuit1.zip(circuit2))
0: ───H───@───────
│
1: ───────X───────
<BLANKLINE>
2: ───X───Y───Z───
>>> print(circuit1.zip(circuit2, circuit3))
0: ───H───@───────
│
1: ───────X───────
<BLANKLINE>
2: ───X───Y───Z───
<BLANKLINE>
3: ───────S───────
>>> print(cirq.Circuit.zip(circuit3, circuit2, circuit1))
0: ───H───@───────
│
1: ───────X───────
<BLANKLINE>
2: ───X───Y───Z───
<BLANKLINE>
3: ───────S───────
"""
circuits = list(circuits)
n = max([len(c) for c in circuits], default=0)
result = cirq.Circuit()
for k in range(n):
try:
result.append(cirq.Moment(c[k] for c in circuits if k < len(c)))
except ValueError as ex:
raise ValueError(
f"Overlapping operations between zipped circuits at moment index {k}.\n{ex}"
) from ex
return result
def insert_at_frontier(
self, operations: 'cirq.OP_TREE', start: int, frontier: Dict['cirq.Qid', int] = None
) -> Dict['cirq.Qid', int]:
"""Inserts operations inline at frontier.
Args:
operations: the operations to insert
start: the moment at which to start inserting the operations
frontier: frontier[q] is the earliest moment in which an operation
acting on qubit q can be placed.
"""
if frontier is None:
frontier = defaultdict(lambda: 0)
flat_ops = tuple(ops.flatten_to_ops(operations))
if not flat_ops:
return frontier
qubits = set(q for op in flat_ops for q in op.qubits)
if any(frontier[q] > start for q in qubits):
raise ValueError(
'The frontier for qubits on which the operations'
'to insert act cannot be after start.'
)
next_moments = self.next_moments_operating_on(qubits, start)
insertion_indices, _ = self._pick_inserted_ops_moment_indices(flat_ops, start, frontier)
self._push_frontier(frontier, next_moments)
self._insert_operations(flat_ops, insertion_indices)
return frontier
def batch_remove(self, removals: Iterable[Tuple[int, 'cirq.Operation']]) -> None:
"""Removes several operations from a circuit.
Args:
removals: A sequence of (moment_index, operation) tuples indicating
operations to delete from the moments that are present. All
listed operations must actually be present or the edit will
fail (without making any changes to the circuit).
ValueError:
One of the operations to delete wasn't present to start with.
IndexError:
Deleted from a moment that doesn't exist.
"""
copy = self.copy()
for i, op in removals:
if op not in copy._moments[i].operations:
raise ValueError("Can't remove {} @ {} because it doesn't exist.".format(op, i))
copy._moments[i] = ops.Moment(
old_op for old_op in copy._moments[i].operations if op != old_op
)
self._device.validate_circuit(copy)
self._moments = copy._moments
def batch_replace(
self, replacements: Iterable[Tuple[int, 'cirq.Operation', 'cirq.Operation']]
) -> None:
"""Replaces several operations in a circuit with new operations.
Args:
replacements: A sequence of (moment_index, old_op, new_op) tuples
indicating operations to be replaced in this circuit. All "old"
operations must actually be present or the edit will fail
(without making any changes to the circuit).
ValueError:
One of the operations to replace wasn't present to start with.
IndexError:
Replaced in a moment that doesn't exist.
"""
copy = self.copy()
for i, op, new_op in replacements:
if op not in copy._moments[i].operations:
raise ValueError(f"Can't replace {op} @ {i} because it doesn't exist.")
copy._moments[i] = ops.Moment(
old_op if old_op != op else new_op for old_op in copy._moments[i].operations
)
self._device.validate_circuit(copy)
self._moments = copy._moments
def batch_insert_into(self, insert_intos: Iterable[Tuple[int, 'cirq.OP_TREE']]) -> None:
"""Inserts operations into empty spaces in existing moments.
If any of the insertions fails (due to colliding with an existing
operation), this method fails without making any changes to the circuit.
Args:
insert_intos: A sequence of (moment_index, new_op_tree)
pairs indicating a moment to add new operations into.
ValueError:
One of the insertions collided with an existing operation.
IndexError:
Inserted into a moment index that doesn't exist.
"""
copy = self.copy()
for i, insertions in insert_intos:
copy._moments[i] = copy._moments[i].with_operations(insertions)
self._device.validate_circuit(copy)
self._validate_op_tree_qids(copy)
self._moments = copy._moments
def batch_insert(self, insertions: Iterable[Tuple[int, 'cirq.OP_TREE']]) -> None:
"""Applies a batched insert operation to the circuit.
Transparently handles the fact that earlier insertions may shift
the index that later insertions should occur at. For example, if you
insert an operation at index 2 and at index 4, but the insert at index 2
causes a new moment to be created, then the insert at "4" will actually
occur at index 5 to account for the shift from the new moment.
All insertions are done with the strategy 'EARLIEST'.
When multiple inserts occur at the same index, the gates from the later
inserts end up before the gates from the earlier inserts (exactly as if
you'd called list.insert several times with the same index: the later
inserts shift the earliest inserts forward).
Args:
insertions: A sequence of (insert_index, operations) pairs
indicating operations to add into the circuit at specific
places.
"""
# Work on a copy in case validation fails halfway through.
copy = self.copy()
shift = 0
# Note: python `sorted` is guaranteed to be stable. This matters.
insertions = sorted(insertions, key=lambda e: e[0])
groups = _group_until_different(insertions, key=lambda e: e[0], value=lambda e: e[1])
for i, group in groups:
insert_index = i + shift
next_index = copy.insert(insert_index, reversed(group), InsertStrategy.EARLIEST)
if next_index > insert_index:
shift += next_index - insert_index
self._moments = copy._moments
def append(
self,
moment_or_operation_tree: Union['cirq.Moment', 'cirq.OP_TREE'],
strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST,
):
"""Appends operations onto the end of the circuit.
Moments within the operation tree are appended intact.
Args:
moment_or_operation_tree: The moment or operation tree to append.
strategy: How to pick/create the moment to put operations into.
"""
self.insert(len(self._moments), moment_or_operation_tree, strategy)
def clear_operations_touching(
self, qubits: Iterable['cirq.Qid'], moment_indices: Iterable[int]
):
"""Clears operations that are touching given qubits at given moments.
Args:
qubits: The qubits to check for operations on.
moment_indices: The indices of moments to check for operations
within.
"""
qubits = frozenset(qubits)
for k in moment_indices:
if 0 <= k < len(self._moments):
self._moments[k] = self._moments[k].without_operations_touching(qubits)
def _resolve_parameters_(
self, param_resolver: 'cirq.ParamResolver', recursive: bool
) -> 'Circuit':
resolved_moments = []
for moment in self:
resolved_operations = _resolve_operations(moment.operations, param_resolver, recursive)
new_moment = ops.Moment(resolved_operations)
resolved_moments.append(new_moment)
resolved_circuit = Circuit(resolved_moments, device=self.device)
return resolved_circuit
@property
def moments(self):
return self._moments
def with_noise(self, noise: 'cirq.NOISE_MODEL_LIKE') -> 'cirq.Circuit':
"""Make a noisy version of the circuit.
Args:
noise: The noise model to use. This describes the kind of noise to
add to the circuit.
Returns:
A new circuit with the same moment structure but with new moments
inserted where needed when more than one noisy operation is
generated for an input operation. Emptied moments are removed.
"""
noise_model = devices.NoiseModel.from_noise_model_like(noise)
qubits = sorted(self.all_qubits())
c_noisy = Circuit()
for op_tree in noise_model.noisy_moments(self, qubits):
# Keep moments aligned
c_noisy += Circuit(op_tree)
return c_noisy
def _resolve_operations(
operations: Iterable['cirq.Operation'], param_resolver: 'cirq.ParamResolver', recursive: bool
) -> List['cirq.Operation']:
resolved_operations = [] # type: List['cirq.Operation']
for op in operations:
resolved_operations.append(protocols.resolve_parameters(op, param_resolver, recursive))
return resolved_operations
def _draw_moment_in_diagram(
moment: 'cirq.Moment',
use_unicode_characters: bool,
qubit_map: Dict['cirq.Qid', int],
out_diagram: TextDiagramDrawer,
precision: Optional[int],
moment_groups: List[Tuple[int, int]],
get_circuit_diagram_info: Optional[
Callable[['cirq.Operation', 'cirq.CircuitDiagramInfoArgs'], 'cirq.CircuitDiagramInfo']
] = None,
include_tags: bool = True,
):
if get_circuit_diagram_info is None:
get_circuit_diagram_info = protocols.CircuitDiagramInfo._op_info_with_fallback
x0 = out_diagram.width()
non_global_ops = [op for op in moment.operations if op.qubits]
max_x = x0
for op in non_global_ops:
indices = [qubit_map[q] for q in op.qubits]
y1 = min(indices)
y2 = max(indices)
# Find an available column.
x = x0
while any(out_diagram.content_present(x, y) for y in range(y1, y2 + 1)):
out_diagram.force_horizontal_padding_after(x, 0)
x += 1
args = protocols.CircuitDiagramInfoArgs(
known_qubits=op.qubits,
known_qubit_count=len(op.qubits),
use_unicode_characters=use_unicode_characters,
qubit_map=qubit_map,
precision=precision,
include_tags=include_tags,
)
info = get_circuit_diagram_info(op, args)
# Draw vertical line linking the gate's qubits.
if y2 > y1 and info.connected:
out_diagram.vertical_line(x, y1, y2)
# Print gate qubit labels.
symbols = info._wire_symbols_including_formatted_exponent(
args,
preferred_exponent_index=max(
range(len(op.qubits)), key=lambda i: qubit_map[op.qubits[i]]
),
)
for s, q in zip(symbols, op.qubits):
out_diagram.write(x, qubit_map[q], s)
if x > max_x:
max_x = x
global_phase: Optional[complex] = None
tags: List[Any] = []
for op in moment:
if isinstance(op.untagged, ops.GlobalPhaseOperation):
tags.extend(op.tags)
if global_phase is None:
global_phase = complex(1)
global_phase *= complex(op.untagged.coefficient)
# Print out global phase, unless it's 1 (phase of 0pi) or it's the only op.
if global_phase and (global_phase != 1 or not non_global_ops):
desc = _formatted_phase(global_phase, use_unicode_characters, precision)
if desc:
y = max(qubit_map.values(), default=0) + 1
if tags and include_tags:
desc = desc + str(tags)
out_diagram.write(x0, y, desc)
if not non_global_ops:
out_diagram.write(x0, 0, '')
# Group together columns belonging to the same Moment.
if moment.operations and max_x > x0:
moment_groups.append((x0, max_x))
def _formatted_phase(coefficient: complex, unicode: bool, precision: Optional[int]) -> str:
h = math.atan2(coefficient.imag, coefficient.real) / math.pi
unit = 'π' if unicode else 'pi'
if h == 1:
return unit
return '{{:.{}}}'.format(precision).format(h) + unit
def _draw_moment_groups_in_diagram(
moment_groups: List[Tuple[int, int]],
use_unicode_characters: bool,
out_diagram: TextDiagramDrawer,
):
out_diagram.insert_empty_rows(0)
h = out_diagram.height()
# Insert columns starting from the back since the insertion
# affects subsequent indices.
for x1, x2 in reversed(moment_groups):
out_diagram.insert_empty_columns(x2 + 1)
out_diagram.force_horizontal_padding_after(x2, 0)
out_diagram.insert_empty_columns(x1)
out_diagram.force_horizontal_padding_after(x1, 0)
x2 += 2
for x in range(x1, x2):
out_diagram.force_horizontal_padding_after(x, 0)
for y in [0, h]:
out_diagram.horizontal_line(y, x1, x2)
out_diagram.vertical_line(x1, 0, 0.5)
out_diagram.vertical_line(x2, 0, 0.5)
out_diagram.vertical_line(x1, h, h - 0.5)
out_diagram.vertical_line(x2, h, h - 0.5)
# Rounds up to 1 when horizontal, down to 0 when vertical.
# (Matters when transposing.)
out_diagram.force_vertical_padding_after(0, 0.5)
out_diagram.force_vertical_padding_after(h - 1, 0.5)
def _apply_unitary_circuit(
circuit: AbstractCircuit,
state: np.ndarray,
qubits: Tuple['cirq.Qid', ...],
dtype: Type[np.number],
) -> np.ndarray:
"""Applies a circuit's unitary effect to the given vector or matrix.
This method assumes that the caller wants to ignore measurements.
Args:
circuit: The circuit to simulate. All operations must have a known
matrix or decompositions leading to known matrices. Measurements
are allowed to be in the circuit, but they will be ignored.
state: The initial state tensor (i.e. superposition or unitary matrix).
This is what will be left-multiplied by the circuit's effective
unitary. If this is a state vector, it must have shape
(2,) * num_qubits. If it is a unitary matrix it should have shape
(2,) * (2*num_qubits).
qubits: The qubits in the state tensor. Determines which axes operations
apply to. An operation targeting the k'th qubit in this list will
operate on the k'th axis of the state tensor.
dtype: The numpy dtype to use for applying the unitary. Must be a
complex dtype.
Returns:
The left-multiplied state tensor.
"""
buffer = np.empty_like(state)
def on_stuck(bad_op):
return TypeError('Operation without a known matrix or decomposition: {!r}'.format(bad_op))
unitary_ops = protocols.decompose(
circuit.all_operations(),
keep=protocols.has_unitary,
intercepting_decomposer=_decompose_measurement_inversions,
on_stuck_raise=on_stuck,
)
return protocols.apply_unitaries(
unitary_ops, qubits, protocols.ApplyUnitaryArgs(state, buffer, range(len(qubits)))
)
def _decompose_measurement_inversions(op: 'cirq.Operation') -> 'cirq.OP_TREE':
if isinstance(op.gate, ops.MeasurementGate):
return [ops.X(q) for q, b in zip(op.qubits, op.gate.invert_mask) if b]
return NotImplemented
def _list_repr_with_indented_item_lines(items: Sequence[Any]) -> str:
block = '\n'.join([repr(op) + ',' for op in items])
indented = ' ' + '\n '.join(block.split('\n'))
return '[\n{}\n]'.format(indented)
TIn = TypeVar('TIn')
TOut = TypeVar('TOut')
TKey = TypeVar('TKey')
@overload
def _group_until_different(
items: Iterable[TIn],
key: Callable[[TIn], TKey],
) -> Iterable[Tuple[TKey, List[TIn]]]:
pass
@overload
def _group_until_different(
items: Iterable[TIn], key: Callable[[TIn], TKey], value: Callable[[TIn], TOut]
) -> Iterable[Tuple[TKey, List[TOut]]]:
pass
def _group_until_different(items: Iterable[TIn], key: Callable[[TIn], TKey], value=lambda e: e):
"""Groups runs of items that are identical according to a keying function.
Args:
items: The items to group.
key: If two adjacent items produce the same output from this function,
they will be grouped.
value: Maps each item into a value to put in the group. Defaults to the
item itself.
Examples:
_group_until_different(range(11), key=is_prime) yields
(False, [0, 1])
(True, [2, 3])
(False, [4])
(True, [5])
(False, [6])
(True, [7])
(False, [8, 9, 10])
Yields:
Tuples containing the group key and item values.
"""
return ((k, [value(i) for i in v]) for (k, v) in groupby(items, key))
| # Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The circuit data structure.
Circuits consist of a list of Moments, each Moment made up of a set of
Operations. Each Operation is a Gate that acts on some Qubits, for a given
Moment the Operations must all act on distinct Qubits.
"""
from collections import defaultdict
from itertools import groupby
import math
from typing import (
AbstractSet,
Any,
Callable,
cast,
Dict,
FrozenSet,
Iterable,
Iterator,
List,
Optional,
overload,
Sequence,
Set,
Tuple,
Type,
TYPE_CHECKING,
TypeVar,
Union,
)
import abc
import html
import numpy as np
from cirq import devices, ops, protocols, qis
from cirq.circuits._bucket_priority_queue import BucketPriorityQueue
from cirq.circuits.insert_strategy import InsertStrategy
from cirq.circuits.text_diagram_drawer import TextDiagramDrawer
from cirq.circuits.qasm_output import QasmOutput
from cirq.circuits.quil_output import QuilOutput
from cirq.type_workarounds import NotImplementedType
from cirq._compat import deprecated
import cirq._version
if TYPE_CHECKING:
import cirq
T_DESIRED_GATE_TYPE = TypeVar('T_DESIRED_GATE_TYPE', bound='ops.Gate')
CIRCUIT_TYPE = TypeVar('CIRCUIT_TYPE', bound='AbstractCircuit')
INT_TYPE = Union[int, np.integer]
class AbstractCircuit(abc.ABC):
"""The base class for Circuit-like objects.
A circuit-like object must have a list of moments (which can be empty) and
a device (which may be `devices.UNCONSTRAINED_DEVICE`).
These methods return information about the circuit, and can be called on
either Circuit or FrozenCircuit objects:
* next_moment_operating_on
* prev_moment_operating_on
* next_moments_operating_on
* operation_at
* all_qubits
* all_operations
* findall_operations
* findall_operations_between
* findall_operations_until_blocked
* findall_operations_with_gate_type
* reachable_frontier_from
* has_measurements
* are_all_matches_terminal
* are_all_measurements_terminal
* unitary
* final_state_vector
* to_text_diagram
* to_text_diagram_drawer
* qid_shape
* all_measurement_keys
* to_quil
* to_qasm
* save_qasm
"""
@property
@abc.abstractmethod
def moments(self) -> Sequence['cirq.Moment']:
pass
@property
@abc.abstractmethod
def device(self) -> devices.Device:
pass
def freeze(self) -> 'cirq.FrozenCircuit':
"""Creates a FrozenCircuit from this circuit.
If 'self' is a FrozenCircuit, the original object is returned.
"""
from cirq.circuits import FrozenCircuit
if isinstance(self, FrozenCircuit):
return self
return FrozenCircuit(self, strategy=InsertStrategy.EARLIEST, device=self.device)
def unfreeze(self) -> 'cirq.Circuit':
"""Creates a Circuit from this circuit.
If 'self' is a Circuit, this returns a copy of that circuit.
"""
if isinstance(self, Circuit):
return Circuit.copy(self)
return Circuit(self, strategy=InsertStrategy.EARLIEST, device=self.device)
def __bool__(self):
return bool(self.moments)
def __eq__(self, other):
if not isinstance(other, type(self)):
return NotImplemented
return self.moments == other.moments and self.device == other.device
def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool:
"""See `cirq.protocols.SupportsApproximateEquality`."""
if not isinstance(other, type(self)):
return NotImplemented
return (
cirq.protocols.approx_eq(self.moments, other.moments, atol=atol)
and self.device == other.device
)
def __ne__(self, other) -> bool:
return not self == other
def __len__(self) -> int:
return len(self.moments)
def __iter__(self) -> Iterator['cirq.Moment']:
return iter(self.moments)
def _decompose_(self) -> 'cirq.OP_TREE':
"""See `cirq.SupportsDecompose`."""
return self.all_operations()
# pylint: disable=function-redefined
@overload
def __getitem__(self, key: int) -> 'cirq.Moment':
pass
@overload
def __getitem__(self, key: Tuple[int, 'cirq.Qid']) -> 'cirq.Operation':
pass
@overload
def __getitem__(self, key: Tuple[int, Iterable['cirq.Qid']]) -> 'cirq.Moment':
pass
@overload
def __getitem__(self: CIRCUIT_TYPE, key: slice) -> CIRCUIT_TYPE:
pass
@overload
def __getitem__(self: CIRCUIT_TYPE, key: Tuple[slice, 'cirq.Qid']) -> CIRCUIT_TYPE:
pass
@overload
def __getitem__(self: CIRCUIT_TYPE, key: Tuple[slice, Iterable['cirq.Qid']]) -> CIRCUIT_TYPE:
pass
def __getitem__(self, key):
if isinstance(key, slice):
sliced_moments = self.moments[key]
return self._with_sliced_moments(sliced_moments)
if hasattr(key, '__index__'):
return self.moments[key]
if isinstance(key, tuple):
if len(key) != 2:
raise ValueError('If key is tuple, it must be a pair.')
moment_idx, qubit_idx = key
# moment_idx - int or slice; qubit_idx - Qid or Iterable[Qid].
selected_moments = self.moments[moment_idx]
if isinstance(selected_moments, ops.Moment):
return selected_moments[qubit_idx]
if isinstance(qubit_idx, ops.Qid):
qubit_idx = [qubit_idx]
sliced_moments = [moment[qubit_idx] for moment in selected_moments]
return self._with_sliced_moments(sliced_moments)
raise TypeError('__getitem__ called with key not of type slice, int, or tuple.')
# pylint: enable=function-redefined
@abc.abstractmethod
def _with_sliced_moments(self, moments: Sequence['cirq.Moment']):
"""Helper method for constructing circuits from __getitem__."""
def __str__(self) -> str:
return self.to_text_diagram()
def __repr__(self) -> str:
cls_name = self.__class__.__name__
args = []
if self.moments:
args.append(_list_repr_with_indented_item_lines(self.moments))
if self.device != devices.UNCONSTRAINED_DEVICE:
args.append(f'device={self.device!r}')
return f'cirq.{cls_name}({", ".join(args)})'
def _repr_pretty_(self, p: Any, cycle: bool) -> None:
"""Print ASCII diagram in Jupyter."""
cls_name = self.__class__.__name__
if cycle:
# There should never be a cycle. This is just in case.
p.text(f'{cls_name}(...)')
else:
p.text(self.to_text_diagram())
def _repr_html_(self) -> str:
"""Print ASCII diagram in Jupyter notebook without wrapping lines."""
return (
'<pre style="overflow: auto; white-space: pre;">'
+ html.escape(self.to_text_diagram())
+ '</pre>'
)
def _first_moment_operating_on(
self, qubits: Iterable['cirq.Qid'], indices: Iterable[int]
) -> Optional[int]:
qubits = frozenset(qubits)
for m in indices:
if self._has_op_at(m, qubits):
return m
return None
def next_moment_operating_on(
self, qubits: Iterable['cirq.Qid'], start_moment_index: int = 0, max_distance: int = None
) -> Optional[int]:
"""Finds the index of the next moment that touches the given qubits.
Args:
qubits: We're looking for operations affecting any of these qubits.
start_moment_index: The starting point of the search.
max_distance: The number of moments (starting from the start index
and moving forward) to check. Defaults to no limit.
Returns:
None if there is no matching moment, otherwise the index of the
earliest matching moment.
Raises:
ValueError: negative max_distance.
"""
max_circuit_distance = len(self.moments) - start_moment_index
if max_distance is None:
max_distance = max_circuit_distance
elif max_distance < 0:
raise ValueError('Negative max_distance: {}'.format(max_distance))
else:
max_distance = min(max_distance, max_circuit_distance)
return self._first_moment_operating_on(
qubits, range(start_moment_index, start_moment_index + max_distance)
)
def next_moments_operating_on(
self, qubits: Iterable['cirq.Qid'], start_moment_index: int = 0
) -> Dict['cirq.Qid', int]:
"""Finds the index of the next moment that touches each qubit.
Args:
qubits: The qubits to find the next moments acting on.
start_moment_index: The starting point of the search.
Returns:
The index of the next moment that touches each qubit. If there
is no such moment, the next moment is specified as the number of
moments in the circuit. Equivalently, can be characterized as one
plus the index of the last moment after start_moment_index
(inclusive) that does *not* act on a given qubit.
"""
next_moments = {}
for q in qubits:
next_moment = self.next_moment_operating_on([q], start_moment_index)
next_moments[q] = len(self.moments) if next_moment is None else next_moment
return next_moments
def prev_moment_operating_on(
self,
qubits: Sequence['cirq.Qid'],
end_moment_index: Optional[int] = None,
max_distance: Optional[int] = None,
) -> Optional[int]:
"""Finds the index of the next moment that touches the given qubits.
Args:
qubits: We're looking for operations affecting any of these qubits.
end_moment_index: The moment index just after the starting point of
the reverse search. Defaults to the length of the list of
moments.
max_distance: The number of moments (starting just before from the
end index and moving backward) to check. Defaults to no limit.
Returns:
None if there is no matching moment, otherwise the index of the
latest matching moment.
Raises:
ValueError: negative max_distance.
"""
if end_moment_index is None:
end_moment_index = len(self.moments)
if max_distance is None:
max_distance = len(self.moments)
elif max_distance < 0:
raise ValueError('Negative max_distance: {}'.format(max_distance))
else:
max_distance = min(end_moment_index, max_distance)
# Don't bother searching indices past the end of the list.
if end_moment_index > len(self.moments):
d = end_moment_index - len(self.moments)
end_moment_index -= d
max_distance -= d
if max_distance <= 0:
return None
return self._first_moment_operating_on(
qubits, (end_moment_index - k - 1 for k in range(max_distance))
)
def reachable_frontier_from(
self,
start_frontier: Dict['cirq.Qid', int],
*,
is_blocker: Callable[['cirq.Operation'], bool] = lambda op: False,
) -> Dict['cirq.Qid', int]:
"""Determines how far can be reached into a circuit under certain rules.
The location L = (qubit, moment_index) is *reachable* if and only if:
a) There is not a blocking operation covering L.
AND
[
b1) qubit is in start frontier and moment_index =
max(start_frontier[qubit], 0).
OR
b2) There is no operation at L and prev(L) = (qubit,
moment_index-1) is reachable.
OR
b3) There is an (non-blocking) operation P covering L such that
(q', moment_index - 1) is reachable for every q' on which P
acts.
]
An operation in moment moment_index is blocking if
a) `is_blocker` returns a truthy value.
OR
b) The operation acts on a qubit not in start_frontier.
OR
c) The operation acts on a qubit q such that start_frontier[q] >
moment_index.
In other words, the reachable region extends forward through time along
each qubit in start_frontier until it hits a blocking operation. Any
location involving a qubit not in start_frontier is unreachable.
For each qubit q in `start_frontier`, the reachable locations will
correspond to a contiguous range starting at start_frontier[q] and
ending just before some index end_q. The result of this method is a
dictionary, and that dictionary maps each qubit q to its end_q.
Examples:
If start_frontier is {
cirq.LineQubit(0): 6,
cirq.LineQubit(1): 2,
cirq.LineQubit(2): 2,
} then the reachable wire locations in the following circuit are
highlighted with '█' characters:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0: ───H───@─────────────────█████████████████████─@───H───
│ │
1: ───────@─██H███@██████████████████████─@───H───@───────
│ │
2: ─────────██████@███H██─@───────@───H───@───────────────
│ │
3: ───────────────────────@───H───@───────────────────────
And the computed end_frontier is {
cirq.LineQubit(0): 11,
cirq.LineQubit(1): 9,
cirq.LineQubit(2): 6,
}
Note that the frontier indices (shown above the circuit) are
best thought of (and shown) as happening *between* moment indices.
If we specify a blocker as follows:
is_blocker=lambda: op == cirq.CZ(cirq.LineQubit(1),
cirq.LineQubit(2))
and use this start_frontier:
{
cirq.LineQubit(0): 0,
cirq.LineQubit(1): 0,
cirq.LineQubit(2): 0,
cirq.LineQubit(3): 0,
}
Then this is the reachable area:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0: ─██H███@██████████████████████████████████████─@───H───
│ │
1: ─██████@███H██─@───────────────────────@───H───@───────
│ │
2: ─█████████████─@───H───@───────@───H───@───────────────
│ │
3: ─█████████████████████─@───H───@───────────────────────
and the computed end_frontier is:
{
cirq.LineQubit(0): 11,
cirq.LineQubit(1): 3,
cirq.LineQubit(2): 3,
cirq.LineQubit(3): 5,
}
Args:
start_frontier: A starting set of reachable locations.
is_blocker: A predicate that determines if operations block
reachability. Any location covered by an operation that causes
`is_blocker` to return True is considered to be an unreachable
location.
Returns:
An end_frontier dictionary, containing an end index for each qubit q
mapped to a start index by the given `start_frontier` dictionary.
To determine if a location (q, i) was reachable, you can use
this expression:
q in start_frontier and start_frontier[q] <= i < end_frontier[q]
where i is the moment index, q is the qubit, and end_frontier is the
result of this method.
"""
active: Set['cirq.Qid'] = set()
end_frontier = {}
queue = BucketPriorityQueue[ops.Operation](drop_duplicate_entries=True)
def enqueue_next(qubit: 'cirq.Qid', moment: int) -> None:
next_moment = self.next_moment_operating_on([qubit], moment)
if next_moment is None:
end_frontier[qubit] = max(len(self), start_frontier[qubit])
if qubit in active:
active.remove(qubit)
else:
next_op = self.operation_at(qubit, next_moment)
assert next_op is not None
queue.enqueue(next_moment, next_op)
for start_qubit, start_moment in start_frontier.items():
enqueue_next(start_qubit, start_moment)
while queue:
cur_moment, cur_op = queue.dequeue()
for q in cur_op.qubits:
if (
q in start_frontier
and cur_moment >= start_frontier[q]
and q not in end_frontier
):
active.add(q)
continue_past = (
cur_op is not None and active.issuperset(cur_op.qubits) and not is_blocker(cur_op)
)
if continue_past:
for q in cur_op.qubits:
enqueue_next(q, cur_moment + 1)
else:
for q in cur_op.qubits:
if q in active:
end_frontier[q] = cur_moment
active.remove(q)
return end_frontier
def findall_operations_between(
self,
start_frontier: Dict['cirq.Qid', int],
end_frontier: Dict['cirq.Qid', int],
omit_crossing_operations: bool = False,
) -> List[Tuple[int, 'cirq.Operation']]:
"""Finds operations between the two given frontiers.
If a qubit is in `start_frontier` but not `end_frontier`, its end index
defaults to the end of the circuit. If a qubit is in `end_frontier` but
not `start_frontier`, its start index defaults to the start of the
circuit. Operations on qubits not mentioned in either frontier are not
included in the results.
Args:
start_frontier: Just before where to start searching for operations,
for each qubit of interest. Start frontier indices are
inclusive.
end_frontier: Just before where to stop searching for operations,
for each qubit of interest. End frontier indices are exclusive.
omit_crossing_operations: Determines whether or not operations that
cross from a location between the two frontiers to a location
outside the two frontiers are included or excluded. (Operations
completely inside are always included, and operations completely
outside are always excluded.)
Returns:
A list of tuples. Each tuple describes an operation found between
the two frontiers. The first item of each tuple is the index of the
moment containing the operation, and the second item is the
operation itself. The list is sorted so that the moment index
increases monotonically.
"""
result = BucketPriorityQueue[ops.Operation](drop_duplicate_entries=True)
involved_qubits = set(start_frontier.keys()) | set(end_frontier.keys())
# Note: only sorted to ensure a deterministic result ordering.
for q in sorted(involved_qubits):
for i in range(start_frontier.get(q, 0), end_frontier.get(q, len(self))):
op = self.operation_at(q, i)
if op is None:
continue
if omit_crossing_operations and not involved_qubits.issuperset(op.qubits):
continue
result.enqueue(i, op)
return list(result)
def findall_operations_until_blocked(
self,
start_frontier: Dict['cirq.Qid', int],
is_blocker: Callable[['cirq.Operation'], bool] = lambda op: False,
) -> List[Tuple[int, ops.Operation]]:
"""
Finds all operations until a blocking operation is hit.
An operation is considered blocking if
a) It is in the 'light cone' of start_frontier.
AND
(
1) is_blocker returns a truthy value.
OR
2) It acts on a blocked qubit.
)
Every qubit acted on by a blocking operation is thereafter itself
blocked.
The notion of reachability here differs from that in
reachable_frontier_from in two respects:
1) An operation is not considered blocking only because it is in a
moment before the start_frontier of one of the qubits on which it
acts.
2) Operations that act on qubits not in start_frontier are not
automatically blocking.
For every (moment_index, operation) returned:
1) moment_index >= min((start_frontier[q] for q in operation.qubits
if q in start_frontier), default=0)
2) set(operation.qubits).intersection(start_frontier)
Below are some examples, where on the left the opening parentheses show
`start_frontier` and on the right are the operations included (with
their moment indices) in the output. `F` and `T` indicate that
`is_blocker` return `False` or `True`, respectively, when applied to
the gates; `M` indicates that it doesn't matter.
─(─F───F─────── ┄(─F───F─)┄┄┄┄┄
│ │ │ │
─(─F───F───T─── => ┄(─F───F─)┄┄┄┄┄
│ ┊
───────────T─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
───M─────(─F─── ┄┄┄┄┄┄┄┄┄(─F─)┄┄
│ │ ┊ │
───M───M─(─F─── ┄┄┄┄┄┄┄┄┄(─F─)┄┄
│ => ┊
───────M───M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ ┊
───────────M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
───M─(─────M─── ┄┄┄┄┄()┄┄┄┄┄┄┄┄
│ │ ┊ ┊
───M─(─T───M─── ┄┄┄┄┄()┄┄┄┄┄┄┄┄
│ => ┊
───────T───M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ ┊
───────────M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
─(─F───F─── ┄(─F───F─)┄
│ │ => │ │
───F─(─F─── ┄(─F───F─)┄
─(─F─────────── ┄(─F─)┄┄┄┄┄┄┄┄┄
│ │
───F───F─────── ┄(─F─)┄┄┄┄┄┄┄┄┄
│ => ┊
───────F───F─── ┄┄┄┄┄┄┄┄┄(─F─)┄
│ │
─(─────────F─── ┄┄┄┄┄┄┄┄┄(─F─)┄
Args:
start_frontier: A starting set of reachable locations.
is_blocker: A predicate that determines if operations block
reachability. Any location covered by an operation that causes
`is_blocker` to return True is considered to be an unreachable
location.
Returns:
A list of tuples. Each tuple describes an operation found between
the start frontier and a blocking operation. The first item of
each tuple is the index of the moment containing the operation,
and the second item is the operation itself.
"""
op_list = [] # type: List[Tuple[int, ops.Operation]]
if not start_frontier:
return op_list
start_index = min(start_frontier.values())
blocked_qubits = set() # type: Set[cirq.Qid]
for index, moment in enumerate(self[start_index:], start_index):
active_qubits = set(q for q, s in start_frontier.items() if s <= index)
for op in moment.operations:
if is_blocker(op) or blocked_qubits.intersection(op.qubits):
blocked_qubits.update(op.qubits)
elif active_qubits.intersection(op.qubits):
op_list.append((index, op))
if blocked_qubits.issuperset(start_frontier):
break
return op_list
def operation_at(self, qubit: 'cirq.Qid', moment_index: int) -> Optional['cirq.Operation']:
"""Finds the operation on a qubit within a moment, if any.
Args:
qubit: The qubit to check for an operation on.
moment_index: The index of the moment to check for an operation
within. Allowed to be beyond the end of the circuit.
Returns:
None if there is no operation on the qubit at the given moment, or
else the operation.
"""
if not 0 <= moment_index < len(self.moments):
return None
return self.moments[moment_index].operation_at(qubit)
def findall_operations(
self, predicate: Callable[['cirq.Operation'], bool]
) -> Iterable[Tuple[int, 'cirq.Operation']]:
"""Find the locations of all operations that satisfy a given condition.
This returns an iterator of (index, operation) tuples where each
operation satisfies op_cond(operation) is truthy. The indices are
in order of the moments and then order of the ops within that moment.
Args:
predicate: A method that takes an Operation and returns a Truthy
value indicating the operation meets the find condition.
Returns:
An iterator (index, operation)'s that satisfy the op_condition.
"""
for index, moment in enumerate(self.moments):
for op in moment.operations:
if predicate(op):
yield index, op
def findall_operations_with_gate_type(
self, gate_type: Type[T_DESIRED_GATE_TYPE]
) -> Iterable[Tuple[int, ops.GateOperation, T_DESIRED_GATE_TYPE]]:
"""Find the locations of all gate operations of a given type.
Args:
gate_type: The type of gate to find, e.g. XPowGate or
MeasurementGate.
Returns:
An iterator (index, operation, gate)'s for operations with the given
gate type.
"""
result = self.findall_operations(lambda operation: isinstance(operation.gate, gate_type))
for index, op in result:
gate_op = cast(ops.GateOperation, op)
yield index, gate_op, cast(T_DESIRED_GATE_TYPE, gate_op.gate)
def has_measurements(self):
return any(self.findall_operations(protocols.is_measurement))
def are_all_measurements_terminal(self):
"""Whether all measurement gates are at the end of the circuit."""
return self.are_all_matches_terminal(protocols.is_measurement)
def are_all_matches_terminal(self, predicate: Callable[['cirq.Operation'], bool]):
"""Check whether all of the ops that satisfy a predicate are terminal.
This method will transparently descend into any CircuitOperations this
circuit contains; as a result, it will misbehave if the predicate
refers to CircuitOperations. See the tests for an example of this.
Args:
predicate: A predicate on ops.Operations which is being checked.
Returns:
Whether or not all `Operation` s in a circuit that satisfy the
given predicate are terminal. Also checks within any CircuitGates
the circuit may contain.
"""
from cirq.circuits import CircuitOperation
# TaggedOperations can wrap CircuitOperations.
def get_op_circuit(op: ops.Operation) -> Optional['cirq.FrozenCircuit']:
while isinstance(op, ops.TaggedOperation):
op = op.sub_operation
return op.circuit if isinstance(op, CircuitOperation) else None
if not all(
self.next_moment_operating_on(op.qubits, i + 1) is None
for (i, op) in self.findall_operations(predicate)
if get_op_circuit(op) is None
):
return False
for i, moment in enumerate(self.moments):
for op in moment.operations:
circuit = get_op_circuit(op)
if circuit is None:
continue
if not circuit.are_all_matches_terminal(predicate):
return False
if i < len(self.moments) - 1 and not all(
self.next_moment_operating_on(op.qubits, i + 1) is None
for _, op in circuit.findall_operations(predicate)
):
return False
return True
def _has_op_at(self, moment_index: int, qubits: Iterable['cirq.Qid']) -> bool:
return 0 <= moment_index < len(self.moments) and self.moments[moment_index].operates_on(
qubits
)
def _validate_op_tree_qids(self, op_tree: 'cirq.OP_TREE') -> None:
"""Raises an exception if any operation in `op_tree` has qids that don't
match its qid shape.
Args:
operation: The operation to validate.
Raises:
ValueError: The operation had qids that don't match its qid shape.
"""
# Cast from Iterable[Operation, Moment] because preserve_moments is
# False.
for op in cast(Iterable['cirq.Operation'], ops.flatten_op_tree(op_tree)):
if protocols.qid_shape(op) != protocols.qid_shape(op.qubits):
raise ValueError(
'Invalid operation. '
'An operation has qid shape <{!r}> but is on qids with '
'shape <{!r}>. The operation is <{!r}>.'.format(
protocols.qid_shape(op), protocols.qid_shape(op.qubits), op
)
)
def all_qubits(self) -> FrozenSet['cirq.Qid']:
"""Returns the qubits acted upon by Operations in this circuit."""
return frozenset(q for m in self.moments for q in m.qubits)
def all_operations(self) -> Iterator[ops.Operation]:
"""Iterates over the operations applied by this circuit.
Operations from earlier moments will be iterated over first. Operations
within a moment are iterated in the order they were given to the
moment's constructor.
"""
return (op for moment in self for op in moment.operations)
def qid_shape(
self, qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT
) -> Tuple[int, ...]:
qids = ops.QubitOrder.as_qubit_order(qubit_order).order_for(self.all_qubits())
return protocols.qid_shape(qids)
def all_measurement_keys(self) -> AbstractSet[str]:
return protocols.measurement_keys(self)
def _with_measurement_key_mapping_(self, key_map: Dict[str, str]):
return self._with_sliced_moments(
[protocols.with_measurement_key_mapping(moment, key_map) for moment in self.moments]
)
def _qid_shape_(self) -> Tuple[int, ...]:
return self.qid_shape()
def _has_unitary_(self) -> bool:
if not self.are_all_measurements_terminal():
return False
unitary_ops = protocols.decompose(
self.all_operations(),
keep=protocols.has_unitary,
intercepting_decomposer=_decompose_measurement_inversions,
on_stuck_raise=None,
)
return all(protocols.has_unitary(e) for e in unitary_ops)
def _unitary_(self) -> Union[np.ndarray, NotImplementedType]:
"""Converts the circuit into a unitary matrix, if possible.
If the circuit contains any non-terminal measurements, the conversion
into a unitary matrix fails (i.e. returns NotImplemented). Terminal
measurements are ignored when computing the unitary matrix. The unitary
matrix is the product of the unitary matrix of all operations in the
circuit (after expanding them to apply to the whole system).
"""
if not self._has_unitary_():
return NotImplemented
return self.unitary(ignore_terminal_measurements=True)
def unitary(
self,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
qubits_that_should_be_present: Iterable['cirq.Qid'] = (),
ignore_terminal_measurements: bool = True,
dtype: Type[np.number] = np.complex128,
) -> np.ndarray:
"""Converts the circuit into a unitary matrix, if possible.
Returns the same result as `cirq.unitary`, but provides more options.
Args:
qubit_order: Determines how qubits are ordered when passing matrices
into np.kron.
qubits_that_should_be_present: Qubits that may or may not appear
in operations within the circuit, but that should be included
regardless when generating the matrix.
ignore_terminal_measurements: When set, measurements at the end of
the circuit are ignored instead of causing the method to
fail.
dtype: The numpy dtype for the returned unitary. Defaults to
np.complex128. Specifying np.complex64 will run faster at the
cost of precision. `dtype` must be a complex np.dtype, unless
all operations in the circuit have unitary matrices with
exclusively real coefficients (e.g. an H + TOFFOLI circuit).
Returns:
A (possibly gigantic) 2d numpy array corresponding to a matrix
equivalent to the circuit's effect on a quantum state.
Raises:
ValueError: The circuit contains measurement gates that are not
ignored.
TypeError: The circuit contains gates that don't have a known
unitary matrix, e.g. gates parameterized by a Symbol.
"""
if not ignore_terminal_measurements and any(
protocols.is_measurement(op) for op in self.all_operations()
):
raise ValueError('Circuit contains a measurement.')
if not self.are_all_measurements_terminal():
raise ValueError('Circuit contains a non-terminal measurement.')
qs = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
self.all_qubits().union(qubits_that_should_be_present)
)
# Force qubits to have dimension at least 2 for backwards compatibility.
qid_shape = self.qid_shape(qubit_order=qs)
side_len = np.product(qid_shape, dtype=int)
state = qis.eye_tensor(qid_shape, dtype=dtype)
result = _apply_unitary_circuit(self, state, qs, dtype)
return result.reshape((side_len, side_len))
def final_state_vector(
self,
initial_state: 'cirq.STATE_VECTOR_LIKE' = 0,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
qubits_that_should_be_present: Iterable['cirq.Qid'] = (),
ignore_terminal_measurements: bool = True,
dtype: Type[np.number] = np.complex128,
) -> np.ndarray:
"""Left-multiplies a state vector by the circuit's unitary effect.
A circuit's "unitary effect" is the unitary matrix produced by
multiplying together all of its gates' unitary matrices. A circuit
with non-unitary gates (such as measurement or parameterized gates) does
not have a well-defined unitary effect, and the method will fail if such
operations are present.
For convenience, terminal measurements are automatically ignored
instead of causing a failure. Set the `ignore_terminal_measurements`
argument to False to disable this behavior.
This method is equivalent to left-multiplying the input state by
`cirq.unitary(circuit)` but it's computed in a more efficient
way.
Args:
initial_state: The input state for the circuit. This can be a list
of qudit values, a big endian int encoding the qudit values,
a vector of amplitudes, or a tensor of amplitudes.
When this is an int, it refers to a computational
basis state (e.g. 5 means initialize to ``|5⟩ = |...000101⟩``).
If this is a vector of amplitudes (a flat numpy array of the
correct length for the system) or a tensor of amplitudes (a
numpy array whose shape equals this circuit's `qid_shape`), it
directly specifies the initial state's amplitudes. The vector
type must be convertible to the given `dtype` argument.
qubit_order: Determines how qubits are ordered when passing matrices
into np.kron.
qubits_that_should_be_present: Qubits that may or may not appear
in operations within the circuit, but that should be included
regardless when generating the matrix.
ignore_terminal_measurements: When set, measurements at the end of
the circuit are ignored instead of causing the method to
fail.
dtype: The numpy dtype for the returned unitary. Defaults to
np.complex128. Specifying np.complex64 will run faster at the
cost of precision. `dtype` must be a complex np.dtype, unless
all operations in the circuit have unitary matrices with
exclusively real coefficients (e.g. an H + TOFFOLI circuit).
Returns:
A (possibly gigantic) numpy array storing the superposition that
came out of the circuit for the given input state.
Raises:
ValueError: The circuit contains measurement gates that are not
ignored.
TypeError: The circuit contains gates that don't have a known
unitary matrix, e.g. gates parameterized by a Symbol.
"""
if not ignore_terminal_measurements and any(
protocols.is_measurement(op) for op in self.all_operations()
):
raise ValueError('Circuit contains a measurement.')
if not self.are_all_measurements_terminal():
raise ValueError('Circuit contains a non-terminal measurement.')
qs = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
self.all_qubits().union(qubits_that_should_be_present)
)
# Force qubits to have dimension at least 2 for backwards compatibility.
qid_shape = self.qid_shape(qubit_order=qs)
state_len = np.product(qid_shape, dtype=int)
state = qis.to_valid_state_vector(initial_state, qid_shape=qid_shape, dtype=dtype).reshape(
qid_shape
)
result = _apply_unitary_circuit(self, state, qs, dtype)
return result.reshape((state_len,))
@deprecated(deadline='v0.10.0', fix='Use final_state_vector instead.')
def final_wavefunction(
self,
initial_state: 'cirq.STATE_VECTOR_LIKE' = 0,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
qubits_that_should_be_present: Iterable['cirq.Qid'] = (),
ignore_terminal_measurements: bool = True,
dtype: Type[np.number] = np.complex128,
) -> np.ndarray:
"""Deprecated. Please use `final_state_vector`."""
return self.final_state_vector(
initial_state=initial_state,
qubit_order=qubit_order,
qubits_that_should_be_present=qubits_that_should_be_present,
ignore_terminal_measurements=ignore_terminal_measurements,
dtype=dtype,
)
def to_text_diagram(
self,
*,
use_unicode_characters: bool = True,
transpose: bool = False,
include_tags: bool = True,
precision: Optional[int] = 3,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
) -> str:
"""Returns text containing a diagram describing the circuit.
Args:
use_unicode_characters: Determines if unicode characters are
allowed (as opposed to ascii-only diagrams).
transpose: Arranges qubit wires vertically instead of horizontally.
include_tags: Whether tags on TaggedOperations should be printed
precision: Number of digits to display in text diagram
qubit_order: Determines how qubits are ordered in the diagram.
Returns:
The text diagram.
"""
diagram = self.to_text_diagram_drawer(
use_unicode_characters=use_unicode_characters,
include_tags=include_tags,
precision=precision,
qubit_order=qubit_order,
transpose=transpose,
)
return diagram.render(
crossing_char=(None if use_unicode_characters else ('-' if transpose else '|')),
horizontal_spacing=1 if transpose else 3,
use_unicode_characters=use_unicode_characters,
)
def to_text_diagram_drawer(
self,
*,
use_unicode_characters: bool = True,
qubit_namer: Optional[Callable[['cirq.Qid'], str]] = None,
transpose: bool = False,
include_tags: bool = True,
draw_moment_groups: bool = True,
precision: Optional[int] = 3,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
get_circuit_diagram_info: Optional[
Callable[['cirq.Operation', 'cirq.CircuitDiagramInfoArgs'], 'cirq.CircuitDiagramInfo']
] = None,
) -> TextDiagramDrawer:
"""Returns a TextDiagramDrawer with the circuit drawn into it.
Args:
use_unicode_characters: Determines if unicode characters are
allowed (as opposed to ascii-only diagrams).
qubit_namer: Names qubits in diagram. Defaults to str.
transpose: Arranges qubit wires vertically instead of horizontally.
draw_moment_groups: Whether to draw moment symbol or not
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the diagram.
get_circuit_diagram_info: Gets circuit diagram info. Defaults to
protocol with fallback.
Returns:
The TextDiagramDrawer instance.
"""
qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(self.all_qubits())
qubit_map = {qubits[i]: i for i in range(len(qubits))}
if qubit_namer is None:
qubit_namer = lambda q: str(q) + ('' if transpose else ': ')
diagram = TextDiagramDrawer()
diagram.write(0, 0, '')
for q, i in qubit_map.items():
diagram.write(0, i, qubit_namer(q))
if any(isinstance(op.untagged, cirq.GlobalPhaseOperation) for op in self.all_operations()):
diagram.write(0, max(qubit_map.values(), default=0) + 1, 'global phase:')
moment_groups = [] # type: List[Tuple[int, int]]
for moment in self.moments:
_draw_moment_in_diagram(
moment,
use_unicode_characters,
qubit_map,
diagram,
precision,
moment_groups,
get_circuit_diagram_info,
include_tags,
)
w = diagram.width()
for i in qubit_map.values():
diagram.horizontal_line(i, 0, w)
if moment_groups and draw_moment_groups:
_draw_moment_groups_in_diagram(moment_groups, use_unicode_characters, diagram)
if transpose:
diagram = diagram.transpose()
return diagram
def _is_parameterized_(self) -> bool:
return any(protocols.is_parameterized(op) for op in self.all_operations())
def _parameter_names_(self) -> AbstractSet[str]:
return {name for op in self.all_operations() for name in protocols.parameter_names(op)}
def _qasm_(self) -> str:
return self.to_qasm()
def _to_qasm_output(
self,
header: Optional[str] = None,
precision: int = 10,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
) -> QasmOutput:
"""Returns a QASM object equivalent to the circuit.
Args:
header: A multi-line string that is placed in a comment at the top
of the QASM. Defaults to a cirq version specifier.
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the QASM
register.
"""
if header is None:
header = 'Generated from Cirq v{}'.format(cirq._version.__version__)
qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(self.all_qubits())
return QasmOutput(
operations=self.all_operations(),
qubits=qubits,
header=header,
precision=precision,
version='2.0',
)
def _to_quil_output(
self, qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT
) -> QuilOutput:
qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(self.all_qubits())
return QuilOutput(operations=self.all_operations(), qubits=qubits)
def to_qasm(
self,
header: Optional[str] = None,
precision: int = 10,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
) -> str:
"""Returns QASM equivalent to the circuit.
Args:
header: A multi-line string that is placed in a comment at the top
of the QASM. Defaults to a cirq version specifier.
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the QASM
register.
"""
return str(self._to_qasm_output(header, precision, qubit_order))
def to_quil(self, qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT) -> str:
return str(self._to_quil_output(qubit_order))
def save_qasm(
self,
file_path: Union[str, bytes, int],
header: Optional[str] = None,
precision: int = 10,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
) -> None:
"""Save a QASM file equivalent to the circuit.
Args:
file_path: The location of the file where the qasm will be written.
header: A multi-line string that is placed in a comment at the top
of the QASM. Defaults to a cirq version specifier.
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the QASM
register.
"""
self._to_qasm_output(header, precision, qubit_order).save(file_path)
def _json_dict_(self):
return protocols.obj_to_dict_helper(self, ['moments', 'device'])
@classmethod
def _from_json_dict_(cls, moments, device, **kwargs):
return cls(moments, strategy=InsertStrategy.EARLIEST, device=device)
class Circuit(AbstractCircuit):
"""A mutable list of groups of operations to apply to some qubits.
Methods returning information about the circuit (inherited from
AbstractCircuit):
* next_moment_operating_on
* prev_moment_operating_on
* next_moments_operating_on
* operation_at
* all_qubits
* all_operations
* findall_operations
* findall_operations_between
* findall_operations_until_blocked
* findall_operations_with_gate_type
* reachable_frontier_from
* has_measurements
* are_all_matches_terminal
* are_all_measurements_terminal
* unitary
* final_state_vector
* to_text_diagram
* to_text_diagram_drawer
* qid_shape
* all_measurement_keys
* to_quil
* to_qasm
* save_qasm
Methods for mutation:
* insert
* append
* insert_into_range
* clear_operations_touching
* batch_insert
* batch_remove
* batch_insert_into
* insert_at_frontier
Circuits can also be iterated over,
```
for moment in circuit:
...
```
and sliced,
* `circuit[1:3]` is a new Circuit made up of two moments, the first being
`circuit[1]` and the second being `circuit[2]`;
* `circuit[:, qubit]` is a new Circuit with the same moments, but with
only those operations which act on the given Qubit;
* `circuit[:, qubits]`, where 'qubits' is list of Qubits, is a new Circuit
with the same moments, but only with those operations which touch
any of the given qubits;
* `circuit[1:3, qubit]` is equivalent to `circuit[1:3][:, qubit]`;
* `circuit[1:3, qubits]` is equivalent to `circuit[1:3][:, qubits]`;
and concatenated,
* `circuit1 + circuit2` is a new Circuit made up of the moments in
circuit1 followed by the moments in circuit2;
and multiplied by an integer,
* `circuit * k` is a new Circuit made up of the moments in circuit repeated
k times.
and mutated,
* `circuit[1:7] = [Moment(...)]`
"""
def __init__(
self,
*contents: 'cirq.OP_TREE',
strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST,
device: 'cirq.Device' = devices.UNCONSTRAINED_DEVICE,
) -> None:
"""Initializes a circuit.
Args:
contents: The initial list of moments and operations defining the
circuit. You can also pass in operations, lists of operations,
or generally anything meeting the `cirq.OP_TREE` contract.
Non-moment entries will be inserted according to the specified
insertion strategy.
strategy: When initializing the circuit with operations and moments
from `contents`, this determines how the operations are packed
together. This option does not affect later insertions into the
circuit.
device: Hardware that the circuit should be able to run on.
"""
self._moments: List['cirq.Moment'] = []
self._device = device
self.append(contents, strategy=strategy)
@property
def device(self) -> devices.Device:
return self._device
@device.setter
def device(self, new_device: 'cirq.Device') -> None:
new_device.validate_circuit(self)
self._device = new_device
def __copy__(self) -> 'Circuit':
return self.copy()
def copy(self) -> 'Circuit':
copied_circuit = Circuit(device=self._device)
copied_circuit._moments = self._moments[:]
return copied_circuit
def _with_sliced_moments(self, moments: Sequence['cirq.Moment']) -> 'Circuit':
new_circuit = Circuit(device=self.device)
new_circuit._moments = list(moments)
return new_circuit
# pylint: disable=function-redefined
@overload
def __setitem__(self, key: int, value: 'cirq.Moment'):
pass
@overload
def __setitem__(self, key: slice, value: Iterable['cirq.Moment']):
pass
def __setitem__(self, key, value):
if isinstance(key, int):
if not isinstance(value, ops.Moment):
raise TypeError('Can only assign Moments into Circuits.')
self._device.validate_moment(value)
self._validate_op_tree_qids(value)
if isinstance(key, slice):
value = list(value)
if any(not isinstance(v, ops.Moment) for v in value):
raise TypeError('Can only assign Moments into Circuits.')
for moment in value:
self._device.validate_moment(moment)
self._validate_op_tree_qids(moment)
self._moments[key] = value
# pylint: enable=function-redefined
def __delitem__(self, key: Union[int, slice]):
del self._moments[key]
def __iadd__(self, other):
self.append(other)
return self
def __add__(self, other):
if isinstance(other, type(self)):
if (
devices.UNCONSTRAINED_DEVICE not in [self._device, other.device]
and self._device != other.device
):
raise ValueError("Can't add circuits with incompatible devices.")
elif not isinstance(other, (ops.Operation, Iterable)):
return NotImplemented
result = self.copy()
return result.__iadd__(other)
def __radd__(self, other):
# The Circuit + Circuit case is handled by __add__
if not isinstance(other, (ops.Operation, Iterable)):
return NotImplemented
# Auto wrap OP_TREE inputs into a circuit.
result = self.copy()
result._moments[:0] = Circuit(other)._moments
result._device.validate_circuit(result)
return result
# Needed for numpy to handle multiplication by np.int64 correctly.
__array_priority__ = 10000
def __imul__(self, repetitions: INT_TYPE):
if not isinstance(repetitions, (int, np.integer)):
return NotImplemented
self._moments *= int(repetitions)
return self
def __mul__(self, repetitions: INT_TYPE):
if not isinstance(repetitions, (int, np.integer)):
return NotImplemented
return Circuit(self._moments * int(repetitions), device=self._device)
def __rmul__(self, repetitions: INT_TYPE):
if not isinstance(repetitions, (int, np.integer)):
return NotImplemented
return self * int(repetitions)
def __pow__(self, exponent: int) -> 'Circuit':
"""A circuit raised to a power, only valid for exponent -1, the inverse.
This will fail if anything other than -1 is passed to the Circuit by
returning NotImplemented. Otherwise this will return the inverse
circuit, which is the circuit with its moment order reversed and for
every moment all the moment's operations are replaced by its inverse.
If any of the operations do not support inverse, NotImplemented will be
returned.
"""
if exponent != -1:
return NotImplemented
inv_moments = []
for moment in self[::-1]:
inv_moment = cirq.inverse(moment, default=NotImplemented)
if inv_moment is NotImplemented:
return NotImplemented
inv_moments.append(inv_moment)
return cirq.Circuit(inv_moments, device=self._device)
__hash__ = None # type: ignore
def with_device(
self,
new_device: 'cirq.Device',
qubit_mapping: Callable[['cirq.Qid'], 'cirq.Qid'] = lambda e: e,
) -> 'Circuit':
"""Maps the current circuit onto a new device, and validates.
Args:
new_device: The new device that the circuit should be on.
qubit_mapping: How to translate qubits from the old device into
qubits on the new device.
Returns:
The translated circuit.
"""
return Circuit(
[
ops.Moment(
operation.transform_qubits(qubit_mapping) for operation in moment.operations
)
for moment in self._moments
],
device=new_device,
)
def transform_qubits(
self, func: Callable[['cirq.Qid'], 'cirq.Qid'], *, new_device: 'cirq.Device' = None
) -> 'cirq.Circuit':
"""Returns the same circuit, but with different qubits.
Note that this method does essentially the same thing as
`cirq.Circuit.with_device`. It is included regardless because there are
also `transform_qubits` methods on `cirq.Operation` and `cirq.Moment`.
Args:
func: The function to use to turn each current qubit into a desired
new qubit.
new_device: The device to use for the new circuit, if different.
If this is not set, the new device defaults to the current
device.
Returns:
The receiving circuit but with qubits transformed by the given
function, and with an updated device (if specified).
"""
return self.with_device(
new_device=self.device if new_device is None else new_device, qubit_mapping=func
)
def _prev_moment_available(self, op: 'cirq.Operation', end_moment_index: int) -> Optional[int]:
last_available = end_moment_index
k = end_moment_index
while k > 0:
k -= 1
if not self._can_commute_past(k, op):
return last_available
if self._can_add_op_at(k, op):
last_available = k
return last_available
def _pick_or_create_inserted_op_moment_index(
self, splitter_index: int, op: 'cirq.Operation', strategy: 'cirq.InsertStrategy'
) -> int:
"""Determines and prepares where an insertion will occur.
Args:
splitter_index: The index to insert at.
op: The operation that will be inserted.
strategy: The insertion strategy.
Returns:
The index of the (possibly new) moment where the insertion should
occur.
Raises:
ValueError: Unrecognized append strategy.
"""
if strategy is InsertStrategy.NEW or strategy is InsertStrategy.NEW_THEN_INLINE:
self._moments.insert(splitter_index, ops.Moment())
return splitter_index
if strategy is InsertStrategy.INLINE:
if 0 <= splitter_index - 1 < len(self._moments) and self._can_add_op_at(
splitter_index - 1, op
):
return splitter_index - 1
return self._pick_or_create_inserted_op_moment_index(
splitter_index, op, InsertStrategy.NEW
)
if strategy is InsertStrategy.EARLIEST:
if self._can_add_op_at(splitter_index, op):
p = self._prev_moment_available(op, splitter_index)
return p or 0
return self._pick_or_create_inserted_op_moment_index(
splitter_index, op, InsertStrategy.INLINE
)
raise ValueError('Unrecognized append strategy: {}'.format(strategy))
def _can_add_op_at(self, moment_index: int, operation: 'cirq.Operation') -> bool:
if not 0 <= moment_index < len(self._moments):
return True
return self._device.can_add_operation_into_moment(operation, self._moments[moment_index])
def _can_commute_past(self, moment_index: int, operation: 'cirq.Operation') -> bool:
return not self._moments[moment_index].operates_on(operation.qubits)
def insert(
self,
index: int,
moment_or_operation_tree: Union['cirq.Operation', 'cirq.OP_TREE'],
strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST,
) -> int:
"""Inserts operations into the circuit.
Operations are inserted into the moment specified by the index and
'InsertStrategy'.
Moments within the operation tree are inserted intact.
Args:
index: The index to insert all of the operations at.
moment_or_operation_tree: The moment or operation tree to insert.
strategy: How to pick/create the moment to put operations into.
Returns:
The insertion index that will place operations just after the
operations that were inserted by this method.
Raises:
ValueError: Bad insertion strategy.
"""
moments_and_operations = list(
ops.flatten_to_ops_or_moments(
ops.transform_op_tree(
moment_or_operation_tree,
self._device.decompose_operation,
preserve_moments=True,
),
)
)
for moment_or_op in moments_and_operations:
if isinstance(moment_or_op, ops.Moment):
self._device.validate_moment(cast(ops.Moment, moment_or_op))
else:
self._device.validate_operation(cast(ops.Operation, moment_or_op))
self._validate_op_tree_qids(moment_or_op)
# limit index to 0..len(self._moments), also deal with indices smaller 0
k = max(min(index if index >= 0 else len(self._moments) + index, len(self._moments)), 0)
for moment_or_op in moments_and_operations:
if isinstance(moment_or_op, ops.Moment):
self._moments.insert(k, moment_or_op)
k += 1
else:
op = cast(ops.Operation, moment_or_op)
p = self._pick_or_create_inserted_op_moment_index(k, op, strategy)
while p >= len(self._moments):
self._moments.append(ops.Moment())
self._moments[p] = self._moments[p].with_operation(op)
self._device.validate_moment(self._moments[p])
k = max(k, p + 1)
if strategy is InsertStrategy.NEW_THEN_INLINE:
strategy = InsertStrategy.INLINE
return k
def insert_into_range(self, operations: 'cirq.OP_TREE', start: int, end: int) -> int:
"""Writes operations inline into an area of the circuit.
Args:
start: The start of the range (inclusive) to write the
given operations into.
end: The end of the range (exclusive) to write the given
operations into. If there are still operations remaining,
new moments are created to fit them.
operations: An operation or tree of operations to insert.
Returns:
An insertion index that will place operations after the operations
that were inserted by this method.
Raises:
IndexError: Bad inline_start and/or inline_end.
"""
if not 0 <= start <= end <= len(self):
raise IndexError('Bad insert indices: [{}, {})'.format(start, end))
flat_ops = list(ops.flatten_to_ops(operations))
for op in flat_ops:
self._device.validate_operation(op)
self._validate_op_tree_qids(flat_ops)
i = start
op_index = 0
while op_index < len(flat_ops):
op = flat_ops[op_index]
while i < end and not self._device.can_add_operation_into_moment(op, self._moments[i]):
i += 1
if i >= end:
break
self._moments[i] = self._moments[i].with_operation(op)
op_index += 1
if op_index >= len(flat_ops):
return end
return self.insert(end, flat_ops[op_index:])
@staticmethod
def _pick_inserted_ops_moment_indices(
operations: Sequence['cirq.Operation'],
start: int = 0,
frontier: Dict['cirq.Qid', int] = None,
) -> Tuple[Sequence[int], Dict['cirq.Qid', int]]:
"""Greedily assigns operations to moments.
Args:
operations: The operations to assign to moments.
start: The first moment to consider assignment to.
frontier: The first moment to which an operation acting on a qubit
can be assigned. Updated in place as operations are assigned.
Returns:
The frontier giving the index of the moment after the last one to
which an operation that acts on each qubit is assigned. If a
frontier was specified as an argument, this is the same object.
"""
if frontier is None:
frontier = defaultdict(lambda: 0)
moment_indices = []
for op in operations:
op_start = max(start, max(frontier[q] for q in op.qubits))
moment_indices.append(op_start)
for q in op.qubits:
frontier[q] = max(frontier[q], op_start + 1)
return moment_indices, frontier
def _push_frontier(
self,
early_frontier: Dict['cirq.Qid', int],
late_frontier: Dict['cirq.Qid', int],
update_qubits: Iterable['cirq.Qid'] = None,
) -> Tuple[int, int]:
"""Inserts moments to separate two frontiers.
After insertion n_new moments, the following holds:
for q in late_frontier:
early_frontier[q] <= late_frontier[q] + n_new
for q in update_qubits:
early_frontier[q] the identifies the same moment as before
(but whose index may have changed if this moment is after
those inserted).
Args:
early_frontier: The earlier frontier. For qubits not in the later
frontier, this is updated to account for the newly inserted
moments.
late_frontier: The later frontier. This is not modified.
update_qubits: The qubits for which to update early_frontier to
account for the newly inserted moments.
Returns:
(index at which new moments were inserted, how many new moments
were inserted) if new moments were indeed inserted. (0, 0)
otherwise.
"""
if update_qubits is None:
update_qubits = set(early_frontier).difference(late_frontier)
n_new_moments = (
max(early_frontier.get(q, 0) - late_frontier[q] for q in late_frontier)
if late_frontier
else 0
)
if n_new_moments > 0:
insert_index = min(late_frontier.values())
self._moments[insert_index:insert_index] = [ops.Moment()] * n_new_moments
for q in update_qubits:
if early_frontier.get(q, 0) > insert_index:
early_frontier[q] += n_new_moments
return insert_index, n_new_moments
return (0, 0)
def _insert_operations(
self, operations: Sequence['cirq.Operation'], insertion_indices: Sequence[int]
) -> None:
"""Inserts operations at the specified moments. Appends new moments if
necessary.
Args:
operations: The operations to insert.
insertion_indices: Where to insert them, i.e. operations[i] is
inserted into moments[insertion_indices[i].
Raises:
ValueError: operations and insert_indices have different lengths.
NB: It's on the caller to ensure that the operations won't conflict
with operations already in the moment or even each other.
"""
if len(operations) != len(insertion_indices):
raise ValueError('operations and insertion_indices must have the same length.')
self._moments += [ops.Moment() for _ in range(1 + max(insertion_indices) - len(self))]
moment_to_ops = defaultdict(list) # type: Dict[int, List['cirq.Operation']]
for op_index, moment_index in enumerate(insertion_indices):
moment_to_ops[moment_index].append(operations[op_index])
for moment_index, new_ops in moment_to_ops.items():
self._moments[moment_index] = ops.Moment(
self._moments[moment_index].operations + tuple(new_ops)
)
def zip(*circuits):
"""Combines operations from circuits in a moment-by-moment fashion.
Moment k of the resulting circuit will have all operations from moment
k of each of the given circuits.
When the given circuits have different lengths, the shorter circuits are
implicitly padded with empty moments. This differs from the behavior of
python's built-in zip function, which would instead truncate the longer
circuits.
The zipped circuits can't have overlapping operations occurring at the
same moment index.
Args:
circuits: The circuits to merge together.
Returns:
The merged circuit.
Raises:
ValueError:
The zipped circuits have overlapping operations occurring at the
same moment index.
Examples:
>>> import cirq
>>> a, b, c, d = cirq.LineQubit.range(4)
>>> circuit1 = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b))
>>> circuit2 = cirq.Circuit(cirq.X(c), cirq.Y(c), cirq.Z(c))
>>> circuit3 = cirq.Circuit(cirq.Moment(), cirq.Moment(cirq.S(d)))
>>> print(circuit1.zip(circuit2))
0: ───H───@───────
│
1: ───────X───────
<BLANKLINE>
2: ───X───Y───Z───
>>> print(circuit1.zip(circuit2, circuit3))
0: ───H───@───────
│
1: ───────X───────
<BLANKLINE>
2: ───X───Y───Z───
<BLANKLINE>
3: ───────S───────
>>> print(cirq.Circuit.zip(circuit3, circuit2, circuit1))
0: ───H───@───────
│
1: ───────X───────
<BLANKLINE>
2: ───X───Y───Z───
<BLANKLINE>
3: ───────S───────
"""
circuits = list(circuits)
n = max([len(c) for c in circuits], default=0)
result = cirq.Circuit()
for k in range(n):
try:
result.append(cirq.Moment(c[k] for c in circuits if k < len(c)))
except ValueError as ex:
raise ValueError(
f"Overlapping operations between zipped circuits at moment index {k}.\n{ex}"
) from ex
return result
def insert_at_frontier(
self, operations: 'cirq.OP_TREE', start: int, frontier: Dict['cirq.Qid', int] = None
) -> Dict['cirq.Qid', int]:
"""Inserts operations inline at frontier.
Args:
operations: the operations to insert
start: the moment at which to start inserting the operations
frontier: frontier[q] is the earliest moment in which an operation
acting on qubit q can be placed.
"""
if frontier is None:
frontier = defaultdict(lambda: 0)
flat_ops = tuple(ops.flatten_to_ops(operations))
if not flat_ops:
return frontier
qubits = set(q for op in flat_ops for q in op.qubits)
if any(frontier[q] > start for q in qubits):
raise ValueError(
'The frontier for qubits on which the operations'
'to insert act cannot be after start.'
)
next_moments = self.next_moments_operating_on(qubits, start)
insertion_indices, _ = self._pick_inserted_ops_moment_indices(flat_ops, start, frontier)
self._push_frontier(frontier, next_moments)
self._insert_operations(flat_ops, insertion_indices)
return frontier
def batch_remove(self, removals: Iterable[Tuple[int, 'cirq.Operation']]) -> None:
"""Removes several operations from a circuit.
Args:
removals: A sequence of (moment_index, operation) tuples indicating
operations to delete from the moments that are present. All
listed operations must actually be present or the edit will
fail (without making any changes to the circuit).
ValueError:
One of the operations to delete wasn't present to start with.
IndexError:
Deleted from a moment that doesn't exist.
"""
copy = self.copy()
for i, op in removals:
if op not in copy._moments[i].operations:
raise ValueError("Can't remove {} @ {} because it doesn't exist.".format(op, i))
copy._moments[i] = ops.Moment(
old_op for old_op in copy._moments[i].operations if op != old_op
)
self._device.validate_circuit(copy)
self._moments = copy._moments
def batch_replace(
self, replacements: Iterable[Tuple[int, 'cirq.Operation', 'cirq.Operation']]
) -> None:
"""Replaces several operations in a circuit with new operations.
Args:
replacements: A sequence of (moment_index, old_op, new_op) tuples
indicating operations to be replaced in this circuit. All "old"
operations must actually be present or the edit will fail
(without making any changes to the circuit).
ValueError:
One of the operations to replace wasn't present to start with.
IndexError:
Replaced in a moment that doesn't exist.
"""
copy = self.copy()
for i, op, new_op in replacements:
if op not in copy._moments[i].operations:
raise ValueError(f"Can't replace {op} @ {i} because it doesn't exist.")
copy._moments[i] = ops.Moment(
old_op if old_op != op else new_op for old_op in copy._moments[i].operations
)
self._device.validate_circuit(copy)
self._moments = copy._moments
def batch_insert_into(self, insert_intos: Iterable[Tuple[int, 'cirq.OP_TREE']]) -> None:
"""Inserts operations into empty spaces in existing moments.
If any of the insertions fails (due to colliding with an existing
operation), this method fails without making any changes to the circuit.
Args:
insert_intos: A sequence of (moment_index, new_op_tree)
pairs indicating a moment to add new operations into.
ValueError:
One of the insertions collided with an existing operation.
IndexError:
Inserted into a moment index that doesn't exist.
"""
copy = self.copy()
for i, insertions in insert_intos:
copy._moments[i] = copy._moments[i].with_operations(insertions)
self._device.validate_circuit(copy)
self._validate_op_tree_qids(copy)
self._moments = copy._moments
def batch_insert(self, insertions: Iterable[Tuple[int, 'cirq.OP_TREE']]) -> None:
"""Applies a batched insert operation to the circuit.
Transparently handles the fact that earlier insertions may shift
the index that later insertions should occur at. For example, if you
insert an operation at index 2 and at index 4, but the insert at index 2
causes a new moment to be created, then the insert at "4" will actually
occur at index 5 to account for the shift from the new moment.
All insertions are done with the strategy 'EARLIEST'.
When multiple inserts occur at the same index, the gates from the later
inserts end up before the gates from the earlier inserts (exactly as if
you'd called list.insert several times with the same index: the later
inserts shift the earliest inserts forward).
Args:
insertions: A sequence of (insert_index, operations) pairs
indicating operations to add into the circuit at specific
places.
"""
# Work on a copy in case validation fails halfway through.
copy = self.copy()
shift = 0
# Note: python `sorted` is guaranteed to be stable. This matters.
insertions = sorted(insertions, key=lambda e: e[0])
groups = _group_until_different(insertions, key=lambda e: e[0], value=lambda e: e[1])
for i, group in groups:
insert_index = i + shift
next_index = copy.insert(insert_index, reversed(group), InsertStrategy.EARLIEST)
if next_index > insert_index:
shift += next_index - insert_index
self._moments = copy._moments
def append(
self,
moment_or_operation_tree: Union['cirq.Moment', 'cirq.OP_TREE'],
strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST,
):
"""Appends operations onto the end of the circuit.
Moments within the operation tree are appended intact.
Args:
moment_or_operation_tree: The moment or operation tree to append.
strategy: How to pick/create the moment to put operations into.
"""
self.insert(len(self._moments), moment_or_operation_tree, strategy)
def clear_operations_touching(
self, qubits: Iterable['cirq.Qid'], moment_indices: Iterable[int]
):
"""Clears operations that are touching given qubits at given moments.
Args:
qubits: The qubits to check for operations on.
moment_indices: The indices of moments to check for operations
within.
"""
qubits = frozenset(qubits)
for k in moment_indices:
if 0 <= k < len(self._moments):
self._moments[k] = self._moments[k].without_operations_touching(qubits)
def _resolve_parameters_(
self, param_resolver: 'cirq.ParamResolver', recursive: bool
) -> 'Circuit':
resolved_moments = []
for moment in self:
resolved_operations = _resolve_operations(moment.operations, param_resolver, recursive)
new_moment = ops.Moment(resolved_operations)
resolved_moments.append(new_moment)
resolved_circuit = Circuit(resolved_moments, device=self.device)
return resolved_circuit
@property
def moments(self):
return self._moments
def with_noise(self, noise: 'cirq.NOISE_MODEL_LIKE') -> 'cirq.Circuit':
"""Make a noisy version of the circuit.
Args:
noise: The noise model to use. This describes the kind of noise to
add to the circuit.
Returns:
A new circuit with the same moment structure but with new moments
inserted where needed when more than one noisy operation is
generated for an input operation. Emptied moments are removed.
"""
noise_model = devices.NoiseModel.from_noise_model_like(noise)
qubits = sorted(self.all_qubits())
c_noisy = Circuit()
for op_tree in noise_model.noisy_moments(self, qubits):
# Keep moments aligned
c_noisy += Circuit(op_tree)
return c_noisy
def _resolve_operations(
operations: Iterable['cirq.Operation'], param_resolver: 'cirq.ParamResolver', recursive: bool
) -> List['cirq.Operation']:
resolved_operations = [] # type: List['cirq.Operation']
for op in operations:
resolved_operations.append(protocols.resolve_parameters(op, param_resolver, recursive))
return resolved_operations
def _draw_moment_in_diagram(
moment: 'cirq.Moment',
use_unicode_characters: bool,
qubit_map: Dict['cirq.Qid', int],
out_diagram: TextDiagramDrawer,
precision: Optional[int],
moment_groups: List[Tuple[int, int]],
get_circuit_diagram_info: Optional[
Callable[['cirq.Operation', 'cirq.CircuitDiagramInfoArgs'], 'cirq.CircuitDiagramInfo']
] = None,
include_tags: bool = True,
):
if get_circuit_diagram_info is None:
get_circuit_diagram_info = protocols.CircuitDiagramInfo._op_info_with_fallback
x0 = out_diagram.width()
non_global_ops = [op for op in moment.operations if op.qubits]
max_x = x0
for op in non_global_ops:
indices = [qubit_map[q] for q in op.qubits]
y1 = min(indices)
y2 = max(indices)
# Find an available column.
x = x0
while any(out_diagram.content_present(x, y) for y in range(y1, y2 + 1)):
out_diagram.force_horizontal_padding_after(x, 0)
x += 1
args = protocols.CircuitDiagramInfoArgs(
known_qubits=op.qubits,
known_qubit_count=len(op.qubits),
use_unicode_characters=use_unicode_characters,
qubit_map=qubit_map,
precision=precision,
include_tags=include_tags,
)
info = get_circuit_diagram_info(op, args)
# Draw vertical line linking the gate's qubits.
if y2 > y1 and info.connected:
out_diagram.vertical_line(x, y1, y2)
# Print gate qubit labels.
symbols = info._wire_symbols_including_formatted_exponent(
args,
preferred_exponent_index=max(
range(len(op.qubits)), key=lambda i: qubit_map[op.qubits[i]]
),
)
for s, q in zip(symbols, op.qubits):
out_diagram.write(x, qubit_map[q], s)
if x > max_x:
max_x = x
global_phase: Optional[complex] = None
tags: List[Any] = []
for op in moment:
if isinstance(op.untagged, ops.GlobalPhaseOperation):
tags.extend(op.tags)
if global_phase is None:
global_phase = complex(1)
global_phase *= complex(op.untagged.coefficient)
# Print out global phase, unless it's 1 (phase of 0pi) or it's the only op.
if global_phase and (global_phase != 1 or not non_global_ops):
desc = _formatted_phase(global_phase, use_unicode_characters, precision)
if desc:
y = max(qubit_map.values(), default=0) + 1
if tags and include_tags:
desc = desc + str(tags)
out_diagram.write(x0, y, desc)
if not non_global_ops:
out_diagram.write(x0, 0, '')
# Group together columns belonging to the same Moment.
if moment.operations and max_x > x0:
moment_groups.append((x0, max_x))
def _formatted_phase(coefficient: complex, unicode: bool, precision: Optional[int]) -> str:
h = math.atan2(coefficient.imag, coefficient.real) / math.pi
unit = 'π' if unicode else 'pi'
if h == 1:
return unit
return '{{:.{}}}'.format(precision).format(h) + unit
def _draw_moment_groups_in_diagram(
moment_groups: List[Tuple[int, int]],
use_unicode_characters: bool,
out_diagram: TextDiagramDrawer,
):
out_diagram.insert_empty_rows(0)
h = out_diagram.height()
# Insert columns starting from the back since the insertion
# affects subsequent indices.
for x1, x2 in reversed(moment_groups):
out_diagram.insert_empty_columns(x2 + 1)
out_diagram.force_horizontal_padding_after(x2, 0)
out_diagram.insert_empty_columns(x1)
out_diagram.force_horizontal_padding_after(x1, 0)
x2 += 2
for x in range(x1, x2):
out_diagram.force_horizontal_padding_after(x, 0)
for y in [0, h]:
out_diagram.horizontal_line(y, x1, x2)
out_diagram.vertical_line(x1, 0, 0.5)
out_diagram.vertical_line(x2, 0, 0.5)
out_diagram.vertical_line(x1, h, h - 0.5)
out_diagram.vertical_line(x2, h, h - 0.5)
# Rounds up to 1 when horizontal, down to 0 when vertical.
# (Matters when transposing.)
out_diagram.force_vertical_padding_after(0, 0.5)
out_diagram.force_vertical_padding_after(h - 1, 0.5)
def _apply_unitary_circuit(
circuit: AbstractCircuit,
state: np.ndarray,
qubits: Tuple['cirq.Qid', ...],
dtype: Type[np.number],
) -> np.ndarray:
"""Applies a circuit's unitary effect to the given vector or matrix.
This method assumes that the caller wants to ignore measurements.
Args:
circuit: The circuit to simulate. All operations must have a known
matrix or decompositions leading to known matrices. Measurements
are allowed to be in the circuit, but they will be ignored.
state: The initial state tensor (i.e. superposition or unitary matrix).
This is what will be left-multiplied by the circuit's effective
unitary. If this is a state vector, it must have shape
(2,) * num_qubits. If it is a unitary matrix it should have shape
(2,) * (2*num_qubits).
qubits: The qubits in the state tensor. Determines which axes operations
apply to. An operation targeting the k'th qubit in this list will
operate on the k'th axis of the state tensor.
dtype: The numpy dtype to use for applying the unitary. Must be a
complex dtype.
Returns:
The left-multiplied state tensor.
"""
buffer = np.empty_like(state)
def on_stuck(bad_op):
return TypeError('Operation without a known matrix or decomposition: {!r}'.format(bad_op))
unitary_ops = protocols.decompose(
circuit.all_operations(),
keep=protocols.has_unitary,
intercepting_decomposer=_decompose_measurement_inversions,
on_stuck_raise=on_stuck,
)
return protocols.apply_unitaries(
unitary_ops, qubits, protocols.ApplyUnitaryArgs(state, buffer, range(len(qubits)))
)
def _decompose_measurement_inversions(op: 'cirq.Operation') -> 'cirq.OP_TREE':
if isinstance(op.gate, ops.MeasurementGate):
return [ops.X(q) for q, b in zip(op.qubits, op.gate.invert_mask) if b]
return NotImplemented
def _list_repr_with_indented_item_lines(items: Sequence[Any]) -> str:
block = '\n'.join([repr(op) + ',' for op in items])
indented = ' ' + '\n '.join(block.split('\n'))
return '[\n{}\n]'.format(indented)
TIn = TypeVar('TIn')
TOut = TypeVar('TOut')
TKey = TypeVar('TKey')
@overload
def _group_until_different(
items: Iterable[TIn],
key: Callable[[TIn], TKey],
) -> Iterable[Tuple[TKey, List[TIn]]]:
pass
@overload
def _group_until_different(
items: Iterable[TIn], key: Callable[[TIn], TKey], value: Callable[[TIn], TOut]
) -> Iterable[Tuple[TKey, List[TOut]]]:
pass
def _group_until_different(items: Iterable[TIn], key: Callable[[TIn], TKey], value=lambda e: e):
"""Groups runs of items that are identical according to a keying function.
Args:
items: The items to group.
key: If two adjacent items produce the same output from this function,
they will be grouped.
value: Maps each item into a value to put in the group. Defaults to the
item itself.
Examples:
_group_until_different(range(11), key=is_prime) yields
(False, [0, 1])
(True, [2, 3])
(False, [4])
(True, [5])
(False, [6])
(True, [7])
(False, [8, 9, 10])
Yields:
Tuples containing the group key and item values.
"""
return ((k, [value(i) for i in v]) for (k, v) in groupby(items, key))
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConditionedCNNClassifier(nn.Module):
def __init__(self, net_cfg, embed_cfg):
super().__init__()
self.net_cfg = net_cfg
self.embed_cfg = embed_cfg
print('----------- Model Config---------------')
print(f'Headline Embedding Size: {self.embed_cfg['H_V']}')
print(f'Body Embedding Size: {self.embed_cfg['B_V']}')
print(f'Number of Classes: {self.net_cfg['num_classes']}')
print('---------------------------------------')
self.h_embedding = nn.Embedding(self.embed_cfg['H_V'], self.embed_cfg['D'])
self.b_embedding = nn.Embedding(self.embed_cfg['B_V'], self.embed_cfg['D'])
self.convs_headline = nn.ModuleList(
[self.n_gram_conv(n, self.net_cfg['h_num_filt'])
for n in self.net_cfg['h_n_list']])
self.convs_body = nn.ModuleList(
[self.n_gram_conv(n, self.net_cfg['b_num_filt'])
for n in self.net_cfg['b_n_list']])
self.fc_out = nn.Sequential(
nn.Linear(
(len(self.net_cfg['b_n_list']) * self.net_cfg['b_num_filt']) +
(len(self.net_cfg['h_n_list']) * self.net_cfg['h_num_filt']), 1024),
nn.ReLU(),
nn.Dropout(self.net_cfg['dropout_rate']),
nn.Linear(1024, 256),
nn.ReLU(),
nn.Dropout(self.net_cfg['dropout_rate']),
nn.Linear(256, self.net_cfg['num_classes'])
)
def n_gram_conv(self, n, num_filt):
return nn.Sequential(
nn.Conv2d(
in_channels = 1,
out_channels = num_filt,
kernel_size = (n, self.embed_cfg['D'])),
nn.ReLU())
def forward(self, h, b):
# h = (Batch, Sentence Words)
# b = (Batch, Sentence Words)
h = self.h_embedding(h) # (Batch, Word, Vector)
b = self.b_embedding(b) # (Batch, Word, Vector)
h = h.unsqueeze(1) # (Batch, 1, Word, Vector)
b = b.unsqueeze(1) # (Batch, 1, Word, Vector)
# (Batch, Num_Filters, Num_Feature_Map, 1) * len(h_n_list)
h_convs_out = [conv(h) for conv in self.convs_headline]
# (Batch, Num_Filters, Num_Feature_Map, 1) * len(b_n_list)
b_convs_out = [conv(b) for conv in self.convs_body]
# (Batch, Num_Filters, Num_Feature_Map) * len(h_n_list)
h_convs_out = [output.squeeze(3) for output in h_convs_out]
# (Batch, Num_Filters, Num_Feature_Map) * len(b_n_list)
b_convs_out = [output.squeeze(3) for output in b_convs_out]
# (Batch, Num_Filters, 1) * len(h_n_list)
# MaxPool1D: 2nd arg is kernel size
# the stride is taken to be equal to kernel size by default
h_convs_out = [F.max_pool1d(h_conv_out, h_conv_out.shape[2])
for h_conv_out in h_convs_out]
# (Batch, Num_Filters, 1) * len(b_n_list)
b_convs_out = [F.max_pool1d(b_conv_out, b_conv_out.shape[2])
for b_conv_out in b_convs_out]
# (Batch, Num_Filters) * len(h_n_list)
h_convs_out = [h_conv_out.squeeze(2) for h_conv_out in h_convs_out]
# (Batch, Num_Filters) * len(h_n_list)
b_convs_out = [b_conv_out.squeeze(2) for b_conv_out in b_convs_out]
# (Batch, Num_Filters * len(h_n_list))
h_feature_vec = torch.cat(h_convs_out, dim = 1)
b_feature_vec = torch.cat(b_convs_out, dim = 1)
h_b_ft = torch.cat([h_feature_vec, b_feature_vec], dim = 1)
logits = self.fc_out(h_b_ft)
return logits, h_feature_vec, b_feature_vec
class ConditionedSharedCNNClassifier(nn.Module):
def __init__(self, net_cfg, embed_cfg):
super().__init__()
self.net_cfg = net_cfg
self.embed_cfg = embed_cfg
print('----------- Model Config---------------')
print(f'Headline Embedding Size: {self.embed_cfg['H_V']}')
print(f'Body Embedding Size: {self.embed_cfg['B_V']}')
print(f'Number of Classes: {self.net_cfg['num_classes']}')
print('---------------------------------------')
self.h_embedding = nn.Embedding(self.embed_cfg['H_V'], self.embed_cfg['D'])
self.b_embedding = nn.Embedding(self.embed_cfg['B_V'], self.embed_cfg['D'])
self.shared_convs = nn.ModuleList(
[self.n_gram_conv(n, self.net_cfg['num_filt'])
for n in self.net_cfg['n_list']])
self.fc_out = nn.Sequential(
nn.Linear(
(2 * len(self.net_cfg['n_list']) * self.net_cfg['num_filt']), 1024),
nn.ReLU(),
nn.Dropout(self.net_cfg['dropout_rate']),
nn.Linear(1024, 256),
nn.ReLU(),
nn.Dropout(self.net_cfg['dropout_rate']),
nn.Linear(256, self.net_cfg['num_classes'])
)
def n_gram_conv(self, n, num_filt):
return nn.Sequential(
nn.Conv2d(
in_channels = 1,
out_channels = num_filt,
kernel_size = (n, self.embed_cfg['D'])),
nn.ReLU())
def forward(self, h, b):
# h = (Batch, Sentence Words)
# b = (Batch, Sentence Words)
h = self.h_embedding(h) # (Batch, Word, Vector)
b = self.b_embedding(b) # (Batch, Word, Vector)
h = h.unsqueeze(1) # (Batch, 1, Word, Vector)
b = b.unsqueeze(1) # (Batch, 1, Word, Vector)
# (Batch, Num_Filters, Num_Feature_Map, 1) * len(n_list)
h_convs_out = [conv(h) for conv in self.shared_convs]
# (Batch, Num_Filters, Num_Feature_Map, 1) * len(n_list)
b_convs_out = [conv(b) for conv in self.shared_convs]
# (Batch, Num_Filters, Num_Feature_Map) * len(n_list)
h_convs_out = [output.squeeze(3) for output in h_convs_out]
# (Batch, Num_Filters, Num_Feature_Map) * len(n_list)
b_convs_out = [output.squeeze(3) for output in b_convs_out]
# (Batch, Num_Filters, 1) * len(n_list)
# MaxPool1D: 2nd arg is kernel size
# the stride is taken to be equal to kernel size by default
h_convs_out = [F.max_pool1d(h_conv_out, h_conv_out.shape[2])
for h_conv_out in h_convs_out]
# (Batch, Num_Filters, 1) * len(n_list)
b_convs_out = [F.max_pool1d(b_conv_out, b_conv_out.shape[2])
for b_conv_out in b_convs_out]
# (Batch, Num_Filters) * len(n_list)
h_convs_out = [h_conv_out.squeeze(2) for h_conv_out in h_convs_out]
# (Batch, Num_Filters) * len(n_list)
b_convs_out = [b_conv_out.squeeze(2) for b_conv_out in b_convs_out]
# (Batch, Num_Filters * len(h_n_list))
h_feature_vec = torch.cat(h_convs_out, dim = 1)
b_feature_vec = torch.cat(b_convs_out, dim = 1)
h_b_ft = torch.cat([h_feature_vec, b_feature_vec], dim = 1)
logits = self.fc_out(h_b_ft)
return logits, h_feature_vec, b_feature_vec
| import torch
import torch.nn as nn
import torch.nn.functional as F
class ConditionedCNNClassifier(nn.Module):
def __init__(self, net_cfg, embed_cfg):
super().__init__()
self.net_cfg = net_cfg
self.embed_cfg = embed_cfg
print('----------- Model Config---------------')
print(f'Headline Embedding Size: {self.embed_cfg["H_V"]}')
print(f'Body Embedding Size: {self.embed_cfg["B_V"]}')
print(f'Number of Classes: {self.net_cfg["num_classes"]}')
print('---------------------------------------')
self.h_embedding = nn.Embedding(self.embed_cfg['H_V'], self.embed_cfg['D'])
self.b_embedding = nn.Embedding(self.embed_cfg['B_V'], self.embed_cfg['D'])
self.convs_headline = nn.ModuleList(
[self.n_gram_conv(n, self.net_cfg['h_num_filt'])
for n in self.net_cfg['h_n_list']])
self.convs_body = nn.ModuleList(
[self.n_gram_conv(n, self.net_cfg['b_num_filt'])
for n in self.net_cfg['b_n_list']])
self.fc_out = nn.Sequential(
nn.Linear(
(len(self.net_cfg['b_n_list']) * self.net_cfg['b_num_filt']) +
(len(self.net_cfg['h_n_list']) * self.net_cfg['h_num_filt']), 1024),
nn.ReLU(),
nn.Dropout(self.net_cfg['dropout_rate']),
nn.Linear(1024, 256),
nn.ReLU(),
nn.Dropout(self.net_cfg['dropout_rate']),
nn.Linear(256, self.net_cfg['num_classes'])
)
def n_gram_conv(self, n, num_filt):
return nn.Sequential(
nn.Conv2d(
in_channels = 1,
out_channels = num_filt,
kernel_size = (n, self.embed_cfg['D'])),
nn.ReLU())
def forward(self, h, b):
# h = (Batch, Sentence Words)
# b = (Batch, Sentence Words)
h = self.h_embedding(h) # (Batch, Word, Vector)
b = self.b_embedding(b) # (Batch, Word, Vector)
h = h.unsqueeze(1) # (Batch, 1, Word, Vector)
b = b.unsqueeze(1) # (Batch, 1, Word, Vector)
# (Batch, Num_Filters, Num_Feature_Map, 1) * len(h_n_list)
h_convs_out = [conv(h) for conv in self.convs_headline]
# (Batch, Num_Filters, Num_Feature_Map, 1) * len(b_n_list)
b_convs_out = [conv(b) for conv in self.convs_body]
# (Batch, Num_Filters, Num_Feature_Map) * len(h_n_list)
h_convs_out = [output.squeeze(3) for output in h_convs_out]
# (Batch, Num_Filters, Num_Feature_Map) * len(b_n_list)
b_convs_out = [output.squeeze(3) for output in b_convs_out]
# (Batch, Num_Filters, 1) * len(h_n_list)
# MaxPool1D: 2nd arg is kernel size
# the stride is taken to be equal to kernel size by default
h_convs_out = [F.max_pool1d(h_conv_out, h_conv_out.shape[2])
for h_conv_out in h_convs_out]
# (Batch, Num_Filters, 1) * len(b_n_list)
b_convs_out = [F.max_pool1d(b_conv_out, b_conv_out.shape[2])
for b_conv_out in b_convs_out]
# (Batch, Num_Filters) * len(h_n_list)
h_convs_out = [h_conv_out.squeeze(2) for h_conv_out in h_convs_out]
# (Batch, Num_Filters) * len(h_n_list)
b_convs_out = [b_conv_out.squeeze(2) for b_conv_out in b_convs_out]
# (Batch, Num_Filters * len(h_n_list))
h_feature_vec = torch.cat(h_convs_out, dim = 1)
b_feature_vec = torch.cat(b_convs_out, dim = 1)
h_b_ft = torch.cat([h_feature_vec, b_feature_vec], dim = 1)
logits = self.fc_out(h_b_ft)
return logits, h_feature_vec, b_feature_vec
class ConditionedSharedCNNClassifier(nn.Module):
def __init__(self, net_cfg, embed_cfg):
super().__init__()
self.net_cfg = net_cfg
self.embed_cfg = embed_cfg
print('----------- Model Config---------------')
print(f'Headline Embedding Size: {self.embed_cfg["H_V"]}')
print(f'Body Embedding Size: {self.embed_cfg["B_V"]}')
print(f'Number of Classes: {self.net_cfg["num_classes"]}')
print('---------------------------------------')
self.h_embedding = nn.Embedding(self.embed_cfg['H_V'], self.embed_cfg['D'])
self.b_embedding = nn.Embedding(self.embed_cfg['B_V'], self.embed_cfg['D'])
self.shared_convs = nn.ModuleList(
[self.n_gram_conv(n, self.net_cfg['num_filt'])
for n in self.net_cfg['n_list']])
self.fc_out = nn.Sequential(
nn.Linear(
(2 * len(self.net_cfg['n_list']) * self.net_cfg['num_filt']), 1024),
nn.ReLU(),
nn.Dropout(self.net_cfg['dropout_rate']),
nn.Linear(1024, 256),
nn.ReLU(),
nn.Dropout(self.net_cfg['dropout_rate']),
nn.Linear(256, self.net_cfg['num_classes'])
)
def n_gram_conv(self, n, num_filt):
return nn.Sequential(
nn.Conv2d(
in_channels = 1,
out_channels = num_filt,
kernel_size = (n, self.embed_cfg['D'])),
nn.ReLU())
def forward(self, h, b):
# h = (Batch, Sentence Words)
# b = (Batch, Sentence Words)
h = self.h_embedding(h) # (Batch, Word, Vector)
b = self.b_embedding(b) # (Batch, Word, Vector)
h = h.unsqueeze(1) # (Batch, 1, Word, Vector)
b = b.unsqueeze(1) # (Batch, 1, Word, Vector)
# (Batch, Num_Filters, Num_Feature_Map, 1) * len(n_list)
h_convs_out = [conv(h) for conv in self.shared_convs]
# (Batch, Num_Filters, Num_Feature_Map, 1) * len(n_list)
b_convs_out = [conv(b) for conv in self.shared_convs]
# (Batch, Num_Filters, Num_Feature_Map) * len(n_list)
h_convs_out = [output.squeeze(3) for output in h_convs_out]
# (Batch, Num_Filters, Num_Feature_Map) * len(n_list)
b_convs_out = [output.squeeze(3) for output in b_convs_out]
# (Batch, Num_Filters, 1) * len(n_list)
# MaxPool1D: 2nd arg is kernel size
# the stride is taken to be equal to kernel size by default
h_convs_out = [F.max_pool1d(h_conv_out, h_conv_out.shape[2])
for h_conv_out in h_convs_out]
# (Batch, Num_Filters, 1) * len(n_list)
b_convs_out = [F.max_pool1d(b_conv_out, b_conv_out.shape[2])
for b_conv_out in b_convs_out]
# (Batch, Num_Filters) * len(n_list)
h_convs_out = [h_conv_out.squeeze(2) for h_conv_out in h_convs_out]
# (Batch, Num_Filters) * len(n_list)
b_convs_out = [b_conv_out.squeeze(2) for b_conv_out in b_convs_out]
# (Batch, Num_Filters * len(h_n_list))
h_feature_vec = torch.cat(h_convs_out, dim = 1)
b_feature_vec = torch.cat(b_convs_out, dim = 1)
h_b_ft = torch.cat([h_feature_vec, b_feature_vec], dim = 1)
logits = self.fc_out(h_b_ft)
return logits, h_feature_vec, b_feature_vec
|
import lusid
import lusid.models as models
from lusid.api import InstrumentsApi, SearchApi
import numpy as np
import time
from lusidtools.cocoon.utilities import checkargs
import pandas as pd
import logging
import re
from lusidtools.cocoon.async_tools import run_in_executor
import asyncio
from typing import Callable
@checkargs
def prepare_key(identifier_lusid: str, full_key_format: bool) -> str:
"""
This function prepares the key for the identifier based on whether the full key or just the code is required
Parameters
----------
identifier_lusid : str
The LUSID identifier in either full key format or code only
full_key_format : bool
Whether or not they key needs to be in the full key format
Returns
-------
str
The LUSID identifier in the correct format
"""
if full_key_format:
return (
identifier_lusid
if re.findall("Instrument/\S+/\S+", identifier_lusid)
else f"Instrument/default/{identifier_lusid}"
)
else:
return (
identifier_lusid.split("/")[2]
if re.findall("Instrument/default/\S+", identifier_lusid)
else identifier_lusid
)
@checkargs
def create_identifiers(
index,
row: pd.Series,
file_type: str,
instrument_identifier_mapping: dict = None,
unique_identifiers: list = None,
full_key_format: bool = True,
prepare_key: Callable = prepare_key,
) -> dict:
"""
Parameters
----------
index
The index of the row in the DataFrame
row : pd.Series
The row of the DataFrame to create identifiers for
file_type : str
The file type to create identifiers for
instrument_identifier_mapping : dict
The instrument identifier mapping to use
unique_identifiers : list
The list of allowable unique instrument identifiers
full_key_format : bool
Whether or not the full key format i.e. 'Instrument/default/Figi' is required
prepare_key : callable
The function to use to prepare the key
Returns
-------
identifiers : dict
The identifiers to use on the request
"""
# Populate the identifiers for this instrument
identifiers = {
# Handles specifying the entire property key e.g. Instrument/default/Figi or just the code e.g. Figi
prepare_key(identifier_lusid, full_key_format): models.InstrumentIdValue(
value=row[identifier_column]
)
if file_type == "instrument"
else row[identifier_column]
for identifier_lusid, identifier_column in instrument_identifier_mapping.items()
if not pd.isna( # Only use the identifier it it has a value
row[identifier_column]
)
}
# If there are no identifiers raise an error
if len(identifiers) == 0:
raise ValueError(
f"""The row at index {str(index)} has no value for every single one of the provided
identifiers. Please ensure that each row has at least one identifier and try again"""
)
# Check that at least one unique identifier exists if it is an instrument file (need to move this out of here)
if file_type == "instrument":
# Get the unique list of unique identifiers which have been populated
unique_identifiers_populated = list(
set(unique_identifiers).intersection(set(list(identifiers.keys())))
)
# If there are no unique identifiers raise an Exception as you need at least one to make a successful call
if len(unique_identifiers_populated) == 0:
raise ValueError(
f"""The instrument at index {str(index)} has no value for at least one unique
identifier. Please ensure that each instrument has at least one unique identifier and try again. The
allowed unique identifiers are {str(unique_identifiers)}"""
)
else:
# If the transaction/holding is cash remove all other identifiers and just use this one
if "Instrument/default/Currency" in list(identifiers.keys()):
currency_value = identifiers["Instrument/default/Currency"]
identifiers.clear()
identifiers["Instrument/default/Currency"] = currency_value
return identifiers
@checkargs
def resolve_instruments(
api_factory: lusid.utilities.ApiClientFactory,
data_frame: pd.DataFrame,
identifier_mapping: dict,
):
"""
This function attempts to resolve each row of the file to an instrument in LUSID
Parameters
----------
api_factory : lusid.utilities.ApiClientFactory
An instance of the Lusid Api Factory
data_frame : pd.DataFrame
The DataFrame containing the transactions or holdings to resolve to unique instruments
identifier_mapping : dict
The column mapping between allowable identifiers in LUSID and identifier columns in the dataframe
Returns
-------
_data_frame : pd.DataFrame
The input DataFrame with resolution columns added
"""
if "Currency" not in list(
identifier_mapping.keys()
) and "Instrument/default/Currency" not in list(identifier_mapping.keys()):
raise KeyError(
"""There is no column specified in the identifier_mapping to identify whether or not an instrument is cash.
Please specify add the key "Currency" or "Instrument/default/Currency" to your mapping. If no instruments
are cash you can set the value to be None"""
)
if "Currency" in list(identifier_mapping.keys()):
identifier_mapping["Instrument/default/Currency"] = identifier_mapping[
"Currency"
]
del identifier_mapping["Currency"]
# Check that the values of the mapping exist in the DataFrame
if not (set(identifier_mapping.values()) <= set(data_frame.columns)):
raise KeyError(
"there are values in identifier_mapping that are not columns in the dataframe"
)
# Get the allowable instrument identifiers from LUSID
response = api_factory.build(InstrumentsApi).get_instrument_identifier_types()
"""
# Collect the names and property keys for the identifiers and concatenate them
allowable_identifier_names = [identifier.identifier_type for identifier in response.values]
allowable_identifier_keys = [identifier.property_key for identifier in response.values]
allowable_identifiers = allowable_identifier_names + allowable_identifier_keys
# Check that the identifiers in the mapping are all allowed to be used in LUSID
if not (set(identifier_mapping['identifier_mapping'].keys()) <= set(allowable_identifiers)):
raise Exception(
'there are LUSID identifiers in the identifier_mapping which are not configured in LUSID')
"""
# Copy the data_frame to ensure the original isn't modified
_data_frame = data_frame.copy(deep=True)
# Set up the result Pandas Series to track resolution
found_with = pd.Series(index=_data_frame.index, dtype=np.dtype(object))
resolvable = pd.Series(index=_data_frame.index, dtype=np.dtype(bool))
luid = pd.Series(index=_data_frame.index, dtype=np.dtype(object))
comment = pd.Series(index=_data_frame.index, dtype=np.dtype(object))
logging.info("Beginning instrument resolution process")
# Iterate over each row in the DataFrame
for index, row in _data_frame.iterrows():
if index % 10 == 0:
logging.info(f"Up to row {index}")
# Initialise list to hold the identifiers used to resolve
found_with_current = []
# Initialise a value of False for the row's resolvability to an instrument in LUSID
resolvable_current = False
# Initilise the LUID value
luid_current = None
# Initialise the comment value
comment_current = "No instruments found for the given identifiers"
# Takes the currency resolution function and applies it
currency = row[identifier_mapping["Instrument/default/Currency"]]
if not pd.isna(currency):
resolvable_current = True
found_with_current.append(currency)
luid_current = currency
comment_current = "Resolved as cash with a currency"
search_requests = [
models.InstrumentSearchProperty(
key=f"Instrument/default/{identifier_lusid}"
if "Instrument/" not in identifier_lusid
else identifier_lusid,
value=row[identifier_dataframe],
)
for identifier_lusid, identifier_dataframe in identifier_mapping.items()
if not pd.isnull(row[identifier_dataframe])
]
# Call LUSID to search for instruments
attempts = 0
if len(search_requests) > 0:
while attempts < 3:
try:
response = api_factory.build(SearchApi).instruments_search(
symbols=search_requests, mastered_only=True
)
break
except lusid.exceptions.ApiException as error_message:
attempts += 1
comment_current = f"Failed to find instrument due to LUSID error during search due to status {error_message.status} with reason {error_message.reason}"
time.sleep(5)
if attempts == 3:
# Update the luid series
luid.iloc[index] = luid_current
# Update the found with series
found_with.iloc[index] = found_with_current
# Update the resolvable series
resolvable.iloc[index] = resolvable_current
# Update the comment series
comment.iloc[index] = comment_current
continue
search_request_number = -1
for result in response:
search_request_number += 1
# If there are matches
if len(result.mastered_instruments) == 1:
# Add the identifier responsible for the successful search request to the list
found_with_current.append(
search_requests[search_request_number].key.split("/")[2]
)
comment_current = (
"Uniquely resolved to an instrument in the securities master"
)
resolvable_current = True
luid_current = (
result.mastered_instruments[0]
.identifiers["LusidInstrumentId"]
.value
)
break
elif len(result.mastered_instruments) > 1:
comment_current = f'Multiple instruments found for the instrument using identifier {search_requests[search_request_number].key.split('/')[2]}'
resolvable_current = False
luid_current = np.NaN
# Update the luid series
luid.iloc[index] = luid_current
# Update the found with series
found_with.iloc[index] = found_with_current
# Update the resolvable series
resolvable.iloc[index] = resolvable_current
# Update the comment series
comment.iloc[index] = comment_current
# Add the series to the dataframe
_data_frame["resolvable"] = resolvable
_data_frame["foundWith"] = found_with
_data_frame["LusidInstrumentId"] = luid
_data_frame["comment"] = comment
return _data_frame
@checkargs
def get_unique_identifiers(api_factory: lusid.utilities.ApiClientFactory):
"""
Tests getting the unique instrument identifiers
Parameters
----------
api_factory : lusid.utilities.ApiClientFactory
The LUSID api factory to use
Returns
-------
list[str]
The property keys of the available identifiers
"""
# Get the allowed instrument identifiers from LUSID
identifiers = api_factory.build(
lusid.api.InstrumentsApi
).get_instrument_identifier_types()
# Return the identifiers that are configured to be unique
return [
identifier.identifier_type
for identifier in identifiers.values
if identifier.is_unique_identifier_type
]
async def enrich_instruments(
api_factory: lusid.utilities.ApiClientFactory,
data_frame: pd.DataFrame,
instrument_identifier_mapping: dict,
mapping_required: dict,
constant_prefix: str = "$",
**kwargs,
):
search_requests_all = []
for index, row in data_frame.iterrows():
search_requests_instrument = [
lusid.models.InstrumentSearchProperty(
key=identifier_lusid
if re.findall("Instrument/default/\S+", identifier_lusid)
else f"Instrument/default/{identifier_lusid}",
value=row[identifier_column],
)
for identifier_lusid, identifier_column in instrument_identifier_mapping.items()
if not pd.isna(row[identifier_column])
]
search_requests_all.append(search_requests_instrument)
responses = await asyncio.gather(
*[
instrument_search(
api_factory=api_factory, search_requests=search_requests, **kwargs
)
for search_requests in search_requests_all
],
return_exceptions=False,
)
names = []
for response in responses:
name = np.NaN
for single_search in response:
if isinstance(single_search, Exception):
logging.warning(single_search)
continue
elif len(single_search[0].external_instruments) > 0:
name = single_search[0].external_instruments[0].name
break
names.append(name)
enriched_column_name = "LUSID.Name.Enriched"
data_frame[enriched_column_name] = names
# Missing mapping for name altogether
if "name" not in list(mapping_required.keys()):
mapping_required["name"] = enriched_column_name
# A column for name already exists and needs to be enriched
elif (
isinstance(mapping_required["name"], str)
and mapping_required["name"][0] != constant_prefix
):
data_frame[mapping_required["name"]] = data_frame[
mapping_required["name"]
].fillna(value=data_frame[enriched_column_name])
elif isinstance(mapping_required["name"], dict) and "column" in list(
mapping_required["name"].keys()
):
data_frame[mapping_required["name"]["column"]] = data_frame[
mapping_required["name"]["column"]
].fillna(value=data_frame[enriched_column_name])
# Is a constant specified by the constant prefix
elif (
isinstance(mapping_required["name"], str)
and mapping_required["name"][0] == constant_prefix
):
mapping_required["name"] = {"default": mapping_required["name"][1:]}
mapping_required["name"]["column"] = enriched_column_name
# Is a constant specified by the default nested dictionary specification
elif (
isinstance(mapping_required["name"], dict)
and "default" in list(mapping_required["name"].keys())
and "column" not in list(mapping_required["name"].keys())
):
mapping_required["name"]["column"] = enriched_column_name
return data_frame, mapping_required
async def instrument_search(
api_factory: lusid.utilities.ApiClientFactory, search_requests: list, **kwargs
) -> list:
"""
Conducts an instrument search for a single instrument
Parameters
----------
api_factory : lusid.utilities.ApiClientFactory
The api factory to use
search_requests: list[lusid.models.InstrumentSearchProperty]
The search requests for this instrument
kwargs
Returns
-------
None
"""
instrument_search_results = []
for search_request in search_requests:
try:
result = await instrument_search_single(
api_factory, search_request, **kwargs
)
instrument_search_results.append(result)
except lusid.exceptions.ApiException as e:
instrument_search_results.append(e)
return instrument_search_results
@run_in_executor
def instrument_search_single(
api_factory: lusid.utilities.ApiClientFactory,
search_request: lusid.models.InstrumentSearchProperty,
**kwargs,
) -> list:
"""
Conducts an instrument search with a single search request
Parameters
----------
api_factory : lusid.utilities.ApiClientFactory
The Api factory to use
search_request : lusid.models.InstrumentSearchProperty
The search request
kwargs
Returns
-------
list[lusid.models.InstrumentMatch]
The results of the search
"""
return lusid.api.SearchApi(
api_factory.build(lusid.api.SearchApi)
).instruments_search(symbols=[search_request])
| import lusid
import lusid.models as models
from lusid.api import InstrumentsApi, SearchApi
import numpy as np
import time
from lusidtools.cocoon.utilities import checkargs
import pandas as pd
import logging
import re
from lusidtools.cocoon.async_tools import run_in_executor
import asyncio
from typing import Callable
@checkargs
def prepare_key(identifier_lusid: str, full_key_format: bool) -> str:
"""
This function prepares the key for the identifier based on whether the full key or just the code is required
Parameters
----------
identifier_lusid : str
The LUSID identifier in either full key format or code only
full_key_format : bool
Whether or not they key needs to be in the full key format
Returns
-------
str
The LUSID identifier in the correct format
"""
if full_key_format:
return (
identifier_lusid
if re.findall("Instrument/\S+/\S+", identifier_lusid)
else f"Instrument/default/{identifier_lusid}"
)
else:
return (
identifier_lusid.split("/")[2]
if re.findall("Instrument/default/\S+", identifier_lusid)
else identifier_lusid
)
@checkargs
def create_identifiers(
index,
row: pd.Series,
file_type: str,
instrument_identifier_mapping: dict = None,
unique_identifiers: list = None,
full_key_format: bool = True,
prepare_key: Callable = prepare_key,
) -> dict:
"""
Parameters
----------
index
The index of the row in the DataFrame
row : pd.Series
The row of the DataFrame to create identifiers for
file_type : str
The file type to create identifiers for
instrument_identifier_mapping : dict
The instrument identifier mapping to use
unique_identifiers : list
The list of allowable unique instrument identifiers
full_key_format : bool
Whether or not the full key format i.e. 'Instrument/default/Figi' is required
prepare_key : callable
The function to use to prepare the key
Returns
-------
identifiers : dict
The identifiers to use on the request
"""
# Populate the identifiers for this instrument
identifiers = {
# Handles specifying the entire property key e.g. Instrument/default/Figi or just the code e.g. Figi
prepare_key(identifier_lusid, full_key_format): models.InstrumentIdValue(
value=row[identifier_column]
)
if file_type == "instrument"
else row[identifier_column]
for identifier_lusid, identifier_column in instrument_identifier_mapping.items()
if not pd.isna( # Only use the identifier it it has a value
row[identifier_column]
)
}
# If there are no identifiers raise an error
if len(identifiers) == 0:
raise ValueError(
f"""The row at index {str(index)} has no value for every single one of the provided
identifiers. Please ensure that each row has at least one identifier and try again"""
)
# Check that at least one unique identifier exists if it is an instrument file (need to move this out of here)
if file_type == "instrument":
# Get the unique list of unique identifiers which have been populated
unique_identifiers_populated = list(
set(unique_identifiers).intersection(set(list(identifiers.keys())))
)
# If there are no unique identifiers raise an Exception as you need at least one to make a successful call
if len(unique_identifiers_populated) == 0:
raise ValueError(
f"""The instrument at index {str(index)} has no value for at least one unique
identifier. Please ensure that each instrument has at least one unique identifier and try again. The
allowed unique identifiers are {str(unique_identifiers)}"""
)
else:
# If the transaction/holding is cash remove all other identifiers and just use this one
if "Instrument/default/Currency" in list(identifiers.keys()):
currency_value = identifiers["Instrument/default/Currency"]
identifiers.clear()
identifiers["Instrument/default/Currency"] = currency_value
return identifiers
@checkargs
def resolve_instruments(
api_factory: lusid.utilities.ApiClientFactory,
data_frame: pd.DataFrame,
identifier_mapping: dict,
):
"""
This function attempts to resolve each row of the file to an instrument in LUSID
Parameters
----------
api_factory : lusid.utilities.ApiClientFactory
An instance of the Lusid Api Factory
data_frame : pd.DataFrame
The DataFrame containing the transactions or holdings to resolve to unique instruments
identifier_mapping : dict
The column mapping between allowable identifiers in LUSID and identifier columns in the dataframe
Returns
-------
_data_frame : pd.DataFrame
The input DataFrame with resolution columns added
"""
if "Currency" not in list(
identifier_mapping.keys()
) and "Instrument/default/Currency" not in list(identifier_mapping.keys()):
raise KeyError(
"""There is no column specified in the identifier_mapping to identify whether or not an instrument is cash.
Please specify add the key "Currency" or "Instrument/default/Currency" to your mapping. If no instruments
are cash you can set the value to be None"""
)
if "Currency" in list(identifier_mapping.keys()):
identifier_mapping["Instrument/default/Currency"] = identifier_mapping[
"Currency"
]
del identifier_mapping["Currency"]
# Check that the values of the mapping exist in the DataFrame
if not (set(identifier_mapping.values()) <= set(data_frame.columns)):
raise KeyError(
"there are values in identifier_mapping that are not columns in the dataframe"
)
# Get the allowable instrument identifiers from LUSID
response = api_factory.build(InstrumentsApi).get_instrument_identifier_types()
"""
# Collect the names and property keys for the identifiers and concatenate them
allowable_identifier_names = [identifier.identifier_type for identifier in response.values]
allowable_identifier_keys = [identifier.property_key for identifier in response.values]
allowable_identifiers = allowable_identifier_names + allowable_identifier_keys
# Check that the identifiers in the mapping are all allowed to be used in LUSID
if not (set(identifier_mapping['identifier_mapping'].keys()) <= set(allowable_identifiers)):
raise Exception(
'there are LUSID identifiers in the identifier_mapping which are not configured in LUSID')
"""
# Copy the data_frame to ensure the original isn't modified
_data_frame = data_frame.copy(deep=True)
# Set up the result Pandas Series to track resolution
found_with = pd.Series(index=_data_frame.index, dtype=np.dtype(object))
resolvable = pd.Series(index=_data_frame.index, dtype=np.dtype(bool))
luid = pd.Series(index=_data_frame.index, dtype=np.dtype(object))
comment = pd.Series(index=_data_frame.index, dtype=np.dtype(object))
logging.info("Beginning instrument resolution process")
# Iterate over each row in the DataFrame
for index, row in _data_frame.iterrows():
if index % 10 == 0:
logging.info(f"Up to row {index}")
# Initialise list to hold the identifiers used to resolve
found_with_current = []
# Initialise a value of False for the row's resolvability to an instrument in LUSID
resolvable_current = False
# Initilise the LUID value
luid_current = None
# Initialise the comment value
comment_current = "No instruments found for the given identifiers"
# Takes the currency resolution function and applies it
currency = row[identifier_mapping["Instrument/default/Currency"]]
if not pd.isna(currency):
resolvable_current = True
found_with_current.append(currency)
luid_current = currency
comment_current = "Resolved as cash with a currency"
search_requests = [
models.InstrumentSearchProperty(
key=f"Instrument/default/{identifier_lusid}"
if "Instrument/" not in identifier_lusid
else identifier_lusid,
value=row[identifier_dataframe],
)
for identifier_lusid, identifier_dataframe in identifier_mapping.items()
if not pd.isnull(row[identifier_dataframe])
]
# Call LUSID to search for instruments
attempts = 0
if len(search_requests) > 0:
while attempts < 3:
try:
response = api_factory.build(SearchApi).instruments_search(
symbols=search_requests, mastered_only=True
)
break
except lusid.exceptions.ApiException as error_message:
attempts += 1
comment_current = f"Failed to find instrument due to LUSID error during search due to status {error_message.status} with reason {error_message.reason}"
time.sleep(5)
if attempts == 3:
# Update the luid series
luid.iloc[index] = luid_current
# Update the found with series
found_with.iloc[index] = found_with_current
# Update the resolvable series
resolvable.iloc[index] = resolvable_current
# Update the comment series
comment.iloc[index] = comment_current
continue
search_request_number = -1
for result in response:
search_request_number += 1
# If there are matches
if len(result.mastered_instruments) == 1:
# Add the identifier responsible for the successful search request to the list
found_with_current.append(
search_requests[search_request_number].key.split("/")[2]
)
comment_current = (
"Uniquely resolved to an instrument in the securities master"
)
resolvable_current = True
luid_current = (
result.mastered_instruments[0]
.identifiers["LusidInstrumentId"]
.value
)
break
elif len(result.mastered_instruments) > 1:
comment_current = f'Multiple instruments found for the instrument using identifier {search_requests[search_request_number].key.split("/")[2]}'
resolvable_current = False
luid_current = np.NaN
# Update the luid series
luid.iloc[index] = luid_current
# Update the found with series
found_with.iloc[index] = found_with_current
# Update the resolvable series
resolvable.iloc[index] = resolvable_current
# Update the comment series
comment.iloc[index] = comment_current
# Add the series to the dataframe
_data_frame["resolvable"] = resolvable
_data_frame["foundWith"] = found_with
_data_frame["LusidInstrumentId"] = luid
_data_frame["comment"] = comment
return _data_frame
@checkargs
def get_unique_identifiers(api_factory: lusid.utilities.ApiClientFactory):
"""
Tests getting the unique instrument identifiers
Parameters
----------
api_factory : lusid.utilities.ApiClientFactory
The LUSID api factory to use
Returns
-------
list[str]
The property keys of the available identifiers
"""
# Get the allowed instrument identifiers from LUSID
identifiers = api_factory.build(
lusid.api.InstrumentsApi
).get_instrument_identifier_types()
# Return the identifiers that are configured to be unique
return [
identifier.identifier_type
for identifier in identifiers.values
if identifier.is_unique_identifier_type
]
async def enrich_instruments(
api_factory: lusid.utilities.ApiClientFactory,
data_frame: pd.DataFrame,
instrument_identifier_mapping: dict,
mapping_required: dict,
constant_prefix: str = "$",
**kwargs,
):
search_requests_all = []
for index, row in data_frame.iterrows():
search_requests_instrument = [
lusid.models.InstrumentSearchProperty(
key=identifier_lusid
if re.findall("Instrument/default/\S+", identifier_lusid)
else f"Instrument/default/{identifier_lusid}",
value=row[identifier_column],
)
for identifier_lusid, identifier_column in instrument_identifier_mapping.items()
if not pd.isna(row[identifier_column])
]
search_requests_all.append(search_requests_instrument)
responses = await asyncio.gather(
*[
instrument_search(
api_factory=api_factory, search_requests=search_requests, **kwargs
)
for search_requests in search_requests_all
],
return_exceptions=False,
)
names = []
for response in responses:
name = np.NaN
for single_search in response:
if isinstance(single_search, Exception):
logging.warning(single_search)
continue
elif len(single_search[0].external_instruments) > 0:
name = single_search[0].external_instruments[0].name
break
names.append(name)
enriched_column_name = "LUSID.Name.Enriched"
data_frame[enriched_column_name] = names
# Missing mapping for name altogether
if "name" not in list(mapping_required.keys()):
mapping_required["name"] = enriched_column_name
# A column for name already exists and needs to be enriched
elif (
isinstance(mapping_required["name"], str)
and mapping_required["name"][0] != constant_prefix
):
data_frame[mapping_required["name"]] = data_frame[
mapping_required["name"]
].fillna(value=data_frame[enriched_column_name])
elif isinstance(mapping_required["name"], dict) and "column" in list(
mapping_required["name"].keys()
):
data_frame[mapping_required["name"]["column"]] = data_frame[
mapping_required["name"]["column"]
].fillna(value=data_frame[enriched_column_name])
# Is a constant specified by the constant prefix
elif (
isinstance(mapping_required["name"], str)
and mapping_required["name"][0] == constant_prefix
):
mapping_required["name"] = {"default": mapping_required["name"][1:]}
mapping_required["name"]["column"] = enriched_column_name
# Is a constant specified by the default nested dictionary specification
elif (
isinstance(mapping_required["name"], dict)
and "default" in list(mapping_required["name"].keys())
and "column" not in list(mapping_required["name"].keys())
):
mapping_required["name"]["column"] = enriched_column_name
return data_frame, mapping_required
async def instrument_search(
api_factory: lusid.utilities.ApiClientFactory, search_requests: list, **kwargs
) -> list:
"""
Conducts an instrument search for a single instrument
Parameters
----------
api_factory : lusid.utilities.ApiClientFactory
The api factory to use
search_requests: list[lusid.models.InstrumentSearchProperty]
The search requests for this instrument
kwargs
Returns
-------
None
"""
instrument_search_results = []
for search_request in search_requests:
try:
result = await instrument_search_single(
api_factory, search_request, **kwargs
)
instrument_search_results.append(result)
except lusid.exceptions.ApiException as e:
instrument_search_results.append(e)
return instrument_search_results
@run_in_executor
def instrument_search_single(
api_factory: lusid.utilities.ApiClientFactory,
search_request: lusid.models.InstrumentSearchProperty,
**kwargs,
) -> list:
"""
Conducts an instrument search with a single search request
Parameters
----------
api_factory : lusid.utilities.ApiClientFactory
The Api factory to use
search_request : lusid.models.InstrumentSearchProperty
The search request
kwargs
Returns
-------
list[lusid.models.InstrumentMatch]
The results of the search
"""
return lusid.api.SearchApi(
api_factory.build(lusid.api.SearchApi)
).instruments_search(symbols=[search_request])
|
# coding: utf-8
"""Expose data to different interface
ZMQStream explose to a ZeroMQ socket in a REQ/REP pattern.
Copyright (c) 2017, European X-Ray Free-Electron Laser Facility GmbH
All rights reserved.
You should have received a copy of the 3-Clause BSD License along with this
program. If not, see <https://opensource.org/licenses/BSD-3-Clause>
"""
import os.path as osp
from socket import AF_INET
from warnings import warn
from karabo_bridge import ServerInThread
from karabo_bridge.server import Sender
from psutil import net_if_addrs
from .components import XtdfDetectorBase
from .exceptions import SourceNameError
from .reader import RunDirectory, H5File
from .stacking import stack_detector_data
__all__ = ['ZMQStreamer', 'serve_files']
def find_infiniband_ip():
"""Find the first infiniband IP address
:returns: str
IP of the first infiniband interface if it exists else '*'
"""
addrs = net_if_addrs()
for addr in addrs.get('ib0', ()):
if addr.family == AF_INET:
return addr.address
return '*'
class ZMQStreamer(ServerInThread):
def __init__(self, port, sock='REP', maxlen=10, protocol_version='2.2',
dummy_timestamps=False):
warn("Please use :ref:karabo_bridge.ServerInThread instead",
DeprecationWarning, stacklevel=2)
endpoint = f'tcp://*:{port}'
super().__init__(endpoint, sock=sock, maxlen=maxlen,
protocol_version=protocol_version,
dummy_timestamps=dummy_timestamps)
def _iter_trains(data, merge_detector=False):
"""Iterate over trains in data and merge detector tiles in a single source
:data: DataCollection
:merge_detector: bool
if True and data contains detector data (e.g. AGIPD) individual sources
for each detector tiles are merged in a single source. The new source
name keep the original prefix, but replace the last 2 part with
'/DET/APPEND'. Individual sources are removed from the train data
:yield: dict
train data
"""
det, source_name = None, ''
if merge_detector:
for detector in XtdfDetectorBase.__subclasses__():
try:
det = detector(data)
source_name = f'{det.detector_name}/DET/APPEND'
except SourceNameError:
continue
else:
break
for tid, train_data in data.trains():
if not train_data:
continue
if det is not None:
det_data = {
k: v for k, v in train_data.items()
if k in det.data.detector_sources
}
# get one of the module to reference other datasets
train_data[source_name] = mod_data = next(iter(det_data.values()))
stacked = stack_detector_data(det_data, 'image.data')
mod_data['image.data'] = stacked
mod_data['metadata']['source'] = source_name
if 'image.gain' in mod_data:
stacked = stack_detector_data(det_data, 'image.gain')
mod_data['image.gain'] = stacked
if 'image.mask' in mod_data:
stacked = stack_detector_data(det_data, 'image.mask')
mod_data['image.mask'] = stacked
# remove individual module sources
for src in det.data.detector_sources:
del train_data[src]
yield tid, train_data
def serve_files(path, port, source_glob='*', key_glob='*',
append_detector_modules=False, dummy_timestamps=False,
use_infiniband=False, sock='REP'):
"""Stream data from files through a TCP socket.
Parameters
----------
path: str
Path to the HDF5 file or file folder.
port: str or int
A ZMQ endpoint (e.g. 'tcp://*:44444') or a TCP port to bind the socket
to. Integers or strings of all digits are treated as port numbers.
source_glob: str
Only stream sources matching this glob pattern.
Streaming data selectively is more efficient than streaming everything.
key_glob: str
Only stream keys matching this glob pattern in the selected sources.
append_detector_modules: bool
Combine multi-module detector data in a single data source (sources for
individual modules are removed). The last section of the source name is
replaces with 'APPEND', example:
'SPB_DET_AGIPD1M-1/DET/#CH0:xtdf' -> 'SPB_DET_AGIPD1M-1/DET/APPEND'
Supported detectors: AGIPD, DSSC, LPD
dummy_timestamps: bool
Whether to add mock timestamps if the metadata lacks them.
use_infiniband: bool
Use infiniband interface if available (if port specifies a TCP port)
sock: str
socket type - supported: REP, PUB, PUSH (default REP).
"""
if osp.isdir(path):
data = RunDirectory(path)
else:
data = H5File(path)
data = data.select(source_glob, key_glob)
if isinstance(port, int) or port.isdigit():
endpt = f'tcp://{find_infiniband_ip() if use_infiniband else '*'}:{port}'
else:
endpt = port
sender = Sender(endpt, sock=sock, dummy_timestamps=dummy_timestamps)
print(f'Streamer started on: {sender.endpoint}')
for tid, data in _iter_trains(data, merge_detector=append_detector_modules):
sender.send(data)
# The karabo-bridge code sets linger to 0 so that it doesn't get stuck if
# the client goes away. But this would also mean that we close the socket
# when the last messages have been queued but not sent. So if we've
# successfully queued all the messages, set linger -1 (i.e. infinite) to
# wait until ZMQ has finished transferring them before the socket is closed.
sender.server_socket.close(linger=-1)
| # coding: utf-8
"""Expose data to different interface
ZMQStream explose to a ZeroMQ socket in a REQ/REP pattern.
Copyright (c) 2017, European X-Ray Free-Electron Laser Facility GmbH
All rights reserved.
You should have received a copy of the 3-Clause BSD License along with this
program. If not, see <https://opensource.org/licenses/BSD-3-Clause>
"""
import os.path as osp
from socket import AF_INET
from warnings import warn
from karabo_bridge import ServerInThread
from karabo_bridge.server import Sender
from psutil import net_if_addrs
from .components import XtdfDetectorBase
from .exceptions import SourceNameError
from .reader import RunDirectory, H5File
from .stacking import stack_detector_data
__all__ = ['ZMQStreamer', 'serve_files']
def find_infiniband_ip():
"""Find the first infiniband IP address
:returns: str
IP of the first infiniband interface if it exists else '*'
"""
addrs = net_if_addrs()
for addr in addrs.get('ib0', ()):
if addr.family == AF_INET:
return addr.address
return '*'
class ZMQStreamer(ServerInThread):
def __init__(self, port, sock='REP', maxlen=10, protocol_version='2.2',
dummy_timestamps=False):
warn("Please use :ref:karabo_bridge.ServerInThread instead",
DeprecationWarning, stacklevel=2)
endpoint = f'tcp://*:{port}'
super().__init__(endpoint, sock=sock, maxlen=maxlen,
protocol_version=protocol_version,
dummy_timestamps=dummy_timestamps)
def _iter_trains(data, merge_detector=False):
"""Iterate over trains in data and merge detector tiles in a single source
:data: DataCollection
:merge_detector: bool
if True and data contains detector data (e.g. AGIPD) individual sources
for each detector tiles are merged in a single source. The new source
name keep the original prefix, but replace the last 2 part with
'/DET/APPEND'. Individual sources are removed from the train data
:yield: dict
train data
"""
det, source_name = None, ''
if merge_detector:
for detector in XtdfDetectorBase.__subclasses__():
try:
det = detector(data)
source_name = f'{det.detector_name}/DET/APPEND'
except SourceNameError:
continue
else:
break
for tid, train_data in data.trains():
if not train_data:
continue
if det is not None:
det_data = {
k: v for k, v in train_data.items()
if k in det.data.detector_sources
}
# get one of the module to reference other datasets
train_data[source_name] = mod_data = next(iter(det_data.values()))
stacked = stack_detector_data(det_data, 'image.data')
mod_data['image.data'] = stacked
mod_data['metadata']['source'] = source_name
if 'image.gain' in mod_data:
stacked = stack_detector_data(det_data, 'image.gain')
mod_data['image.gain'] = stacked
if 'image.mask' in mod_data:
stacked = stack_detector_data(det_data, 'image.mask')
mod_data['image.mask'] = stacked
# remove individual module sources
for src in det.data.detector_sources:
del train_data[src]
yield tid, train_data
def serve_files(path, port, source_glob='*', key_glob='*',
append_detector_modules=False, dummy_timestamps=False,
use_infiniband=False, sock='REP'):
"""Stream data from files through a TCP socket.
Parameters
----------
path: str
Path to the HDF5 file or file folder.
port: str or int
A ZMQ endpoint (e.g. 'tcp://*:44444') or a TCP port to bind the socket
to. Integers or strings of all digits are treated as port numbers.
source_glob: str
Only stream sources matching this glob pattern.
Streaming data selectively is more efficient than streaming everything.
key_glob: str
Only stream keys matching this glob pattern in the selected sources.
append_detector_modules: bool
Combine multi-module detector data in a single data source (sources for
individual modules are removed). The last section of the source name is
replaces with 'APPEND', example:
'SPB_DET_AGIPD1M-1/DET/#CH0:xtdf' -> 'SPB_DET_AGIPD1M-1/DET/APPEND'
Supported detectors: AGIPD, DSSC, LPD
dummy_timestamps: bool
Whether to add mock timestamps if the metadata lacks them.
use_infiniband: bool
Use infiniband interface if available (if port specifies a TCP port)
sock: str
socket type - supported: REP, PUB, PUSH (default REP).
"""
if osp.isdir(path):
data = RunDirectory(path)
else:
data = H5File(path)
data = data.select(source_glob, key_glob)
if isinstance(port, int) or port.isdigit():
endpt = f'tcp://{find_infiniband_ip() if use_infiniband else "*"}:{port}'
else:
endpt = port
sender = Sender(endpt, sock=sock, dummy_timestamps=dummy_timestamps)
print(f'Streamer started on: {sender.endpoint}')
for tid, data in _iter_trains(data, merge_detector=append_detector_modules):
sender.send(data)
# The karabo-bridge code sets linger to 0 so that it doesn't get stuck if
# the client goes away. But this would also mean that we close the socket
# when the last messages have been queued but not sent. So if we've
# successfully queued all the messages, set linger -1 (i.e. infinite) to
# wait until ZMQ has finished transferring them before the socket is closed.
sender.server_socket.close(linger=-1)
|
from dotenv import load_dotenv
from twitchio.ext import commands
import os
load_dotenv()
# Set up the bot.
bot = commands.Bot(
irc_token=os.environ['TMI_TOKEN'],
client_id=os.environ['CLIENT_ID'],
nick=os.environ['BOT_NICK'],
prefix=os.environ['BOT_PREFIX'],
initial_channels=[os.environ['CHANNEL']]
)
# Bot sign on message.
@bot.event
async def event_ready():
"""Called once when the bot goes online"""
print(f"{os.environ["BOT_NICK"]} is online!")
# Bot reads messages and ignores itself.
@bot.event
async def event_message(ctx):
"""Runs every time a message is sent in chat"""
if ctx.author.name.lower() == os.environ['BOT_NICK'].lower():
return
await bot.handle_commands(ctx)
# Bot reads music text output and sends as message.
@bot.command(name='song')
async def song(ctx):
with open(os.environ['MUSIC_FILE'], 'r', encoding='utf8') as f:
now_playing = f.readline()
await ctx.send('Now playing: ' + now_playing)
if __name__ == "__main__":
bot.run()
| from dotenv import load_dotenv
from twitchio.ext import commands
import os
load_dotenv()
# Set up the bot.
bot = commands.Bot(
irc_token=os.environ['TMI_TOKEN'],
client_id=os.environ['CLIENT_ID'],
nick=os.environ['BOT_NICK'],
prefix=os.environ['BOT_PREFIX'],
initial_channels=[os.environ['CHANNEL']]
)
# Bot sign on message.
@bot.event
async def event_ready():
"""Called once when the bot goes online"""
print(f"{os.environ['BOT_NICK']} is online!")
# Bot reads messages and ignores itself.
@bot.event
async def event_message(ctx):
"""Runs every time a message is sent in chat"""
if ctx.author.name.lower() == os.environ['BOT_NICK'].lower():
return
await bot.handle_commands(ctx)
# Bot reads music text output and sends as message.
@bot.command(name='song')
async def song(ctx):
with open(os.environ['MUSIC_FILE'], 'r', encoding='utf8') as f:
now_playing = f.readline()
await ctx.send('Now playing: ' + now_playing)
if __name__ == "__main__":
bot.run()
|
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Any, List, Tuple
import yaml
# loading package files: https://stackoverflow.com/a/20885799
try:
import importlib.resources as pkg_resources
except ImportError:
# Try backported to PY<37 `importlib_resources`.
import importlib_resources as pkg_resources
from . import resources
BASE_REF_URL = "https://github.com/huggingface/datasets/tree/master/src/datasets/utils"
this_url = f"{BASE_REF_URL}/{__file__}"
logger = logging.getLogger(__name__)
def load_yaml_resource(resource: str) -> Tuple[Any, str]:
content = pkg_resources.read_text(resources, resource)
return yaml.safe_load(content), f"{BASE_REF_URL}/resources/{resource}"
readme_structure, known_readme_structure_url = load_yaml_resource("readme_structure.yaml")
FILLER_TEXT = [
"[Needs More Information]",
"[More Information Needed]",
"(https://github.com/huggingface/datasets/blob/master/CONTRIBUTING.md#how-to-contribute-to-the-dataset-cards)",
]
# Dictionary representation of section/readme, error_list, warning_list
ReadmeValidatorOutput = Tuple[dict, List[str], List[str]]
@dataclass
class Section:
name: str
level: str
lines: List[str] = None
def __post_init__(self):
self.text = ""
self.is_empty_text = True
self.content = {}
self.parsing_error_list = []
self.parsing_warning_list = []
if self.lines is not None:
self.parse()
def parse(self):
current_sub_level = ""
current_lines = []
code_start = False
for line in self.lines:
if line.strip(" \n") == "":
continue
elif line.strip(" \n")[:3] == "```":
code_start = not code_start
elif line.split()[0] == self.level + "#" and not code_start:
if current_sub_level != "":
self.content[current_sub_level] = Section(current_sub_level, self.level + "#", current_lines)
current_lines = []
else:
if current_lines != []:
self.text += "".join(current_lines).strip()
if self.text != "" and self.text not in FILLER_TEXT:
self.is_empty_text = False
current_lines = []
current_sub_level = " ".join(line.split()[1:]).strip(" \n")
else:
current_lines.append(line)
else:
if current_sub_level != "":
if current_sub_level in self.content:
self.parsing_error_list.append(
f"Multiple sections with the same heading `{current_sub_level}` have been found. Please keep only one of these sections."
)
self.content[current_sub_level] = Section(current_sub_level, self.level + "#", current_lines)
else:
if current_lines != []:
self.text += "".join(current_lines).strip()
if self.text != "" and self.text not in FILLER_TEXT:
self.is_empty_text = False
def validate(self, structure: dict) -> ReadmeValidatorOutput:
"""Validates a Section class object recursively using the structure provided as a dictionary.
Args:
structute (:obj: `dict`): The dictionary representing expected structure.
Returns:
:obj: `ReadmeValidatorOutput`: The dictionary representation of the section, and the errors.
"""
# Header text validation
error_list = []
warning_list = []
if structure["allow_empty"] is False:
# If content is expected
if self.is_empty_text and self.content == {}:
# If no content is found, mention it in the error_list
error_list.append(f"Expected some content in section `{self.name}` but it is empty.")
if structure["allow_empty_text"] is False:
# If some text is expected
if self.is_empty_text:
# If no text is found, mention it in the error_list
error_list.append(
f"Expected some text in section `{self.name}` but it is empty (text in subsections are ignored)."
)
# Subsections Validation
if structure["subsections"] is not None:
# If subsections are expected
if self.content == {}:
# If no subsections are present
values = [subsection["name"] for subsection in structure["subsections"]]
# Mention the expected values in the error_list
error_list.append(
f"Section `{self.name}` expected the following subsections: {", ".join(["`"+x+"`" for x in values])}. Found 'None'."
)
else:
# If some subsections are present
structure_names = [subsection["name"] for subsection in structure["subsections"]]
for idx, name in enumerate(structure_names):
if name not in self.content:
# If the expected subsection is not present
error_list.append(f"Section `{self.name}` is missing subsection: `{name}`.")
else:
# If the subsection is present, validate subsection, return the result
# and concat the errors from subsection to section error_list
# Skip sublevel validation if current level is `###`
if self.level == "###":
continue
else:
_, subsec_error_list, subsec_warning_list = self.content[name].validate(
structure["subsections"][idx]
)
error_list += subsec_error_list
warning_list += subsec_warning_list
for name in self.content:
if name not in structure_names:
# If an extra subsection is present
warning_list.append(
f"`{self.name}` has an extra subsection: `{name}`. Skipping further validation checks for this subsection as expected structure is unknown."
)
error_list = self.parsing_error_list + error_list
warning_list = self.parsing_warning_list + warning_list
if error_list:
# If there are errors, do not return the dictionary as it is invalid
return {}, error_list, warning_list
else:
return self.to_dict(), error_list, warning_list
def to_dict(self) -> dict:
"""Returns the dictionary representation of a section."""
return {
"name": self.name,
"text": self.text,
"is_empty_text": self.is_empty_text,
"subsections": [value.to_dict() for value in self.content.values()],
}
class ReadMe(Section): # Level 0
def __init__(self, name: str, lines: List[str], structure: dict = None):
super().__init__(name=name, level="") # Not using lines here as we need to use a child class parse
self.structure = structure
self.yaml_tags_line_count = -2
self.tag_count = 0
self.lines = lines
if self.lines is not None:
self.parse()
# Validation
if self.structure is None:
content, error_list, warning_list = self.validate(readme_structure)
else:
content, error_list, warning_list = self.validate(self.structure)
error_list = self.parsing_error_list + error_list
warning_list = self.parsing_warning_list + warning_list
if error_list != [] or warning_list != []:
errors = "\n".join(list(map(lambda x: "-\t" + x, error_list + warning_list)))
error_string = f"The following issues were found for the README at `{self.name}`:\n" + errors
raise ValueError(error_string)
@classmethod
def from_readme(cls, path: Path, structure: dict = None):
with open(path, encoding="utf-8") as f:
lines = f.readlines()
return cls(path, lines, structure)
@classmethod
def from_string(cls, string: str, structure: dict = None, root_name: str = "root"):
lines = string.split("\n")
return cls(root_name, lines, structure)
def parse(self):
# Skip Tags
line_count = 0
for line in self.lines:
self.yaml_tags_line_count += 1
if line.strip(" \n") == "---":
self.tag_count += 1
if self.tag_count == 2:
break
line_count += 1
if self.tag_count == 2:
self.lines = self.lines[line_count + 1 :] # Get the last + 1 th item.
else:
self.lines = self.lines[self.tag_count :]
super().parse()
def __str__(self):
"""Returns the string of dictionary representation of the ReadMe."""
return str(self.to_dict())
def validate(self, readme_structure):
error_list = []
warning_list = []
if self.yaml_tags_line_count == 0:
warning_list.append("Empty YAML markers are present in the README.")
elif self.tag_count == 0:
warning_list.append("No YAML markers are present in the README.")
elif self.tag_count == 1:
warning_list.append("Only the start of YAML tags present in the README.")
# Check how many first level sections are present.
num_first_level_keys = len(self.content.keys())
if num_first_level_keys > 1:
# If more than one, add to the error list, continue
error_list.append(
f"The README has several first-level headings: {", ".join(["`"+x+"`" for x in list(self.content.keys())])}. Only one heading is expected. Skipping further validation for this README."
)
elif num_first_level_keys < 1:
# If less than one, append error.
error_list.append(
f"The README has no first-level headings. One heading is expected. Skipping further validation for this README."
)
else:
# If one exactly
start_key = list(self.content.keys())[0] # Get the key
if start_key.startswith("Dataset Card for"): # Check correct start
# If the starting is correct, validate all the sections
_, sec_error_list, sec_warning_list = self.content[start_key].validate(
readme_structure["subsections"][0]
)
error_list += sec_error_list
warning_list += sec_warning_list
else:
# If not found, append error
error_list.append(
f"No first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README."
)
if error_list:
# If there are errors, do not return the dictionary as it is invalid
return {}, error_list, warning_list
else:
return self.to_dict(), error_list, warning_list
if __name__ == "__main__":
from argparse import ArgumentParser
ap = ArgumentParser(usage="Validate the content (excluding YAML tags) of a README.md file.")
ap.add_argument("readme_filepath")
args = ap.parse_args()
readme_filepath = Path(args.readme_filepath)
readme = ReadMe.from_readme(readme_filepath)
| import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Any, List, Tuple
import yaml
# loading package files: https://stackoverflow.com/a/20885799
try:
import importlib.resources as pkg_resources
except ImportError:
# Try backported to PY<37 `importlib_resources`.
import importlib_resources as pkg_resources
from . import resources
BASE_REF_URL = "https://github.com/huggingface/datasets/tree/master/src/datasets/utils"
this_url = f"{BASE_REF_URL}/{__file__}"
logger = logging.getLogger(__name__)
def load_yaml_resource(resource: str) -> Tuple[Any, str]:
content = pkg_resources.read_text(resources, resource)
return yaml.safe_load(content), f"{BASE_REF_URL}/resources/{resource}"
readme_structure, known_readme_structure_url = load_yaml_resource("readme_structure.yaml")
FILLER_TEXT = [
"[Needs More Information]",
"[More Information Needed]",
"(https://github.com/huggingface/datasets/blob/master/CONTRIBUTING.md#how-to-contribute-to-the-dataset-cards)",
]
# Dictionary representation of section/readme, error_list, warning_list
ReadmeValidatorOutput = Tuple[dict, List[str], List[str]]
@dataclass
class Section:
name: str
level: str
lines: List[str] = None
def __post_init__(self):
self.text = ""
self.is_empty_text = True
self.content = {}
self.parsing_error_list = []
self.parsing_warning_list = []
if self.lines is not None:
self.parse()
def parse(self):
current_sub_level = ""
current_lines = []
code_start = False
for line in self.lines:
if line.strip(" \n") == "":
continue
elif line.strip(" \n")[:3] == "```":
code_start = not code_start
elif line.split()[0] == self.level + "#" and not code_start:
if current_sub_level != "":
self.content[current_sub_level] = Section(current_sub_level, self.level + "#", current_lines)
current_lines = []
else:
if current_lines != []:
self.text += "".join(current_lines).strip()
if self.text != "" and self.text not in FILLER_TEXT:
self.is_empty_text = False
current_lines = []
current_sub_level = " ".join(line.split()[1:]).strip(" \n")
else:
current_lines.append(line)
else:
if current_sub_level != "":
if current_sub_level in self.content:
self.parsing_error_list.append(
f"Multiple sections with the same heading `{current_sub_level}` have been found. Please keep only one of these sections."
)
self.content[current_sub_level] = Section(current_sub_level, self.level + "#", current_lines)
else:
if current_lines != []:
self.text += "".join(current_lines).strip()
if self.text != "" and self.text not in FILLER_TEXT:
self.is_empty_text = False
def validate(self, structure: dict) -> ReadmeValidatorOutput:
"""Validates a Section class object recursively using the structure provided as a dictionary.
Args:
structute (:obj: `dict`): The dictionary representing expected structure.
Returns:
:obj: `ReadmeValidatorOutput`: The dictionary representation of the section, and the errors.
"""
# Header text validation
error_list = []
warning_list = []
if structure["allow_empty"] is False:
# If content is expected
if self.is_empty_text and self.content == {}:
# If no content is found, mention it in the error_list
error_list.append(f"Expected some content in section `{self.name}` but it is empty.")
if structure["allow_empty_text"] is False:
# If some text is expected
if self.is_empty_text:
# If no text is found, mention it in the error_list
error_list.append(
f"Expected some text in section `{self.name}` but it is empty (text in subsections are ignored)."
)
# Subsections Validation
if structure["subsections"] is not None:
# If subsections are expected
if self.content == {}:
# If no subsections are present
values = [subsection["name"] for subsection in structure["subsections"]]
# Mention the expected values in the error_list
error_list.append(
f"Section `{self.name}` expected the following subsections: {', '.join(['`'+x+'`' for x in values])}. Found 'None'."
)
else:
# If some subsections are present
structure_names = [subsection["name"] for subsection in structure["subsections"]]
for idx, name in enumerate(structure_names):
if name not in self.content:
# If the expected subsection is not present
error_list.append(f"Section `{self.name}` is missing subsection: `{name}`.")
else:
# If the subsection is present, validate subsection, return the result
# and concat the errors from subsection to section error_list
# Skip sublevel validation if current level is `###`
if self.level == "###":
continue
else:
_, subsec_error_list, subsec_warning_list = self.content[name].validate(
structure["subsections"][idx]
)
error_list += subsec_error_list
warning_list += subsec_warning_list
for name in self.content:
if name not in structure_names:
# If an extra subsection is present
warning_list.append(
f"`{self.name}` has an extra subsection: `{name}`. Skipping further validation checks for this subsection as expected structure is unknown."
)
error_list = self.parsing_error_list + error_list
warning_list = self.parsing_warning_list + warning_list
if error_list:
# If there are errors, do not return the dictionary as it is invalid
return {}, error_list, warning_list
else:
return self.to_dict(), error_list, warning_list
def to_dict(self) -> dict:
"""Returns the dictionary representation of a section."""
return {
"name": self.name,
"text": self.text,
"is_empty_text": self.is_empty_text,
"subsections": [value.to_dict() for value in self.content.values()],
}
class ReadMe(Section): # Level 0
def __init__(self, name: str, lines: List[str], structure: dict = None):
super().__init__(name=name, level="") # Not using lines here as we need to use a child class parse
self.structure = structure
self.yaml_tags_line_count = -2
self.tag_count = 0
self.lines = lines
if self.lines is not None:
self.parse()
# Validation
if self.structure is None:
content, error_list, warning_list = self.validate(readme_structure)
else:
content, error_list, warning_list = self.validate(self.structure)
error_list = self.parsing_error_list + error_list
warning_list = self.parsing_warning_list + warning_list
if error_list != [] or warning_list != []:
errors = "\n".join(list(map(lambda x: "-\t" + x, error_list + warning_list)))
error_string = f"The following issues were found for the README at `{self.name}`:\n" + errors
raise ValueError(error_string)
@classmethod
def from_readme(cls, path: Path, structure: dict = None):
with open(path, encoding="utf-8") as f:
lines = f.readlines()
return cls(path, lines, structure)
@classmethod
def from_string(cls, string: str, structure: dict = None, root_name: str = "root"):
lines = string.split("\n")
return cls(root_name, lines, structure)
def parse(self):
# Skip Tags
line_count = 0
for line in self.lines:
self.yaml_tags_line_count += 1
if line.strip(" \n") == "---":
self.tag_count += 1
if self.tag_count == 2:
break
line_count += 1
if self.tag_count == 2:
self.lines = self.lines[line_count + 1 :] # Get the last + 1 th item.
else:
self.lines = self.lines[self.tag_count :]
super().parse()
def __str__(self):
"""Returns the string of dictionary representation of the ReadMe."""
return str(self.to_dict())
def validate(self, readme_structure):
error_list = []
warning_list = []
if self.yaml_tags_line_count == 0:
warning_list.append("Empty YAML markers are present in the README.")
elif self.tag_count == 0:
warning_list.append("No YAML markers are present in the README.")
elif self.tag_count == 1:
warning_list.append("Only the start of YAML tags present in the README.")
# Check how many first level sections are present.
num_first_level_keys = len(self.content.keys())
if num_first_level_keys > 1:
# If more than one, add to the error list, continue
error_list.append(
f"The README has several first-level headings: {', '.join(['`'+x+'`' for x in list(self.content.keys())])}. Only one heading is expected. Skipping further validation for this README."
)
elif num_first_level_keys < 1:
# If less than one, append error.
error_list.append(
f"The README has no first-level headings. One heading is expected. Skipping further validation for this README."
)
else:
# If one exactly
start_key = list(self.content.keys())[0] # Get the key
if start_key.startswith("Dataset Card for"): # Check correct start
# If the starting is correct, validate all the sections
_, sec_error_list, sec_warning_list = self.content[start_key].validate(
readme_structure["subsections"][0]
)
error_list += sec_error_list
warning_list += sec_warning_list
else:
# If not found, append error
error_list.append(
f"No first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README."
)
if error_list:
# If there are errors, do not return the dictionary as it is invalid
return {}, error_list, warning_list
else:
return self.to_dict(), error_list, warning_list
if __name__ == "__main__":
from argparse import ArgumentParser
ap = ArgumentParser(usage="Validate the content (excluding YAML tags) of a README.md file.")
ap.add_argument("readme_filepath")
args = ap.parse_args()
readme_filepath = Path(args.readme_filepath)
readme = ReadMe.from_readme(readme_filepath)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.