hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c3f95a51251d4cf6c48c3abb5bd40665ab2c61e | 4,984 | py | Python | bcbio/pipeline/fastq.py | arvados/bcbio-nextgen | 2a5cfa8c3a1d540bb2f2e66f51835042195cbc87 | [
"MIT"
] | null | null | null | bcbio/pipeline/fastq.py | arvados/bcbio-nextgen | 2a5cfa8c3a1d540bb2f2e66f51835042195cbc87 | [
"MIT"
] | null | null | null | bcbio/pipeline/fastq.py | arvados/bcbio-nextgen | 2a5cfa8c3a1d540bb2f2e66f51835042195cbc87 | [
"MIT"
] | null | null | null | """Pipeline utilities to retrieve FASTQ formatted files for processing.
"""
import os
import sys
from bcbio import bam, broad, utils
from bcbio.bam import fastq
from bcbio.bam import cram
from bcbio.pipeline import alignment
from bcbio.utils import file_exists, safe_makedir, splitext_plus
from bcbio.provenance import do
from bcbio.distributed.transaction import file_transaction
def get_fastq_files(data):
"""Retrieve fastq files for the given lane, ready to process.
"""
assert "files" in data, "Did not find `files` in input; nothing to process"
ready_files = []
should_gzip = True
# Bowtie does not accept gzipped fastq
if 'bowtie' in data['reference'].keys():
should_gzip = False
for fname in data["files"]:
if fname.endswith(".bam"):
if _pipeline_needs_fastq(data["config"], data):
ready_files = _convert_bam_to_fastq(fname, data["dirs"]["work"],
data, data["dirs"], data["config"])
else:
ready_files = [fname]
elif fname.startswith(utils.SUPPORTED_REMOTES):
ready_files.append(fname)
else:
ready_files.append(fname)
ready_files = [x for x in ready_files if x is not None]
if should_gzip:
ready_files = [_gzip_fastq(x) for x in ready_files]
for in_file in ready_files:
if not in_file.startswith(utils.SUPPORTED_REMOTES):
assert os.path.exists(in_file), "%s does not exist." % in_file
return ((ready_files[0] if len(ready_files) > 0 else None),
(ready_files[1] if len(ready_files) > 1 else None))
def _gzip_fastq(in_file):
"""
gzip a fastq file if it is not already gzipped
"""
if (fastq.is_fastq(in_file) and not utils.is_gzipped(in_file)
and not in_file.startswith(utils.SUPPORTED_REMOTES)):
gzipped_file = in_file + ".gz"
if file_exists(gzipped_file):
return gzipped_file
message = "gzipping {in_file}.".format(in_file=in_file)
do.run("gzip -c {in_file} > {gzipped_file}".format(**locals()), message)
return gzipped_file
return in_file
def _pipeline_needs_fastq(config, data):
"""Determine if the pipeline can proceed with a BAM file, or needs fastq conversion.
"""
aligner = config["algorithm"].get("aligner")
support_bam = aligner in alignment.metadata.get("support_bam", [])
return aligner and not support_bam
def _convert_bam_to_fastq(in_file, work_dir, data, dirs, config):
"""Convert BAM input file into FASTQ files.
"""
out_dir = safe_makedir(os.path.join(work_dir, "fastq_convert"))
qual_bin_method = config["algorithm"].get("quality_bin")
if (qual_bin_method == "prealignment" or
(isinstance(qual_bin_method, list) and "prealignment" in qual_bin_method)):
out_bindir = safe_makedir(os.path.join(out_dir, "qualbin"))
in_file = cram.illumina_qual_bin(in_file, data["sam_ref"], out_bindir, config)
out_files = [os.path.join(out_dir, "{0}_{1}.fastq".format(
os.path.splitext(os.path.basename(in_file))[0], x))
for x in ["1", "2"]]
if bam.is_paired(in_file):
out1, out2 = out_files
else:
out1 = out_files[0]
out2 = None
if not file_exists(out1):
broad_runner = broad.runner_from_config(config)
broad_runner.run_fn("picard_bam_to_fastq", in_file, out1, out2)
if out2 and os.path.getsize(out2) == 0:
out2 = None
return [out1, out2]
def merge(files, out_file, config):
"""merge smartly fastq files. It recognizes paired fastq files."""
pair1 = [fastq_file[0] for fastq_file in files]
if len(files[0]) > 1:
path = splitext_plus(out_file)
pair1_out_file = path[0] + "_R1" + path[1]
pair2 = [fastq_file[1] for fastq_file in files]
pair2_out_file = path[0] + "_R2" + path[1]
_merge_list_fastqs(pair1, pair1_out_file, config)
_merge_list_fastqs(pair2, pair2_out_file, config)
return [pair1_out_file, pair2_out_file]
else:
return _merge_list_fastqs(pair1, out_file, config)
def _merge_list_fastqs(files, out_file, config):
"""merge list of fastq files into one"""
if not all(map(fastq.is_fastq, files)):
raise ValueError("Not all of the files to merge are fastq files: %s " % (files))
assert all(map(utils.file_exists, files)), ("Not all of the files to merge "
"exist: %s" % (files))
if not os.path.exists(out_file):
if len(files) == 1:
os.symlink(files[0], out_file)
return out_file
gz_files = [_gzip_fastq(fn) for fn in files]
with file_transaction(out_file) as file_txt_out:
files_str = " ".join(list(gz_files))
cmd = "cat {files_str} > {file_txt_out}".format(**locals())
do.run(cmd, "merge fastq files")
return out_file
| 41.190083 | 88 | 0.642055 | import os
import sys
from bcbio import bam, broad, utils
from bcbio.bam import fastq
from bcbio.bam import cram
from bcbio.pipeline import alignment
from bcbio.utils import file_exists, safe_makedir, splitext_plus
from bcbio.provenance import do
from bcbio.distributed.transaction import file_transaction
def get_fastq_files(data):
assert "files" in data, "Did not find `files` in input; nothing to process"
ready_files = []
should_gzip = True
if 'bowtie' in data['reference'].keys():
should_gzip = False
for fname in data["files"]:
if fname.endswith(".bam"):
if _pipeline_needs_fastq(data["config"], data):
ready_files = _convert_bam_to_fastq(fname, data["dirs"]["work"],
data, data["dirs"], data["config"])
else:
ready_files = [fname]
elif fname.startswith(utils.SUPPORTED_REMOTES):
ready_files.append(fname)
else:
ready_files.append(fname)
ready_files = [x for x in ready_files if x is not None]
if should_gzip:
ready_files = [_gzip_fastq(x) for x in ready_files]
for in_file in ready_files:
if not in_file.startswith(utils.SUPPORTED_REMOTES):
assert os.path.exists(in_file), "%s does not exist." % in_file
return ((ready_files[0] if len(ready_files) > 0 else None),
(ready_files[1] if len(ready_files) > 1 else None))
def _gzip_fastq(in_file):
if (fastq.is_fastq(in_file) and not utils.is_gzipped(in_file)
and not in_file.startswith(utils.SUPPORTED_REMOTES)):
gzipped_file = in_file + ".gz"
if file_exists(gzipped_file):
return gzipped_file
message = "gzipping {in_file}.".format(in_file=in_file)
do.run("gzip -c {in_file} > {gzipped_file}".format(**locals()), message)
return gzipped_file
return in_file
def _pipeline_needs_fastq(config, data):
aligner = config["algorithm"].get("aligner")
support_bam = aligner in alignment.metadata.get("support_bam", [])
return aligner and not support_bam
def _convert_bam_to_fastq(in_file, work_dir, data, dirs, config):
out_dir = safe_makedir(os.path.join(work_dir, "fastq_convert"))
qual_bin_method = config["algorithm"].get("quality_bin")
if (qual_bin_method == "prealignment" or
(isinstance(qual_bin_method, list) and "prealignment" in qual_bin_method)):
out_bindir = safe_makedir(os.path.join(out_dir, "qualbin"))
in_file = cram.illumina_qual_bin(in_file, data["sam_ref"], out_bindir, config)
out_files = [os.path.join(out_dir, "{0}_{1}.fastq".format(
os.path.splitext(os.path.basename(in_file))[0], x))
for x in ["1", "2"]]
if bam.is_paired(in_file):
out1, out2 = out_files
else:
out1 = out_files[0]
out2 = None
if not file_exists(out1):
broad_runner = broad.runner_from_config(config)
broad_runner.run_fn("picard_bam_to_fastq", in_file, out1, out2)
if out2 and os.path.getsize(out2) == 0:
out2 = None
return [out1, out2]
def merge(files, out_file, config):
pair1 = [fastq_file[0] for fastq_file in files]
if len(files[0]) > 1:
path = splitext_plus(out_file)
pair1_out_file = path[0] + "_R1" + path[1]
pair2 = [fastq_file[1] for fastq_file in files]
pair2_out_file = path[0] + "_R2" + path[1]
_merge_list_fastqs(pair1, pair1_out_file, config)
_merge_list_fastqs(pair2, pair2_out_file, config)
return [pair1_out_file, pair2_out_file]
else:
return _merge_list_fastqs(pair1, out_file, config)
def _merge_list_fastqs(files, out_file, config):
if not all(map(fastq.is_fastq, files)):
raise ValueError("Not all of the files to merge are fastq files: %s " % (files))
assert all(map(utils.file_exists, files)), ("Not all of the files to merge "
"exist: %s" % (files))
if not os.path.exists(out_file):
if len(files) == 1:
os.symlink(files[0], out_file)
return out_file
gz_files = [_gzip_fastq(fn) for fn in files]
with file_transaction(out_file) as file_txt_out:
files_str = " ".join(list(gz_files))
cmd = "cat {files_str} > {file_txt_out}".format(**locals())
do.run(cmd, "merge fastq files")
return out_file
| true | true |
1c3f95a83bc3368b846edc6e57fe656d9a2c100c | 5,821 | py | Python | rocket_soc/lib/templates/lut-gamma-application/filter-image.py | PACO-CPU/rocket-soc | 34e10472a51830669bae3635dae6d52b8b41426d | [
"BSD-2-Clause"
] | 2 | 2017-08-11T13:15:02.000Z | 2019-01-15T10:10:58.000Z | rocket_soc/lib/templates/lut-gamma-application/filter-image.py | PACO-CPU/rocket-soc | 34e10472a51830669bae3635dae6d52b8b41426d | [
"BSD-2-Clause"
] | null | null | null | rocket_soc/lib/templates/lut-gamma-application/filter-image.py | PACO-CPU/rocket-soc | 34e10472a51830669bae3635dae6d52b8b41426d | [
"BSD-2-Clause"
] | 3 | 2019-01-15T10:11:00.000Z | 2020-10-14T18:18:01.000Z | #!/usr/bin/env python3
import sys
import time
import struct
import os.path
import serial
import threading
import re
import subprocess
from paco import util
from PIL import Image
port="/dev/ttyUSB0"
baud=115200
fRunRocket=False
fRunPython=False
filenames=[]
def print_help(f):
f.write(
"filter-image.py [options] file1 [file2 ...]\n"
"applies gamma correction to a specified image\n"
"options:\n"
" --rocket\n"
" run the filter on the rocket core.\n"
" --python\n"
" run the filter in python (quality reference)\n"
" -p|--port <port>\n"
" specify the port to be used for UART communication with the rocket\n"
" SoC. Default: {port}\n"
" -b|--baud <baudrate>\n"
" specify the baud rate used by the UART interface. default: {baud}\n"
"".format(port=port,baud=baud)
)
try:
s=None
for arg in sys.argv[1:]:
if s==None:
if arg[:1]=="-":
if arg in {"--rocket"}: fRunRocket=True
elif arg in {"--python"}: fRunPython=True
elif arg in {"-p","--port"}: s="--port"
elif arg in {"-b","--baud"}: s="--baud"
elif arg in {"-h","--help"}:
print_help(sys.stdout)
sys.exit(0)
else:
raise Exception("unrecognized switch: %s"%arg)
else:
filenames.append(arg)
elif s=="--baud":
baud=int(arg)
s=None
elif s=="--port":
port=arg
s=None
if len(filenames)<1:
raise Exception("no filename specified")
if (fRunRocket+fRunPython)<1:
raise Exception("no target selected to run on")
except Exception as e:
sys.stderr.write("\x1b[31;1mERROR\x1b[30;0m: %s\n"%e)
print_help(sys.stderr)
raise
sys.exit(1)
CMD_PUT_BLOCK=0x12
CMD_GET_BLOCK=0x32
CMD_EXECUTE=0x44
CMD_INFO=0x01
block_size=100000
EXPONENT=1.99
class ReadBuffer(threading.Thread):
def __init__(s,iface):
s._iface=iface
s._mutex=threading.Lock()
s._cond=threading.Condition(s._mutex)
s._buffer=[]
threading.Thread.__init__(s)
def run(s):
s._running=True
while s._running:
buf=s._iface.read(1)
with s._mutex:
s._buffer.append(buf[0])
s._cond.notifyAll()
def terminate(s):
s._running=False
def write(s,data):
s._iface.write(data)
def read(s,cb):
with s._mutex:
while len(s._buffer)<cb:
s._cond.wait()
res=bytes(s._buffer[:cb])
s._buffer=s._buffer[cb:]
return res
if fRunRocket:
with open("mode.h","w") as f:
f.write("#define MODE MODE_STATIC")
if fRunRocket and False:
rocket=ReadBuffer(serial.Serial(port=port,baudrate=baud))
rocket.start()
for i in range(120):
rocket.write(struct.pack("<B",CMD_INFO))
(block_size,)=struct.unpack("<I",rocket.read(4))
print("rocket connected. block size: %i"%(block_size))
def rocket_process_block(buf,res1,res2):
with open("image.h","w") as f:
f.write("uint32_t image[] = {%s};\n"%",".join(["0x%xuL"%(v<<16) for v in buf]))
p=subprocess.Popen("CMP_FIXMATH=1 make run",shell=True,stdout=subprocess.PIPE)
e=re.compile(".*\x1b\\[3.;1m([0-9a-fA-F]+) ([0-9a-fA-F]+).*")
n_read1=0
n_read2=0
state=0
for ln in p.stdout:
ln=ln.decode()
if ln.find("computing image..")!=-1:
state=1
sys.stdout.write(ln)
continue
elif ln.find("computing image (fixmath)..")!=-1:
state=2
sys.stdout.write(ln)
continue
elif state==0:
sys.stdout.write(ln)
continue
m=e.match(ln.strip())
if not m:
sys.stdout.write(ln)
continue
# perform conversion to signed integer
v=int(m.groups()[1],16)%0xffffffff
if v&0x80000000:
v-=0x100000000
# only use top 8 bits
v>>=16
if state==1:
res1.append(v)
n_read1+=1
elif state==2:
res2.append(v)
n_read2+=1
print(
"%i -> %i,%i (total: %i,%i)"%(len(buf),n_read1,n_read2,len(res1),len(res2)))
return res1,res2
def rocket_process(buf,pb):
res1=[]
res2=[]
for i in range(0,len(buf),block_size):
rocket_process_block(buf[i:i+block_size],res1,res2)
return res1,res2
def python_process(buf,pb):
res=list(buf)
for i,v in enumerate(buf):
res[i]= min(2**8-1,max(0,int(255.0/(255.0**EXPONENT)*v**EXPONENT)))
pb.increment()
return res
for fn in filenames:
print("loading file %s"%fn)
img=Image.open(fn)
in_data=img.getdata()
print("done. size: %s x %s"%img.size)
in_comp=[
[ pix[k] for pix in in_data ]
for k in range(3) ]
rocket_comp_lut=[
[ 0 for v in strm]
for strm in in_comp]
rocket_comp_fix=[
[ 0 for v in strm]
for strm in in_comp]
python_comp=[
strm
for strm in in_comp]
if fRunRocket:
sys.stdout.write(" computing on rocket.. ")
sys.stdout.flush()
rocket_comp_lut=[]
rocket_comp_fix=[]
with util.ProgressBar(0,len(in_data)*len(in_comp)) as pb:
for strm in in_comp:
(lut,fix)=rocket_process(strm,pb)
rocket_comp_lut.append(lut)
rocket_comp_fix.append(fix)
if fRunPython:
sys.stdout.write(" computing on host.. ")
sys.stdout.flush()
with util.ProgressBar(0,len(in_data)*len(in_comp)) as pb:
python_comp=[
python_process(strm,pb)
for strm in in_comp]
pix_out=b""
print(" outputting..")
(w,h)=img.size
for y in reversed(range(h)):
for comps in [ in_comp,rocket_comp_lut,rocket_comp_fix,python_comp ]:
pix_out+= (
b"".join(
[
struct.pack(
"BBB",
*[min(255,max(0,comps[k][y*w+x])) for k in range(len(in_comp))])
for x in range(w) ]))
img_out=Image.frombuffer("RGB",(w*4,h),pix_out)
(fc,fe)=os.path.splitext(fn)
img_out.save("%s-out%s"%(fc,fe))
if fRunRocket and False:
rocket.terminate()
| 23.37751 | 83 | 0.606769 |
import sys
import time
import struct
import os.path
import serial
import threading
import re
import subprocess
from paco import util
from PIL import Image
port="/dev/ttyUSB0"
baud=115200
fRunRocket=False
fRunPython=False
filenames=[]
def print_help(f):
f.write(
"filter-image.py [options] file1 [file2 ...]\n"
"applies gamma correction to a specified image\n"
"options:\n"
" --rocket\n"
" run the filter on the rocket core.\n"
" --python\n"
" run the filter in python (quality reference)\n"
" -p|--port <port>\n"
" specify the port to be used for UART communication with the rocket\n"
" SoC. Default: {port}\n"
" -b|--baud <baudrate>\n"
" specify the baud rate used by the UART interface. default: {baud}\n"
"".format(port=port,baud=baud)
)
try:
s=None
for arg in sys.argv[1:]:
if s==None:
if arg[:1]=="-":
if arg in {"--rocket"}: fRunRocket=True
elif arg in {"--python"}: fRunPython=True
elif arg in {"-p","--port"}: s="--port"
elif arg in {"-b","--baud"}: s="--baud"
elif arg in {"-h","--help"}:
print_help(sys.stdout)
sys.exit(0)
else:
raise Exception("unrecognized switch: %s"%arg)
else:
filenames.append(arg)
elif s=="--baud":
baud=int(arg)
s=None
elif s=="--port":
port=arg
s=None
if len(filenames)<1:
raise Exception("no filename specified")
if (fRunRocket+fRunPython)<1:
raise Exception("no target selected to run on")
except Exception as e:
sys.stderr.write("\x1b[31;1mERROR\x1b[30;0m: %s\n"%e)
print_help(sys.stderr)
raise
sys.exit(1)
CMD_PUT_BLOCK=0x12
CMD_GET_BLOCK=0x32
CMD_EXECUTE=0x44
CMD_INFO=0x01
block_size=100000
EXPONENT=1.99
class ReadBuffer(threading.Thread):
def __init__(s,iface):
s._iface=iface
s._mutex=threading.Lock()
s._cond=threading.Condition(s._mutex)
s._buffer=[]
threading.Thread.__init__(s)
def run(s):
s._running=True
while s._running:
buf=s._iface.read(1)
with s._mutex:
s._buffer.append(buf[0])
s._cond.notifyAll()
def terminate(s):
s._running=False
def write(s,data):
s._iface.write(data)
def read(s,cb):
with s._mutex:
while len(s._buffer)<cb:
s._cond.wait()
res=bytes(s._buffer[:cb])
s._buffer=s._buffer[cb:]
return res
if fRunRocket:
with open("mode.h","w") as f:
f.write("#define MODE MODE_STATIC")
if fRunRocket and False:
rocket=ReadBuffer(serial.Serial(port=port,baudrate=baud))
rocket.start()
for i in range(120):
rocket.write(struct.pack("<B",CMD_INFO))
(block_size,)=struct.unpack("<I",rocket.read(4))
print("rocket connected. block size: %i"%(block_size))
def rocket_process_block(buf,res1,res2):
with open("image.h","w") as f:
f.write("uint32_t image[] = {%s};\n"%",".join(["0x%xuL"%(v<<16) for v in buf]))
p=subprocess.Popen("CMP_FIXMATH=1 make run",shell=True,stdout=subprocess.PIPE)
e=re.compile(".*\x1b\\[3.;1m([0-9a-fA-F]+) ([0-9a-fA-F]+).*")
n_read1=0
n_read2=0
state=0
for ln in p.stdout:
ln=ln.decode()
if ln.find("computing image..")!=-1:
state=1
sys.stdout.write(ln)
continue
elif ln.find("computing image (fixmath)..")!=-1:
state=2
sys.stdout.write(ln)
continue
elif state==0:
sys.stdout.write(ln)
continue
m=e.match(ln.strip())
if not m:
sys.stdout.write(ln)
continue
v=int(m.groups()[1],16)%0xffffffff
if v&0x80000000:
v-=0x100000000
v>>=16
if state==1:
res1.append(v)
n_read1+=1
elif state==2:
res2.append(v)
n_read2+=1
print(
"%i -> %i,%i (total: %i,%i)"%(len(buf),n_read1,n_read2,len(res1),len(res2)))
return res1,res2
def rocket_process(buf,pb):
res1=[]
res2=[]
for i in range(0,len(buf),block_size):
rocket_process_block(buf[i:i+block_size],res1,res2)
return res1,res2
def python_process(buf,pb):
res=list(buf)
for i,v in enumerate(buf):
res[i]= min(2**8-1,max(0,int(255.0/(255.0**EXPONENT)*v**EXPONENT)))
pb.increment()
return res
for fn in filenames:
print("loading file %s"%fn)
img=Image.open(fn)
in_data=img.getdata()
print("done. size: %s x %s"%img.size)
in_comp=[
[ pix[k] for pix in in_data ]
for k in range(3) ]
rocket_comp_lut=[
[ 0 for v in strm]
for strm in in_comp]
rocket_comp_fix=[
[ 0 for v in strm]
for strm in in_comp]
python_comp=[
strm
for strm in in_comp]
if fRunRocket:
sys.stdout.write(" computing on rocket.. ")
sys.stdout.flush()
rocket_comp_lut=[]
rocket_comp_fix=[]
with util.ProgressBar(0,len(in_data)*len(in_comp)) as pb:
for strm in in_comp:
(lut,fix)=rocket_process(strm,pb)
rocket_comp_lut.append(lut)
rocket_comp_fix.append(fix)
if fRunPython:
sys.stdout.write(" computing on host.. ")
sys.stdout.flush()
with util.ProgressBar(0,len(in_data)*len(in_comp)) as pb:
python_comp=[
python_process(strm,pb)
for strm in in_comp]
pix_out=b""
print(" outputting..")
(w,h)=img.size
for y in reversed(range(h)):
for comps in [ in_comp,rocket_comp_lut,rocket_comp_fix,python_comp ]:
pix_out+= (
b"".join(
[
struct.pack(
"BBB",
*[min(255,max(0,comps[k][y*w+x])) for k in range(len(in_comp))])
for x in range(w) ]))
img_out=Image.frombuffer("RGB",(w*4,h),pix_out)
(fc,fe)=os.path.splitext(fn)
img_out.save("%s-out%s"%(fc,fe))
if fRunRocket and False:
rocket.terminate()
| true | true |
1c3f95b5f09f03b747ec1fdd2b7a742a398b2bbc | 429 | py | Python | Giraffe/If statement.py | MaggieIllustrations/softuni-github-programming | f5695cb14602f3d2974359f6d8734332acc650d3 | [
"MIT"
] | null | null | null | Giraffe/If statement.py | MaggieIllustrations/softuni-github-programming | f5695cb14602f3d2974359f6d8734332acc650d3 | [
"MIT"
] | null | null | null | Giraffe/If statement.py | MaggieIllustrations/softuni-github-programming | f5695cb14602f3d2974359f6d8734332acc650d3 | [
"MIT"
] | 1 | 2022-01-14T17:12:44.000Z | 2022-01-14T17:12:44.000Z | is_male = True
is_tall = True
if is_male or is_tall:
print("You are a male or tall or both")
else:
print("You are neither male no tall")
is_male = False
is_tall = False
if is_male and is_tall:
print("You are a tall male")
elif is_male and not(is_tall):
print("You are a short male")
elif is_male and not is_tall:
print("You are not a male but are tall")
else:
print("You are not a male and not tall") | 20.428571 | 44 | 0.685315 | is_male = True
is_tall = True
if is_male or is_tall:
print("You are a male or tall or both")
else:
print("You are neither male no tall")
is_male = False
is_tall = False
if is_male and is_tall:
print("You are a tall male")
elif is_male and not(is_tall):
print("You are a short male")
elif is_male and not is_tall:
print("You are not a male but are tall")
else:
print("You are not a male and not tall") | true | true |
1c3f95e1775b02a01e699032453673f89db1bf1a | 31,415 | py | Python | geopandas/tests/test_plotting.py | schilli/geopandas | 29add0a735b00dc20c79e0fccc8e6a775c4997b0 | [
"BSD-3-Clause"
] | 1 | 2022-01-12T09:00:54.000Z | 2022-01-12T09:00:54.000Z | geopandas/tests/test_plotting.py | samuelduchesne/geopandas | 29add0a735b00dc20c79e0fccc8e6a775c4997b0 | [
"BSD-3-Clause"
] | null | null | null | geopandas/tests/test_plotting.py | samuelduchesne/geopandas | 29add0a735b00dc20c79e0fccc8e6a775c4997b0 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import absolute_import, division
import itertools
import warnings
import numpy as np
from shapely.affinity import rotate
from shapely.geometry import MultiPolygon, Polygon, LineString, Point, MultiPoint
from geopandas import GeoSeries, GeoDataFrame, read_file
from geopandas.datasets import get_path
import pytest
matplotlib = pytest.importorskip('matplotlib')
matplotlib.use('Agg')
import matplotlib.pyplot as plt
@pytest.fixture(autouse=True)
def close_figures(request):
yield
plt.close('all')
try:
cycle = matplotlib.rcParams['axes.prop_cycle'].by_key()
MPL_DFT_COLOR = cycle['color'][0]
except KeyError:
MPL_DFT_COLOR = matplotlib.rcParams['axes.color_cycle'][0]
class TestPointPlotting:
def setup_method(self):
self.N = 10
self.points = GeoSeries(Point(i, i) for i in range(self.N))
values = np.arange(self.N)
self.df = GeoDataFrame({'geometry': self.points, 'values': values})
multipoint1 = MultiPoint(self.points)
multipoint2 = rotate(multipoint1, 90)
self.df2 = GeoDataFrame({'geometry': [multipoint1, multipoint2],
'values': [0, 1]})
def test_figsize(self):
ax = self.points.plot(figsize=(1, 1))
np.testing.assert_array_equal(ax.figure.get_size_inches(), (1, 1))
ax = self.df.plot(figsize=(1, 1))
np.testing.assert_array_equal(ax.figure.get_size_inches(), (1, 1))
def test_default_colors(self):
# # without specifying values -> uniform color
# GeoSeries
ax = self.points.plot()
_check_colors(self.N, ax.collections[0].get_facecolors(),
[MPL_DFT_COLOR] * self.N)
# GeoDataFrame
ax = self.df.plot()
_check_colors(self.N, ax.collections[0].get_facecolors(),
[MPL_DFT_COLOR] * self.N)
# # with specifying values -> different colors for all 10 values
ax = self.df.plot(column='values')
cmap = plt.get_cmap()
expected_colors = cmap(np.arange(self.N)/(self.N-1))
_check_colors(self.N, ax.collections[0].get_facecolors(),
expected_colors)
def test_colormap(self):
# without specifying values but cmap specified -> no uniform color
# but different colors for all points
# GeoSeries
ax = self.points.plot(cmap='RdYlGn')
cmap = plt.get_cmap('RdYlGn')
exp_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)
ax = self.df.plot(cmap='RdYlGn')
_check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)
# # with specifying values -> different colors for all 10 values
ax = self.df.plot(column='values', cmap='RdYlGn')
cmap = plt.get_cmap('RdYlGn')
_check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)
# when using a cmap with specified lut -> limited number of different
# colors
ax = self.points.plot(cmap=plt.get_cmap('Set1', lut=5))
cmap = plt.get_cmap('Set1', lut=5)
exp_colors = cmap(list(range(5))*3)
_check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)
def test_single_color(self):
ax = self.points.plot(color='green')
_check_colors(self.N, ax.collections[0].get_facecolors(), ['green']*self.N)
ax = self.df.plot(color='green')
_check_colors(self.N, ax.collections[0].get_facecolors(), ['green']*self.N)
with warnings.catch_warnings(record=True) as _: # don't print warning
# 'color' overrides 'column'
ax = self.df.plot(column='values', color='green')
_check_colors(self.N, ax.collections[0].get_facecolors(), ['green']*self.N)
def test_markersize(self):
ax = self.points.plot(markersize=10)
assert ax.collections[0].get_sizes() == [10]
ax = self.df.plot(markersize=10)
assert ax.collections[0].get_sizes() == [10]
ax = self.df.plot(column='values', markersize=10)
assert ax.collections[0].get_sizes() == [10]
ax = self.df.plot(markersize='values')
assert (ax.collections[0].get_sizes() == self.df['values']).all()
ax = self.df.plot(column='values', markersize='values')
assert (ax.collections[0].get_sizes() == self.df['values']).all()
def test_style_kwargs(self):
ax = self.points.plot(edgecolors='k')
assert (ax.collections[0].get_edgecolor() == [0, 0, 0, 1]).all()
def test_legend(self):
with warnings.catch_warnings(record=True) as _: # don't print warning
# legend ignored if color is given.
ax = self.df.plot(column='values', color='green', legend=True)
assert len(ax.get_figure().axes) == 1 # no separate legend axis
# legend ignored if no column is given.
ax = self.df.plot(legend=True)
assert len(ax.get_figure().axes) == 1 # no separate legend axis
# # Continuous legend
# the colorbar matches the Point colors
ax = self.df.plot(column='values', cmap='RdYlGn', legend=True)
point_colors = ax.collections[0].get_facecolors()
cbar_colors = ax.get_figure().axes[1].collections[0].get_facecolors()
# first point == bottom of colorbar
np.testing.assert_array_equal(point_colors[0], cbar_colors[0])
# last point == top of colorbar
np.testing.assert_array_equal(point_colors[-1], cbar_colors[-1])
# # Categorical legend
# the colorbar matches the Point colors
ax = self.df.plot(column='values', categorical=True, legend=True)
point_colors = ax.collections[0].get_facecolors()
cbar_colors = ax.get_legend().axes.collections[0].get_facecolors()
# first point == bottom of colorbar
np.testing.assert_array_equal(point_colors[0], cbar_colors[0])
# last point == top of colorbar
np.testing.assert_array_equal(point_colors[-1], cbar_colors[-1])
def test_empty_plot(self):
s = GeoSeries([])
with pytest.warns(UserWarning):
ax = s.plot()
assert len(ax.collections) == 0
df = GeoDataFrame([])
with pytest.warns(UserWarning):
ax = df.plot()
assert len(ax.collections) == 0
def test_multipoints(self):
# MultiPoints
ax = self.df2.plot()
_check_colors(4, ax.collections[0].get_facecolors(),
[MPL_DFT_COLOR] * 4)
ax = self.df2.plot(column='values')
cmap = plt.get_cmap()
expected_colors = [cmap(0)]* self.N + [cmap(1)] * self.N
_check_colors(2, ax.collections[0].get_facecolors(),
expected_colors)
class TestPointZPlotting:
def setup_method(self):
self.N = 10
self.points = GeoSeries(Point(i, i, i) for i in range(self.N))
values = np.arange(self.N)
self.df = GeoDataFrame({'geometry': self.points, 'values': values})
def test_plot(self):
# basic test that points with z coords don't break plotting
self.df.plot()
class TestLineStringPlotting:
def setup_method(self):
self.N = 10
values = np.arange(self.N)
self.lines = GeoSeries([LineString([(0, i), (4, i+0.5), (9, i)])
for i in range(self.N)],
index=list('ABCDEFGHIJ'))
self.df = GeoDataFrame({'geometry': self.lines, 'values': values})
def test_single_color(self):
ax = self.lines.plot(color='green')
_check_colors(self.N, ax.collections[0].get_colors(), ['green']*self.N)
ax = self.df.plot(color='green')
_check_colors(self.N, ax.collections[0].get_colors(), ['green']*self.N)
with warnings.catch_warnings(record=True) as _: # don't print warning
# 'color' overrides 'column'
ax = self.df.plot(column='values', color='green')
_check_colors(self.N, ax.collections[0].get_colors(), ['green']*self.N)
def test_style_kwargs(self):
# linestyle (style patterns depend on linewidth, therefore pin to 1)
linestyle = 'dashed'
linewidth = 1
ax = self.lines.plot(linestyle=linestyle, linewidth=linewidth)
exp_ls = _style_to_linestring_onoffseq(linestyle, linewidth)
for ls in ax.collections[0].get_linestyles():
assert ls[0] == exp_ls[0]
assert ls[1] == exp_ls[1]
ax = self.df.plot(linestyle=linestyle, linewidth=linewidth)
for ls in ax.collections[0].get_linestyles():
assert ls[0] == exp_ls[0]
assert ls[1] == exp_ls[1]
ax = self.df.plot(column='values', linestyle=linestyle,
linewidth=linewidth)
for ls in ax.collections[0].get_linestyles():
assert ls[0] == exp_ls[0]
assert ls[1] == exp_ls[1]
class TestPolygonPlotting:
def setup_method(self):
t1 = Polygon([(0, 0), (1, 0), (1, 1)])
t2 = Polygon([(1, 0), (2, 0), (2, 1)])
self.polys = GeoSeries([t1, t2], index=list('AB'))
self.df = GeoDataFrame({'geometry': self.polys, 'values': [0, 1]})
multipoly1 = MultiPolygon([t1, t2])
multipoly2 = rotate(multipoly1, 180)
self.df2 = GeoDataFrame({'geometry': [multipoly1, multipoly2],
'values': [0, 1]})
t3 = Polygon([(2, 0), (3, 0), (3, 1)])
df_nan = GeoDataFrame({'geometry': t3, 'values': [np.nan]})
self.df3 = self.df.append(df_nan)
def test_single_color(self):
ax = self.polys.plot(color='green')
_check_colors(2, ax.collections[0].get_facecolors(), ['green']*2)
# color only sets facecolor
_check_colors(2, ax.collections[0].get_edgecolors(), ['k'] * 2)
ax = self.df.plot(color='green')
_check_colors(2, ax.collections[0].get_facecolors(), ['green']*2)
_check_colors(2, ax.collections[0].get_edgecolors(), ['k'] * 2)
with warnings.catch_warnings(record=True) as _: # don't print warning
# 'color' overrides 'values'
ax = self.df.plot(column='values', color='green')
_check_colors(2, ax.collections[0].get_facecolors(), ['green']*2)
def test_vmin_vmax(self):
# when vmin == vmax, all polygons should be the same color
# non-categorical
ax = self.df.plot(column='values', categorical=False, vmin=0, vmax=0)
actual_colors = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(actual_colors[0], actual_colors[1])
# categorical
ax = self.df.plot(column='values', categorical=True, vmin=0, vmax=0)
actual_colors = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(actual_colors[0], actual_colors[1])
# vmin vmax set correctly for array with NaN (GitHub issue 877)
ax = self.df3.plot(column='values')
actual_colors = ax.collections[0].get_facecolors()
assert np.any(np.not_equal(actual_colors[0], actual_colors[1]))
def test_style_kwargs(self):
# facecolor overrides default cmap when color is not set
ax = self.polys.plot(facecolor='k')
_check_colors(2, ax.collections[0].get_facecolors(), ['k']*2)
# facecolor overrides more general-purpose color when both are set
ax = self.polys.plot(color='red', facecolor='k')
# TODO with new implementation, color overrides facecolor
# _check_colors(2, ax.collections[0], ['k']*2, alpha=0.5)
# edgecolor
ax = self.polys.plot(edgecolor='red')
np.testing.assert_array_equal([(1, 0, 0, 1)],
ax.collections[0].get_edgecolors())
ax = self.df.plot('values', edgecolor='red')
np.testing.assert_array_equal([(1, 0, 0, 1)],
ax.collections[0].get_edgecolors())
# alpha sets both edge and face
ax = self.polys.plot(facecolor='g', edgecolor='r', alpha=0.4)
_check_colors(2, ax.collections[0].get_facecolors(), ['g'] * 2, alpha=0.4)
_check_colors(2, ax.collections[0].get_edgecolors(), ['r'] * 2, alpha=0.4)
def test_legend_kwargs(self):
ax = self.df.plot(column='values', categorical=True, legend=True,
legend_kwds={'frameon': False})
assert ax.get_legend().get_frame_on() is False
def test_colorbar_kwargs(self):
# Test if kwargs are passed to colorbar
label_txt = 'colorbar test'
ax = self.df.plot(column='values', categorical=False, legend=True,
legend_kwds={'label': label_txt})
assert ax.get_figure().axes[1].get_ylabel() == label_txt
ax = self.df.plot(column='values', categorical=False, legend=True,
legend_kwds={'label': label_txt, "orientation": "horizontal"})
assert ax.get_figure().axes[1].get_xlabel() == label_txt
def test_multipolygons(self):
# MultiPolygons
ax = self.df2.plot()
assert len(ax.collections[0].get_paths()) == 4
_check_colors(4, ax.collections[0].get_facecolors(), [MPL_DFT_COLOR]*4)
ax = self.df2.plot('values')
cmap = plt.get_cmap(lut=2)
# colors are repeated for all components within a MultiPolygon
expected_colors = [cmap(0), cmap(0), cmap(1), cmap(1)]
_check_colors(4, ax.collections[0].get_facecolors(), expected_colors)
class TestPolygonZPlotting:
def setup_method(self):
t1 = Polygon([(0, 0, 0), (1, 0, 0), (1, 1, 1)])
t2 = Polygon([(1, 0, 0), (2, 0, 0), (2, 1, 1)])
self.polys = GeoSeries([t1, t2], index=list('AB'))
self.df = GeoDataFrame({'geometry': self.polys, 'values': [0, 1]})
multipoly1 = MultiPolygon([t1, t2])
multipoly2 = rotate(multipoly1, 180)
self.df2 = GeoDataFrame({'geometry': [multipoly1, multipoly2],
'values': [0, 1]})
def test_plot(self):
# basic test that points with z coords don't break plotting
self.df.plot()
class TestNonuniformGeometryPlotting:
def setup_method(self):
pytest.importorskip('matplotlib', '1.5.0')
poly = Polygon([(1, 0), (2, 0), (2, 1)])
line = LineString([(0.5, 0.5), (1, 1), (1, 0.5), (1.5, 1)])
point = Point(0.75, 0.25)
self.series = GeoSeries([poly, line, point])
self.df = GeoDataFrame({'geometry': self.series, 'values': [1, 2, 3]})
def test_colors(self):
# default uniform color
ax = self.series.plot()
_check_colors(1, ax.collections[0].get_facecolors(), [MPL_DFT_COLOR])
_check_colors(1, ax.collections[1].get_edgecolors(), [MPL_DFT_COLOR])
_check_colors(1, ax.collections[2].get_facecolors(), [MPL_DFT_COLOR])
# colormap: different colors
ax = self.series.plot(cmap='RdYlGn')
cmap = plt.get_cmap('RdYlGn')
exp_colors = cmap(np.arange(3) / (3 - 1))
_check_colors(1, ax.collections[0].get_facecolors(), [exp_colors[0]])
_check_colors(1, ax.collections[1].get_edgecolors(), [exp_colors[1]])
_check_colors(1, ax.collections[2].get_facecolors(), [exp_colors[2]])
def test_style_kwargs(self):
ax = self.series.plot(markersize=10)
assert ax.collections[2].get_sizes() == [10]
ax = self.df.plot(markersize=10)
assert ax.collections[2].get_sizes() == [10]
class TestMapclassifyPlotting:
@classmethod
def setup_class(cls):
try:
import mapclassify
except ImportError:
try:
import pysal
except ImportError:
pytest.importorskip('mapclassify')
pth = get_path('naturalearth_lowres')
cls.df = read_file(pth)
cls.df['NEGATIVES'] = np.linspace(-10, 10, len(cls.df.index))
def test_legend(self):
with warnings.catch_warnings(record=True) as _: # don't print warning
# warning coming from scipy.stats
ax = self.df.plot(column='pop_est', scheme='QUANTILES', k=3,
cmap='OrRd', legend=True)
labels = [t.get_text() for t in ax.get_legend().get_texts()]
expected = [u'140.00 - 5217064.00', u'5217064.00 - 19532732.33',
u'19532732.33 - 1379302771.00']
assert labels == expected
def test_negative_legend(self):
ax = self.df.plot(column='NEGATIVES', scheme='FISHER_JENKS', k=3,
cmap='OrRd', legend=True)
labels = [t.get_text() for t in ax.get_legend().get_texts()]
expected = [u'-10.00 - -3.41', u'-3.41 - 3.30', u'3.30 - 10.00']
assert labels == expected
@pytest.mark.parametrize('scheme', ['FISHER_JENKS', 'FISHERJENKS'])
def test_scheme_name_compat(self, scheme):
ax = self.df.plot(column='NEGATIVES', scheme=scheme, k=3, legend=True)
assert len(ax.get_legend().get_texts()) == 3
def test_classification_kwds(self):
ax = self.df.plot(column='pop_est', scheme='percentiles', k=3,
classification_kwds={'pct': [50, 100]}, cmap='OrRd',
legend=True)
labels = [t.get_text() for t in ax.get_legend().get_texts()]
expected = ['140.00 - 9961396.00', '9961396.00 - 1379302771.00']
assert labels == expected
def test_invalid_scheme(self):
with pytest.raises(ValueError):
scheme = 'invalid_scheme_*#&)(*#'
self.df.plot(column='gdp_md_est', scheme=scheme, k=3,
cmap='OrRd', legend=True)
def test_cax_legend_passing(self):
"""Pass a 'cax' argument to 'df.plot(.)', that is valid only if 'ax' is
passed as well (if not, a new figure is created ad hoc, and 'cax' is
ignored)
"""
ax = plt.axes()
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.1)
with pytest.raises(ValueError):
ax = self.df.plot(
column='pop_est', cmap='OrRd', legend=True, cax=cax
)
def test_cax_legend_height(self):
"""Pass a cax argument to 'df.plot(.)', the legend location must be
aligned with those of main plot
"""
# base case
with warnings.catch_warnings(record=True) as _: # don't print warning
ax = self.df.plot(
column='pop_est', cmap='OrRd', legend=True
)
plot_height = ax.get_figure().get_axes()[0].get_position().height
legend_height = ax.get_figure().get_axes()[1].get_position().height
assert abs(plot_height - legend_height) >= 1e-6
# fix heights with cax argument
ax2 = plt.axes()
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax2)
cax = divider.append_axes('right', size='5%', pad=0.1)
with warnings.catch_warnings(record=True) as _:
ax2 = self.df.plot(
column='pop_est', cmap='OrRd', legend=True, cax=cax, ax=ax2
)
plot_height = ax2.get_figure().get_axes()[0].get_position().height
legend_height = ax2.get_figure().get_axes()[1].get_position().height
assert abs(plot_height - legend_height) < 1e-6
class TestPlotCollections:
def setup_method(self):
self.N = 3
self.values = np.arange(self.N)
self.points = GeoSeries(Point(i, i) for i in range(self.N))
self.lines = GeoSeries([LineString([(0, i), (4, i + 0.5), (9, i)])
for i in range(self.N)])
self.polygons = GeoSeries([Polygon([(0, i), (4, i + 0.5), (9, i)])
for i in range(self.N)])
def test_points(self):
# failing with matplotlib 1.4.3 (edge stays black even when specified)
pytest.importorskip('matplotlib', '1.5.0')
from geopandas.plotting import plot_point_collection
from matplotlib.collections import PathCollection
fig, ax = plt.subplots()
coll = plot_point_collection(ax, self.points)
assert isinstance(coll, PathCollection)
ax.cla()
# default: single default matplotlib color
coll = plot_point_collection(ax, self.points)
_check_colors(self.N, coll.get_facecolors(), [MPL_DFT_COLOR] * self.N)
# edgecolor depends on matplotlib version
# _check_colors(self.N, coll.get_edgecolors(), [MPL_DFT_COLOR]*self.N)
ax.cla()
# specify single other color
coll = plot_point_collection(ax, self.points, color='g')
_check_colors(self.N, coll.get_facecolors(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolors(), ['g'] * self.N)
ax.cla()
# specify edgecolor/facecolor
coll = plot_point_collection(ax, self.points, facecolor='g',
edgecolor='r')
_check_colors(self.N, coll.get_facecolors(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolors(), ['r'] * self.N)
ax.cla()
# list of colors
coll = plot_point_collection(ax, self.points, color=['r', 'g', 'b'])
_check_colors(self.N, coll.get_facecolors(), ['r', 'g', 'b'])
_check_colors(self.N, coll.get_edgecolors(), ['r', 'g', 'b'])
ax.cla()
def test_points_values(self):
from geopandas.plotting import plot_point_collection
# default colormap
fig, ax = plt.subplots()
coll = plot_point_collection(ax, self.points, self.values)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
expected_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_facecolors(), expected_colors)
# edgecolor depends on matplotlib version
# _check_colors(self.N, coll.get_edgecolors(), expected_colors)
def test_linestrings(self):
from geopandas.plotting import plot_linestring_collection
from matplotlib.collections import LineCollection
fig, ax = plt.subplots()
coll = plot_linestring_collection(ax, self.lines)
assert isinstance(coll, LineCollection)
ax.cla()
# default: single default matplotlib color
coll = plot_linestring_collection(ax, self.lines)
_check_colors(self.N, coll.get_color(), [MPL_DFT_COLOR] * self.N)
ax.cla()
# specify single other color
coll = plot_linestring_collection(ax, self.lines, color='g')
_check_colors(self.N, coll.get_colors(), ['g'] * self.N)
ax.cla()
# specify edgecolor / facecolor
coll = plot_linestring_collection(ax, self.lines, facecolor='g',
edgecolor='r')
_check_colors(self.N, coll.get_facecolors(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolors(), ['r'] * self.N)
ax.cla()
# list of colors
coll = plot_linestring_collection(ax, self.lines,
color=['r', 'g', 'b'])
_check_colors(self.N, coll.get_colors(), ['r', 'g', 'b'])
ax.cla()
# pass through of kwargs
coll = plot_linestring_collection(ax, self.lines, linestyle='--',
linewidth=1)
exp_ls = _style_to_linestring_onoffseq('dashed', 1)
res_ls = coll.get_linestyle()[0]
assert res_ls[0] == exp_ls[0]
assert res_ls[1] == exp_ls[1]
ax.cla()
def test_linestrings_values(self):
from geopandas.plotting import plot_linestring_collection
fig, ax = plt.subplots()
# default colormap
coll = plot_linestring_collection(ax, self.lines, self.values)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
expected_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_color(), expected_colors)
ax.cla()
# specify colormap
coll = plot_linestring_collection(ax, self.lines, self.values,
cmap='RdBu')
fig.canvas.draw_idle()
cmap = plt.get_cmap('RdBu')
expected_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_color(), expected_colors)
ax.cla()
# specify vmin/vmax
coll = plot_linestring_collection(ax, self.lines, self.values,
vmin=3, vmax=5)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
expected_colors = cmap([0])
_check_colors(self.N, coll.get_color(), expected_colors)
ax.cla()
def test_polygons(self):
from geopandas.plotting import plot_polygon_collection
from matplotlib.collections import PatchCollection
fig, ax = plt.subplots()
coll = plot_polygon_collection(ax, self.polygons)
assert isinstance(coll, PatchCollection)
ax.cla()
# default: single default matplotlib color
coll = plot_polygon_collection(ax, self.polygons)
_check_colors(self.N, coll.get_facecolor(), [MPL_DFT_COLOR] * self.N)
_check_colors(self.N, coll.get_edgecolor(), ['k'] * self.N)
ax.cla()
# default: color sets both facecolor and edgecolor
coll = plot_polygon_collection(ax, self.polygons, color='g')
_check_colors(self.N, coll.get_facecolor(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolor(), ['g'] * self.N)
ax.cla()
# only setting facecolor keeps default for edgecolor
coll = plot_polygon_collection(ax, self.polygons, facecolor='g')
_check_colors(self.N, coll.get_facecolor(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolor(), ['k'] * self.N)
ax.cla()
# custom facecolor and edgecolor
coll = plot_polygon_collection(ax, self.polygons, facecolor='g',
edgecolor='r')
_check_colors(self.N, coll.get_facecolor(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolor(), ['r'] * self.N)
ax.cla()
def test_polygons_values(self):
from geopandas.plotting import plot_polygon_collection
fig, ax = plt.subplots()
# default colormap, edge is still black by default
coll = plot_polygon_collection(ax, self.polygons, self.values)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
exp_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_facecolor(), exp_colors)
# edgecolor depends on matplotlib version
#_check_colors(self.N, coll.get_edgecolor(), ['k'] * self.N)
ax.cla()
# specify colormap
coll = plot_polygon_collection(ax, self.polygons, self.values,
cmap='RdBu')
fig.canvas.draw_idle()
cmap = plt.get_cmap('RdBu')
exp_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_facecolor(), exp_colors)
ax.cla()
# specify vmin/vmax
coll = plot_polygon_collection(ax, self.polygons, self.values,
vmin=3, vmax=5)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
exp_colors = cmap([0])
_check_colors(self.N, coll.get_facecolor(), exp_colors)
ax.cla()
# override edgecolor
coll = plot_polygon_collection(ax, self.polygons, self.values,
edgecolor='g')
fig.canvas.draw_idle()
cmap = plt.get_cmap()
exp_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_facecolor(), exp_colors)
_check_colors(self.N, coll.get_edgecolor(), ['g'] * self.N)
ax.cla()
def test_column_values():
"""
Check that the dataframe plot method returns same values with an
input string (column in df), pd.Series, or np.array
"""
# Build test data
t1 = Polygon([(0, 0), (1, 0), (1, 1)])
t2 = Polygon([(1, 0), (2, 0), (2, 1)])
polys = GeoSeries([t1, t2], index=list('AB'))
df = GeoDataFrame({'geometry': polys, 'values': [0, 1]})
# Test with continous values
ax = df.plot(column='values')
colors = ax.collections[0].get_facecolors()
ax = df.plot(column=df['values'])
colors_series = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(colors, colors_series)
ax = df.plot(column=df['values'].values)
colors_array = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(colors, colors_array)
# Test with categorical values
ax = df.plot(column='values', categorical=True)
colors = ax.collections[0].get_facecolors()
ax = df.plot(column=df['values'], categorical=True)
colors_series = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(colors, colors_series)
ax = df.plot(column=df['values'].values, categorical=True)
colors_array = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(colors, colors_array)
# Check raised error: is df rows number equal to column legth?
with pytest.raises(ValueError, match="different number of rows"):
ax = df.plot(column=np.array([1, 2, 3]))
def _check_colors(N, actual_colors, expected_colors, alpha=None):
"""
Asserts that the members of `collection` match the `expected_colors`
(in order)
Parameters
----------
N : int
The number of geometries believed to be in collection.
matplotlib.collection is implemented such that the number of geoms in
`collection` doesn't have to match the number of colors assignments in
the collection: the colors will cycle to meet the needs of the geoms.
`N` helps us resolve this.
collection : matplotlib.collections.Collection
The colors of this collection's patches are read from
`collection.get_facecolors()`
expected_colors : sequence of RGBA tuples
alpha : float (optional)
If set, this alpha transparency will be applied to the
`expected_colors`. (Any transparency on the `collection` is assumed
to be set in its own facecolor RGBA tuples.)
"""
import matplotlib.colors as colors
conv = colors.colorConverter
# Convert 2D numpy array to a list of RGBA tuples.
actual_colors = map(tuple, actual_colors)
all_actual_colors = list(itertools.islice(
itertools.cycle(actual_colors), N))
for actual, expected in zip(all_actual_colors, expected_colors):
assert actual == conv.to_rgba(expected, alpha=alpha), \
'{} != {}'.format(actual, conv.to_rgba(expected, alpha=alpha))
def _style_to_linestring_onoffseq(linestyle, linewidth):
""" Converts a linestyle string representation, namely one of:
['dashed', 'dotted', 'dashdot', 'solid'],
documented in `Collections.set_linestyle`,
to the form `onoffseq`.
"""
offset, dashes = matplotlib.lines._get_dash_pattern(linestyle)
return matplotlib.lines._scale_dashes(offset, dashes, linewidth)
| 39.367168 | 88 | 0.607831 | from __future__ import absolute_import, division
import itertools
import warnings
import numpy as np
from shapely.affinity import rotate
from shapely.geometry import MultiPolygon, Polygon, LineString, Point, MultiPoint
from geopandas import GeoSeries, GeoDataFrame, read_file
from geopandas.datasets import get_path
import pytest
matplotlib = pytest.importorskip('matplotlib')
matplotlib.use('Agg')
import matplotlib.pyplot as plt
@pytest.fixture(autouse=True)
def close_figures(request):
yield
plt.close('all')
try:
cycle = matplotlib.rcParams['axes.prop_cycle'].by_key()
MPL_DFT_COLOR = cycle['color'][0]
except KeyError:
MPL_DFT_COLOR = matplotlib.rcParams['axes.color_cycle'][0]
class TestPointPlotting:
def setup_method(self):
self.N = 10
self.points = GeoSeries(Point(i, i) for i in range(self.N))
values = np.arange(self.N)
self.df = GeoDataFrame({'geometry': self.points, 'values': values})
multipoint1 = MultiPoint(self.points)
multipoint2 = rotate(multipoint1, 90)
self.df2 = GeoDataFrame({'geometry': [multipoint1, multipoint2],
'values': [0, 1]})
def test_figsize(self):
ax = self.points.plot(figsize=(1, 1))
np.testing.assert_array_equal(ax.figure.get_size_inches(), (1, 1))
ax = self.df.plot(figsize=(1, 1))
np.testing.assert_array_equal(ax.figure.get_size_inches(), (1, 1))
def test_default_colors(self):
_check_colors(self.N, ax.collections[0].get_facecolors(),
[MPL_DFT_COLOR] * self.N)
ax = self.df.plot()
_check_colors(self.N, ax.collections[0].get_facecolors(),
[MPL_DFT_COLOR] * self.N)
.get_cmap()
expected_colors = cmap(np.arange(self.N)/(self.N-1))
_check_colors(self.N, ax.collections[0].get_facecolors(),
expected_colors)
def test_colormap(self):
ax = self.points.plot(cmap='RdYlGn')
cmap = plt.get_cmap('RdYlGn')
exp_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)
ax = self.df.plot(cmap='RdYlGn')
_check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)
cmap = plt.get_cmap('RdYlGn')
_check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)
ax = self.points.plot(cmap=plt.get_cmap('Set1', lut=5))
cmap = plt.get_cmap('Set1', lut=5)
exp_colors = cmap(list(range(5))*3)
_check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)
def test_single_color(self):
ax = self.points.plot(color='green')
_check_colors(self.N, ax.collections[0].get_facecolors(), ['green']*self.N)
ax = self.df.plot(color='green')
_check_colors(self.N, ax.collections[0].get_facecolors(), ['green']*self.N)
with warnings.catch_warnings(record=True) as _:
# 'color' overrides 'column'
ax = self.df.plot(column='values', color='green')
_check_colors(self.N, ax.collections[0].get_facecolors(), ['green']*self.N)
def test_markersize(self):
ax = self.points.plot(markersize=10)
assert ax.collections[0].get_sizes() == [10]
ax = self.df.plot(markersize=10)
assert ax.collections[0].get_sizes() == [10]
ax = self.df.plot(column='values', markersize=10)
assert ax.collections[0].get_sizes() == [10]
ax = self.df.plot(markersize='values')
assert (ax.collections[0].get_sizes() == self.df['values']).all()
ax = self.df.plot(column='values', markersize='values')
assert (ax.collections[0].get_sizes() == self.df['values']).all()
def test_style_kwargs(self):
ax = self.points.plot(edgecolors='k')
assert (ax.collections[0].get_edgecolor() == [0, 0, 0, 1]).all()
def test_legend(self):
with warnings.catch_warnings(record=True) as _: # don't print warning
ax = self.df.plot(column='values', color='green', legend=True)
assert len(ax.get_figure().axes) == 1
ax = self.df.plot(legend=True)
assert len(ax.get_figure().axes) == 1
x = self.df.plot(column='values', cmap='RdYlGn', legend=True)
point_colors = ax.collections[0].get_facecolors()
cbar_colors = ax.get_figure().axes[1].collections[0].get_facecolors()
np.testing.assert_array_equal(point_colors[0], cbar_colors[0])
np.testing.assert_array_equal(point_colors[-1], cbar_colors[-1])
= self.df.plot(column='values', categorical=True, legend=True)
point_colors = ax.collections[0].get_facecolors()
cbar_colors = ax.get_legend().axes.collections[0].get_facecolors()
np.testing.assert_array_equal(point_colors[0], cbar_colors[0])
np.testing.assert_array_equal(point_colors[-1], cbar_colors[-1])
def test_empty_plot(self):
s = GeoSeries([])
with pytest.warns(UserWarning):
ax = s.plot()
assert len(ax.collections) == 0
df = GeoDataFrame([])
with pytest.warns(UserWarning):
ax = df.plot()
assert len(ax.collections) == 0
def test_multipoints(self):
ax = self.df2.plot()
_check_colors(4, ax.collections[0].get_facecolors(),
[MPL_DFT_COLOR] * 4)
ax = self.df2.plot(column='values')
cmap = plt.get_cmap()
expected_colors = [cmap(0)]* self.N + [cmap(1)] * self.N
_check_colors(2, ax.collections[0].get_facecolors(),
expected_colors)
class TestPointZPlotting:
def setup_method(self):
self.N = 10
self.points = GeoSeries(Point(i, i, i) for i in range(self.N))
values = np.arange(self.N)
self.df = GeoDataFrame({'geometry': self.points, 'values': values})
def test_plot(self):
self.df.plot()
class TestLineStringPlotting:
def setup_method(self):
self.N = 10
values = np.arange(self.N)
self.lines = GeoSeries([LineString([(0, i), (4, i+0.5), (9, i)])
for i in range(self.N)],
index=list('ABCDEFGHIJ'))
self.df = GeoDataFrame({'geometry': self.lines, 'values': values})
def test_single_color(self):
ax = self.lines.plot(color='green')
_check_colors(self.N, ax.collections[0].get_colors(), ['green']*self.N)
ax = self.df.plot(color='green')
_check_colors(self.N, ax.collections[0].get_colors(), ['green']*self.N)
with warnings.catch_warnings(record=True) as _: # don't print warning
ax = self.df.plot(column='values', color='green')
_check_colors(self.N, ax.collections[0].get_colors(), ['green']*self.N)
def test_style_kwargs(self):
linestyle = 'dashed'
linewidth = 1
ax = self.lines.plot(linestyle=linestyle, linewidth=linewidth)
exp_ls = _style_to_linestring_onoffseq(linestyle, linewidth)
for ls in ax.collections[0].get_linestyles():
assert ls[0] == exp_ls[0]
assert ls[1] == exp_ls[1]
ax = self.df.plot(linestyle=linestyle, linewidth=linewidth)
for ls in ax.collections[0].get_linestyles():
assert ls[0] == exp_ls[0]
assert ls[1] == exp_ls[1]
ax = self.df.plot(column='values', linestyle=linestyle,
linewidth=linewidth)
for ls in ax.collections[0].get_linestyles():
assert ls[0] == exp_ls[0]
assert ls[1] == exp_ls[1]
class TestPolygonPlotting:
def setup_method(self):
t1 = Polygon([(0, 0), (1, 0), (1, 1)])
t2 = Polygon([(1, 0), (2, 0), (2, 1)])
self.polys = GeoSeries([t1, t2], index=list('AB'))
self.df = GeoDataFrame({'geometry': self.polys, 'values': [0, 1]})
multipoly1 = MultiPolygon([t1, t2])
multipoly2 = rotate(multipoly1, 180)
self.df2 = GeoDataFrame({'geometry': [multipoly1, multipoly2],
'values': [0, 1]})
t3 = Polygon([(2, 0), (3, 0), (3, 1)])
df_nan = GeoDataFrame({'geometry': t3, 'values': [np.nan]})
self.df3 = self.df.append(df_nan)
def test_single_color(self):
ax = self.polys.plot(color='green')
_check_colors(2, ax.collections[0].get_facecolors(), ['green']*2)
_check_colors(2, ax.collections[0].get_edgecolors(), ['k'] * 2)
ax = self.df.plot(color='green')
_check_colors(2, ax.collections[0].get_facecolors(), ['green']*2)
_check_colors(2, ax.collections[0].get_edgecolors(), ['k'] * 2)
with warnings.catch_warnings(record=True) as _:
# 'color' overrides 'values'
ax = self.df.plot(column='values', color='green')
_check_colors(2, ax.collections[0].get_facecolors(), ['green']*2)
def test_vmin_vmax(self):
# when vmin == vmax, all polygons should be the same color
# non-categorical
ax = self.df.plot(column='values', categorical=False, vmin=0, vmax=0)
actual_colors = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(actual_colors[0], actual_colors[1])
# categorical
ax = self.df.plot(column='values', categorical=True, vmin=0, vmax=0)
actual_colors = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(actual_colors[0], actual_colors[1])
# vmin vmax set correctly for array with NaN (GitHub issue 877)
ax = self.df3.plot(column='values')
actual_colors = ax.collections[0].get_facecolors()
assert np.any(np.not_equal(actual_colors[0], actual_colors[1]))
def test_style_kwargs(self):
# facecolor overrides default cmap when color is not set
ax = self.polys.plot(facecolor='k')
_check_colors(2, ax.collections[0].get_facecolors(), ['k']*2)
# facecolor overrides more general-purpose color when both are set
ax = self.polys.plot(color='red', facecolor='k')
# TODO with new implementation, color overrides facecolor
# _check_colors(2, ax.collections[0], ['k']*2, alpha=0.5)
# edgecolor
ax = self.polys.plot(edgecolor='red')
np.testing.assert_array_equal([(1, 0, 0, 1)],
ax.collections[0].get_edgecolors())
ax = self.df.plot('values', edgecolor='red')
np.testing.assert_array_equal([(1, 0, 0, 1)],
ax.collections[0].get_edgecolors())
# alpha sets both edge and face
ax = self.polys.plot(facecolor='g', edgecolor='r', alpha=0.4)
_check_colors(2, ax.collections[0].get_facecolors(), ['g'] * 2, alpha=0.4)
_check_colors(2, ax.collections[0].get_edgecolors(), ['r'] * 2, alpha=0.4)
def test_legend_kwargs(self):
ax = self.df.plot(column='values', categorical=True, legend=True,
legend_kwds={'frameon': False})
assert ax.get_legend().get_frame_on() is False
def test_colorbar_kwargs(self):
# Test if kwargs are passed to colorbar
label_txt = 'colorbar test'
ax = self.df.plot(column='values', categorical=False, legend=True,
legend_kwds={'label': label_txt})
assert ax.get_figure().axes[1].get_ylabel() == label_txt
ax = self.df.plot(column='values', categorical=False, legend=True,
legend_kwds={'label': label_txt, "orientation": "horizontal"})
assert ax.get_figure().axes[1].get_xlabel() == label_txt
def test_multipolygons(self):
# MultiPolygons
ax = self.df2.plot()
assert len(ax.collections[0].get_paths()) == 4
_check_colors(4, ax.collections[0].get_facecolors(), [MPL_DFT_COLOR]*4)
ax = self.df2.plot('values')
cmap = plt.get_cmap(lut=2)
# colors are repeated for all components within a MultiPolygon
expected_colors = [cmap(0), cmap(0), cmap(1), cmap(1)]
_check_colors(4, ax.collections[0].get_facecolors(), expected_colors)
class TestPolygonZPlotting:
def setup_method(self):
t1 = Polygon([(0, 0, 0), (1, 0, 0), (1, 1, 1)])
t2 = Polygon([(1, 0, 0), (2, 0, 0), (2, 1, 1)])
self.polys = GeoSeries([t1, t2], index=list('AB'))
self.df = GeoDataFrame({'geometry': self.polys, 'values': [0, 1]})
multipoly1 = MultiPolygon([t1, t2])
multipoly2 = rotate(multipoly1, 180)
self.df2 = GeoDataFrame({'geometry': [multipoly1, multipoly2],
'values': [0, 1]})
def test_plot(self):
# basic test that points with z coords don't break plotting
self.df.plot()
class TestNonuniformGeometryPlotting:
def setup_method(self):
pytest.importorskip('matplotlib', '1.5.0')
poly = Polygon([(1, 0), (2, 0), (2, 1)])
line = LineString([(0.5, 0.5), (1, 1), (1, 0.5), (1.5, 1)])
point = Point(0.75, 0.25)
self.series = GeoSeries([poly, line, point])
self.df = GeoDataFrame({'geometry': self.series, 'values': [1, 2, 3]})
def test_colors(self):
ax = self.series.plot()
_check_colors(1, ax.collections[0].get_facecolors(), [MPL_DFT_COLOR])
_check_colors(1, ax.collections[1].get_edgecolors(), [MPL_DFT_COLOR])
_check_colors(1, ax.collections[2].get_facecolors(), [MPL_DFT_COLOR])
ax = self.series.plot(cmap='RdYlGn')
cmap = plt.get_cmap('RdYlGn')
exp_colors = cmap(np.arange(3) / (3 - 1))
_check_colors(1, ax.collections[0].get_facecolors(), [exp_colors[0]])
_check_colors(1, ax.collections[1].get_edgecolors(), [exp_colors[1]])
_check_colors(1, ax.collections[2].get_facecolors(), [exp_colors[2]])
def test_style_kwargs(self):
ax = self.series.plot(markersize=10)
assert ax.collections[2].get_sizes() == [10]
ax = self.df.plot(markersize=10)
assert ax.collections[2].get_sizes() == [10]
class TestMapclassifyPlotting:
@classmethod
def setup_class(cls):
try:
import mapclassify
except ImportError:
try:
import pysal
except ImportError:
pytest.importorskip('mapclassify')
pth = get_path('naturalearth_lowres')
cls.df = read_file(pth)
cls.df['NEGATIVES'] = np.linspace(-10, 10, len(cls.df.index))
def test_legend(self):
with warnings.catch_warnings(record=True) as _:
# warning coming from scipy.stats
ax = self.df.plot(column='pop_est', scheme='QUANTILES', k=3,
cmap='OrRd', legend=True)
labels = [t.get_text() for t in ax.get_legend().get_texts()]
expected = [u'140.00 - 5217064.00', u'5217064.00 - 19532732.33',
u'19532732.33 - 1379302771.00']
assert labels == expected
def test_negative_legend(self):
ax = self.df.plot(column='NEGATIVES', scheme='FISHER_JENKS', k=3,
cmap='OrRd', legend=True)
labels = [t.get_text() for t in ax.get_legend().get_texts()]
expected = [u'-10.00 - -3.41', u'-3.41 - 3.30', u'3.30 - 10.00']
assert labels == expected
@pytest.mark.parametrize('scheme', ['FISHER_JENKS', 'FISHERJENKS'])
def test_scheme_name_compat(self, scheme):
ax = self.df.plot(column='NEGATIVES', scheme=scheme, k=3, legend=True)
assert len(ax.get_legend().get_texts()) == 3
def test_classification_kwds(self):
ax = self.df.plot(column='pop_est', scheme='percentiles', k=3,
classification_kwds={'pct': [50, 100]}, cmap='OrRd',
legend=True)
labels = [t.get_text() for t in ax.get_legend().get_texts()]
expected = ['140.00 - 9961396.00', '9961396.00 - 1379302771.00']
assert labels == expected
def test_invalid_scheme(self):
with pytest.raises(ValueError):
scheme = 'invalid_scheme_* self.df.plot(column='gdp_md_est', scheme=scheme, k=3,
cmap='OrRd', legend=True)
def test_cax_legend_passing(self):
ax = plt.axes()
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.1)
with pytest.raises(ValueError):
ax = self.df.plot(
column='pop_est', cmap='OrRd', legend=True, cax=cax
)
def test_cax_legend_height(self):
# base case
with warnings.catch_warnings(record=True) as _: # don't print warning
ax = self.df.plot(
column='pop_est', cmap='OrRd', legend=True
)
plot_height = ax.get_figure().get_axes()[0].get_position().height
legend_height = ax.get_figure().get_axes()[1].get_position().height
assert abs(plot_height - legend_height) >= 1e-6
ax2 = plt.axes()
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax2)
cax = divider.append_axes('right', size='5%', pad=0.1)
with warnings.catch_warnings(record=True) as _:
ax2 = self.df.plot(
column='pop_est', cmap='OrRd', legend=True, cax=cax, ax=ax2
)
plot_height = ax2.get_figure().get_axes()[0].get_position().height
legend_height = ax2.get_figure().get_axes()[1].get_position().height
assert abs(plot_height - legend_height) < 1e-6
class TestPlotCollections:
def setup_method(self):
self.N = 3
self.values = np.arange(self.N)
self.points = GeoSeries(Point(i, i) for i in range(self.N))
self.lines = GeoSeries([LineString([(0, i), (4, i + 0.5), (9, i)])
for i in range(self.N)])
self.polygons = GeoSeries([Polygon([(0, i), (4, i + 0.5), (9, i)])
for i in range(self.N)])
def test_points(self):
pytest.importorskip('matplotlib', '1.5.0')
from geopandas.plotting import plot_point_collection
from matplotlib.collections import PathCollection
fig, ax = plt.subplots()
coll = plot_point_collection(ax, self.points)
assert isinstance(coll, PathCollection)
ax.cla()
coll = plot_point_collection(ax, self.points)
_check_colors(self.N, coll.get_facecolors(), [MPL_DFT_COLOR] * self.N)
ax.cla()
coll = plot_point_collection(ax, self.points, color='g')
_check_colors(self.N, coll.get_facecolors(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolors(), ['g'] * self.N)
ax.cla()
coll = plot_point_collection(ax, self.points, facecolor='g',
edgecolor='r')
_check_colors(self.N, coll.get_facecolors(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolors(), ['r'] * self.N)
ax.cla()
coll = plot_point_collection(ax, self.points, color=['r', 'g', 'b'])
_check_colors(self.N, coll.get_facecolors(), ['r', 'g', 'b'])
_check_colors(self.N, coll.get_edgecolors(), ['r', 'g', 'b'])
ax.cla()
def test_points_values(self):
from geopandas.plotting import plot_point_collection
fig, ax = plt.subplots()
coll = plot_point_collection(ax, self.points, self.values)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
expected_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_facecolors(), expected_colors)
def test_linestrings(self):
from geopandas.plotting import plot_linestring_collection
from matplotlib.collections import LineCollection
fig, ax = plt.subplots()
coll = plot_linestring_collection(ax, self.lines)
assert isinstance(coll, LineCollection)
ax.cla()
coll = plot_linestring_collection(ax, self.lines)
_check_colors(self.N, coll.get_color(), [MPL_DFT_COLOR] * self.N)
ax.cla()
coll = plot_linestring_collection(ax, self.lines, color='g')
_check_colors(self.N, coll.get_colors(), ['g'] * self.N)
ax.cla()
coll = plot_linestring_collection(ax, self.lines, facecolor='g',
edgecolor='r')
_check_colors(self.N, coll.get_facecolors(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolors(), ['r'] * self.N)
ax.cla()
coll = plot_linestring_collection(ax, self.lines,
color=['r', 'g', 'b'])
_check_colors(self.N, coll.get_colors(), ['r', 'g', 'b'])
ax.cla()
coll = plot_linestring_collection(ax, self.lines, linestyle='--',
linewidth=1)
exp_ls = _style_to_linestring_onoffseq('dashed', 1)
res_ls = coll.get_linestyle()[0]
assert res_ls[0] == exp_ls[0]
assert res_ls[1] == exp_ls[1]
ax.cla()
def test_linestrings_values(self):
from geopandas.plotting import plot_linestring_collection
fig, ax = plt.subplots()
coll = plot_linestring_collection(ax, self.lines, self.values)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
expected_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_color(), expected_colors)
ax.cla()
coll = plot_linestring_collection(ax, self.lines, self.values,
cmap='RdBu')
fig.canvas.draw_idle()
cmap = plt.get_cmap('RdBu')
expected_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_color(), expected_colors)
ax.cla()
coll = plot_linestring_collection(ax, self.lines, self.values,
vmin=3, vmax=5)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
expected_colors = cmap([0])
_check_colors(self.N, coll.get_color(), expected_colors)
ax.cla()
def test_polygons(self):
from geopandas.plotting import plot_polygon_collection
from matplotlib.collections import PatchCollection
fig, ax = plt.subplots()
coll = plot_polygon_collection(ax, self.polygons)
assert isinstance(coll, PatchCollection)
ax.cla()
coll = plot_polygon_collection(ax, self.polygons)
_check_colors(self.N, coll.get_facecolor(), [MPL_DFT_COLOR] * self.N)
_check_colors(self.N, coll.get_edgecolor(), ['k'] * self.N)
ax.cla()
coll = plot_polygon_collection(ax, self.polygons, color='g')
_check_colors(self.N, coll.get_facecolor(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolor(), ['g'] * self.N)
ax.cla()
coll = plot_polygon_collection(ax, self.polygons, facecolor='g')
_check_colors(self.N, coll.get_facecolor(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolor(), ['k'] * self.N)
ax.cla()
coll = plot_polygon_collection(ax, self.polygons, facecolor='g',
edgecolor='r')
_check_colors(self.N, coll.get_facecolor(), ['g'] * self.N)
_check_colors(self.N, coll.get_edgecolor(), ['r'] * self.N)
ax.cla()
def test_polygons_values(self):
from geopandas.plotting import plot_polygon_collection
fig, ax = plt.subplots()
coll = plot_polygon_collection(ax, self.polygons, self.values)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
exp_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_facecolor(), exp_colors)
ax.cla()
coll = plot_polygon_collection(ax, self.polygons, self.values,
cmap='RdBu')
fig.canvas.draw_idle()
cmap = plt.get_cmap('RdBu')
exp_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_facecolor(), exp_colors)
ax.cla()
coll = plot_polygon_collection(ax, self.polygons, self.values,
vmin=3, vmax=5)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
exp_colors = cmap([0])
_check_colors(self.N, coll.get_facecolor(), exp_colors)
ax.cla()
coll = plot_polygon_collection(ax, self.polygons, self.values,
edgecolor='g')
fig.canvas.draw_idle()
cmap = plt.get_cmap()
exp_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_facecolor(), exp_colors)
_check_colors(self.N, coll.get_edgecolor(), ['g'] * self.N)
ax.cla()
def test_column_values():
t1 = Polygon([(0, 0), (1, 0), (1, 1)])
t2 = Polygon([(1, 0), (2, 0), (2, 1)])
polys = GeoSeries([t1, t2], index=list('AB'))
df = GeoDataFrame({'geometry': polys, 'values': [0, 1]})
ax = df.plot(column='values')
colors = ax.collections[0].get_facecolors()
ax = df.plot(column=df['values'])
colors_series = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(colors, colors_series)
ax = df.plot(column=df['values'].values)
colors_array = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(colors, colors_array)
ax = df.plot(column='values', categorical=True)
colors = ax.collections[0].get_facecolors()
ax = df.plot(column=df['values'], categorical=True)
colors_series = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(colors, colors_series)
ax = df.plot(column=df['values'].values, categorical=True)
colors_array = ax.collections[0].get_facecolors()
np.testing.assert_array_equal(colors, colors_array)
with pytest.raises(ValueError, match="different number of rows"):
ax = df.plot(column=np.array([1, 2, 3]))
def _check_colors(N, actual_colors, expected_colors, alpha=None):
import matplotlib.colors as colors
conv = colors.colorConverter
actual_colors = map(tuple, actual_colors)
all_actual_colors = list(itertools.islice(
itertools.cycle(actual_colors), N))
for actual, expected in zip(all_actual_colors, expected_colors):
assert actual == conv.to_rgba(expected, alpha=alpha), \
'{} != {}'.format(actual, conv.to_rgba(expected, alpha=alpha))
def _style_to_linestring_onoffseq(linestyle, linewidth):
offset, dashes = matplotlib.lines._get_dash_pattern(linestyle)
return matplotlib.lines._scale_dashes(offset, dashes, linewidth)
| true | true |
1c3f95fa312334189873cf27fbc1e290bd179dc9 | 22,964 | py | Python | neurips2019/hgnn_composer.py | SunHaozhe/modular-metalearning | c94dd18c6d105f18667d4de7bb4c81fa538a541c | [
"MIT"
] | 70 | 2018-10-30T01:05:43.000Z | 2022-02-11T04:08:19.000Z | neurips2019/hgnn_composer.py | SunHaozhe/modular-metalearning | c94dd18c6d105f18667d4de7bb4c81fa538a541c | [
"MIT"
] | 7 | 2019-03-25T17:14:22.000Z | 2021-06-11T11:57:22.000Z | neurips2019/hgnn_composer.py | SunHaozhe/modular-metalearning | c94dd18c6d105f18667d4de7bb4c81fa538a541c | [
"MIT"
] | 12 | 2019-01-27T01:14:16.000Z | 2021-10-05T17:47:19.000Z | from __future__ import print_function
import copy
import numpy as np
import torch
from torch import nn
from composition import Composer
from structure import Structure
from tqdm import tqdm as Tqdm
import json
# import matplotlib.pyplot as plt
import os
import networkx as nx
# from torchviz import make_dot
from scipy.stats import entropy
torch.set_default_tensor_type('torch.cuda.FloatTensor')
nn_device='cuda:0'
torch.device(nn_device)
class HGNN_Composer(Composer):
def __init__(self, composer, module_list, loss_fn=None, structure={},
instructions={}):
super(HGNN_Composer, self).__init__(composer=composer,
module_list=module_list,
loss_fn=loss_fn, structure=structure, instructions=instructions)
self.graph = self.structure['graph']
#Order must be:
# a) Nodes
# b) Edges
end_nodes = self.structure['end_nodes']
end_edges = self.structure['end_edges']
self.node_modules = self.module_list[:end_nodes]
self.edge_modules = self.module_list[end_nodes:end_edges]
self.msg_sz = self.structure['msg_sz']
self.node_dim = self.structure['node_dim']
self.update_sz = self.structure['update_sz']
self.visualize = ('visualize' in self.instructions
and self.instructions['visualize'])
def visualize_graph(self):
# import networkx as nx
G = nx.Graph()
G.add_nodes_from(list(range(1, self.structure["num_nodes"])))
for i, edge in enumerate(map(tuple, self.structure['graph']["edges"])):
type = 'r' if self.structure["edge_idx_inv"][i] else 'b'
G.add_edge(*edge, color=type, weight=5)
# edges = G.edges()
# colors = [G[u][v]['color'] for u, v in edges]
# weights = [G[u][v]['weight'] for u, v in edges]
# nx.draw(G, edges=edges, edge_color=colors, width=5, with_labels=True, font_weight='bold')
# # plt.show()
# from datetime import datetime
# plt.savefig('runs/{}.png'.format(datetime.now()))
def forward_no_weights(self, x):
nodes = self.inp_to_graph_inp(x)
# number of steps to predict: -1 because the first one is input
# self.visualize_graph()
steps = self.structure['self_regress_steps']
self.bs = nodes.shape[0] # batch_size
self.n = nodes.shape[1] # number of nodes
# incoming messages?
incoming = [torch.zeros(self.bs, self.n, self.msg_sz).cuda() for _ in range(steps + 1)]
## Pointing tensors ##
edge_sources = self.structure['edge_sources'] # module->[list of nodes]
edge_sinks = self.structure['edge_sinks'] # module->[list of nodes]
node_idx = self.structure['node_idx'] # module->[list of nodes]
node_hist = []
# node_hist.append(nodes.clone())
#Sinks
self.structure['sinks_one_hot'] = []
# import ipdb; ipdb.set_trace()
# create one-hot feature embedding of edge sinks?
for sinks in self.structure['edge_sinks']:
if sinks == []:
self.structure['sinks_one_hot'].append(None)
continue
z = torch.zeros(self.structure['num_nodes'], len(sinks)).cuda()
aux_idx = torch.cuda.LongTensor(np.array(sinks)).reshape(-1, len(sinks))
self.structure['sinks_one_hot'].append(z.scatter_(dim=0, index=aux_idx, value=1.).cuda())
# print('1-hot: ', self.structure['sinks_one_hot'][-1])
for step in range(steps):
# Edge modules: concat input from sources and sinks and feed through edge module
for i, module in enumerate(self.edge_modules):
if len(edge_sources[i]) == 0: continue
sources = nodes[:, edge_sources[i], :].clone()
sinks = nodes[:, edge_sinks[i], :].clone()
# concat messages from source and sink to form edge state
inp = torch.cat([sources, sinks], dim=2)
# feed through edge module
out = module(inp.view(-1, inp.shape[2])).view(self.bs, -1, self.msg_sz)
incoming[step] = (incoming[step] + torch.matmul(self.structure['sinks_one_hot'][i], out))
# for (j, sink) in enumerate(edge_sinks[i]): # TODO: vectorize
# incoming[step][:, sink, :] = (incoming[step][:, sink, :].clone() + out[:, j, :])
# Node modules: pick added messages and old value -> put new
for (i, module) in enumerate(self.node_modules):
if len(node_idx[i]) == 0: continue
msg = incoming[step][:, node_idx[i], :].clone()
old = nodes[:, node_idx[i], :].clone()
# Updates node's value; no worries about updating too early since each node only affects itself.
aux = torch.cat([msg, old], dim=2).view(-1, self.node_dim + self.msg_sz)
aux = module(aux).view(self.bs, -1, self.update_sz)
nodes[:, node_idx[i], -self.update_sz:] = nodes[:, node_idx[i], -self.update_sz:].clone() + aux
node_hist.append(nodes.clone())
del self.structure['sinks_one_hot']
# if np.random.rand() < 1./2500:
# import pdb; pdb.set_trace()
if self.visualize:
return self.graph_out_to_out(node_hist), [_.data.cpu().numpy() for _ in node_hist]
else: return self.graph_out_to_out(node_hist)
def inp_to_graph_inp(self, x):
'''
Goes from input tensor to tensor in graph space
'''
# graph_type = self.graph['type']
# if 'original_input_shape' in self.structure:
# x = x.reshape(tuple([-1]+list(self.structure['original_input_shape'][1:])))
self.initial_inp = x #maybe clone()?
if 'self_regress_steps' in self.structure:
# taking only the first step of every self_regress_step steps as input upon which we will make predictions
x = x[0::self.structure['self_regress_steps'],:,:].clone()
else: raise NotImplementedError
return x
def graph_out_to_out(self, node_hist):
'''
Goes from output in graph space to final output
'''
# graph_type = self.graph['type']
for i in range(len(node_hist)):
# import ipdb; ipdb.set_trace()
node_hist[i] = node_hist[i].reshape((node_hist[i].shape[0], -1))
out = torch.zeros([node_hist[0].shape[0] * len(node_hist), node_hist[0].shape[1]])
if 'self_regress_steps' in self.structure:
for i in range(self.structure['self_regress_steps']):
out[i::self.structure['self_regress_steps']] = node_hist[i].clone()
# out = out.reshape((out.shape[0], -1))
# make_dot(out).save('help.dot')
# print('Saved figure!')
# import pdb; pdb.set_trace()
return out[:self.initial_inp.shape[0]-1]
else:
raise NotImplementedError
return node_hist[-1].reshape((node_hist[-1].shape[0], -1))
class HGNN_Structure(Structure):
def __init__(self, args):
self.composer_class = HGNN_Composer
self.composer_abbreviation = 'H_GRAPH'
#Loads configuration file for graph composer
self.composer = args.composer
assert len(self.composer.split('@')) == 2
[self.composer, self.composer_file] = self.composer.split('@')
with open(self.composer_file, 'r') as infile:
self.graph = json.load(infile)
self.graph['num_nodes'] = len(self.graph['nodes'])
self.graph['num_edges'] = len(self.graph['edges'])
self.graph['num_slots'] = self.graph['num_nodes'] + self.graph['num_edges']
self.loaded_graph = copy.deepcopy(self.graph)
self.composer = 'gnn'
self.type_modules = self.graph['type_modules'].split(',')
self.num_steps = self.graph['num_steps']
super(HGNN_Structure, self).__init__(args=args)
self.has_global_variable = False
self.PosUsage = None
self.GNNUsage = np.zeros((
max(len(self.graph['nodes']),len(self.graph['edges'])), self.tot_modules))
self.StructureParameters = None
def save_customized_files(self, directory):
with open(os.path.join(directory, 'graph.json'), 'w') as outfile:
json.dump(self.loaded_graph, outfile)
def get_plot_name(self, args, plot_name):
if args.plot_name.startswith('wf'):
extra = args.plot_name[2:]
if len(extra) and extra[0] in ['-','_']: extra = extra[1:]
plot_name = self.composer_file[:-5] #remove json
plot_name += 'nm=' + args.num_modules + 'lr='+str(args.adam_lr)
plot_name += 'opt='+str(args.optimization_steps)
plot_name += 'data='+args.data_desc.split('@')[1][:5]
plot_name = plot_name.replace('/','')
plot_name += 'name='+extra
plot_name += '/'
print('Plot name: ', plot_name)
input('press enter to continue')
def initialize_all_structures(self, T):
#Initialize node x node -> edge
find_node = self.find_node
if find_node: self.StructureParameters = nn.ParameterList()
if 'num_types' in self.graph:
self.num_types = self.graph['num_types']
else: self.num_types = 2
C = 5
self.TypeTypeToEdge = C*np.ones((self.num_types, self.num_types,
self.num_modules[1]))
self.TypeTypeNode = C*np.ones((self.num_types, self.num_types,
self.num_modules[0]))
assert self.num_modules[0] == 1
self.TrainStructures = [None for _ in T.MTRAIN]
self.ValStructures = [None for _ in T.MVAL]
for i in Tqdm(range(len(self.TrainStructures))):
self.TrainStructures[i] = self.initialize_structure(
find_node=find_node, dataset=T.MTRAIN[i])
self.TrainStructures[i]['original_input_shape'] = (
T.MTRAIN[i].original_input_shape)
self.TrainStructures[i]['original_output_shape'] = (
T.MTRAIN[i].original_output_shape)
for i in range(len(self.ValStructures)):
self.ValStructures[i] = self.initialize_structure(
find_node=find_node, dataset=T.MVAL[i])
self.ValStructures[i]['original_input_shape'] = (
T.MVAL[i].original_input_shape)
self.ValStructures[i]['original_output_shape'] = (
T.MVAL[i].original_output_shape)
def edges_from_node_types(self, node_types):
raise NotImplementedError
return [self.NodeNodeToEdge[node_types[s]][node_types[t]]
for (s,t) in self.graph['edges']]
def initialize_structure(self, find_node=False, dataset=None):
structure = {}
structure['graph'] = self.graph
structure['num_node_modules'] = self.num_modules[0]
structure['num_edge_modules'] = self.num_modules[1]
structure['num_nodes'] = len(self.graph['nodes'])
structure['num_edges'] = len(self.graph['edges'])
structure['num_steps'] = self.graph['num_steps']
if 'self_regress' in self.graph and self.graph['self_regress']:
structure['self_regress'] = True
structure['self_regress_steps'] = structure['num_steps']
structure['msg_sz'] = self.graph['msg_sz']
structure['update_sz'] = self.graph['update_sz']
structure['node_dim'] = self.graph['node_dim']
structure['initial_input'] = self.graph['initial_input']
structure['num_types'] = self.num_types
## Limits ##
structure['end_nodes'] = structure['num_node_modules']
structure['end_edges'] = (structure['end_nodes'] +
structure['num_edge_modules'])
structure['end_final'] = structure['end_edges']
## Types ##
structure['types'] = list(map(int, list(
np.random.choice(structure['num_types'],len(self.graph['nodes'])))))
## Nodes ##
structure['node_idx_inv'] = list(map(int, list(
np.random.choice(structure['num_node_modules'],
len(self.graph['nodes'])))))#node->mod
structure['node_idx'] = [[] for _ in
range(structure['num_node_modules'])]
for i in range(len(structure['node_idx_inv'])):
idx = structure['node_idx_inv'][i]
structure['node_idx'][idx].append(i) #module->[list of nodes]
## Edges ##
structure['edge_idx_inv'] = list(map(int, list(np.random.choice(
self.num_modules[1],len(self.graph['edges'])))))#edge->mod
## to make sure they are undirected
# for idx, module in enumerate(structure['edge_idx_inv']):
# r, c = tuple(structure['graph']['edges'][idx])
# other_idx = structure['graph']['edges'].index([c, r])
# structure['edge_idx_inv'][other_idx] = module
self.update_edge_variables(structure)
# Find node variables
if find_node:
self.StructureParameters.extend([torch.nn.Parameter(
torch.rand_like(dataset.TrainInput[:,:1,:])*2.-1.)])
structure['parameters'] = range(len(self.StructureParameters)-1,
len(self.StructureParameters))
return structure
def update_edges_from_nodes_all_structures(self):
for i in range(len(self.TrainStructures)):
self.update_edges_from_nodes(self.TrainStructures[i])
for i in range(len(self.ValStructures)):
self.update_edges_from_nodes(self.ValStructures[i])
def update_edge_variables(self, structure):
# structure['edge_idx_inv'] = (
# self.edges_from_node_types(structure['node_idx_inv']))
structure['edge_sources'] = [[] for _ in
range(structure['num_edge_modules'])]
structure['edge_sinks'] = [[] for _ in
range(structure['num_edge_modules'])]
structure['edge_idx'] = [[] for _ in
range(structure['num_edge_modules'])]
structure['node_receives']= [[] for _ in range(structure['num_nodes'])]
for i in range(len(structure['edge_idx_inv'])):
idx = structure['edge_idx_inv'][i]
#module->[list of edge indices]
structure['edge_idx'][idx].append(i)
#module->[list of node indices]
structure['edge_sources'][idx].append(self.graph['edges'][i][0])
#module->[list of node indices]
structure['edge_sinks'][idx].append(self.graph['edges'][i][1])
#'inverse' from edge_sinks
structure['node_receives'][self.graph['edges'][i][1]].append(i)
def reset_global_variable(self):
raise NotImplementedError
def set_new_global_variable(self):
'''
Mutates global variables
'''
raise NotImplementedError
@staticmethod
def _zero_out_current_probs(curr_edge_idx_inv, probs):
for edge, module in enumerate(curr_edge_idx_inv):
probs[edge, module] = 0
@staticmethod
def _normalize_probabilities(probs, axis=None):
dividend = np.sum(probs, axis=axis, keepdims=True)
np.divide(probs, dividend, out=probs)
def draw_new_edges_for_node(self, flip=False):
'''
given a current structure and an array (of the same dimensions)
of probabilitys of changing each value, and whether to flip
or sample, draws new edges for a randomly chosen node
'''
def f(new_struct, probs):
# pick a node to change edges for
node = np.random.choice(range(new_struct['num_nodes']))
np_edges_array = np.array(new_struct['graph']['edges'])
# get first item, because where returns a tuple
indices_for_node = np.where(np_edges_array[:, 1] == node)[0]
probabilities = copy.deepcopy(probs)
if new_struct['num_edge_modules'] > 1:
if flip:
self._zero_out_current_probs(new_struct['edge_idx_inv'],
probabilities)
self._normalize_probabilities(probabilities, axis=1)
for idx in indices_for_node:
new_module = np.random.choice(
range(new_struct['num_edge_modules']), p=probabilities[idx])
new_struct['edge_idx_inv'][idx] = new_module
self.update_edge_variables(new_struct)
else:
raise RuntimeError("please check to make sure \
either node or edge modules > 1")
return new_struct
return f
def draw_new_structure(self, new_struct, probs):
'''given a current structure and an array (of the same dimensions)
of probabilities of changing each value, draws a value to change'''
probabilities = copy.deepcopy(probs)
self._zero_out_current_probs(new_struct['edge_idx_inv'], probabilities)
self._normalize_probabilities(probabilities)
probabilities = probabilities.flatten()
if new_struct['num_edge_modules'] > 1:
import itertools
choices_to_change = list(itertools.product(range(new_struct['num_edges']),
range(self.num_modules[1]))) # edge, module
choice_idx = np.random.choice(range(len(choices_to_change)), p=probabilities)
idx, new_module = choices_to_change[choice_idx] # edge, new module to change to
new_struct['edge_idx_inv'][idx] = new_module
# undirected graph: change corresponding edge going the other way
# r, c = tuple(new_struct['graph']['edges'][idx])
# other_idx = new_struct['graph']['edges'].index([c, r])
# new_struct['edge_idx_inv'][other_idx] = new_module
self.update_edge_variables(new_struct)
else:
raise RuntimeError("please check to make sure either node or edge modules > 1")
return new_struct
def update_structure_to(self, structure, new_edges):
structure['edge_idx_inv'] = new_edges
self.update_edge_variables(structure)
def propose_new_structure(self, new_structure):
#Pick either a node or an edge and try switching module
change_node = (np.random.rand() > 0.5)
if new_structure['num_node_modules'] == 1: change_node = False
if new_structure['num_edge_modules'] == 1: change_node = True
if change_node and new_structure['num_node_modules']>1:
idx = -1
while (idx == -1 or #don't modify nodes w/ no assigned module
new_structure['node_idx_inv'][idx] >=
new_structure['num_node_modules']):
idx = np.random.randint(len(new_structure['node_idx_inv']))
#Remove from old
old_module = new_structure['node_idx_inv'][idx]
pos_in_old = new_structure['node_idx'][old_module].index(idx)
del new_structure['node_idx'][old_module][pos_in_old]
#Add to new
new_module = old_module
while new_module == old_module:
new_module = np.random.randint(self.num_modules[0])
new_structure['node_idx_inv'][idx] = new_module
new_structure['node_idx'][new_module].append(idx)
elif new_structure['num_edge_modules'] > 1:
idx = -1
while (idx == -1 or #don't modify edges w/ no assigned module
new_structure['edge_idx_inv'][idx] >=
new_structure['num_edge_modules']):
idx = np.random.randint(len(new_structure['edge_idx_inv']) // 2)
#Add to new
new_module = np.random.randint(self.num_modules[1])
new_structure['edge_idx_inv'][idx] = new_module
# undirected graph: change corresponding edge going the other way
# r, c = tuple(new_structure['graph']['edges'][idx])
# other_idx = new_structure['graph']['edges'].index([c, r])
# new_structure['edge_idx_inv'][other_idx] = new_module
self.update_edge_variables(new_structure)
else:
raise RuntimeError("please check to make sure either node or edge modules > 1")
return new_structure
def update_PosUsage_counters(self, METRICS):
'''
Updates table of fraction of times module is used for each dataset.
and for each slot.
'''
eps = 1./30
if self.PosUsage is None:
self.PosUsage = [np.zeros((self.graph['num_slots'], self.tot_modules))
for _ in range(len(self.TrainStructures)+len(self.ValStructures))]
for i in range(len(self.PosUsage)):
self.PosUsage[i] *= (1-eps)
for i,structure in enumerate(self.TrainStructures+self.ValStructures):
for j, node in enumerate(structure['node_idx_inv']):
if node>=0 and node<self.num_modules[0]:
self.PosUsage[i][j][node] += eps
for j, node in enumerate(structure['edge_idx_inv']):
if (node>=self.num_modules[0] and
node<self.num_modules[0]+self.num_modules[1]):
self.PosUsage[i][j][node+self.num_modules[0]] += eps
METRICS['PosUsage'] = [
[[b.item() for b in a] for a in _] for _ in self.PosUsage]
def update_customized_counters(self, METRICS=None):
return #TODO: implement, but not critical, just debugging
def update_Usage_counters(self, METRICS, T):
'''
Updates table of fraction of times module is used for each dataset.
'''
eps = 1e-3
self.Usage *= (1-eps)
for i_s, structure in enumerate(self.TrainStructures+self.ValStructures):
for i, l in enumerate(structure['node_idx']):
self.Usage[i_s][self.Modules[0][i]] += (
eps * len(l)/structure['num_nodes'])
for i, l in enumerate(structure['edge_idx']):
self.Usage[i_s][self.Modules[1][i]] += (
eps * len(l)/structure['num_edges'])
names = (
[_.name for _ in T.MTRAIN] + [_.name for _ in T.MVAL])
names = list(enumerate(names))
names.sort(key = lambda x : x[1])
values = self.Usage[[_[0] for _ in names],:]
METRICS['Usage'] = [[values[i][j] for j in range(values.shape[1])]
for i in range(values.shape[0]) ]
METRICS['Usage-names'] = [_[1] for _ in names]
def modules_given_structure(self, structure):
return ([m for m in structure['node_idx_inv']] +
[int(m)+structure['end_nodes'] for m in structure['edge_idx_inv']])
def plot_customized_usage_rate(self, directory):
return #TODO: implement, but not critical, just debugging
@staticmethod
def compose_multiple_structures(structures):
'''
:return: dictionary representing a mega-graph made of several structure propositions,
which can be fed into a composer class to be composed into an NN
'''
mega_structure = copy.deepcopy(structures[0])
if len(structures) > 1:
for structure in structures[1:]:
# add each structure to mega-composition
# store for use in calculating updated indices
prev_num_nodes = mega_structure['num_nodes']
prev_num_edges = mega_structure['num_edges']
# num nodes, num edges
mega_structure['num_nodes'] += structure['num_nodes']
mega_structure['num_edges'] += structure['num_edges']
mega_structure['graph']['num_nodes'] += structure['graph']['num_nodes']
mega_structure['graph']['num_edges'] += structure['graph']['num_edges']
# create the mega graph
mega_structure['graph']['nodes'] += structure['graph']['nodes']
mega_structure['graph']['edges'] += [[node_idx + prev_num_nodes for node_idx in edge]
for edge in structure['graph']['edges']]
for i, edge_type_list in enumerate(structure['edge_sources']):
mega_structure['edge_sources'][i] += [node_idx + prev_num_nodes for node_idx in edge_type_list]
for i, edge_type_list in enumerate(structure['edge_sinks']):
mega_structure['edge_sinks'][i] += [node_idx + prev_num_nodes for node_idx in edge_type_list]
# node to type_idx
for i, node_type_list in enumerate(structure['node_idx']):
mega_structure['node_idx'][i] += [node_idx + prev_num_nodes for node_idx in node_type_list]
for i, edge_type_list in enumerate(structure['edge_idx']):
mega_structure['edge_idx'][i] += [edge_idx + prev_num_edges for edge_idx in edge_type_list]
# type_list to node_idx
mega_structure['node_idx_inv'] += structure['node_idx_inv']
mega_structure['edge_idx_inv'] += structure['edge_idx_inv']
return mega_structure
| 43.492424 | 112 | 0.661514 | from __future__ import print_function
import copy
import numpy as np
import torch
from torch import nn
from composition import Composer
from structure import Structure
from tqdm import tqdm as Tqdm
import json
import os
import networkx as nx
from scipy.stats import entropy
torch.set_default_tensor_type('torch.cuda.FloatTensor')
nn_device='cuda:0'
torch.device(nn_device)
class HGNN_Composer(Composer):
def __init__(self, composer, module_list, loss_fn=None, structure={},
instructions={}):
super(HGNN_Composer, self).__init__(composer=composer,
module_list=module_list,
loss_fn=loss_fn, structure=structure, instructions=instructions)
self.graph = self.structure['graph']
end_nodes = self.structure['end_nodes']
end_edges = self.structure['end_edges']
self.node_modules = self.module_list[:end_nodes]
self.edge_modules = self.module_list[end_nodes:end_edges]
self.msg_sz = self.structure['msg_sz']
self.node_dim = self.structure['node_dim']
self.update_sz = self.structure['update_sz']
self.visualize = ('visualize' in self.instructions
and self.instructions['visualize'])
def visualize_graph(self):
G = nx.Graph()
G.add_nodes_from(list(range(1, self.structure["num_nodes"])))
for i, edge in enumerate(map(tuple, self.structure['graph']["edges"])):
type = 'r' if self.structure["edge_idx_inv"][i] else 'b'
G.add_edge(*edge, color=type, weight=5)
def forward_no_weights(self, x):
nodes = self.inp_to_graph_inp(x)
steps = self.structure['self_regress_steps']
self.bs = nodes.shape[0]
self.n = nodes.shape[1]
incoming = [torch.zeros(self.bs, self.n, self.msg_sz).cuda() for _ in range(steps + 1)]
.structure['edge_sources']
edge_sinks = self.structure['edge_sinks']
node_idx = self.structure['node_idx']
node_hist = []
self.structure['sinks_one_hot'] = []
for sinks in self.structure['edge_sinks']:
if sinks == []:
self.structure['sinks_one_hot'].append(None)
continue
z = torch.zeros(self.structure['num_nodes'], len(sinks)).cuda()
aux_idx = torch.cuda.LongTensor(np.array(sinks)).reshape(-1, len(sinks))
self.structure['sinks_one_hot'].append(z.scatter_(dim=0, index=aux_idx, value=1.).cuda())
for step in range(steps):
for i, module in enumerate(self.edge_modules):
if len(edge_sources[i]) == 0: continue
sources = nodes[:, edge_sources[i], :].clone()
sinks = nodes[:, edge_sinks[i], :].clone()
inp = torch.cat([sources, sinks], dim=2)
out = module(inp.view(-1, inp.shape[2])).view(self.bs, -1, self.msg_sz)
incoming[step] = (incoming[step] + torch.matmul(self.structure['sinks_one_hot'][i], out))
for (i, module) in enumerate(self.node_modules):
if len(node_idx[i]) == 0: continue
msg = incoming[step][:, node_idx[i], :].clone()
old = nodes[:, node_idx[i], :].clone()
aux = torch.cat([msg, old], dim=2).view(-1, self.node_dim + self.msg_sz)
aux = module(aux).view(self.bs, -1, self.update_sz)
nodes[:, node_idx[i], -self.update_sz:] = nodes[:, node_idx[i], -self.update_sz:].clone() + aux
node_hist.append(nodes.clone())
del self.structure['sinks_one_hot']
# if np.random.rand() < 1./2500:
# import pdb; pdb.set_trace()
if self.visualize:
return self.graph_out_to_out(node_hist), [_.data.cpu().numpy() for _ in node_hist]
else: return self.graph_out_to_out(node_hist)
def inp_to_graph_inp(self, x):
# graph_type = self.graph['type']
# if 'original_input_shape' in self.structure:
# x = x.reshape(tuple([-1]+list(self.structure['original_input_shape'][1:])))
self.initial_inp = x #maybe clone()?
if 'self_regress_steps' in self.structure:
# taking only the first step of every self_regress_step steps as input upon which we will make predictions
x = x[0::self.structure['self_regress_steps'],:,:].clone()
else: raise NotImplementedError
return x
def graph_out_to_out(self, node_hist):
# graph_type = self.graph['type']
for i in range(len(node_hist)):
# import ipdb; ipdb.set_trace()
node_hist[i] = node_hist[i].reshape((node_hist[i].shape[0], -1))
out = torch.zeros([node_hist[0].shape[0] * len(node_hist), node_hist[0].shape[1]])
if 'self_regress_steps' in self.structure:
for i in range(self.structure['self_regress_steps']):
out[i::self.structure['self_regress_steps']] = node_hist[i].clone()
# out = out.reshape((out.shape[0], -1))
# make_dot(out).save('help.dot')
# print('Saved figure!')
# import pdb; pdb.set_trace()
return out[:self.initial_inp.shape[0]-1]
else:
raise NotImplementedError
return node_hist[-1].reshape((node_hist[-1].shape[0], -1))
class HGNN_Structure(Structure):
def __init__(self, args):
self.composer_class = HGNN_Composer
self.composer_abbreviation = 'H_GRAPH'
#Loads configuration file for graph composer
self.composer = args.composer
assert len(self.composer.split('@')) == 2
[self.composer, self.composer_file] = self.composer.split('@')
with open(self.composer_file, 'r') as infile:
self.graph = json.load(infile)
self.graph['num_nodes'] = len(self.graph['nodes'])
self.graph['num_edges'] = len(self.graph['edges'])
self.graph['num_slots'] = self.graph['num_nodes'] + self.graph['num_edges']
self.loaded_graph = copy.deepcopy(self.graph)
self.composer = 'gnn'
self.type_modules = self.graph['type_modules'].split(',')
self.num_steps = self.graph['num_steps']
super(HGNN_Structure, self).__init__(args=args)
self.has_global_variable = False
self.PosUsage = None
self.GNNUsage = np.zeros((
max(len(self.graph['nodes']),len(self.graph['edges'])), self.tot_modules))
self.StructureParameters = None
def save_customized_files(self, directory):
with open(os.path.join(directory, 'graph.json'), 'w') as outfile:
json.dump(self.loaded_graph, outfile)
def get_plot_name(self, args, plot_name):
if args.plot_name.startswith('wf'):
extra = args.plot_name[2:]
if len(extra) and extra[0] in ['-','_']: extra = extra[1:]
plot_name = self.composer_file[:-5] #remove json
plot_name += 'nm=' + args.num_modules + 'lr='+str(args.adam_lr)
plot_name += 'opt='+str(args.optimization_steps)
plot_name += 'data='+args.data_desc.split('@')[1][:5]
plot_name = plot_name.replace('/','')
plot_name += 'name='+extra
plot_name += '/'
print('Plot name: ', plot_name)
input('press enter to continue')
def initialize_all_structures(self, T):
#Initialize node x node -> edge
find_node = self.find_node
if find_node: self.StructureParameters = nn.ParameterList()
if 'num_types' in self.graph:
self.num_types = self.graph['num_types']
else: self.num_types = 2
C = 5
self.TypeTypeToEdge = C*np.ones((self.num_types, self.num_types,
self.num_modules[1]))
self.TypeTypeNode = C*np.ones((self.num_types, self.num_types,
self.num_modules[0]))
assert self.num_modules[0] == 1
self.TrainStructures = [None for _ in T.MTRAIN]
self.ValStructures = [None for _ in T.MVAL]
for i in Tqdm(range(len(self.TrainStructures))):
self.TrainStructures[i] = self.initialize_structure(
find_node=find_node, dataset=T.MTRAIN[i])
self.TrainStructures[i]['original_input_shape'] = (
T.MTRAIN[i].original_input_shape)
self.TrainStructures[i]['original_output_shape'] = (
T.MTRAIN[i].original_output_shape)
for i in range(len(self.ValStructures)):
self.ValStructures[i] = self.initialize_structure(
find_node=find_node, dataset=T.MVAL[i])
self.ValStructures[i]['original_input_shape'] = (
T.MVAL[i].original_input_shape)
self.ValStructures[i]['original_output_shape'] = (
T.MVAL[i].original_output_shape)
def edges_from_node_types(self, node_types):
raise NotImplementedError
return [self.NodeNodeToEdge[node_types[s]][node_types[t]]
for (s,t) in self.graph['edges']]
def initialize_structure(self, find_node=False, dataset=None):
structure = {}
structure['graph'] = self.graph
structure['num_node_modules'] = self.num_modules[0]
structure['num_edge_modules'] = self.num_modules[1]
structure['num_nodes'] = len(self.graph['nodes'])
structure['num_edges'] = len(self.graph['edges'])
structure['num_steps'] = self.graph['num_steps']
if 'self_regress' in self.graph and self.graph['self_regress']:
structure['self_regress'] = True
structure['self_regress_steps'] = structure['num_steps']
structure['msg_sz'] = self.graph['msg_sz']
structure['update_sz'] = self.graph['update_sz']
structure['node_dim'] = self.graph['node_dim']
structure['initial_input'] = self.graph['initial_input']
structure['num_types'] = self.num_types
## Limits ##
structure['end_nodes'] = structure['num_node_modules']
structure['end_edges'] = (structure['end_nodes'] +
structure['num_edge_modules'])
structure['end_final'] = structure['end_edges']
## Types ##
structure['types'] = list(map(int, list(
np.random.choice(structure['num_types'],len(self.graph['nodes'])))))
## Nodes ##
structure['node_idx_inv'] = list(map(int, list(
np.random.choice(structure['num_node_modules'],
len(self.graph['nodes'])))))#node->mod
structure['node_idx'] = [[] for _ in
range(structure['num_node_modules'])]
for i in range(len(structure['node_idx_inv'])):
idx = structure['node_idx_inv'][i]
structure['node_idx'][idx].append(i) #module->[list of nodes]
## Edges ##
structure['edge_idx_inv'] = list(map(int, list(np.random.choice(
self.num_modules[1],len(self.graph['edges'])))))#edge->mod
## to make sure they are undirected
# for idx, module in enumerate(structure['edge_idx_inv']):
# r, c = tuple(structure['graph']['edges'][idx])
# other_idx = structure['graph']['edges'].index([c, r])
# structure['edge_idx_inv'][other_idx] = module
self.update_edge_variables(structure)
# Find node variables
if find_node:
self.StructureParameters.extend([torch.nn.Parameter(
torch.rand_like(dataset.TrainInput[:,:1,:])*2.-1.)])
structure['parameters'] = range(len(self.StructureParameters)-1,
len(self.StructureParameters))
return structure
def update_edges_from_nodes_all_structures(self):
for i in range(len(self.TrainStructures)):
self.update_edges_from_nodes(self.TrainStructures[i])
for i in range(len(self.ValStructures)):
self.update_edges_from_nodes(self.ValStructures[i])
def update_edge_variables(self, structure):
# structure['edge_idx_inv'] = (
# self.edges_from_node_types(structure['node_idx_inv']))
structure['edge_sources'] = [[] for _ in
range(structure['num_edge_modules'])]
structure['edge_sinks'] = [[] for _ in
range(structure['num_edge_modules'])]
structure['edge_idx'] = [[] for _ in
range(structure['num_edge_modules'])]
structure['node_receives']= [[] for _ in range(structure['num_nodes'])]
for i in range(len(structure['edge_idx_inv'])):
idx = structure['edge_idx_inv'][i]
#module->[list of edge indices]
structure['edge_idx'][idx].append(i)
#module->[list of node indices]
structure['edge_sources'][idx].append(self.graph['edges'][i][0])
#module->[list of node indices]
structure['edge_sinks'][idx].append(self.graph['edges'][i][1])
#'inverse' from edge_sinks
structure['node_receives'][self.graph['edges'][i][1]].append(i)
def reset_global_variable(self):
raise NotImplementedError
def set_new_global_variable(self):
raise NotImplementedError
@staticmethod
def _zero_out_current_probs(curr_edge_idx_inv, probs):
for edge, module in enumerate(curr_edge_idx_inv):
probs[edge, module] = 0
@staticmethod
def _normalize_probabilities(probs, axis=None):
dividend = np.sum(probs, axis=axis, keepdims=True)
np.divide(probs, dividend, out=probs)
def draw_new_edges_for_node(self, flip=False):
def f(new_struct, probs):
# pick a node to change edges for
node = np.random.choice(range(new_struct['num_nodes']))
np_edges_array = np.array(new_struct['graph']['edges'])
# get first item, because where returns a tuple
indices_for_node = np.where(np_edges_array[:, 1] == node)[0]
probabilities = copy.deepcopy(probs)
if new_struct['num_edge_modules'] > 1:
if flip:
self._zero_out_current_probs(new_struct['edge_idx_inv'],
probabilities)
self._normalize_probabilities(probabilities, axis=1)
for idx in indices_for_node:
new_module = np.random.choice(
range(new_struct['num_edge_modules']), p=probabilities[idx])
new_struct['edge_idx_inv'][idx] = new_module
self.update_edge_variables(new_struct)
else:
raise RuntimeError("please check to make sure \
either node or edge modules > 1")
return new_struct
return f
def draw_new_structure(self, new_struct, probs):
probabilities = copy.deepcopy(probs)
self._zero_out_current_probs(new_struct['edge_idx_inv'], probabilities)
self._normalize_probabilities(probabilities)
probabilities = probabilities.flatten()
if new_struct['num_edge_modules'] > 1:
import itertools
choices_to_change = list(itertools.product(range(new_struct['num_edges']),
range(self.num_modules[1]))) # edge, module
choice_idx = np.random.choice(range(len(choices_to_change)), p=probabilities)
idx, new_module = choices_to_change[choice_idx] # edge, new module to change to
new_struct['edge_idx_inv'][idx] = new_module
# undirected graph: change corresponding edge going the other way
# r, c = tuple(new_struct['graph']['edges'][idx])
# other_idx = new_struct['graph']['edges'].index([c, r])
# new_struct['edge_idx_inv'][other_idx] = new_module
self.update_edge_variables(new_struct)
else:
raise RuntimeError("please check to make sure either node or edge modules > 1")
return new_struct
def update_structure_to(self, structure, new_edges):
structure['edge_idx_inv'] = new_edges
self.update_edge_variables(structure)
def propose_new_structure(self, new_structure):
#Pick either a node or an edge and try switching module
change_node = (np.random.rand() > 0.5)
if new_structure['num_node_modules'] == 1: change_node = False
if new_structure['num_edge_modules'] == 1: change_node = True
if change_node and new_structure['num_node_modules']>1:
idx = -1
while (idx == -1 or #don't modify nodes w/ no assigned module
new_structure['node_idx_inv'][idx] >=
new_structure['num_node_modules']):
idx = np.random.randint(len(new_structure['node_idx_inv']))
old_module = new_structure['node_idx_inv'][idx]
pos_in_old = new_structure['node_idx'][old_module].index(idx)
del new_structure['node_idx'][old_module][pos_in_old]
new_module = old_module
while new_module == old_module:
new_module = np.random.randint(self.num_modules[0])
new_structure['node_idx_inv'][idx] = new_module
new_structure['node_idx'][new_module].append(idx)
elif new_structure['num_edge_modules'] > 1:
idx = -1
while (idx == -1 or
new_structure['edge_idx_inv'][idx] >=
new_structure['num_edge_modules']):
idx = np.random.randint(len(new_structure['edge_idx_inv']) // 2)
#Add to new
new_module = np.random.randint(self.num_modules[1])
new_structure['edge_idx_inv'][idx] = new_module
# undirected graph: change corresponding edge going the other way
# r, c = tuple(new_structure['graph']['edges'][idx])
# other_idx = new_structure['graph']['edges'].index([c, r])
# new_structure['edge_idx_inv'][other_idx] = new_module
self.update_edge_variables(new_structure)
else:
raise RuntimeError("please check to make sure either node or edge modules > 1")
return new_structure
def update_PosUsage_counters(self, METRICS):
eps = 1./30
if self.PosUsage is None:
self.PosUsage = [np.zeros((self.graph['num_slots'], self.tot_modules))
for _ in range(len(self.TrainStructures)+len(self.ValStructures))]
for i in range(len(self.PosUsage)):
self.PosUsage[i] *= (1-eps)
for i,structure in enumerate(self.TrainStructures+self.ValStructures):
for j, node in enumerate(structure['node_idx_inv']):
if node>=0 and node<self.num_modules[0]:
self.PosUsage[i][j][node] += eps
for j, node in enumerate(structure['edge_idx_inv']):
if (node>=self.num_modules[0] and
node<self.num_modules[0]+self.num_modules[1]):
self.PosUsage[i][j][node+self.num_modules[0]] += eps
METRICS['PosUsage'] = [
[[b.item() for b in a] for a in _] for _ in self.PosUsage]
def update_customized_counters(self, METRICS=None):
return #TODO: implement, but not critical, just debugging
def update_Usage_counters(self, METRICS, T):
eps = 1e-3
self.Usage *= (1-eps)
for i_s, structure in enumerate(self.TrainStructures+self.ValStructures):
for i, l in enumerate(structure['node_idx']):
self.Usage[i_s][self.Modules[0][i]] += (
eps * len(l)/structure['num_nodes'])
for i, l in enumerate(structure['edge_idx']):
self.Usage[i_s][self.Modules[1][i]] += (
eps * len(l)/structure['num_edges'])
names = (
[_.name for _ in T.MTRAIN] + [_.name for _ in T.MVAL])
names = list(enumerate(names))
names.sort(key = lambda x : x[1])
values = self.Usage[[_[0] for _ in names],:]
METRICS['Usage'] = [[values[i][j] for j in range(values.shape[1])]
for i in range(values.shape[0]) ]
METRICS['Usage-names'] = [_[1] for _ in names]
def modules_given_structure(self, structure):
return ([m for m in structure['node_idx_inv']] +
[int(m)+structure['end_nodes'] for m in structure['edge_idx_inv']])
def plot_customized_usage_rate(self, directory):
return #TODO: implement, but not critical, just debugging
@staticmethod
def compose_multiple_structures(structures):
mega_structure = copy.deepcopy(structures[0])
if len(structures) > 1:
for structure in structures[1:]:
# add each structure to mega-composition
# store for use in calculating updated indices
prev_num_nodes = mega_structure['num_nodes']
prev_num_edges = mega_structure['num_edges']
# num nodes, num edges
mega_structure['num_nodes'] += structure['num_nodes']
mega_structure['num_edges'] += structure['num_edges']
mega_structure['graph']['num_nodes'] += structure['graph']['num_nodes']
mega_structure['graph']['num_edges'] += structure['graph']['num_edges']
# create the mega graph
mega_structure['graph']['nodes'] += structure['graph']['nodes']
mega_structure['graph']['edges'] += [[node_idx + prev_num_nodes for node_idx in edge]
for edge in structure['graph']['edges']]
for i, edge_type_list in enumerate(structure['edge_sources']):
mega_structure['edge_sources'][i] += [node_idx + prev_num_nodes for node_idx in edge_type_list]
for i, edge_type_list in enumerate(structure['edge_sinks']):
mega_structure['edge_sinks'][i] += [node_idx + prev_num_nodes for node_idx in edge_type_list]
# node to type_idx
for i, node_type_list in enumerate(structure['node_idx']):
mega_structure['node_idx'][i] += [node_idx + prev_num_nodes for node_idx in node_type_list]
for i, edge_type_list in enumerate(structure['edge_idx']):
mega_structure['edge_idx'][i] += [edge_idx + prev_num_edges for edge_idx in edge_type_list]
# type_list to node_idx
mega_structure['node_idx_inv'] += structure['node_idx_inv']
mega_structure['edge_idx_inv'] += structure['edge_idx_inv']
return mega_structure
| true | true |
1c3f9641e3c27b495230081a66c93766d00145b8 | 15,089 | py | Python | ixnetwork_restpy/testplatform/sessions/ixnetwork/quicktest/results_bd0cbe4a54d59462bce70486b688621e.py | OpenIxia/ixnetwork_restpy | f628db450573a104f327cf3c737ca25586e067ae | [
"MIT"
] | 20 | 2019-05-07T01:59:14.000Z | 2022-02-11T05:24:47.000Z | ixnetwork_restpy/testplatform/sessions/ixnetwork/quicktest/results_0e8c0f2566f300a755bc9b2735193666.py | OpenIxia/ixnetwork_restpy | f628db450573a104f327cf3c737ca25586e067ae | [
"MIT"
] | 60 | 2019-04-03T18:59:35.000Z | 2022-02-22T12:05:05.000Z | ixnetwork_restpy/testplatform/sessions/ixnetwork/quicktest/results_9d6b50c703ce2587fc1f039c09570043.py | OpenIxia/ixnetwork_restpy | f628db450573a104f327cf3c737ca25586e067ae | [
"MIT"
] | 13 | 2019-05-20T10:48:31.000Z | 2021-10-06T07:45:44.000Z | # MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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.
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
from typing import List, Any, Union
class Results(Base):
"""This is the collected result based on the configuration of the tracking area for each of the traffic items.
The Results class encapsulates a required results resource which will be retrieved from the server every time the property is accessed.
"""
__slots__ = ()
_SDM_NAME = 'results'
_SDM_ATT_MAP = {
'CurrentActions': 'currentActions',
'CurrentViews': 'currentViews',
'Duration': 'duration',
'IsRunning': 'isRunning',
'Progress': 'progress',
'Result': 'result',
'ResultPath': 'resultPath',
'StartTime': 'startTime',
'Status': 'status',
'TrafficStatus': 'trafficStatus',
'WaitingStatus': 'waitingStatus',
}
_SDM_ENUM_MAP = {
}
def __init__(self, parent, list_op=False):
super(Results, self).__init__(parent, list_op)
@property
def CurrentActions(self):
"""
Returns
-------
- list(dict(arg1:str,arg2:str[AgingTable | ApplyFlowGroups | CheckingForAvailableStats | CheckingLicense | ClearingStats | CollectingStats | DropLink | frameLossCriteriaNotMet | HoldDown | InitializingTest | IterationStart | LicenseFailed | LicenseVerified | None | NoRibInConvergenceStopping | ReleasingResources | SendingLearningFrames | SetTestConfiguration | SetupStatisticsCollection | StartingTraffic | TestEnded | TestStarted | ThresholdReachedStopping | TransmittingComplete | TransmittingFrames | WaitAfterFailover | WaitBeforeFailover | WaitingAfterLearningFramesSent | WaitingBeforeSendingTraffic | WaitingForDelayBetweenIterations | WaitingForPorts | WaitingForStats | WaitingTrafficToStop])): Current actions
"""
return self._get_attribute(self._SDM_ATT_MAP['CurrentActions'])
@property
def CurrentViews(self):
# type: () -> List[str]
"""
Returns
-------
- list(str): Views used by this QuickTest
"""
return self._get_attribute(self._SDM_ATT_MAP['CurrentViews'])
@property
def Duration(self):
# type: () -> str
"""
Returns
-------
- str: Test duration
"""
return self._get_attribute(self._SDM_ATT_MAP['Duration'])
@property
def IsRunning(self):
# type: () -> bool
"""
Returns
-------
- bool: Indicates whether the test is currently running
"""
return self._get_attribute(self._SDM_ATT_MAP['IsRunning'])
@property
def Progress(self):
# type: () -> str
"""
Returns
-------
- str: Test progress
"""
return self._get_attribute(self._SDM_ATT_MAP['Progress'])
@property
def Result(self):
# type: () -> str
"""
Returns
-------
- str: Test result
"""
return self._get_attribute(self._SDM_ATT_MAP['Result'])
@property
def ResultPath(self):
# type: () -> str
"""
Returns
-------
- str: Folder containing test result files
"""
return self._get_attribute(self._SDM_ATT_MAP['ResultPath'])
@property
def StartTime(self):
# type: () -> str
"""
Returns
-------
- str: Test start time
"""
return self._get_attribute(self._SDM_ATT_MAP['StartTime'])
@property
def Status(self):
# type: () -> str
"""
Returns
-------
- str: Test status
"""
return self._get_attribute(self._SDM_ATT_MAP['Status'])
@property
def TrafficStatus(self):
"""
Returns
-------
- dict(arg1:number,arg2:number): Test traffic status
"""
return self._get_attribute(self._SDM_ATT_MAP['TrafficStatus'])
@property
def WaitingStatus(self):
"""
Returns
-------
- dict(arg1:number,arg2:number): Test waiting status
"""
return self._get_attribute(self._SDM_ATT_MAP['WaitingStatus'])
def Apply(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Executes the apply operation on the server.
Applies the specified Quick Test.
apply(async_operation=bool)
---------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('apply', payload=payload, response_object=None)
def ApplyAsync(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Executes the applyAsync operation on the server.
applyAsync(async_operation=bool)
--------------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('applyAsync', payload=payload, response_object=None)
def ApplyAsyncResult(self, *args, **kwargs):
# type: (*Any, **Any) -> Union[bool, None]
"""Executes the applyAsyncResult operation on the server.
applyAsyncResult(async_operation=bool)bool
------------------------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
- Returns bool:
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('applyAsyncResult', payload=payload, response_object=None)
def ApplyITWizardConfiguration(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Executes the applyITWizardConfiguration operation on the server.
Applies the specified Quick Test.
applyITWizardConfiguration(async_operation=bool)
------------------------------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('applyITWizardConfiguration', payload=payload, response_object=None)
def GenerateReport(self, *args, **kwargs):
# type: (*Any, **Any) -> Union[str, None]
"""Executes the generateReport operation on the server.
Generate a PDF report for the last succesfull test run.
generateReport(async_operation=bool)string
------------------------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
- Returns str: This method is asynchronous and has no return value.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('generateReport', payload=payload, response_object=None)
def Run(self, *args, **kwargs):
# type: (*Any, **Any) -> Union[List[str], None]
"""Executes the run operation on the server.
Starts the specified Quick Test and waits for its execution to finish.
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
run(async_operation=bool)list
-----------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
- Returns list(str): This method is synchronous and returns the result of the test.
run(InputParameters=string, async_operation=bool)list
-----------------------------------------------------
- InputParameters (str): The input arguments of the test.
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
- Returns list(str): This method is synchronous and returns the result of the test.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('run', payload=payload, response_object=None)
def Start(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Executes the start operation on the server.
Starts the specified Quick Test.
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
start(async_operation=bool)
---------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
start(InputParameters=string, async_operation=bool)
---------------------------------------------------
- InputParameters (str): The input arguments of the test.
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('start', payload=payload, response_object=None)
def Stop(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Executes the stop operation on the server.
Stops the currently running Quick Test.
stop(async_operation=bool)
--------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('stop', payload=payload, response_object=None)
def WaitForTest(self, *args, **kwargs):
# type: (*Any, **Any) -> Union[List[str], None]
"""Executes the waitForTest operation on the server.
Waits for the execution of the specified Quick Test to be completed.
waitForTest(async_operation=bool)list
-------------------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
- Returns list(str): This method is synchronous and returns the result of the test.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('waitForTest', payload=payload, response_object=None)
| 42.624294 | 729 | 0.629068 |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
from typing import List, Any, Union
class Results(Base):
__slots__ = ()
_SDM_NAME = 'results'
_SDM_ATT_MAP = {
'CurrentActions': 'currentActions',
'CurrentViews': 'currentViews',
'Duration': 'duration',
'IsRunning': 'isRunning',
'Progress': 'progress',
'Result': 'result',
'ResultPath': 'resultPath',
'StartTime': 'startTime',
'Status': 'status',
'TrafficStatus': 'trafficStatus',
'WaitingStatus': 'waitingStatus',
}
_SDM_ENUM_MAP = {
}
def __init__(self, parent, list_op=False):
super(Results, self).__init__(parent, list_op)
@property
def CurrentActions(self):
return self._get_attribute(self._SDM_ATT_MAP['CurrentActions'])
@property
def CurrentViews(self):
return self._get_attribute(self._SDM_ATT_MAP['CurrentViews'])
@property
def Duration(self):
return self._get_attribute(self._SDM_ATT_MAP['Duration'])
@property
def IsRunning(self):
return self._get_attribute(self._SDM_ATT_MAP['IsRunning'])
@property
def Progress(self):
return self._get_attribute(self._SDM_ATT_MAP['Progress'])
@property
def Result(self):
return self._get_attribute(self._SDM_ATT_MAP['Result'])
@property
def ResultPath(self):
return self._get_attribute(self._SDM_ATT_MAP['ResultPath'])
@property
def StartTime(self):
return self._get_attribute(self._SDM_ATT_MAP['StartTime'])
@property
def Status(self):
return self._get_attribute(self._SDM_ATT_MAP['Status'])
@property
def TrafficStatus(self):
return self._get_attribute(self._SDM_ATT_MAP['TrafficStatus'])
@property
def WaitingStatus(self):
return self._get_attribute(self._SDM_ATT_MAP['WaitingStatus'])
def Apply(self, *args, **kwargs):
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('apply', payload=payload, response_object=None)
def ApplyAsync(self, *args, **kwargs):
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('applyAsync', payload=payload, response_object=None)
def ApplyAsyncResult(self, *args, **kwargs):
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('applyAsyncResult', payload=payload, response_object=None)
def ApplyITWizardConfiguration(self, *args, **kwargs):
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('applyITWizardConfiguration', payload=payload, response_object=None)
def GenerateReport(self, *args, **kwargs):
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('generateReport', payload=payload, response_object=None)
def Run(self, *args, **kwargs):
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('run', payload=payload, response_object=None)
def Start(self, *args, **kwargs):
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('start', payload=payload, response_object=None)
def Stop(self, *args, **kwargs):
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('stop', payload=payload, response_object=None)
def WaitForTest(self, *args, **kwargs):
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('waitForTest', payload=payload, response_object=None)
| true | true |
1c3f96648192ebf6e892f6aace58fee113c272a2 | 3,900 | py | Python | ankidict/addon/collection.py | wojtex/millandict | 6601873a1541ef7aaf938ac1a6b7aecb5f82cbf8 | [
"MIT"
] | 1 | 2015-10-15T19:04:05.000Z | 2015-10-15T19:04:05.000Z | ankidict/addon/collection.py | wojtex/ankidict | 6601873a1541ef7aaf938ac1a6b7aecb5f82cbf8 | [
"MIT"
] | 9 | 2015-03-24T08:06:51.000Z | 2015-05-21T13:44:10.000Z | ankidict/addon/collection.py | wojtex/ankidict | 6601873a1541ef7aaf938ac1a6b7aecb5f82cbf8 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
####
# Copyright (c) 2014 Wojciech Kordalski
# Copyright (c) 2014 Franciszek Piszcz
#
# 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.
####
from aqt import mw
import re
def get_plugin():
return mw.ankidict
def setup():
select_deck()
def select_deck():
# selects deck
# [TODO] test
self = get_plugin()
deckname = self.config.deck
deckid = mw.col.decks.id(deckname)
# select proper model
select_model()
# choosing deck
# we need to set it in the model
m = mw.col.models.current()
m['did'] = deckid
mw.col.models.save(m)
def select_model():
self = get_plugin()
mod = mw.col.models.byName(self.config.model)
if not mod:
# new model is required
mod = mw.col.models.new(self.config.model)
mw.col.models.addField(mod, mw.col.models.newField(self.config.note_question))
mw.col.models.addField(mod, mw.col.models.newField(self.config.note_answer))
mw.col.models.addField(mod, mw.col.models.newField(self.config.note_info))
# simple template for the model
tmp = mw.col.models.newTemplate(self.config.template)
if self.config.type_answer:
tmp['qfmt'] = '{{'+self.config.note_question+'}}<hr/>{{type:'+self.config.note_answer+'}}'
tmp['afmt'] = '{{FrontSide}}<hr/>{{'+self.config.note_info+'}}'
else:
tmp['qfmt'] = '{{'+self.config.note_question+'}}'
tmp['afmt'] = '{{FrontSide}}<hr/>{{'+self.config.note_answer+'}}<hr/>{{'+self.config.note_info+'}}'
mw.col.models.addTemplate(mod, tmp)
# [TODO] Maby should I here move deck selecting?
mw.col.models.add(mod)
mw.col.models.setCurrent(mod)
def add_note(q, a, e = ''):
# adds card to collection
self = get_plugin()
setup()
note = get_note(q)
if note != None:
if not a in [s.strip() for s in note[self.config.note_answer].split(';')]:
note[self.config.note_answer] += '; ' + a
note[self.config.note_info] += '; ' + e
note.flush()
else:
note = mw.col.newNote()
note[self.config.note_question] = q
note[self.config.note_answer] = a
note[self.config.note_info] = e
mw.col.addNote(note)
mw.reset()
def add_tag(q, t):
# adds tag to note
self = get_plugin()
setup()
note = get_note(q)
if not note: raise "Najpierw otaguj siebie, zanim zaczniesz tagować to co nie istnieje..."
note.tags.append(t)
note.flush()
mw.reset()
def get_note(q):
# returns card with selected question
self = get_plugin()
setup()
notes = mw.col.findNotes('"'+re.escape(q)+'"')
for note in [mw.col.getNote(n) for n in notes]:
if note[self.config.note_question] == q: return note
return None
def is_note(q, a):
# checks if <question, answer> is in collection
self = get_plugin()
note = get_note(q)
if not note: return False
answers = [s.strip() for s in note[self.config.note_answer].split(';')]
if a in answers: return True
return False
| 30.952381 | 105 | 0.686667 |
aqt import mw
import re
def get_plugin():
return mw.ankidict
def setup():
select_deck()
def select_deck():
self = get_plugin()
deckname = self.config.deck
deckid = mw.col.decks.id(deckname)
select_model()
m = mw.col.models.current()
m['did'] = deckid
mw.col.models.save(m)
def select_model():
self = get_plugin()
mod = mw.col.models.byName(self.config.model)
if not mod:
mod = mw.col.models.new(self.config.model)
mw.col.models.addField(mod, mw.col.models.newField(self.config.note_question))
mw.col.models.addField(mod, mw.col.models.newField(self.config.note_answer))
mw.col.models.addField(mod, mw.col.models.newField(self.config.note_info))
tmp = mw.col.models.newTemplate(self.config.template)
if self.config.type_answer:
tmp['qfmt'] = '{{'+self.config.note_question+'}}<hr/>{{type:'+self.config.note_answer+'}}'
tmp['afmt'] = '{{FrontSide}}<hr/>{{'+self.config.note_info+'}}'
else:
tmp['qfmt'] = '{{'+self.config.note_question+'}}'
tmp['afmt'] = '{{FrontSide}}<hr/>{{'+self.config.note_answer+'}}<hr/>{{'+self.config.note_info+'}}'
mw.col.models.addTemplate(mod, tmp)
mw.col.models.add(mod)
mw.col.models.setCurrent(mod)
def add_note(q, a, e = ''):
self = get_plugin()
setup()
note = get_note(q)
if note != None:
if not a in [s.strip() for s in note[self.config.note_answer].split(';')]:
note[self.config.note_answer] += '; ' + a
note[self.config.note_info] += '; ' + e
note.flush()
else:
note = mw.col.newNote()
note[self.config.note_question] = q
note[self.config.note_answer] = a
note[self.config.note_info] = e
mw.col.addNote(note)
mw.reset()
def add_tag(q, t):
self = get_plugin()
setup()
note = get_note(q)
if not note: raise "Najpierw otaguj siebie, zanim zaczniesz tagować to co nie istnieje..."
note.tags.append(t)
note.flush()
mw.reset()
def get_note(q):
self = get_plugin()
setup()
notes = mw.col.findNotes('"'+re.escape(q)+'"')
for note in [mw.col.getNote(n) for n in notes]:
if note[self.config.note_question] == q: return note
return None
def is_note(q, a):
self = get_plugin()
note = get_note(q)
if not note: return False
answers = [s.strip() for s in note[self.config.note_answer].split(';')]
if a in answers: return True
return False
| true | true |
1c3f979de1e38890393e0ca641ceec5d0d350d12 | 717 | py | Python | openstack_dashboard/dashboards/project/appdetail/tests.py | soma-micro-service/Horizon | 45243061b8a99935e0e483a314d95a82d33cc4cf | [
"Apache-2.0"
] | null | null | null | openstack_dashboard/dashboards/project/appdetail/tests.py | soma-micro-service/Horizon | 45243061b8a99935e0e483a314d95a82d33cc4cf | [
"Apache-2.0"
] | null | null | null | openstack_dashboard/dashboards/project/appdetail/tests.py | soma-micro-service/Horizon | 45243061b8a99935e0e483a314d95a82d33cc4cf | [
"Apache-2.0"
] | null | null | null | # 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 horizon.test import helpers as test
class AppdetailTests(test.TestCase):
# Unit tests for appdetail.
def test_me(self):
self.assertTrue(1 + 1 == 2)
| 35.85 | 75 | 0.743375 |
from horizon.test import helpers as test
class AppdetailTests(test.TestCase):
def test_me(self):
self.assertTrue(1 + 1 == 2)
| true | true |
1c3f97ce62b9cf4a3d0b30e9a3ea4994c6c6751e | 939 | py | Python | play/shutdownSystem.py | Svolcano/python_exercise | a50e05891cc7f1fbb40ebcae324b09b6a14473d2 | [
"MIT"
] | 6 | 2015-07-09T08:47:08.000Z | 2020-05-16T10:47:31.000Z | play/shutdownSystem.py | Svolcano/python_exercise | a50e05891cc7f1fbb40ebcae324b09b6a14473d2 | [
"MIT"
] | 7 | 2019-03-27T04:13:12.000Z | 2022-03-02T14:54:56.000Z | play/shutdownSystem.py | Svolcano/python_exercise | a50e05891cc7f1fbb40ebcae324b09b6a14473d2 | [
"MIT"
] | 2 | 2019-06-21T06:46:28.000Z | 2019-12-23T09:31:09.000Z | #coding=utf-8
import time
from os import system
def shutdownSystem():
runing = True
while runing:
input_cmd = input('shutdown(s)reboot(r)?quit(q)')
input_cmd = input_cmd.lower()
if input_cmd == 'q' or input_cmd == 'quit':
runing = False
print ('byebye')
break
seconds = int(input('aftime what seconds excute your command'))
if seconds < 0:
seconds = 0
time.sleep(seconds)
print ('pause time is :%d'%seconds)
runing = False
if input_cmd == 's' or input_cmd =='shutdown':
print ('shutdowning....')
system('halt')
elif input_cmd == 'r' or input_cmd == 'reboot':
print ('rebooting....')
system('reboot')
else:
print ('invalid command!')
runing = True
print ('Over!')
if __name__ == '__main__':
shutdownSystem()
| 28.454545 | 71 | 0.526092 |
import time
from os import system
def shutdownSystem():
runing = True
while runing:
input_cmd = input('shutdown(s)reboot(r)?quit(q)')
input_cmd = input_cmd.lower()
if input_cmd == 'q' or input_cmd == 'quit':
runing = False
print ('byebye')
break
seconds = int(input('aftime what seconds excute your command'))
if seconds < 0:
seconds = 0
time.sleep(seconds)
print ('pause time is :%d'%seconds)
runing = False
if input_cmd == 's' or input_cmd =='shutdown':
print ('shutdowning....')
system('halt')
elif input_cmd == 'r' or input_cmd == 'reboot':
print ('rebooting....')
system('reboot')
else:
print ('invalid command!')
runing = True
print ('Over!')
if __name__ == '__main__':
shutdownSystem()
| true | true |
1c3f9850d2bddf85fd1ad2831f488a02393e90ab | 1,513 | py | Python | genie/mafSP.py | kdaily/Genie | e2ff86938a9cdc9fc0415d4447d68762333b0cea | [
"MIT"
] | null | null | null | genie/mafSP.py | kdaily/Genie | e2ff86938a9cdc9fc0415d4447d68762333b0cea | [
"MIT"
] | 1 | 2020-02-12T19:09:03.000Z | 2020-09-18T22:23:34.000Z | genie/mafSP.py | kdaily/Genie | e2ff86938a9cdc9fc0415d4447d68762333b0cea | [
"MIT"
] | 1 | 2019-08-30T23:16:26.000Z | 2019-08-30T23:16:26.000Z | from __future__ import absolute_import
from genie import maf, process_functions
import os
import logging
import pandas as pd
logger = logging.getLogger(__name__)
class mafSP(maf):
'''
MAF SP file format validation / processing
'''
_fileType = "mafSP"
def _validateFilename(self, filePath):
'''
Validates filename. Should be
nonGENIE_data_mutations_extended_CENTER.txt
'''
assert os.path.basename(filePath[0]) == \
"nonGENIE_data_mutations_extended_{}.txt".format(self.center)
def formatMAF(self, mafDf):
'''
The sponsored project maf file doesn't have less columns
'''
mafDf['Center'] = self.center
mafDf['Tumor_Sample_Barcode'] = [
process_functions.checkGenieId(i, self.center)
for i in mafDf['Tumor_Sample_Barcode']]
mafDf['Sequence_Source'] = pd.np.nan
mafDf['Sequencer'] = pd.np.nan
mafDf['Validation_Status'][
mafDf['Validation_Status'].isin(["Unknown", "unknown"])] = ''
return(mafDf)
def storeProcessedMaf(
self, filePath, mafSynId, centerMafSynId, isNarrow=False):
'''
Stores SP maf to database
'''
logger.info('STORING %s' % filePath)
mafDataFrame = pd.read_csv(filePath, sep="\t")
process_functions.updateData(
self.syn, mafSynId, mafDataFrame,
self.center, filterByColumn="Center", toDelete=True)
return(filePath)
| 30.877551 | 73 | 0.623265 | from __future__ import absolute_import
from genie import maf, process_functions
import os
import logging
import pandas as pd
logger = logging.getLogger(__name__)
class mafSP(maf):
_fileType = "mafSP"
def _validateFilename(self, filePath):
assert os.path.basename(filePath[0]) == \
"nonGENIE_data_mutations_extended_{}.txt".format(self.center)
def formatMAF(self, mafDf):
mafDf['Center'] = self.center
mafDf['Tumor_Sample_Barcode'] = [
process_functions.checkGenieId(i, self.center)
for i in mafDf['Tumor_Sample_Barcode']]
mafDf['Sequence_Source'] = pd.np.nan
mafDf['Sequencer'] = pd.np.nan
mafDf['Validation_Status'][
mafDf['Validation_Status'].isin(["Unknown", "unknown"])] = ''
return(mafDf)
def storeProcessedMaf(
self, filePath, mafSynId, centerMafSynId, isNarrow=False):
logger.info('STORING %s' % filePath)
mafDataFrame = pd.read_csv(filePath, sep="\t")
process_functions.updateData(
self.syn, mafSynId, mafDataFrame,
self.center, filterByColumn="Center", toDelete=True)
return(filePath)
| true | true |
1c3f98c14fba98bd6f8af7e9419d91e0bdc2240d | 4,475 | py | Python | scripts/get_github_project_issues.py | mercycorps/toladata | 4d5f9b45905a81af9981b586690e020d5b3bfc60 | [
"Apache-2.0"
] | null | null | null | scripts/get_github_project_issues.py | mercycorps/toladata | 4d5f9b45905a81af9981b586690e020d5b3bfc60 | [
"Apache-2.0"
] | 268 | 2020-03-31T15:46:59.000Z | 2022-03-31T18:01:08.000Z | scripts/get_github_project_issues.py | mercycorps/toladata | 4d5f9b45905a81af9981b586690e020d5b3bfc60 | [
"Apache-2.0"
] | 1 | 2021-01-05T01:58:24.000Z | 2021-01-05T01:58:24.000Z |
"""
This script uses GitHub APIs to fetch a list of issues associated with a project.
It outputs issue numbers and titles for all cards in all columns of the project.
The output is particularly useful for putting into the GitHub release notes.
You can store your github token in the settings.secret.yml file, if you wish, as GITHUB_TOKEN
"""
import requests
from requests.auth import HTTPBasicAuth
import json
import os
import yaml
import sys
import re
import getpass
import argparse
headers = {'Accept': 'application/vnd.github.inertia-preview+json'}
parser = argparse.ArgumentParser(description='Parse a .po file')
parser.add_argument('--column', help='the column name of the tickets you want to extract')
parser.add_argument('--closeissues', action='store_true', help='Close all of the issues in the column')
args = parser.parse_args()
project_name = input('Enter the project name: ')
print('\nEnter 1 to use GitHub token authorization (https://github.com/settings/tokens)')
print('Enter 2 to use GitHub username and password: ')
auth_pref = input('Enter 1 or 2: ')
if auth_pref == '1':
CONFIG_PATH = os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir, os.pardir, 'config', 'settings.secret.yml'))
with open(CONFIG_PATH, 'r') as fh:
app_settings = yaml.full_load(fh)
try:
token = app_settings['GITHUB_TOKEN']
print('Found your GitHub key in the settings file\n')
except KeyError:
token = getpass.getpass('GitHub token: ')
headers['Authorization'] = 'token %s' % token
auth = ''
elif auth_pref == '2':
username = input('GitHub username: ')
password = getpass.getpass('GitHub password: ')
auth = HTTPBasicAuth(username, password)
else:
print (type(auth_pref))
print('You must choose either 1 or 2. You chose %s. Exiting.' % auth_pref)
sys.exit()
projects_url = 'https://api.github.com/repos/mercycorps/TolaActivity/projects'
columns_template = 'https://api.github.com/projects/%s/columns'
cards_template = 'https://api.github.com/projects/columns/{}/cards'
issue_template = 'https://api.github.com/repos/mercycorps/TolaActivity/issues/{}'
# Get the project id
print('Fetching data')
response = requests.get(projects_url, headers=headers, auth=auth)
projects = json.loads(response.text)
project_id = ''
columnn_ids = []
for project in projects:
try:
pname = project['name'].strip()
except TypeError:
print('Exiting, failed to process this project:')
print(project)
sys.exit()
if project_name == pname:
project_id = project['id']
break
else:
print("The project you entered couldn't be found in the list of your available projects. Exiting.")
sys.exit()
# Get the column ids associated with the project
columns_url = columns_template % project_id
response = requests.get(columns_url, headers=headers, auth=auth)
cols_to_fetch = ['Done', 'Ready for Deploy']
if args.column:
cols_to_fetch = args.column.split(",")
column_ids = [col['id'] for col in json.loads(response.text) if col['name'] in cols_to_fetch]
issues = []
for col_id in column_ids:
# Loop through each card in each column and the the issue data associated
# with the card
cards_url_partial = cards_template.format(col_id) + '?page={}'
page_num = 1
has_next = True
while has_next:
cards_url = cards_url_partial.format(page_num)
cards_response = requests.get(cards_url, headers=headers, auth=auth)
for card in json.loads(cards_response.text):
# If there is a note in the column, it will not have a content url and can be skipped
try:
match = re.search('(\d+)$', card['content_url'])
except KeyError:
continue
issue_num = match.group(1)
issue_url = issue_template.format(issue_num)
issue_response = requests.get(issue_url, headers=headers, auth=auth)
issues.append((issue_num, json.loads(issue_response.text)['title']))
if args.closeissues:
response = requests.patch(issue_url, headers=headers, auth=auth, json={'state': 'closed'})
if 'next' in cards_response.links:
page_num += 1
else:
has_next = False
if issues:
issues.sort(key=lambda k: int(k[0]), reverse=True)
print('')
for i in issues:
print('#%s - %s' % i)
else:
print("No cards in the column(s)", ', '.join(cols_to_fetch))
| 37.605042 | 129 | 0.682682 |
import requests
from requests.auth import HTTPBasicAuth
import json
import os
import yaml
import sys
import re
import getpass
import argparse
headers = {'Accept': 'application/vnd.github.inertia-preview+json'}
parser = argparse.ArgumentParser(description='Parse a .po file')
parser.add_argument('--column', help='the column name of the tickets you want to extract')
parser.add_argument('--closeissues', action='store_true', help='Close all of the issues in the column')
args = parser.parse_args()
project_name = input('Enter the project name: ')
print('\nEnter 1 to use GitHub token authorization (https://github.com/settings/tokens)')
print('Enter 2 to use GitHub username and password: ')
auth_pref = input('Enter 1 or 2: ')
if auth_pref == '1':
CONFIG_PATH = os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir, os.pardir, 'config', 'settings.secret.yml'))
with open(CONFIG_PATH, 'r') as fh:
app_settings = yaml.full_load(fh)
try:
token = app_settings['GITHUB_TOKEN']
print('Found your GitHub key in the settings file\n')
except KeyError:
token = getpass.getpass('GitHub token: ')
headers['Authorization'] = 'token %s' % token
auth = ''
elif auth_pref == '2':
username = input('GitHub username: ')
password = getpass.getpass('GitHub password: ')
auth = HTTPBasicAuth(username, password)
else:
print (type(auth_pref))
print('You must choose either 1 or 2. You chose %s. Exiting.' % auth_pref)
sys.exit()
projects_url = 'https://api.github.com/repos/mercycorps/TolaActivity/projects'
columns_template = 'https://api.github.com/projects/%s/columns'
cards_template = 'https://api.github.com/projects/columns/{}/cards'
issue_template = 'https://api.github.com/repos/mercycorps/TolaActivity/issues/{}'
print('Fetching data')
response = requests.get(projects_url, headers=headers, auth=auth)
projects = json.loads(response.text)
project_id = ''
columnn_ids = []
for project in projects:
try:
pname = project['name'].strip()
except TypeError:
print('Exiting, failed to process this project:')
print(project)
sys.exit()
if project_name == pname:
project_id = project['id']
break
else:
print("The project you entered couldn't be found in the list of your available projects. Exiting.")
sys.exit()
# Get the column ids associated with the project
columns_url = columns_template % project_id
response = requests.get(columns_url, headers=headers, auth=auth)
cols_to_fetch = ['Done', 'Ready for Deploy']
if args.column:
cols_to_fetch = args.column.split(",")
column_ids = [col['id'] for col in json.loads(response.text) if col['name'] in cols_to_fetch]
issues = []
for col_id in column_ids:
# Loop through each card in each column and the the issue data associated
# with the card
cards_url_partial = cards_template.format(col_id) + '?page={}'
page_num = 1
has_next = True
while has_next:
cards_url = cards_url_partial.format(page_num)
cards_response = requests.get(cards_url, headers=headers, auth=auth)
for card in json.loads(cards_response.text):
# If there is a note in the column, it will not have a content url and can be skipped
try:
match = re.search('(\d+)$', card['content_url'])
except KeyError:
continue
issue_num = match.group(1)
issue_url = issue_template.format(issue_num)
issue_response = requests.get(issue_url, headers=headers, auth=auth)
issues.append((issue_num, json.loads(issue_response.text)['title']))
if args.closeissues:
response = requests.patch(issue_url, headers=headers, auth=auth, json={'state': 'closed'})
if 'next' in cards_response.links:
page_num += 1
else:
has_next = False
if issues:
issues.sort(key=lambda k: int(k[0]), reverse=True)
print('')
for i in issues:
print('
else:
print("No cards in the column(s)", ', '.join(cols_to_fetch))
| true | true |
1c3f9a7759248b86862afe650b24be7a650c7e82 | 24,653 | py | Python | tests/cli/commands/test_task_command.py | utkarsharma2/airflow | 52569ef1cf90554d1a8d119ecc9f8fd767653c2b | [
"Apache-2.0"
] | null | null | null | tests/cli/commands/test_task_command.py | utkarsharma2/airflow | 52569ef1cf90554d1a8d119ecc9f8fd767653c2b | [
"Apache-2.0"
] | null | null | null | tests/cli/commands/test_task_command.py | utkarsharma2/airflow | 52569ef1cf90554d1a8d119ecc9f8fd767653c2b | [
"Apache-2.0"
] | null | null | null | #
# 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.
#
import io
import json
import logging
import os
import re
import unittest
from argparse import ArgumentParser
from contextlib import redirect_stdout
from datetime import datetime
from unittest import mock
import pytest
from parameterized import parameterized
from airflow import DAG
from airflow.cli import cli_parser
from airflow.cli.commands import task_command
from airflow.configuration import conf
from airflow.exceptions import AirflowException, DagRunNotFound
from airflow.models import DagBag, DagRun, Pool, TaskInstance
from airflow.models.serialized_dag import SerializedDagModel
from airflow.utils import timezone
from airflow.utils.dates import days_ago
from airflow.utils.session import create_session
from airflow.utils.state import State
from airflow.utils.types import DagRunType
from tests.test_utils.config import conf_vars
from tests.test_utils.db import clear_db_pools, clear_db_runs
DEFAULT_DATE = days_ago(1)
ROOT_FOLDER = os.path.realpath(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir)
)
def reset(dag_id):
with create_session() as session:
tis = session.query(TaskInstance).filter_by(dag_id=dag_id)
tis.delete()
runs = session.query(DagRun).filter_by(dag_id=dag_id)
runs.delete()
# TODO: Check if tests needs side effects - locally there's missing DAG
class TestCliTasks(unittest.TestCase):
run_id = 'TEST_RUN_ID'
dag_id = 'example_python_operator'
parser: ArgumentParser
dagbag: DagBag
dag: DAG
dag_run: DagRun
@classmethod
def setUpClass(cls):
cls.dagbag = DagBag(include_examples=True)
cls.parser = cli_parser.get_parser()
clear_db_runs()
cls.dag = cls.dagbag.get_dag(cls.dag_id)
cls.dag_run = cls.dag.create_dagrun(
state=State.NONE, run_id=cls.run_id, run_type=DagRunType.MANUAL, execution_date=DEFAULT_DATE
)
@classmethod
def tearDownClass(cls) -> None:
clear_db_runs()
def test_cli_list_tasks(self):
for dag_id in self.dagbag.dags:
args = self.parser.parse_args(['tasks', 'list', dag_id])
task_command.task_list(args)
args = self.parser.parse_args(['tasks', 'list', 'example_bash_operator', '--tree'])
task_command.task_list(args)
@pytest.mark.filterwarnings("ignore::airflow.utils.context.AirflowContextDeprecationWarning")
def test_test(self):
"""Test the `airflow test` command"""
args = self.parser.parse_args(
["tasks", "test", "example_python_operator", 'print_the_context', '2018-01-01']
)
with redirect_stdout(io.StringIO()) as stdout:
task_command.task_test(args)
# Check that prints, and log messages, are shown
assert "'example_python_operator__print_the_context__20180101'" in stdout.getvalue()
@pytest.mark.filterwarnings("ignore::airflow.utils.context.AirflowContextDeprecationWarning")
def test_test_with_existing_dag_run(self):
"""Test the `airflow test` command"""
task_id = 'print_the_context'
args = self.parser.parse_args(["tasks", "test", self.dag_id, task_id, DEFAULT_DATE.isoformat()])
with self.assertLogs('airflow.task', level='INFO') as cm:
task_command.task_test(args)
assert any(
[
f"Marking task as SUCCESS. dag_id={self.dag_id}, task_id={task_id}" in log
for log in cm.output
]
)
@mock.patch("airflow.cli.commands.task_command.get_dag_by_deserialization")
@mock.patch("airflow.cli.commands.task_command.LocalTaskJob")
def test_run_get_serialized_dag(self, mock_local_job, mock_get_dag_by_deserialization):
"""
Test using serialized dag for local task_run
"""
task_id = self.dag.task_ids[0]
args = [
'tasks',
'run',
'--ignore-all-dependencies',
'--local',
self.dag_id,
task_id,
self.run_id,
]
mock_get_dag_by_deserialization.return_value = SerializedDagModel.get(self.dag_id).dag
task_command.task_run(self.parser.parse_args(args))
mock_local_job.assert_called_once_with(
task_instance=mock.ANY,
mark_success=False,
ignore_all_deps=True,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
pickle_id=None,
pool=None,
external_executor_id=None,
)
mock_get_dag_by_deserialization.assert_called_once_with(self.dag_id)
@mock.patch("airflow.cli.commands.task_command.LocalTaskJob")
def test_run_with_existing_dag_run_id(self, mock_local_job):
"""
Test that we can run with existing dag_run_id
"""
task0_id = self.dag.task_ids[0]
args0 = [
'tasks',
'run',
'--ignore-all-dependencies',
'--local',
self.dag_id,
task0_id,
self.run_id,
]
task_command.task_run(self.parser.parse_args(args0), dag=self.dag)
mock_local_job.assert_called_once_with(
task_instance=mock.ANY,
mark_success=False,
ignore_all_deps=True,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
pickle_id=None,
pool=None,
external_executor_id=None,
)
@mock.patch("airflow.cli.commands.task_command.LocalTaskJob")
def test_run_raises_when_theres_no_dagrun(self, mock_local_job):
"""
Test that run raises when there's run_id but no dag_run
"""
dag_id = 'test_run_ignores_all_dependencies'
dag = self.dagbag.get_dag(dag_id)
task0_id = 'test_run_dependent_task'
run_id = 'TEST_RUN_ID'
args0 = [
'tasks',
'run',
'--ignore-all-dependencies',
'--local',
dag_id,
task0_id,
run_id,
]
with self.assertRaises(DagRunNotFound):
task_command.task_run(self.parser.parse_args(args0), dag=dag)
def test_cli_test_with_params(self):
task_command.task_test(
self.parser.parse_args(
[
'tasks',
'test',
'example_passing_params_via_test_command',
'run_this',
'--task-params',
'{"foo":"bar"}',
DEFAULT_DATE.isoformat(),
]
)
)
task_command.task_test(
self.parser.parse_args(
[
'tasks',
'test',
'example_passing_params_via_test_command',
'also_run_this',
'--task-params',
'{"foo":"bar"}',
DEFAULT_DATE.isoformat(),
]
)
)
def test_cli_test_with_env_vars(self):
with redirect_stdout(io.StringIO()) as stdout:
task_command.task_test(
self.parser.parse_args(
[
'tasks',
'test',
'example_passing_params_via_test_command',
'env_var_test_task',
'--env-vars',
'{"foo":"bar"}',
DEFAULT_DATE.isoformat(),
]
)
)
output = stdout.getvalue()
assert 'foo=bar' in output
assert 'AIRFLOW_TEST_MODE=True' in output
@parameterized.expand(
[
("--ignore-all-dependencies",),
("--ignore-depends-on-past",),
("--ignore-dependencies",),
("--force",),
],
)
def test_cli_run_invalid_raw_option(self, option: str):
with pytest.raises(
AirflowException,
match="Option --raw does not work with some of the other options on this command.",
):
task_command.task_run(
self.parser.parse_args(
[ # type: ignore
'tasks',
'run',
'example_bash_operator',
'runme_0',
DEFAULT_DATE.isoformat(),
'--raw',
option,
]
)
)
def test_cli_run_mutually_exclusive(self):
with pytest.raises(AirflowException, match="Option --raw and --local are mutually exclusive."):
task_command.task_run(
self.parser.parse_args(
[
'tasks',
'run',
'example_bash_operator',
'runme_0',
DEFAULT_DATE.isoformat(),
'--raw',
'--local',
]
)
)
def test_task_render(self):
"""
tasks render should render and displays templated fields for a given task
"""
with redirect_stdout(io.StringIO()) as stdout:
task_command.task_render(
self.parser.parse_args(['tasks', 'render', 'tutorial', 'templated', '2016-01-01'])
)
output = stdout.getvalue()
assert 'echo "2016-01-01"' in output
assert 'echo "2016-01-08"' in output
def test_cli_run_when_pickle_and_dag_cli_method_selected(self):
"""
tasks run should return an AirflowException when invalid pickle_id is passed
"""
pickle_id = 'pickle_id'
with pytest.raises(
AirflowException,
match=re.escape("You cannot use the --pickle option when using DAG.cli() method."),
):
task_command.task_run(
self.parser.parse_args(
[
'tasks',
'run',
'example_bash_operator',
'runme_0',
DEFAULT_DATE.isoformat(),
'--pickle',
pickle_id,
]
),
self.dag,
)
def test_task_state(self):
task_command.task_state(
self.parser.parse_args(
['tasks', 'state', self.dag_id, 'print_the_context', DEFAULT_DATE.isoformat()]
)
)
def test_task_states_for_dag_run(self):
dag2 = DagBag().dags['example_python_operator']
task2 = dag2.get_task(task_id='print_the_context')
default_date2 = timezone.make_aware(datetime(2016, 1, 9))
dag2.clear()
dagrun = dag2.create_dagrun(
state=State.RUNNING,
execution_date=default_date2,
run_type=DagRunType.MANUAL,
external_trigger=True,
)
ti2 = TaskInstance(task2, dagrun.execution_date)
ti2.set_state(State.SUCCESS)
ti_start = ti2.start_date
ti_end = ti2.end_date
with redirect_stdout(io.StringIO()) as stdout:
task_command.task_states_for_dag_run(
self.parser.parse_args(
[
'tasks',
'states-for-dag-run',
'example_python_operator',
default_date2.isoformat(),
'--output',
"json",
]
)
)
actual_out = json.loads(stdout.getvalue())
assert len(actual_out) == 1
assert actual_out[0] == {
'dag_id': 'example_python_operator',
'execution_date': '2016-01-09T00:00:00+00:00',
'task_id': 'print_the_context',
'state': 'success',
'start_date': ti_start.isoformat(),
'end_date': ti_end.isoformat(),
}
def test_task_states_for_dag_run_when_dag_run_not_exists(self):
"""
task_states_for_dag_run should return an AirflowException when invalid dag id is passed
"""
with pytest.raises(DagRunNotFound):
default_date2 = timezone.make_aware(datetime(2016, 1, 9))
task_command.task_states_for_dag_run(
self.parser.parse_args(
[
'tasks',
'states-for-dag-run',
'not_exists_dag',
default_date2.isoformat(),
'--output',
"json",
]
)
)
def test_subdag_clear(self):
args = self.parser.parse_args(['tasks', 'clear', 'example_subdag_operator', '--yes'])
task_command.task_clear(args)
args = self.parser.parse_args(
['tasks', 'clear', 'example_subdag_operator', '--yes', '--exclude-subdags']
)
task_command.task_clear(args)
def test_parentdag_downstream_clear(self):
args = self.parser.parse_args(['tasks', 'clear', 'example_subdag_operator.section-1', '--yes'])
task_command.task_clear(args)
args = self.parser.parse_args(
['tasks', 'clear', 'example_subdag_operator.section-1', '--yes', '--exclude-parentdag']
)
task_command.task_clear(args)
class TestLogsfromTaskRunCommand(unittest.TestCase):
def setUp(self) -> None:
self.dag_id = "test_logging_dag"
self.task_id = "test_task"
self.run_id = "test_run"
self.dag_path = os.path.join(ROOT_FOLDER, "dags", "test_logging_in_dag.py")
reset(self.dag_id)
self.execution_date = timezone.make_aware(datetime(2017, 1, 1))
self.execution_date_str = self.execution_date.isoformat()
self.task_args = ['tasks', 'run', self.dag_id, self.task_id, '--local', self.execution_date_str]
self.log_dir = conf.get_mandatory_value('logging', 'base_log_folder')
self.log_filename = f"dag_id={self.dag_id}/run_id={self.run_id}/task_id={self.task_id}/attempt=1.log"
self.ti_log_file_path = os.path.join(self.log_dir, self.log_filename)
self.parser = cli_parser.get_parser()
DagBag().get_dag(self.dag_id).create_dagrun(
run_id=self.run_id,
execution_date=self.execution_date,
start_date=timezone.utcnow(),
state=State.RUNNING,
run_type=DagRunType.MANUAL,
)
root = self.root_logger = logging.getLogger()
self.root_handlers = root.handlers.copy()
self.root_filters = root.filters.copy()
self.root_level = root.level
try:
os.remove(self.ti_log_file_path)
except OSError:
pass
def tearDown(self) -> None:
root = self.root_logger
root.setLevel(self.root_level)
root.handlers[:] = self.root_handlers
root.filters[:] = self.root_filters
reset(self.dag_id)
try:
os.remove(self.ti_log_file_path)
except OSError:
pass
def assert_log_line(self, text, logs_list, expect_from_logging_mixin=False):
"""
Get Log Line and assert only 1 Entry exists with the given text. Also check that
"logging_mixin" line does not appear in that log line to avoid duplicate logging as below:
[2020-06-24 16:47:23,537] {logging_mixin.py:91} INFO - [2020-06-24 16:47:23,536] {python.py:135}
"""
log_lines = [log for log in logs_list if text in log]
assert len(log_lines) == 1
log_line = log_lines[0]
if not expect_from_logging_mixin:
# Logs from print statement still show with logging_mixing as filename
# Example: [2020-06-24 17:07:00,482] {logging_mixin.py:91} INFO - Log from Print statement
assert "logging_mixin.py" not in log_line
return log_line
@mock.patch("airflow.cli.commands.task_command.LocalTaskJob")
def test_external_executor_id_present_for_fork_run_task(self, mock_local_job):
args = self.parser.parse_args(self.task_args)
args.external_executor_id = "ABCD12345"
task_command.task_run(args)
mock_local_job.assert_called_once_with(
task_instance=mock.ANY,
mark_success=False,
pickle_id=None,
ignore_all_deps=False,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
pool=None,
external_executor_id="ABCD12345",
)
@mock.patch("airflow.cli.commands.task_command.LocalTaskJob")
def test_external_executor_id_present_for_process_run_task(self, mock_local_job):
args = self.parser.parse_args(self.task_args)
args.external_executor_id = "ABCD12345"
with mock.patch.dict(os.environ, {"external_executor_id": "12345FEDCBA"}):
task_command.task_run(args)
mock_local_job.assert_called_once_with(
task_instance=mock.ANY,
mark_success=False,
pickle_id=None,
ignore_all_deps=False,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
pool=None,
external_executor_id="ABCD12345",
)
@unittest.skipIf(not hasattr(os, 'fork'), "Forking not available")
def test_logging_with_run_task(self):
# We are not using self.assertLogs as we want to verify what actually is stored in the Log file
# as that is what gets displayed
with conf_vars({('core', 'dags_folder'): self.dag_path}):
task_command.task_run(self.parser.parse_args(self.task_args))
with open(self.ti_log_file_path) as l_file:
logs = l_file.read()
print(logs) # In case of a test failures this line would show detailed log
logs_list = logs.splitlines()
assert "INFO - Started process" in logs
assert f"Subtask {self.task_id}" in logs
assert "standard_task_runner.py" in logs
assert (
f"INFO - Running: ['airflow', 'tasks', 'run', '{self.dag_id}', "
f"'{self.task_id}', '{self.run_id}'," in logs
)
self.assert_log_line("Log from DAG Logger", logs_list)
self.assert_log_line("Log from TI Logger", logs_list)
self.assert_log_line("Log from Print statement", logs_list, expect_from_logging_mixin=True)
assert (
f"INFO - Marking task as SUCCESS. dag_id={self.dag_id}, "
f"task_id={self.task_id}, execution_date=20170101T000000" in logs
)
@unittest.skipIf(not hasattr(os, 'fork'), "Forking not available")
def test_run_task_with_pool(self):
pool_name = 'test_pool_run'
clear_db_pools()
with create_session() as session:
pool = Pool(pool=pool_name, slots=1)
session.add(pool)
session.commit()
assert session.query(TaskInstance).filter_by(pool=pool_name).first() is None
task_command.task_run(self.parser.parse_args(self.task_args + ['--pool', pool_name]))
assert session.query(TaskInstance).filter_by(pool=pool_name).first() is not None
session.delete(pool)
session.commit()
# For this test memory spins out of control on Python 3.6. TODO(potiuk): FIXME")
@pytest.mark.quarantined
@mock.patch("airflow.task.task_runner.standard_task_runner.CAN_FORK", False)
def test_logging_with_run_task_subprocess(self):
# We are not using self.assertLogs as we want to verify what actually is stored in the Log file
# as that is what gets displayed
with conf_vars({('core', 'dags_folder'): self.dag_path}):
task_command.task_run(self.parser.parse_args(self.task_args))
with open(self.ti_log_file_path) as l_file:
logs = l_file.read()
print(logs) # In case of a test failures this line would show detailed log
logs_list = logs.splitlines()
assert f"Subtask {self.task_id}" in logs
assert "base_task_runner.py" in logs
self.assert_log_line("Log from DAG Logger", logs_list)
self.assert_log_line("Log from TI Logger", logs_list)
self.assert_log_line("Log from Print statement", logs_list, expect_from_logging_mixin=True)
assert (
f"INFO - Running: ['airflow', 'tasks', 'run', '{self.dag_id}', "
f"'{self.task_id}', '{self.execution_date_str}'," in logs
)
assert (
f"INFO - Marking task as SUCCESS. dag_id={self.dag_id}, "
f"task_id={self.task_id}, execution_date=20170101T000000" in logs
)
def test_log_file_template_with_run_task(self):
"""Verify that the taskinstance has the right context for log_filename_template"""
with conf_vars({('core', 'dags_folder'): self.dag_path}):
# increment the try_number of the task to be run
with create_session() as session:
ti = session.query(TaskInstance).filter_by(run_id=self.run_id).first()
ti.try_number = 1
log_file_path = os.path.join(os.path.dirname(self.ti_log_file_path), "attempt=2.log")
try:
task_command.task_run(self.parser.parse_args(self.task_args))
assert os.path.exists(log_file_path)
finally:
try:
os.remove(log_file_path)
except OSError:
pass
@mock.patch.object(task_command, "_run_task_by_selected_method")
def test_root_logger_restored(self, run_task_mock):
"""Verify that the root logging context is restored"""
logger = logging.getLogger("foo.bar")
def task_inner(*args, **kwargs):
logger.warning("redirected log message")
run_task_mock.side_effect = task_inner
config = {
('core', 'dags_folder'): self.dag_path,
('logging', 'logging_level'): "INFO",
}
with conf_vars(config):
with self.assertLogs(level=logging.WARNING) as captured:
logger.warning("not redirected")
task_command.task_run(self.parser.parse_args(self.task_args))
assert captured.output == ["WARNING:foo.bar:not redirected"]
assert self.root_logger.level == logging.WARNING
assert self.root_logger.handlers == self.root_handlers
@pytest.mark.quarantined
@mock.patch.object(task_command, "_run_task_by_selected_method")
def test_disable_handler_modifying(self, run_task_mock):
"""If [core] donot_modify_handlers is set to True, the root logger is untouched"""
from airflow import settings
logger = logging.getLogger("foo.bar")
def task_inner(*args, **kwargs):
logger.warning("not redirected")
run_task_mock.side_effect = task_inner
config = {
('core', 'dags_folder'): self.dag_path,
('logging', 'logging_level'): "INFO",
}
old_value = settings.DONOT_MODIFY_HANDLERS
settings.DONOT_MODIFY_HANDLERS = True
with conf_vars(config):
with self.assertLogs(level=logging.WARNING) as captured:
task_command.task_run(self.parser.parse_args(self.task_args))
assert captured.output == ["WARNING:foo.bar:not redirected"]
settings.DONOT_MODIFY_HANDLERS = old_value
| 36.850523 | 109 | 0.593031 |
import io
import json
import logging
import os
import re
import unittest
from argparse import ArgumentParser
from contextlib import redirect_stdout
from datetime import datetime
from unittest import mock
import pytest
from parameterized import parameterized
from airflow import DAG
from airflow.cli import cli_parser
from airflow.cli.commands import task_command
from airflow.configuration import conf
from airflow.exceptions import AirflowException, DagRunNotFound
from airflow.models import DagBag, DagRun, Pool, TaskInstance
from airflow.models.serialized_dag import SerializedDagModel
from airflow.utils import timezone
from airflow.utils.dates import days_ago
from airflow.utils.session import create_session
from airflow.utils.state import State
from airflow.utils.types import DagRunType
from tests.test_utils.config import conf_vars
from tests.test_utils.db import clear_db_pools, clear_db_runs
DEFAULT_DATE = days_ago(1)
ROOT_FOLDER = os.path.realpath(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir)
)
def reset(dag_id):
with create_session() as session:
tis = session.query(TaskInstance).filter_by(dag_id=dag_id)
tis.delete()
runs = session.query(DagRun).filter_by(dag_id=dag_id)
runs.delete()
class TestCliTasks(unittest.TestCase):
run_id = 'TEST_RUN_ID'
dag_id = 'example_python_operator'
parser: ArgumentParser
dagbag: DagBag
dag: DAG
dag_run: DagRun
@classmethod
def setUpClass(cls):
cls.dagbag = DagBag(include_examples=True)
cls.parser = cli_parser.get_parser()
clear_db_runs()
cls.dag = cls.dagbag.get_dag(cls.dag_id)
cls.dag_run = cls.dag.create_dagrun(
state=State.NONE, run_id=cls.run_id, run_type=DagRunType.MANUAL, execution_date=DEFAULT_DATE
)
@classmethod
def tearDownClass(cls) -> None:
clear_db_runs()
def test_cli_list_tasks(self):
for dag_id in self.dagbag.dags:
args = self.parser.parse_args(['tasks', 'list', dag_id])
task_command.task_list(args)
args = self.parser.parse_args(['tasks', 'list', 'example_bash_operator', '--tree'])
task_command.task_list(args)
@pytest.mark.filterwarnings("ignore::airflow.utils.context.AirflowContextDeprecationWarning")
def test_test(self):
args = self.parser.parse_args(
["tasks", "test", "example_python_operator", 'print_the_context', '2018-01-01']
)
with redirect_stdout(io.StringIO()) as stdout:
task_command.task_test(args)
# Check that prints, and log messages, are shown
assert "'example_python_operator__print_the_context__20180101'" in stdout.getvalue()
@pytest.mark.filterwarnings("ignore::airflow.utils.context.AirflowContextDeprecationWarning")
def test_test_with_existing_dag_run(self):
task_id = 'print_the_context'
args = self.parser.parse_args(["tasks", "test", self.dag_id, task_id, DEFAULT_DATE.isoformat()])
with self.assertLogs('airflow.task', level='INFO') as cm:
task_command.task_test(args)
assert any(
[
f"Marking task as SUCCESS. dag_id={self.dag_id}, task_id={task_id}" in log
for log in cm.output
]
)
@mock.patch("airflow.cli.commands.task_command.get_dag_by_deserialization")
@mock.patch("airflow.cli.commands.task_command.LocalTaskJob")
def test_run_get_serialized_dag(self, mock_local_job, mock_get_dag_by_deserialization):
task_id = self.dag.task_ids[0]
args = [
'tasks',
'run',
'--ignore-all-dependencies',
'--local',
self.dag_id,
task_id,
self.run_id,
]
mock_get_dag_by_deserialization.return_value = SerializedDagModel.get(self.dag_id).dag
task_command.task_run(self.parser.parse_args(args))
mock_local_job.assert_called_once_with(
task_instance=mock.ANY,
mark_success=False,
ignore_all_deps=True,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
pickle_id=None,
pool=None,
external_executor_id=None,
)
mock_get_dag_by_deserialization.assert_called_once_with(self.dag_id)
@mock.patch("airflow.cli.commands.task_command.LocalTaskJob")
def test_run_with_existing_dag_run_id(self, mock_local_job):
task0_id = self.dag.task_ids[0]
args0 = [
'tasks',
'run',
'--ignore-all-dependencies',
'--local',
self.dag_id,
task0_id,
self.run_id,
]
task_command.task_run(self.parser.parse_args(args0), dag=self.dag)
mock_local_job.assert_called_once_with(
task_instance=mock.ANY,
mark_success=False,
ignore_all_deps=True,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
pickle_id=None,
pool=None,
external_executor_id=None,
)
@mock.patch("airflow.cli.commands.task_command.LocalTaskJob")
def test_run_raises_when_theres_no_dagrun(self, mock_local_job):
dag_id = 'test_run_ignores_all_dependencies'
dag = self.dagbag.get_dag(dag_id)
task0_id = 'test_run_dependent_task'
run_id = 'TEST_RUN_ID'
args0 = [
'tasks',
'run',
'--ignore-all-dependencies',
'--local',
dag_id,
task0_id,
run_id,
]
with self.assertRaises(DagRunNotFound):
task_command.task_run(self.parser.parse_args(args0), dag=dag)
def test_cli_test_with_params(self):
task_command.task_test(
self.parser.parse_args(
[
'tasks',
'test',
'example_passing_params_via_test_command',
'run_this',
'--task-params',
'{"foo":"bar"}',
DEFAULT_DATE.isoformat(),
]
)
)
task_command.task_test(
self.parser.parse_args(
[
'tasks',
'test',
'example_passing_params_via_test_command',
'also_run_this',
'--task-params',
'{"foo":"bar"}',
DEFAULT_DATE.isoformat(),
]
)
)
def test_cli_test_with_env_vars(self):
with redirect_stdout(io.StringIO()) as stdout:
task_command.task_test(
self.parser.parse_args(
[
'tasks',
'test',
'example_passing_params_via_test_command',
'env_var_test_task',
'--env-vars',
'{"foo":"bar"}',
DEFAULT_DATE.isoformat(),
]
)
)
output = stdout.getvalue()
assert 'foo=bar' in output
assert 'AIRFLOW_TEST_MODE=True' in output
@parameterized.expand(
[
("--ignore-all-dependencies",),
("--ignore-depends-on-past",),
("--ignore-dependencies",),
("--force",),
],
)
def test_cli_run_invalid_raw_option(self, option: str):
with pytest.raises(
AirflowException,
match="Option --raw does not work with some of the other options on this command.",
):
task_command.task_run(
self.parser.parse_args(
[ # type: ignore
'tasks',
'run',
'example_bash_operator',
'runme_0',
DEFAULT_DATE.isoformat(),
'--raw',
option,
]
)
)
def test_cli_run_mutually_exclusive(self):
with pytest.raises(AirflowException, match="Option --raw and --local are mutually exclusive."):
task_command.task_run(
self.parser.parse_args(
[
'tasks',
'run',
'example_bash_operator',
'runme_0',
DEFAULT_DATE.isoformat(),
'--raw',
'--local',
]
)
)
def test_task_render(self):
with redirect_stdout(io.StringIO()) as stdout:
task_command.task_render(
self.parser.parse_args(['tasks', 'render', 'tutorial', 'templated', '2016-01-01'])
)
output = stdout.getvalue()
assert 'echo "2016-01-01"' in output
assert 'echo "2016-01-08"' in output
def test_cli_run_when_pickle_and_dag_cli_method_selected(self):
pickle_id = 'pickle_id'
with pytest.raises(
AirflowException,
match=re.escape("You cannot use the --pickle option when using DAG.cli() method."),
):
task_command.task_run(
self.parser.parse_args(
[
'tasks',
'run',
'example_bash_operator',
'runme_0',
DEFAULT_DATE.isoformat(),
'--pickle',
pickle_id,
]
),
self.dag,
)
def test_task_state(self):
task_command.task_state(
self.parser.parse_args(
['tasks', 'state', self.dag_id, 'print_the_context', DEFAULT_DATE.isoformat()]
)
)
def test_task_states_for_dag_run(self):
dag2 = DagBag().dags['example_python_operator']
task2 = dag2.get_task(task_id='print_the_context')
default_date2 = timezone.make_aware(datetime(2016, 1, 9))
dag2.clear()
dagrun = dag2.create_dagrun(
state=State.RUNNING,
execution_date=default_date2,
run_type=DagRunType.MANUAL,
external_trigger=True,
)
ti2 = TaskInstance(task2, dagrun.execution_date)
ti2.set_state(State.SUCCESS)
ti_start = ti2.start_date
ti_end = ti2.end_date
with redirect_stdout(io.StringIO()) as stdout:
task_command.task_states_for_dag_run(
self.parser.parse_args(
[
'tasks',
'states-for-dag-run',
'example_python_operator',
default_date2.isoformat(),
'--output',
"json",
]
)
)
actual_out = json.loads(stdout.getvalue())
assert len(actual_out) == 1
assert actual_out[0] == {
'dag_id': 'example_python_operator',
'execution_date': '2016-01-09T00:00:00+00:00',
'task_id': 'print_the_context',
'state': 'success',
'start_date': ti_start.isoformat(),
'end_date': ti_end.isoformat(),
}
def test_task_states_for_dag_run_when_dag_run_not_exists(self):
with pytest.raises(DagRunNotFound):
default_date2 = timezone.make_aware(datetime(2016, 1, 9))
task_command.task_states_for_dag_run(
self.parser.parse_args(
[
'tasks',
'states-for-dag-run',
'not_exists_dag',
default_date2.isoformat(),
'--output',
"json",
]
)
)
def test_subdag_clear(self):
args = self.parser.parse_args(['tasks', 'clear', 'example_subdag_operator', '--yes'])
task_command.task_clear(args)
args = self.parser.parse_args(
['tasks', 'clear', 'example_subdag_operator', '--yes', '--exclude-subdags']
)
task_command.task_clear(args)
def test_parentdag_downstream_clear(self):
args = self.parser.parse_args(['tasks', 'clear', 'example_subdag_operator.section-1', '--yes'])
task_command.task_clear(args)
args = self.parser.parse_args(
['tasks', 'clear', 'example_subdag_operator.section-1', '--yes', '--exclude-parentdag']
)
task_command.task_clear(args)
class TestLogsfromTaskRunCommand(unittest.TestCase):
def setUp(self) -> None:
self.dag_id = "test_logging_dag"
self.task_id = "test_task"
self.run_id = "test_run"
self.dag_path = os.path.join(ROOT_FOLDER, "dags", "test_logging_in_dag.py")
reset(self.dag_id)
self.execution_date = timezone.make_aware(datetime(2017, 1, 1))
self.execution_date_str = self.execution_date.isoformat()
self.task_args = ['tasks', 'run', self.dag_id, self.task_id, '--local', self.execution_date_str]
self.log_dir = conf.get_mandatory_value('logging', 'base_log_folder')
self.log_filename = f"dag_id={self.dag_id}/run_id={self.run_id}/task_id={self.task_id}/attempt=1.log"
self.ti_log_file_path = os.path.join(self.log_dir, self.log_filename)
self.parser = cli_parser.get_parser()
DagBag().get_dag(self.dag_id).create_dagrun(
run_id=self.run_id,
execution_date=self.execution_date,
start_date=timezone.utcnow(),
state=State.RUNNING,
run_type=DagRunType.MANUAL,
)
root = self.root_logger = logging.getLogger()
self.root_handlers = root.handlers.copy()
self.root_filters = root.filters.copy()
self.root_level = root.level
try:
os.remove(self.ti_log_file_path)
except OSError:
pass
def tearDown(self) -> None:
root = self.root_logger
root.setLevel(self.root_level)
root.handlers[:] = self.root_handlers
root.filters[:] = self.root_filters
reset(self.dag_id)
try:
os.remove(self.ti_log_file_path)
except OSError:
pass
def assert_log_line(self, text, logs_list, expect_from_logging_mixin=False):
log_lines = [log for log in logs_list if text in log]
assert len(log_lines) == 1
log_line = log_lines[0]
if not expect_from_logging_mixin:
# Logs from print statement still show with logging_mixing as filename
# Example: [2020-06-24 17:07:00,482] {logging_mixin.py:91} INFO - Log from Print statement
assert "logging_mixin.py" not in log_line
return log_line
@mock.patch("airflow.cli.commands.task_command.LocalTaskJob")
def test_external_executor_id_present_for_fork_run_task(self, mock_local_job):
args = self.parser.parse_args(self.task_args)
args.external_executor_id = "ABCD12345"
task_command.task_run(args)
mock_local_job.assert_called_once_with(
task_instance=mock.ANY,
mark_success=False,
pickle_id=None,
ignore_all_deps=False,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
pool=None,
external_executor_id="ABCD12345",
)
@mock.patch("airflow.cli.commands.task_command.LocalTaskJob")
def test_external_executor_id_present_for_process_run_task(self, mock_local_job):
args = self.parser.parse_args(self.task_args)
args.external_executor_id = "ABCD12345"
with mock.patch.dict(os.environ, {"external_executor_id": "12345FEDCBA"}):
task_command.task_run(args)
mock_local_job.assert_called_once_with(
task_instance=mock.ANY,
mark_success=False,
pickle_id=None,
ignore_all_deps=False,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
pool=None,
external_executor_id="ABCD12345",
)
@unittest.skipIf(not hasattr(os, 'fork'), "Forking not available")
def test_logging_with_run_task(self):
# We are not using self.assertLogs as we want to verify what actually is stored in the Log file
# as that is what gets displayed
with conf_vars({('core', 'dags_folder'): self.dag_path}):
task_command.task_run(self.parser.parse_args(self.task_args))
with open(self.ti_log_file_path) as l_file:
logs = l_file.read()
print(logs) # In case of a test failures this line would show detailed log
logs_list = logs.splitlines()
assert "INFO - Started process" in logs
assert f"Subtask {self.task_id}" in logs
assert "standard_task_runner.py" in logs
assert (
f"INFO - Running: ['airflow', 'tasks', 'run', '{self.dag_id}', "
f"'{self.task_id}', '{self.run_id}'," in logs
)
self.assert_log_line("Log from DAG Logger", logs_list)
self.assert_log_line("Log from TI Logger", logs_list)
self.assert_log_line("Log from Print statement", logs_list, expect_from_logging_mixin=True)
assert (
f"INFO - Marking task as SUCCESS. dag_id={self.dag_id}, "
f"task_id={self.task_id}, execution_date=20170101T000000" in logs
)
@unittest.skipIf(not hasattr(os, 'fork'), "Forking not available")
def test_run_task_with_pool(self):
pool_name = 'test_pool_run'
clear_db_pools()
with create_session() as session:
pool = Pool(pool=pool_name, slots=1)
session.add(pool)
session.commit()
assert session.query(TaskInstance).filter_by(pool=pool_name).first() is None
task_command.task_run(self.parser.parse_args(self.task_args + ['--pool', pool_name]))
assert session.query(TaskInstance).filter_by(pool=pool_name).first() is not None
session.delete(pool)
session.commit()
# For this test memory spins out of control on Python 3.6. TODO(potiuk): FIXME")
@pytest.mark.quarantined
@mock.patch("airflow.task.task_runner.standard_task_runner.CAN_FORK", False)
def test_logging_with_run_task_subprocess(self):
# We are not using self.assertLogs as we want to verify what actually is stored in the Log file
# as that is what gets displayed
with conf_vars({('core', 'dags_folder'): self.dag_path}):
task_command.task_run(self.parser.parse_args(self.task_args))
with open(self.ti_log_file_path) as l_file:
logs = l_file.read()
print(logs) # In case of a test failures this line would show detailed log
logs_list = logs.splitlines()
assert f"Subtask {self.task_id}" in logs
assert "base_task_runner.py" in logs
self.assert_log_line("Log from DAG Logger", logs_list)
self.assert_log_line("Log from TI Logger", logs_list)
self.assert_log_line("Log from Print statement", logs_list, expect_from_logging_mixin=True)
assert (
f"INFO - Running: ['airflow', 'tasks', 'run', '{self.dag_id}', "
f"'{self.task_id}', '{self.execution_date_str}'," in logs
)
assert (
f"INFO - Marking task as SUCCESS. dag_id={self.dag_id}, "
f"task_id={self.task_id}, execution_date=20170101T000000" in logs
)
def test_log_file_template_with_run_task(self):
with conf_vars({('core', 'dags_folder'): self.dag_path}):
# increment the try_number of the task to be run
with create_session() as session:
ti = session.query(TaskInstance).filter_by(run_id=self.run_id).first()
ti.try_number = 1
log_file_path = os.path.join(os.path.dirname(self.ti_log_file_path), "attempt=2.log")
try:
task_command.task_run(self.parser.parse_args(self.task_args))
assert os.path.exists(log_file_path)
finally:
try:
os.remove(log_file_path)
except OSError:
pass
@mock.patch.object(task_command, "_run_task_by_selected_method")
def test_root_logger_restored(self, run_task_mock):
logger = logging.getLogger("foo.bar")
def task_inner(*args, **kwargs):
logger.warning("redirected log message")
run_task_mock.side_effect = task_inner
config = {
('core', 'dags_folder'): self.dag_path,
('logging', 'logging_level'): "INFO",
}
with conf_vars(config):
with self.assertLogs(level=logging.WARNING) as captured:
logger.warning("not redirected")
task_command.task_run(self.parser.parse_args(self.task_args))
assert captured.output == ["WARNING:foo.bar:not redirected"]
assert self.root_logger.level == logging.WARNING
assert self.root_logger.handlers == self.root_handlers
@pytest.mark.quarantined
@mock.patch.object(task_command, "_run_task_by_selected_method")
def test_disable_handler_modifying(self, run_task_mock):
from airflow import settings
logger = logging.getLogger("foo.bar")
def task_inner(*args, **kwargs):
logger.warning("not redirected")
run_task_mock.side_effect = task_inner
config = {
('core', 'dags_folder'): self.dag_path,
('logging', 'logging_level'): "INFO",
}
old_value = settings.DONOT_MODIFY_HANDLERS
settings.DONOT_MODIFY_HANDLERS = True
with conf_vars(config):
with self.assertLogs(level=logging.WARNING) as captured:
task_command.task_run(self.parser.parse_args(self.task_args))
assert captured.output == ["WARNING:foo.bar:not redirected"]
settings.DONOT_MODIFY_HANDLERS = old_value
| true | true |
1c3f9ba1ef528c098a499f8749bd5a92e3a1417d | 182,454 | py | Python | yt_dlp/YoutubeDL.py | ibook86/yt-dlp | 9a5b0125752179f6447ca29deb89ee452fd78b85 | [
"Unlicense"
] | null | null | null | yt_dlp/YoutubeDL.py | ibook86/yt-dlp | 9a5b0125752179f6447ca29deb89ee452fd78b85 | [
"Unlicense"
] | null | null | null | yt_dlp/YoutubeDL.py | ibook86/yt-dlp | 9a5b0125752179f6447ca29deb89ee452fd78b85 | [
"Unlicense"
] | null | null | null | #!/usr/bin/env python3
# coding: utf-8
from __future__ import absolute_import, unicode_literals
import collections
import contextlib
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 enum import Enum
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,
DownloadCancelled,
DownloadError,
encode_compat_str,
encodeFilename,
EntryNotInPlaylist,
error_to_compat_str,
ExistingVideoReached,
expand_path,
ExtractorError,
float_or_none,
format_bytes,
format_field,
format_decimal_suffix,
formatSeconds,
GeoRestrictedError,
get_domain,
HEADRequest,
InAdvancePagedList,
int_or_none,
iri_to_uri,
ISO3166Utils,
join_nonempty,
LazyList,
LINK_TEMPLATES,
locked_file,
make_dir,
make_HTTPS_handler,
MaxDownloadsReached,
network_exceptions,
number_of_digits,
orderedSet,
OUTTMPL_TYPES,
PagedList,
parse_filesize,
PerRequestProxyHandler,
platform_name,
Popen,
POSTPROCESS_WHEN,
PostProcessingError,
preferredencoding,
prepend_extension,
ReExtractInfo,
register_socks_protocols,
RejectedVideoReached,
remove_terminal_sequences,
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,
timetuple_from_msec,
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 .minicurses import format_text
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,
FFmpegFixupDuplicateMoovPP,
FFmpegFixupDurationPP,
FFmpegFixupM3u8PP,
FFmpegFixupM4aPP,
FFmpegFixupStretchedPP,
FFmpegFixupTimestampPP,
FFmpegMergerPP,
FFmpegPostProcessor,
MoveFilesAfterDownloadPP,
_PLUGIN_CLASSES as plugin_postprocessors
)
from .update import detect_variant
from .version import __version__, RELEASE_GIT_HEAD
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 dict with keys WHEN mapped to a list of templates to
print to stdout. The allowed keys are video or any of the
items in utils.POSTPROCESS_WHEN.
For compatibility, a single list is also accepted
print_to_file: A dict with keys WHEN (same as forceprint) mapped to
a list of tuples with (template, filename)
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.
You can also pass a function. The function takes 'ctx' as
argument and returns the formats to download.
See "build_format_selector" for an implementation
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: A list of fields by which 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),
'selected' (check selected formats),
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.
break_per_url: Whether break_on_reject and break_on_existing
should act on each input URL as opposed to for the entire queue
cookiefile: File name where cookies should be read from and dumped to
cookiesfrombrowser: A tuple containing the name of the browser, the profile
name/pathfrom where cookies are loaded, and the name of the
keyring. Eg: ('chrome', ) or ('vivaldi', 'default', 'BASICTEXT')
legacyserverconnect: Explicitly allow HTTPS connection to servers that do not
support RFC 5746 secure renegotiation
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 (deprecated)
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.
wait_for_video: If given, wait for scheduled streams to become available.
The value should be a tuple containing the range
(min_secs, max_secs) to wait between retries
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. Allowed values are
the entries of utils.POSTPROCESS_WHEN
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
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, no-attach-info-json.
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, file_access_retries, fragment_retries,
continuedl, noprogress, xattr_set_filesize, hls_use_mpegts, http_chunk_size,
external_downloader_args, concurrent_fragment_downloads.
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']}}
mark_watched: Mark videos watched (even with --simulate). Only for YouTube
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 = {k: [] for k in POSTPROCESS_WHEN}
_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 print the header
"""
if params is None:
params = {}
self._ies = {}
self._ies_instances = {}
self._pps = {k: [] for k in POSTPROCESS_WHEN}
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._num_videos = 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()
self._allow_colors = {
'screen': not self.params.get('no_color') and supports_terminal_sequences(self._screen_file),
'err': not self.params.get('no_color') and 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._format_err("UNPLAYABLE", self.Styles.EMPHASIS)} formats to be listed/downloaded. '
'This is a developer option intended for debugging. \n'
' If you experience any issues while using this option, '
f'{self._format_err("DO NOT", self.Styles.ERROR)} 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)
for msg in self.params.get('_deprecation_warnings', []):
self.deprecation_warning(msg)
if 'list-formats' in self.params.get('compat_opts', []):
self.params['listformats_table'] = False
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']
self.params.setdefault('forceprint', {})
self.params.setdefault('print_to_file', {})
# Compatibility with older syntax
if not isinstance(params['forceprint'], dict):
self.params['forceprint'] = {'video': params['forceprint']}
if self.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 self.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 = (
self.params.get('format') if self.params.get('format') in (None, '-')
else self.params['format'] if callable(self.params['format'])
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()
hooks = {
'post_hooks': self.add_post_hook,
'progress_hooks': self.add_progress_hook,
'postprocessor_hooks': self.add_postprocessor_hook,
}
for opt, fn in hooks.items():
for ph in self.params.get(opt, []):
fn(ph)
for pp_def_raw in self.params.get('postprocessors', []):
pp_def = dict(pp_def_raw)
when = pp_def.pop('when', 'post_process')
self.add_post_processor(
get_postprocessor(pp_def.pop('key'))(self, **compat_kwargs(pp_def)),
when=when)
register_socks_protocols()
def preload_download_archive(fn):
"""Preload the archive, if any is specified"""
if fn is None:
return False
self.write_debug(f'Loading archive file {fn!r}')
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' %
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)
for pps in self._pps.values():
for pp in pps:
pp.add_progress_hook(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
message = remove_terminal_sequences(message)
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, is_error=True):
"""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.
@param tb If given, is additional traceback information
@param is_error Whether to raise error according to ignorerrors
"""
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 is_error:
return
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))
class Styles(Enum):
HEADERS = 'yellow'
EMPHASIS = 'light blue'
ID = 'green'
DELIM = 'blue'
ERROR = 'red'
WARNING = 'yellow'
SUPPRESS = 'light black'
def _format_text(self, handle, allow_colors, text, f, fallback=None, *, test_encoding=False):
if test_encoding:
original_text = text
encoding = self.params.get('encoding') or getattr(handle, 'encoding', 'ascii')
text = text.encode(encoding, 'ignore').decode(encoding)
if fallback is not None and text != original_text:
text = fallback
if isinstance(f, self.Styles):
f = f.value
return format_text(text, f) if allow_colors else text if fallback is None else fallback
def _format_screen(self, *args, **kwargs):
return self._format_text(
self._screen_file, self._allow_colors['screen'], *args, **kwargs)
def _format_err(self, *args, **kwargs):
return self._format_text(
self._err_file, self._allow_colors['err'], *args, **kwargs)
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._format_err("WARNING:", self.Styles.WARNING)} {message}', only_once)
def deprecation_warning(self, message):
if self.params.get('logger') is not None:
self.params['logger'].warning('DeprecationWarning: {message}')
else:
self.to_stderr(f'{self._format_err("DeprecationWarning:", self.Styles.ERROR)} {message}', True)
def report_error(self, message, *args, **kwargs):
'''
Do the same as trouble, but prefixes the message with 'ERROR:', colored
in red if stderr is a tty file.
'''
self.trouble(f'{self._format_err("ERROR:", self.Styles.ERROR)} {message}', *args, **kwargs)
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('[^)]*', '[ljqBUDS]'),
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=False):
""" Make the outtmpl and info_dict suitable for substitution: ydl.escape_outtmpl(outtmpl) % info_dict
@param sanitize Whether to sanitize the output as a filename.
For backward compatibility, a function can also be passed
"""
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
info_dict['video_autonumber'] = self._num_videos
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': number_of_digits(info_dict.get('_last_playlist_index') or 0),
'playlist_autonumber': number_of_digits(info_dict.get('n_entries') or 0),
'autonumber': self.params.get('autonumber_size') or 5,
}
TMPL_DICT = {}
EXTERNAL_FORMAT_RE = re.compile(STR_FORMAT_RE_TMPL.format('[^)]*', f'[{STR_FORMAT_TYPES}ljqBUDS]'))
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<replacement>.*?))?
(?:\|(?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 filename_sanitizer(key, value, restricted=self.params.get('restrictfilenames')):
return sanitize_filename(str(value), restricted=restricted,
is_id=re.search(r'(^|[_.])id(\.|$)', key))
sanitizer = sanitize if callable(sanitize) else filename_sanitizer
sanitize = bool(sanitize)
def _dumpjson_default(obj):
if isinstance(obj, (set, LazyList)):
return list(obj)
return repr(obj)
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') if mobj else ''
value, replacement, default = None, None, na
while mobj:
mobj = mobj.groupdict()
default = mobj['default'] if mobj['default'] is not None else default
value = get_value(mobj)
replacement = mobj['replacement']
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 if replacement is None else replacement
flags = outer_mobj.group('conversion') or ''
str_fmt = f'{fmt[:-1]}s'
if fmt[-1] == 'l': # list
delim = '\n' if '#' in flags else ', '
value, fmt = delim.join(map(str, variadic(value, allowed_types=(str, bytes)))), str_fmt
elif fmt[-1] == 'j': # json
value, fmt = json.dumps(value, default=_dumpjson_default, indent=4 if '#' in flags else None), str_fmt
elif fmt[-1] == 'q': # quoted
value = map(str, variadic(value) if '#' in flags else [value])
value, fmt = ' '.join(map(compat_shlex_quote, 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
value, fmt = unicodedata.normalize(
# "+" = compatibility equivalence, "#" = NFD
'NF%s%s' % ('K' if '+' in flags else '', 'D' if '#' in flags else 'C'),
value), str_fmt
elif fmt[-1] == 'D': # decimal suffix
num_fmt, fmt = fmt[:-1].replace('#', ''), 's'
value = format_decimal_suffix(value, f'%{num_fmt}f%s' if num_fmt else '%d%s',
factor=1024 if '#' in flags else 1000)
elif fmt[-1] == 'S': # filename sanitization
value, fmt = filename_sanitizer(initial_field, value, restricted='#' in flags), 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 = sanitizer(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:
outtmpl = self._outtmpl_expandpath(self.outtmpl_dict.get(tmpl_type, self.outtmpl_dict['default']))
filename = self.evaluate_outtmpl(outtmpl, info_dict, True)
if not filename:
return None
if tmpl_type in ('default', 'temp'):
final_ext, ext = self.params.get('final_ext'), info_dict.get('ext')
if final_ext and ext and final_ext != ext and filename.endswith(f'.{final_ext}'):
filename = replace_extension(filename, ext, final_ext)
else:
force_ext = OUTTMPL_TYPES[tmpl_type]
if force_ext:
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:
no_ext, *ext = filename.rsplit('.', 2)
filename = join_nonempty(no_ext[:trim_file_name], *ext, delim='.')
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(f'[{ie_key}] {temp_id}: has already been recorded in the archive')
if self.params.get('break_on_existing', False):
raise ExistingVideoReached()
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):
while True:
try:
return func(self, *args, **kwargs)
except (DownloadCancelled, LazyList.IndexError, PagedList.IndexError):
raise
except ReExtractInfo as e:
if e.expected:
self.to_screen(f'{e}; Re-extracting data')
else:
self.to_stderr('\r')
self.report_warning(f'{e}; Re-extracting data')
continue
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(str(e), e.format_traceback())
except Exception as e:
if self.params.get('ignoreerrors'):
self.report_error(str(e), tb=encode_compat_str(traceback.format_exc()))
else:
raise
break
return wrapper
def _wait_for_video(self, ie_result):
if (not self.params.get('wait_for_video')
or ie_result.get('_type', 'video') != 'video'
or ie_result.get('formats') or ie_result.get('url')):
return
format_dur = lambda dur: '%02d:%02d:%02d' % timetuple_from_msec(dur * 1000)[:-1]
last_msg = ''
def progress(msg):
nonlocal last_msg
self.to_screen(msg + ' ' * (len(last_msg) - len(msg)) + '\r', skip_eol=True)
last_msg = msg
min_wait, max_wait = self.params.get('wait_for_video')
diff = try_get(ie_result, lambda x: x['release_timestamp'] - time.time())
if diff is None and ie_result.get('live_status') == 'is_upcoming':
diff = random.randrange(min_wait, max_wait) if (max_wait and min_wait) else (max_wait or min_wait)
self.report_warning('Release time of video is not known')
elif (diff or 0) <= 0:
self.report_warning('Video should already be available according to extracted info')
diff = min(max(diff or 0, min_wait or 0), max_wait or float('inf'))
self.to_screen(f'[wait] Waiting for {format_dur(diff)} - Press Ctrl+C to try now')
wait_till = time.time() + diff
try:
while True:
diff = wait_till - time.time()
if diff <= 0:
progress('')
raise ReExtractInfo('[wait] Wait period ended', expected=True)
progress(f'[wait] Remaining time until next attempt: {self._format_screen(format_dur(diff), self.Styles.EMPHASIS)}')
time.sleep(1)
except KeyboardInterrupt:
progress('')
raise ReExtractInfo('[wait] Interrupted by user', expected=True)
except BaseException as e:
if not isinstance(e, ReExtractInfo):
self.to_screen('')
raise
@__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:
self._wait_for_video(ie_result)
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 = ie_result.get('webpage_url')
if webpage_url:
self.add_extra_info(ie_result, {
'webpage_url_basename': url_basename(webpage_url),
'webpage_url_domain': get_domain(webpage_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)
info_copy, _ = self.pre_process(info_copy)
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=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']),
'webpage_url_domain': get_domain(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)
@staticmethod
def _playlist_infodict(ie_result, **kwargs):
return {
**ie_result,
'playlist': ie_result.get('title') or ie_result.get('id'),
'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,
**kwargs,
}
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('There are no entries')
MissingEntry = object()
incomplete_entries = bool(ie_result.get('requested_entries'))
if incomplete_entries:
def fill_missing_entries(entries, indices):
ret = [MissingEntry] * max(indices)
for i, entry in zip(indices, 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']
if isinstance(ie_entries, list):
playlist_count = len(ie_entries)
msg = f'Collected {playlist_count} videos; downloading %d of them'
ie_result['playlist_count'] = ie_result.get('playlist_count') or playlist_count
def get_entry(i):
return ie_entries[i - 1]
else:
msg = 'Downloading %d videos'
if not isinstance(ie_entries, (PagedList, LazyList)):
ie_entries = LazyList(ie_entries)
elif isinstance(ie_entries, InAdvancePagedList):
if ie_entries._pagesize == 1:
playlist_count = ie_entries._pagecount
def get_entry(i):
return YoutubeDL.__handle_extraction_exceptions(
lambda self, i: ie_entries[i - 1]
)(self, i)
entries, broken = [], False
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 MissingEntry:
raise EntryNotInPlaylist()
except (IndexError, EntryNotInPlaylist):
if incomplete_entries:
raise EntryNotInPlaylist(f'Entry {i} cannot be found')
elif not playlistitems:
break
entries.append(entry)
try:
if entry is not None:
self._match_entry(entry, incomplete=True, silent=True)
except (ExistingVideoReached, RejectedVideoReached):
broken = True
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 (ie_result.get('playlist_count') or broken or playlistitems or playlistend):
ie_result['playlist_count'] = n_entries
if not playlistitems and (playliststart != 1 or playlistend):
playlistitems = list(range(playliststart, playliststart + n_entries))
ie_result['requested_entries'] = playlistitems
_infojson_written = False
write_playlist_files = self.params.get('allow_playlist_files', True)
if write_playlist_files and self.params.get('list_thumbnails'):
self.list_thumbnails(ie_result)
if write_playlist_files and not self.params.get('simulate'):
ie_copy = self._playlist_infodict(ie_result, n_entries=n_entries)
_infojson_written = self._write_info_json(
'playlist', ie_result, self.prepare_filename(ie_copy, 'pl_infojson'))
if _infojson_written 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_count': ie_result.get('playlist_count'),
'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']),
'webpage_url_domain': get_domain(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
playlist_results.append(entry_result)
ie_result['entries'] = playlist_results
# Write the updated info to json
if _infojson_written and self._write_info_json(
'updated playlist', ie_result,
self.prepare_filename(ie_copy, 'pl_infojson'), overwrite=True) is None:
return
ie_result = self.run_all_pps('playlist', ie_result)
self.to_screen(f'[download] Finished downloading playlist: {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,
'~=': lambda attr, value: value.search(attr) is not None
}
str_operator_rex = re.compile(r'''(?x)\s*
(?P<key>[a-zA-Z0-9._-]+)\s*
(?P<negation>!\s*)?(?P<op>%s)\s*(?P<none_inclusive>\?\s*)?
(?P<quote>["'])?
(?P<value>(?(quote)(?:(?!(?P=quote))[^\\]|\\.)+|[\w.-]+))
(?(quote)(?P=quote))\s*
''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
m = str_operator_rex.fullmatch(filter_spec)
if m:
if m.group('op') == '~=':
comparison_value = re.compile(m.group('value'))
else:
comparison_value = re.sub(r'''\\([\\"'])''', r'\1', 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 _check_formats(self, formats):
for f in formats:
self.to_screen('[info] Testing format %s' % f['format_id'])
path = self.get_output_path('temp')
if not self._ensure_dir_exists(f'{path}/'):
continue
temp_file = tempfile.NamedTemporaryFile(suffix='.tmp', delete=False, dir=path 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 _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') == 'selected'
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'))) or None,
'format_note': '+'.join(orderedSet(filtered('format_note'))) or None,
'filesize_approx': sum(filtered('filesize', 'filesize_approx')) or None,
'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'),
'dynamic_range': the_only_video.get('dynamic_range'),
'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
yield from self._check_formats(formats)
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(ctx), selector_2(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'][::-1])
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 = dict(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()
res.update(info_dict.get('http_headers') or {})
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 _sort_thumbnails(self, 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 _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 not thumbnails:
return
def check_thumbnails(thumbnails):
for t in thumbnails:
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...')
continue
yield t
self._sort_thumbnails(thumbnails)
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') is True:
info_dict['thumbnails'] = LazyList(check_thumbnails(thumbnails[::-1]), reverse=True)
else:
info_dict['thumbnails'] = thumbnails
def process_video_result(self, info_dict, download=True):
assert info_dict.get('_type', 'video') == 'video'
self._num_videos += 1
if 'id' not in info_dict:
raise ExtractorError('Missing "id" field in extractor result', ie=info_dict['extractor'])
elif not info_dict.get('id'):
raise ExtractorError('Extractor failed to obtain "id"', ie=info_dict['extractor'])
info_dict['fulltitle'] = info_dict.get('title')
if 'title' not in info_dict:
raise ExtractorError('Missing "title" field in extractor result',
video_id=info_dict['id'], ie=info_dict['extractor'])
elif not info_dict.get('title'):
self.report_warning('Extractor failed to obtain "title". Creating a generic title instead')
info_dict['title'] = f'{info_dict["extractor"]} video #{info_dict["id"]}'
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'),
('modified_timestamp', 'modified_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)
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 info_dict.get('is_live'):
get_from_start = bool(self.params.get('live_from_start'))
formats = [f for f in formats if bool(f.get('is_from_start')) == get_from_start]
if not get_from_start:
info_dict['title'] += ' ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
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'
if (info_dict.get('duration') and format.get('tbr')
and not format.get('filesize') and not format.get('filesize_approx')):
format['filesize_approx'] = info_dict['duration'] * format['tbr'] * (1024 / 8)
# 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 self.params.get('check_formats') is True:
formats = LazyList(self._check_formats(formats[::-1]), reverse=True)
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)
# The pre-processors may have modified the formats
formats = info_dict.get('formats', [info_dict])
list_only = self.params.get('simulate') is None and (
self.params.get('list_thumbnails') or self.params.get('listformats') or self.params.get('listsubtitles'))
interactive_format_selection = not list_only and self.format_selector == '-'
if self.params.get('list_thumbnails'):
self.list_thumbnails(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')
if self.params.get('listformats') or interactive_format_selection:
self.list_formats(info_dict)
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 True:
if interactive_format_selection:
req_format = input(
self._format_screen('\nEnter format selector: ', self.Styles.EMPHASIS))
try:
format_selector = self.build_format_selector(req_format)
except SyntaxError as err:
self.report_error(err, tb=False, is_error=False)
continue
# 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 interactive_format_selection and not formats_to_download:
self.report_error('Requested format is not available', tb=False, is_error=False)
continue
break
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'])
self.report_warning('Requested format is not available')
# Process what we can, even without any available formats.
formats_to_download = [{}]
best_format = formats_to_download[-1]
if download:
if best_format:
self.to_screen(
f'[info] {info_dict["id"]}: Downloading {len(formats_to_download)} format(s): '
+ ', '.join([f['format_id'] for f in formats_to_download]))
max_downloads_reached = False
for i, fmt in enumerate(formats_to_download):
formats_to_download[i] = 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.update(fmt)
new_info['__original_infodict'] = info_dict
try:
self.process_info(new_info)
except MaxDownloadsReached:
max_downloads_reached = True
new_info.pop('__original_infodict')
# Remove copied info
for key, val in tuple(new_info.items()):
if info_dict.get(key) == val:
new_info.pop(key)
if max_downloads_reached:
break
write_archive = set(f.get('__write_download_archive', False) for f in formats_to_download)
assert write_archive.issubset({True, False, 'ignore'})
if True in write_archive and False not in write_archive:
self.record_download_archive(info_dict)
info_dict['requested_downloads'] = formats_to_download
info_dict = self.run_all_pps('after_video', info_dict)
if max_downloads_reached:
raise MaxDownloadsReached()
# We update the info dict with the selected best quality format (backwards compatibility)
info_dict.update(best_format)
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 _forceprint(self, key, info_dict):
if info_dict is None:
return
info_copy = info_dict.copy()
info_copy['formats_table'] = self.render_formats_table(info_dict)
info_copy['thumbnails_table'] = self.render_thumbnails_table(info_dict)
info_copy['subtitles_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('subtitles'))
info_copy['automatic_captions_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('automatic_captions'))
def format_tmpl(tmpl):
mobj = re.match(r'\w+(=?)$', tmpl)
if mobj and mobj.group(1):
return f'{tmpl[:-1]} = %({tmpl[:-1]})r'
elif mobj:
return f'%({tmpl})s'
return tmpl
for tmpl in self.params['forceprint'].get(key, []):
self.to_stdout(self.evaluate_outtmpl(format_tmpl(tmpl), info_copy))
for tmpl, file_tmpl in self.params['print_to_file'].get(key, []):
filename = self.evaluate_outtmpl(file_tmpl, info_dict)
tmpl = format_tmpl(tmpl)
self.to_screen(f'[info] Writing {tmpl!r} to: {filename}')
with io.open(filename, 'a', encoding='utf-8') as f:
f.write(self.evaluate_outtmpl(tmpl, info_copy) + '\n')
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('forcejson')
or self.params['forceprint'].get('video')
or self.params['print_to_file'].get('video')):
self.post_extract(info_dict)
self._forceprint('video', 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'].split(',')[0] + ',<data>' if f['url'].startswith('data:') else f['url'])
for f in info.get('requested_formats', []) or [info])
self.write_debug('Invoking downloader on "%s"' % urls)
# Note: Ideally info should be a deep-copied so that hooks cannot modify it.
# But it may contain objects that are not deep-copyable
new_info = 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 existing_file(self, filepaths, *, default_overwrite=True):
existing_files = list(filter(os.path.exists, orderedSet(filepaths)))
if existing_files and not self.params.get('overwrites', default_overwrite):
return existing_files[0]
for file in existing_files:
self.report_file_delete(file)
os.remove(file)
return None
def process_info(self, info_dict):
"""Process a single resolved IE result. (Modified it in-place)"""
assert info_dict.get('_type', 'video') == 'video'
original_infodict = info_dict
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:
info_dict['__write_download_archive'] = 'ignore'
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'):
info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
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
# For backward compatibility, even though it was a private field
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
def _write_link_file(link_type):
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 False
linkfn = replace_extension(self.prepare_filename(info_dict, 'link'), link_type, info_dict.get('ext'))
if not self._ensure_dir_exists(encodeFilename(linkfn)):
return False
if self.params.get('overwrites', True) and os.path.exists(encodeFilename(linkfn)):
self.to_screen(f'[info] Internet shortcut (.{link_type}) is already present')
return True
try:
self.to_screen(f'[info] Writing internet shortcut (.{link_type}) to: {linkfn}')
with io.open(encodeFilename(to_high_limit_path(linkfn)), 'w', encoding='utf-8',
newline='\r\n' if link_type == 'url' else '\n') as linkfile:
template_vars = {'url': iri_to_uri(info_dict['webpage_url'])}
if link_type == 'desktop':
template_vars['filename'] = linkfn[:-(len(link_type) + 1)]
linkfile.write(LINK_TEMPLATES[link_type] % template_vars)
except (OSError, IOError):
self.report_error(f'Cannot write internet shortcut {linkfn}')
return False
return True
write_links = {
'url': self.params.get('writeurllink'),
'webloc': self.params.get('writewebloclink'),
'desktop': self.params.get('writedesktoplink'),
}
if self.params.get('writelink'):
link_type = ('webloc' if sys.platform == 'darwin'
else 'desktop' if sys.platform.startswith('linux')
else 'url')
write_links[link_type] = True
if any(should_write and not _write_link_file(link_type)
for link_type, should_write in write_links.items()):
return
def replace_info_dict(new_info):
nonlocal info_dict
if new_info == info_dict:
return
info_dict.clear()
info_dict.update(new_info)
try:
new_info, files_to_move = self.pre_process(info_dict, 'before_dl', files_to_move)
replace_info_dict(new_info)
except PostProcessingError as err:
self.report_error('Preprocessing: %s' % str(err))
return
if self.params.get('skip_download'):
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
replace_info_dict(self.run_pp(MoveFilesAfterDownloadPP(self, False), info_dict))
info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
else:
# Download
info_dict.setdefault('__postprocessors', [])
try:
def existing_video_file(*filepaths):
ext = info_dict.get('ext')
converted = lambda file: replace_extension(file, self.params.get('final_ext') or ext, ext)
file = self.existing_file(itertools.chain(*zip(map(converted, filepaths), filepaths)),
default_overwrite=False)
if file:
info_dict['ext'] = os.path.splitext(file)[1][1:]
return file
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_video_file(full_filename, temp_filename)
info_dict['__real_download'] = False
downloaded = []
merger = FFmpegMergerPP(self)
fd = get_suitable_downloader(info_dict, self.params, to_stdout=temp_filename == '-')
if dl_filename is not None:
self.report_file_already_downloaded(dl_filename)
elif fd:
for f in requested_formats if fd != FFmpegFD else []:
f['filepath'] = fname = prepend_extension(
correct_ext(temp_filename, info_dict['ext']),
'f%s' % f['format_id'], info_dict['ext'])
downloaded.append(fname)
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:
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:
msg = 'You have requested merging of multiple formats but ffmpeg is not installed'
if not self.params.get('ignoreerrors'):
self.report_error(f'{msg}. Aborting due to --abort-on-error')
return
self.report_warning(f'{msg}. The formats won\'t be merged')
if temp_filename == '-':
reason = ('using a downloader other than ffmpeg' if FFmpegFD.can_merge_formats(info_dict, self.params)
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 downloaded and 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_video_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
if info_dict.get('requested_formats') is None: # Not necessary if doing merger
ffmpeg_fixup(downloader == 'HlsFD',
'Possible MPEG-TS in MP4 container or malformed AAC timestamps',
FFmpegFixupM3u8PP)
ffmpeg_fixup(info_dict.get('is_live') and downloader == 'DashSegmentsFD',
'Possible duplicate MOOV atoms', FFmpegFixupDuplicateMoovPP)
ffmpeg_fixup(downloader == 'WebSocketFragmentFD', 'Malformed timestamps detected', FFmpegFixupTimestampPP)
ffmpeg_fixup(downloader == 'WebSocketFragmentFD', 'Malformed duration detected', FFmpegFixupDurationPP)
fixup()
try:
replace_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
info_dict['__write_download_archive'] = True
if self.params.get('force_write_download_archive'):
info_dict['__write_download_archive'] = True
# Make sure the info_dict was modified in-place
assert info_dict is original_infodict
max_downloads = self.params.get('max_downloads')
if max_downloads is not None and self._num_downloads >= int(max_downloads):
raise MaxDownloadsReached()
def __download_wrapper(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
res = func(*args, **kwargs)
except UnavailableVideoError as e:
self.report_error(e)
except MaxDownloadsReached as e:
self.to_screen(f'[info] {e}')
raise
except DownloadCancelled as e:
self.to_screen(f'[info] {e}')
if not self.params.get('break_per_url'):
raise
else:
if self.params.get('dump_single_json', False):
self.post_extract(res)
self.to_stdout(json.dumps(self.sanitize_info(res)))
return wrapper
def download(self, url_list):
"""Download a given list of URLs."""
url_list = variadic(url_list) # Passing a single URL is a common mistake
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:
self.__download_wrapper(self.extract_info)(
url, force_generic_extractor=self.params.get('force_generic_extractor', False))
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.__download_wrapper(self.process_ie_result)(info, download=True)
except (DownloadError, EntryNotInPlaylist, ReExtractInfo) as e:
if not isinstance(e, EntryNotInPlaylist):
self.to_stderr('\r')
webpage_url = info.get('webpage_url')
if webpage_url is not None:
self.report_warning(f'The info failed to download: {e}; trying with URL {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()))
info_dict.setdefault('_type', 'video')
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_downloads', 'requested_formats', 'requested_subtitles', 'requested_entries',
'entries', 'filepath', 'infojson_filename', 'original_url', 'playlist_autonumber',
}
reject = lambda k, v: k not in keep_keys and (
k.startswith('_') or k in remove_keys or v is None)
else:
reject = lambda k, v: k in remove_keys
def filter_fn(obj):
if isinstance(obj, dict):
return {k: filter_fn(v) for k, v in obj.items() if not reject(k, v)}
elif isinstance(obj, (list, tuple, set, LazyList)):
return list(map(filter_fn, obj))
elif obj is None or isinstance(obj, (str, int, float, bool)):
return obj
else:
return repr(obj)
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)
@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 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
def run_all_pps(self, key, info, *, additional_pps=None):
self._forceprint(key, info)
for pp in (additional_pps or []) + self._pps[key]:
info = self.run_pp(pp, info)
return info
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 {}
info = self.run_all_pps(key, info)
return info, info.pop('__files_to_move', None)
def post_process(self, filename, info, files_to_move=None):
"""Run all the postprocessors on the given file."""
info['filepath'] = filename
info['__files_to_move'] = files_to_move or {}
info = self.run_all_pps('post_process', info, additional_pps=info.get('__postprocessors'))
info = self.run_pp(MoveFilesAfterDownloadPP(self), info)
del info['__files_to_move']
return self.run_all_pps('after_move', 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
self.write_debug(f'Adding to archive: {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'):
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'):
return '%dx%d' % (format['width'], format['height'])
elif format.get('height'):
return '%sp' % format['height']
elif format.get('width'):
return '%dx?' % format['width']
return default
def _list_format_headers(self, *headers):
if self.params.get('listformats_table', True) is not False:
return [self._format_screen(header, self.Styles.HEADERS) for header in headers]
return headers
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:
if res:
res += ' '
res += fdict['format_note']
if fdict.get('tbr') is not None:
if res:
res += ', '
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 render_formats_table(self, info_dict):
if not info_dict.get('formats') and not info_dict.get('url'):
return None
formats = info_dict.get('formats', [info_dict])
if not self.params.get('listformats_table', True) is not False:
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]
return render_table(['format code', 'extension', 'resolution', 'note'], table, extra_gap=1)
delim = self._format_screen('\u2502', self.Styles.DELIM, '|', test_encoding=True)
table = [
[
self._format_screen(format_field(f, 'format_id'), self.Styles.ID),
format_field(f, 'ext'),
format_field(f, func=self.format_resolution, ignore=('audio only', 'images')),
format_field(f, 'fps', '\t%d'),
format_field(f, 'dynamic_range', '%s', ignore=(None, 'SDR')).replace('HDR', ''),
delim,
format_field(f, 'filesize', ' \t%s', func=format_bytes) + format_field(f, 'filesize_approx', '~\t%s', func=format_bytes),
format_field(f, 'tbr', '\t%dk'),
shorten_protocol_name(f.get('protocol', '')),
delim,
format_field(f, 'vcodec', default='unknown').replace(
'none', 'images' if f.get('acodec') == 'none'
else self._format_screen('audio only', self.Styles.SUPPRESS)),
format_field(f, 'vbr', '\t%dk'),
format_field(f, 'acodec', default='unknown').replace(
'none', '' if f.get('vcodec') == 'none'
else self._format_screen('video only', self.Styles.SUPPRESS)),
format_field(f, 'abr', '\t%dk'),
format_field(f, 'asr', '\t%dHz'),
join_nonempty(
self._format_screen('UNSUPPORTED', 'light red') if f.get('ext') in ('f4f', 'f4m') else None,
format_field(f, 'language', '[%s]'),
join_nonempty(format_field(f, 'format_note'),
format_field(f, 'container', ignore=(None, f.get('ext'))),
delim=', '),
delim=' '),
] for f in formats if f.get('preference') is None or f['preference'] >= -1000]
header_line = self._list_format_headers(
'ID', 'EXT', 'RESOLUTION', '\tFPS', 'HDR', delim, '\tFILESIZE', '\tTBR', 'PROTO',
delim, 'VCODEC', '\tVBR', 'ACODEC', '\tABR', '\tASR', 'MORE INFO')
return render_table(
header_line, table, hide_empty=True,
delim=self._format_screen('\u2500', self.Styles.DELIM, '-', test_encoding=True))
def render_thumbnails_table(self, info_dict):
thumbnails = list(info_dict.get('thumbnails') or [])
if not thumbnails:
return None
return render_table(
self._list_format_headers('ID', 'Width', 'Height', 'URL'),
[[t.get('id'), t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails])
def render_subtitles_table(self, video_id, subtitles):
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)]
if not subtitles:
return None
return render_table(
self._list_format_headers('Language', 'Name', 'Formats'),
[_row(lang, formats) for lang, formats in subtitles.items()],
hide_empty=True)
def __list_table(self, video_id, name, func, *args):
table = func(*args)
if not table:
self.to_screen(f'{video_id} has no {name}')
return
self.to_screen(f'[info] Available {name} for {video_id}:')
self.to_stdout(table)
def list_formats(self, info_dict):
self.__list_table(info_dict['id'], 'formats', self.render_formats_table, info_dict)
def list_thumbnails(self, info_dict):
self.__list_table(info_dict['id'], 'thumbnails', self.render_thumbnails_table, info_dict)
def list_subtitles(self, video_id, subtitles, name='subtitles'):
self.__list_table(video_id, name, self.render_subtitles_table, video_id, subtitles)
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
def get_encoding(stream):
ret = getattr(stream, 'encoding', 'missing (%s)' % type(stream).__name__)
if not supports_terminal_sequences(stream):
from .compat import WINDOWS_VT_MODE
ret += ' (No VT)' if WINDOWS_VT_MODE is False else ' (No ANSI)'
return ret
encoding_str = 'Encodings: locale %s, fs %s, out %s, err %s, pref %s' % (
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_string(f'[debug] {encoding_str}\n', encoding=None)
write_debug = lambda msg: self._write_string(f'[debug] {msg}\n')
source = detect_variant()
write_debug(join_nonempty(
'yt-dlp version', __version__,
f'[{RELEASE_GIT_HEAD}]' if RELEASE_GIT_HEAD else '',
'' if source == 'unknown' else f'({source})',
delim=' '))
if not _LAZY_LOADER:
if os.environ.get('YTDLP_NO_LAZY_EXTRACTORS'):
write_debug('Lazy loading extractors is forcibly disabled')
else:
write_debug('Lazy loading extractors is disabled')
if plugin_extractors or plugin_postprocessors:
write_debug('Plugins: %s' % [
'%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' % ', '.join(self.params.get('compat_opts')))
if source == 'source':
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' % 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' % (
platform.python_version(),
python_implementation(),
platform.architecture()[0],
platform_name()))
exe_versions, ffmpeg_features = FFmpegPostProcessor.get_versions_and_features(self)
ffmpeg_features = {key for key, val in ffmpeg_features.items() if val}
if ffmpeg_features:
exe_versions['ffmpeg'] += ' (%s)' % ','.join(ffmpeg_features)
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' % exe_str)
from .downloader.websocket import has_websockets
from .postprocessor.embedthumbnail import has_mutagen
from .cookies import SQLITE_AVAILABLE, SECRETSTORAGE_AVAILABLE
lib_str = join_nonempty(
compat_pycrypto_AES and compat_pycrypto_AES.__name__.split('.')[0],
SECRETSTORAGE_AVAILABLE and 'secretstorage',
has_mutagen and 'mutagen',
SQLITE_AVAILABLE and 'sqlite',
has_websockets and 'websockets',
delim=', ') or 'none'
write_debug('Optional libraries: %s' % lib_str)
proxy_map = {}
for handler in self._opener.handlers:
if hasattr(handler, 'proxies'):
proxy_map.update(handler.proxies)
write_debug(f'Proxy map: {proxy_map}')
# Not implemented
if False and self.params.get('call_home'):
ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
write_debug('Public IP address: %s' % ipaddr)
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, overwrite=None):
''' Write infojson and returns True = written, False = skip, None = error '''
if overwrite is None:
overwrite = self.params.get('overwrites', True)
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 overwrite 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'))
existing_sub = self.existing_file((sub_filename_final, sub_filename))
if existing_sub:
self.to_screen(f'[info] Video subtitle {sub_lang}.{sub_format} is already present')
sub_info['filepath'] = existing_sub
ret.append((existing_sub, 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 (DownloadError, ExtractorError, IOError, OSError, ValueError) + network_exceptions as err:
if self.params.get('ignoreerrors') is not True: # False or 'only_download'
raise DownloadError(f'Unable to download video subtitles for {sub_lang!r}: {err}', err)
self.report_warning(f'Unable to download video subtitles for {sub_lang!r}: {err}')
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 idx, t in list(enumerate(thumbnails))[::-1]:
thumb_ext = (f'{t["id"]}.' if multiple else '') + determine_ext(t['url'], 'jpg')
thumb_display_id = f'{label} thumbnail {t["id"]}'
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'))
existing_thumb = self.existing_file((thumb_filename_final, thumb_filename))
if existing_thumb:
self.to_screen('[info] %s is already present' % (
thumb_display_id if multiple else f'{label} thumbnail').capitalize())
t['filepath'] = existing_thumb
ret.append((existing_thumb, thumb_filename_final))
else:
self.to_screen(f'[info] Downloading {thumb_display_id} ...')
try:
uf = self.urlopen(sanitized_Request(t['url'], headers=t.get('http_headers', {})))
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:
thumbnails.pop(idx)
self.report_warning(f'Unable to download {thumb_display_id}: {err}')
if ret and not write_all:
break
return ret
| 46.939542 | 140 | 0.571059 |
from __future__ import absolute_import, unicode_literals
import collections
import contextlib
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 enum import Enum
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,
DownloadCancelled,
DownloadError,
encode_compat_str,
encodeFilename,
EntryNotInPlaylist,
error_to_compat_str,
ExistingVideoReached,
expand_path,
ExtractorError,
float_or_none,
format_bytes,
format_field,
format_decimal_suffix,
formatSeconds,
GeoRestrictedError,
get_domain,
HEADRequest,
InAdvancePagedList,
int_or_none,
iri_to_uri,
ISO3166Utils,
join_nonempty,
LazyList,
LINK_TEMPLATES,
locked_file,
make_dir,
make_HTTPS_handler,
MaxDownloadsReached,
network_exceptions,
number_of_digits,
orderedSet,
OUTTMPL_TYPES,
PagedList,
parse_filesize,
PerRequestProxyHandler,
platform_name,
Popen,
POSTPROCESS_WHEN,
PostProcessingError,
preferredencoding,
prepend_extension,
ReExtractInfo,
register_socks_protocols,
RejectedVideoReached,
remove_terminal_sequences,
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,
timetuple_from_msec,
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 .minicurses import format_text
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,
FFmpegFixupDuplicateMoovPP,
FFmpegFixupDurationPP,
FFmpegFixupM3u8PP,
FFmpegFixupM4aPP,
FFmpegFixupStretchedPP,
FFmpegFixupTimestampPP,
FFmpegMergerPP,
FFmpegPostProcessor,
MoveFilesAfterDownloadPP,
_PLUGIN_CLASSES as plugin_postprocessors
)
from .update import detect_variant
from .version import __version__, RELEASE_GIT_HEAD
if compat_os_name == 'nt':
import ctypes
class YoutubeDL(object):
_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 = {k: [] for k in POSTPROCESS_WHEN}
_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):
if params is None:
params = {}
self._ies = {}
self._ies_instances = {}
self._pps = {k: [] for k in POSTPROCESS_WHEN}
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._num_videos = 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()
self._allow_colors = {
'screen': not self.params.get('no_color') and supports_terminal_sequences(self._screen_file),
'err': not self.params.get('no_color') and 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._format_err("UNPLAYABLE", self.Styles.EMPHASIS)} formats to be listed/downloaded. '
'This is a developer option intended for debugging. \n'
' If you experience any issues while using this option, '
f'{self._format_err("DO NOT", self.Styles.ERROR)} 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)
for msg in self.params.get('_deprecation_warnings', []):
self.deprecation_warning(msg)
if 'list-formats' in self.params.get('compat_opts', []):
self.params['listformats_table'] = False
if 'overwrites' not in self.params and self.params.get('nooverwrites') is not None:
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']
self.params.setdefault('forceprint', {})
self.params.setdefault('print_to_file', {})
if not isinstance(params['forceprint'], dict):
self.params['forceprint'] = {'video': params['forceprint']}
if self.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 self.params.get('restrictfilenames', False)):
ort_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()
self.format_selector = (
self.params.get('format') if self.params.get('format') in (None, '-')
else self.params['format'] if callable(self.params['format'])
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()
hooks = {
'post_hooks': self.add_post_hook,
'progress_hooks': self.add_progress_hook,
'postprocessor_hooks': self.add_postprocessor_hook,
}
for opt, fn in hooks.items():
for ph in self.params.get(opt, []):
fn(ph)
for pp_def_raw in self.params.get('postprocessors', []):
pp_def = dict(pp_def_raw)
when = pp_def.pop('when', 'post_process')
self.add_post_processor(
get_postprocessor(pp_def.pop('key'))(self, **compat_kwargs(pp_def)),
when=when)
register_socks_protocols()
def preload_download_archive(fn):
if fn is None:
return False
self.write_debug(f'Loading archive file {fn!r}')
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):
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' %
args_to_str(correct_argv))
def add_info_extractor(self, ie):
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):
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):
for ie in gen_extractor_classes():
self.add_info_extractor(ie)
def add_post_processor(self, pp, when='post_process'):
self._pps[when].append(pp)
pp.set_downloader(self)
def add_post_hook(self, ph):
self._post_hooks.append(ph)
def add_progress_hook(self, ph):
self._progress_hooks.append(ph)
def add_postprocessor_hook(self, ph):
self._postprocessor_hooks.append(ph)
for pps in self._pps.values():
for pp in pps:
pp.add_progress_hook(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):
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):
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
message = remove_terminal_sequences(message)
if compat_os_name == 'nt':
if ctypes.windll.kernel32.GetConsoleWindow():
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:
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:
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, is_error=True):
if message is not None:
self.to_stderr(message)
if self.params.get('verbose'):
if tb is None:
if sys.exc_info()[0]:
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 is_error:
return
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):
self.to_stdout(
message, skip_eol, quiet=self.params.get('quiet', False))
class Styles(Enum):
HEADERS = 'yellow'
EMPHASIS = 'light blue'
ID = 'green'
DELIM = 'blue'
ERROR = 'red'
WARNING = 'yellow'
SUPPRESS = 'light black'
def _format_text(self, handle, allow_colors, text, f, fallback=None, *, test_encoding=False):
if test_encoding:
original_text = text
encoding = self.params.get('encoding') or getattr(handle, 'encoding', 'ascii')
text = text.encode(encoding, 'ignore').decode(encoding)
if fallback is not None and text != original_text:
text = fallback
if isinstance(f, self.Styles):
f = f.value
return format_text(text, f) if allow_colors else text if fallback is None else fallback
def _format_screen(self, *args, **kwargs):
return self._format_text(
self._screen_file, self._allow_colors['screen'], *args, **kwargs)
def _format_err(self, *args, **kwargs):
return self._format_text(
self._err_file, self._allow_colors['err'], *args, **kwargs)
def report_warning(self, message, only_once=False):
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._format_err("WARNING:", self.Styles.WARNING)} {message}', only_once)
def deprecation_warning(self, message):
if self.params.get('logger') is not None:
self.params['logger'].warning('DeprecationWarning: {message}')
else:
self.to_stderr(f'{self._format_err("DeprecationWarning:", self.Styles.ERROR)} {message}', True)
def report_error(self, message, *args, **kwargs):
self.trouble(f'{self._format_err("ERROR:", self.Styles.ERROR)} {message}', *args, **kwargs)
def write_debug(self, message, only_once=False):
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):
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):
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}
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 '')
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):
sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep))
# because meta fields may contain env variables we don't want to
return expand_path(outtmpl).replace(sep, '')
@staticmethod
def escape_outtmpl(outtmpl):
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):
outtmpl = re.sub(
STR_FORMAT_RE_TMPL.format('[^)]*', '[ljqBUDS]'),
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=False):
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
info_dict['video_autonumber'] = self._num_videos
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': number_of_digits(info_dict.get('_last_playlist_index') or 0),
'playlist_autonumber': number_of_digits(info_dict.get('n_entries') or 0),
'autonumber': self.params.get('autonumber_size') or 5,
}
TMPL_DICT = {}
EXTERNAL_FORMAT_RE = re.compile(STR_FORMAT_RE_TMPL.format('[^)]*', f'[{STR_FORMAT_TYPES}ljqBUDS]'))
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<replacement>.*?))?
(?:\|(?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 filename_sanitizer(key, value, restricted=self.params.get('restrictfilenames')):
return sanitize_filename(str(value), restricted=restricted,
is_id=re.search(r'(^|[_.])id(\.|$)', key))
sanitizer = sanitize if callable(sanitize) else filename_sanitizer
sanitize = bool(sanitize)
def _dumpjson_default(obj):
if isinstance(obj, (set, LazyList)):
return list(obj)
return repr(obj)
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') if mobj else ''
value, replacement, default = None, None, na
while mobj:
mobj = mobj.groupdict()
default = mobj['default'] if mobj['default'] is not None else default
value = get_value(mobj)
replacement = mobj['replacement']
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 if replacement is None else replacement
flags = outer_mobj.group('conversion') or ''
str_fmt = f'{fmt[:-1]}s'
if fmt[-1] == 'l': # list
delim = '\n' if '
value, fmt = delim.join(map(str, variadic(value, allowed_types=(str, bytes)))), str_fmt
elif fmt[-1] == 'j': # json
value, fmt = json.dumps(value, default=_dumpjson_default, indent=4 if '
elif fmt[-1] == 'q': # quoted
value = map(str, variadic(value) if '
value, fmt = ' '.join(map(compat_shlex_quote, 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
value, fmt = unicodedata.normalize(
# "+" = compatibility equivalence, "#" = NFD
'NF%s%s' % ('K' if '+' in flags else '', 'D' if '
value), str_fmt
elif fmt[-1] == 'D': # decimal suffix
num_fmt, fmt = fmt[:-1].replace('
value = format_decimal_suffix(value, f'%{num_fmt}f%s' if num_fmt else '%d%s',
factor=1024 if '
elif fmt[-1] == 'S': # filename sanitization
value, fmt = filename_sanitizer(initial_field, value, restricted='
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 = sanitizer(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:
outtmpl = self._outtmpl_expandpath(self.outtmpl_dict.get(tmpl_type, self.outtmpl_dict['default']))
filename = self.evaluate_outtmpl(outtmpl, info_dict, True)
if not filename:
return None
if tmpl_type in ('default', 'temp'):
final_ext, ext = self.params.get('final_ext'), info_dict.get('ext')
if final_ext and ext and final_ext != ext and filename.endswith(f'.{final_ext}'):
filename = replace_extension(filename, ext, final_ext)
else:
force_ext = OUTTMPL_TYPES[tmpl_type]
if force_ext:
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:
no_ext, *ext = filename.rsplit('.', 2)
filename = join_nonempty(no_ext[:trim_file_name], *ext, delim='.')
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):
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):
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:
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):
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):
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(f'[{ie_key}] {temp_id}: has already been recorded in the archive')
if self.params.get('break_on_existing', False):
raise ExistingVideoReached()
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):
while True:
try:
return func(self, *args, **kwargs)
except (DownloadCancelled, LazyList.IndexError, PagedList.IndexError):
raise
except ReExtractInfo as e:
if e.expected:
self.to_screen(f'{e}; Re-extracting data')
else:
self.to_stderr('\r')
self.report_warning(f'{e}; Re-extracting data')
continue
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:
self.report_error(str(e), e.format_traceback())
except Exception as e:
if self.params.get('ignoreerrors'):
self.report_error(str(e), tb=encode_compat_str(traceback.format_exc()))
else:
raise
break
return wrapper
def _wait_for_video(self, ie_result):
if (not self.params.get('wait_for_video')
or ie_result.get('_type', 'video') != 'video'
or ie_result.get('formats') or ie_result.get('url')):
return
format_dur = lambda dur: '%02d:%02d:%02d' % timetuple_from_msec(dur * 1000)[:-1]
last_msg = ''
def progress(msg):
nonlocal last_msg
self.to_screen(msg + ' ' * (len(last_msg) - len(msg)) + '\r', skip_eol=True)
last_msg = msg
min_wait, max_wait = self.params.get('wait_for_video')
diff = try_get(ie_result, lambda x: x['release_timestamp'] - time.time())
if diff is None and ie_result.get('live_status') == 'is_upcoming':
diff = random.randrange(min_wait, max_wait) if (max_wait and min_wait) else (max_wait or min_wait)
self.report_warning('Release time of video is not known')
elif (diff or 0) <= 0:
self.report_warning('Video should already be available according to extracted info')
diff = min(max(diff or 0, min_wait or 0), max_wait or float('inf'))
self.to_screen(f'[wait] Waiting for {format_dur(diff)} - Press Ctrl+C to try now')
wait_till = time.time() + diff
try:
while True:
diff = wait_till - time.time()
if diff <= 0:
progress('')
raise ReExtractInfo('[wait] Wait period ended', expected=True)
progress(f'[wait] Remaining time until next attempt: {self._format_screen(format_dur(diff), self.Styles.EMPHASIS)}')
time.sleep(1)
except KeyboardInterrupt:
progress('')
raise ReExtractInfo('[wait] Interrupted by user', expected=True)
except BaseException as e:
if not isinstance(e, ReExtractInfo):
self.to_screen('')
raise
@__handle_extraction_exceptions
def __extract_info(self, url, ie, download, extra_info, process):
ie_result = ie.extract(url)
if ie_result is None:
return
if isinstance(ie_result, list):
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:
self._wait_for_video(ie_result)
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 = ie_result.get('webpage_url')
if webpage_url:
self.add_extra_info(ie_result, {
'webpage_url_basename': url_basename(webpage_url),
'webpage_url_domain': get_domain(webpage_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):
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)
info_copy, _ = self.pre_process(info_copy)
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:
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=extra_info,
force_generic_extractor=self.params.get('force_generic_extractor'))
for url in additional_urls
]
return ie_result
elif result_type == 'url':
return self.extract_info(
ie_result['url'], download,
ie_key=ie_result.get('ie_key'),
extra_info=extra_info)
elif result_type == 'url_transparent':
info = self.extract_info(
ie_result['url'], ie_key=ie_result.get('ie_key'),
extra_info=extra_info, download=False, process=False)
# 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']),
'webpage_url_domain': get_domain(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)
@staticmethod
def _playlist_infodict(ie_result, **kwargs):
return {
**ie_result,
'playlist': ie_result.get('title') or ie_result.get('id'),
'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,
**kwargs,
}
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('There are no entries')
MissingEntry = object()
incomplete_entries = bool(ie_result.get('requested_entries'))
if incomplete_entries:
def fill_missing_entries(entries, indices):
ret = [MissingEntry] * max(indices)
for i, entry in zip(indices, 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']
if isinstance(ie_entries, list):
playlist_count = len(ie_entries)
msg = f'Collected {playlist_count} videos; downloading %d of them'
ie_result['playlist_count'] = ie_result.get('playlist_count') or playlist_count
def get_entry(i):
return ie_entries[i - 1]
else:
msg = 'Downloading %d videos'
if not isinstance(ie_entries, (PagedList, LazyList)):
ie_entries = LazyList(ie_entries)
elif isinstance(ie_entries, InAdvancePagedList):
if ie_entries._pagesize == 1:
playlist_count = ie_entries._pagecount
def get_entry(i):
return YoutubeDL.__handle_extraction_exceptions(
lambda self, i: ie_entries[i - 1]
)(self, i)
entries, broken = [], False
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 MissingEntry:
raise EntryNotInPlaylist()
except (IndexError, EntryNotInPlaylist):
if incomplete_entries:
raise EntryNotInPlaylist(f'Entry {i} cannot be found')
elif not playlistitems:
break
entries.append(entry)
try:
if entry is not None:
self._match_entry(entry, incomplete=True, silent=True)
except (ExistingVideoReached, RejectedVideoReached):
broken = True
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 (ie_result.get('playlist_count') or broken or playlistitems or playlistend):
ie_result['playlist_count'] = n_entries
if not playlistitems and (playliststart != 1 or playlistend):
playlistitems = list(range(playliststart, playliststart + n_entries))
ie_result['requested_entries'] = playlistitems
_infojson_written = False
write_playlist_files = self.params.get('allow_playlist_files', True)
if write_playlist_files and self.params.get('list_thumbnails'):
self.list_thumbnails(ie_result)
if write_playlist_files and not self.params.get('simulate'):
ie_copy = self._playlist_infodict(ie_result, n_entries=n_entries)
_infojson_written = self._write_info_json(
'playlist', ie_result, self.prepare_filename(ie_copy, 'pl_infojson'))
if _infojson_written 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_count': ie_result.get('playlist_count'),
'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']),
'webpage_url_domain': get_domain(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
playlist_results.append(entry_result)
ie_result['entries'] = playlist_results
# Write the updated info to json
if _infojson_written and self._write_info_json(
'updated playlist', ie_result,
self.prepare_filename(ie_copy, 'pl_infojson'), overwrite=True) is None:
return
ie_result = self.run_all_pps('playlist', ie_result)
self.to_screen(f'[download] Finished downloading playlist: {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):
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,
'~=': lambda attr, value: value.search(attr) is not None
}
str_operator_rex = re.compile(r'''(?x)\s*
(?P<key>[a-zA-Z0-9._-]+)\s*
(?P<negation>!\s*)?(?P<op>%s)\s*(?P<none_inclusive>\?\s*)?
(?P<quote>["'])?
(?P<value>(?(quote)(?:(?!(?P=quote))[^\\]|\\.)+|[\w.-]+))
(?(quote)(?P=quote))\s*
''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
m = str_operator_rex.fullmatch(filter_spec)
if m:
if m.group('op') == '~=':
comparison_value = re.compile(m.group('value'))
else:
comparison_value = re.sub(r'''\\([\\"'])''', r'\1', 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 _check_formats(self, formats):
for f in formats:
self.to_screen('[info] Testing format %s' % f['format_id'])
path = self.get_output_path('temp')
if not self._ensure_dir_exists(f'{path}/'):
continue
temp_file = tempfile.NamedTemporaryFile(suffix='.tmp', delete=False, dir=path 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 _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') == 'selected'
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
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
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:
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:
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'))) or None,
'format_note': '+'.join(orderedSet(filtered('format_note'))) or None,
'filesize_approx': sum(filtered('filesize', 'filesize_approx')) or None,
'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'),
'dynamic_range': the_only_video.get('dynamic_range'),
'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
yield from self._check_formats(formats)
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(ctx), selector_2(ctx)):
yield _merge(pair)
elif selector.type == SINGLE:
format_spec = selector.selector or 'best'
if format_spec == 'all':
def selector_function(ctx):
yield from _check_formats(ctx['formats'][::-1])
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
_filter_f = (
(lambda f: f.get('%scodec' % format_type) != 'none')
if format_type and format_modified
else (lambda f: f.get('%scodec' % not_format_type) == 'none')
if format_type
else (lambda f: f.get('vcodec') != 'none' and f.get('acodec') != 'none')
if not format_modified
else lambda f: True)
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
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:
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 = dict(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()
res.update(info_dict.get('http_headers') or {})
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 _sort_thumbnails(self, 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 _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 not thumbnails:
return
def check_thumbnails(thumbnails):
for t in thumbnails:
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...')
continue
yield t
self._sort_thumbnails(thumbnails)
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') is True:
info_dict['thumbnails'] = LazyList(check_thumbnails(thumbnails[::-1]), reverse=True)
else:
info_dict['thumbnails'] = thumbnails
def process_video_result(self, info_dict, download=True):
assert info_dict.get('_type', 'video') == 'video'
self._num_videos += 1
if 'id' not in info_dict:
raise ExtractorError('Missing "id" field in extractor result', ie=info_dict['extractor'])
elif not info_dict.get('id'):
raise ExtractorError('Extractor failed to obtain "id"', ie=info_dict['extractor'])
info_dict['fulltitle'] = info_dict.get('title')
if 'title' not in info_dict:
raise ExtractorError('Missing "title" field in extractor result',
video_id=info_dict['id'], ie=info_dict['extractor'])
elif not info_dict.get('title'):
self.report_warning('Extractor failed to obtain "title". Creating a generic title instead')
info_dict['title'] = f'{info_dict["extractor"]} video #{info_dict["id"]}'
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:
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'),
('modified_timestamp', 'modified_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)
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 info_dict.get('is_live'):
get_from_start = bool(self.params.get('live_from_start'))
formats = [f for f in formats if bool(f.get('is_from_start')) == get_from_start]
if not get_from_start:
info_dict['title'] += ' ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
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
formats = list(filter(is_wellformed, formats))
formats_dict = {}
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:
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)
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()
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'
if (info_dict.get('duration') and format.get('tbr')
and not format.get('filesize') and not format.get('filesize_approx')):
format['filesize_approx'] = info_dict['duration'] * format['tbr'] * (1024 / 8)
full_format_info = info_dict.copy()
full_format_info.update(format)
format['http_headers'] = self._calc_headers(full_format_info)
if '__x_forwarded_for_ip' in info_dict:
del info_dict['__x_forwarded_for_ip']
if self.params.get('check_formats') is True:
formats = LazyList(self._check_formats(formats[::-1]), reverse=True)
if not formats or formats[0] is not info_dict:
info_dict['formats'] = formats
info_dict, _ = self.pre_process(info_dict)
# The pre-processors may have modified the formats
formats = info_dict.get('formats', [info_dict])
list_only = self.params.get('simulate') is None and (
self.params.get('list_thumbnails') or self.params.get('listformats') or self.params.get('listsubtitles'))
interactive_format_selection = not list_only and self.format_selector == '-'
if self.params.get('list_thumbnails'):
self.list_thumbnails(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')
if self.params.get('listformats') or interactive_format_selection:
self.list_formats(info_dict)
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 True:
if interactive_format_selection:
req_format = input(
self._format_screen('\nEnter format selector: ', self.Styles.EMPHASIS))
try:
format_selector = self.build_format_selector(req_format)
except SyntaxError as err:
self.report_error(err, tb=False, is_error=False)
continue
# 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 interactive_format_selection and not formats_to_download:
self.report_error('Requested format is not available', tb=False, is_error=False)
continue
break
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'])
self.report_warning('Requested format is not available')
# Process what we can, even without any available formats.
formats_to_download = [{}]
best_format = formats_to_download[-1]
if download:
if best_format:
self.to_screen(
f'[info] {info_dict["id"]}: Downloading {len(formats_to_download)} format(s): '
+ ', '.join([f['format_id'] for f in formats_to_download]))
max_downloads_reached = False
for i, fmt in enumerate(formats_to_download):
formats_to_download[i] = 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.update(fmt)
new_info['__original_infodict'] = info_dict
try:
self.process_info(new_info)
except MaxDownloadsReached:
max_downloads_reached = True
new_info.pop('__original_infodict')
# Remove copied info
for key, val in tuple(new_info.items()):
if info_dict.get(key) == val:
new_info.pop(key)
if max_downloads_reached:
break
write_archive = set(f.get('__write_download_archive', False) for f in formats_to_download)
assert write_archive.issubset({True, False, 'ignore'})
if True in write_archive and False not in write_archive:
self.record_download_archive(info_dict)
info_dict['requested_downloads'] = formats_to_download
info_dict = self.run_all_pps('after_video', info_dict)
if max_downloads_reached:
raise MaxDownloadsReached()
# We update the info dict with the selected best quality format (backwards compatibility)
info_dict.update(best_format)
return info_dict
def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
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 _forceprint(self, key, info_dict):
if info_dict is None:
return
info_copy = info_dict.copy()
info_copy['formats_table'] = self.render_formats_table(info_dict)
info_copy['thumbnails_table'] = self.render_thumbnails_table(info_dict)
info_copy['subtitles_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('subtitles'))
info_copy['automatic_captions_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('automatic_captions'))
def format_tmpl(tmpl):
mobj = re.match(r'\w+(=?)$', tmpl)
if mobj and mobj.group(1):
return f'{tmpl[:-1]} = %({tmpl[:-1]})r'
elif mobj:
return f'%({tmpl})s'
return tmpl
for tmpl in self.params['forceprint'].get(key, []):
self.to_stdout(self.evaluate_outtmpl(format_tmpl(tmpl), info_copy))
for tmpl, file_tmpl in self.params['print_to_file'].get(key, []):
filename = self.evaluate_outtmpl(file_tmpl, info_dict)
tmpl = format_tmpl(tmpl)
self.to_screen(f'[info] Writing {tmpl!r} to: {filename}')
with io.open(filename, 'a', encoding='utf-8') as f:
f.write(self.evaluate_outtmpl(tmpl, info_copy) + '\n')
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('forcejson')
or self.params['forceprint'].get('video')
or self.params['print_to_file'].get('video')):
self.post_extract(info_dict)
self._forceprint('video', 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'].split(',')[0] + ',<data>' if f['url'].startswith('data:') else f['url'])
for f in info.get('requested_formats', []) or [info])
self.write_debug('Invoking downloader on "%s"' % urls)
# Note: Ideally info should be a deep-copied so that hooks cannot modify it.
# But it may contain objects that are not deep-copyable
new_info = 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 existing_file(self, filepaths, *, default_overwrite=True):
existing_files = list(filter(os.path.exists, orderedSet(filepaths)))
if existing_files and not self.params.get('overwrites', default_overwrite):
return existing_files[0]
for file in existing_files:
self.report_file_delete(file)
os.remove(file)
return None
def process_info(self, info_dict):
assert info_dict.get('_type', 'video') == 'video'
original_infodict = info_dict
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:
info_dict['__write_download_archive'] = 'ignore'
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'):
info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
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
# For backward compatibility, even though it was a private field
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
def _write_link_file(link_type):
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 False
linkfn = replace_extension(self.prepare_filename(info_dict, 'link'), link_type, info_dict.get('ext'))
if not self._ensure_dir_exists(encodeFilename(linkfn)):
return False
if self.params.get('overwrites', True) and os.path.exists(encodeFilename(linkfn)):
self.to_screen(f'[info] Internet shortcut (.{link_type}) is already present')
return True
try:
self.to_screen(f'[info] Writing internet shortcut (.{link_type}) to: {linkfn}')
with io.open(encodeFilename(to_high_limit_path(linkfn)), 'w', encoding='utf-8',
newline='\r\n' if link_type == 'url' else '\n') as linkfile:
template_vars = {'url': iri_to_uri(info_dict['webpage_url'])}
if link_type == 'desktop':
template_vars['filename'] = linkfn[:-(len(link_type) + 1)]
linkfile.write(LINK_TEMPLATES[link_type] % template_vars)
except (OSError, IOError):
self.report_error(f'Cannot write internet shortcut {linkfn}')
return False
return True
write_links = {
'url': self.params.get('writeurllink'),
'webloc': self.params.get('writewebloclink'),
'desktop': self.params.get('writedesktoplink'),
}
if self.params.get('writelink'):
link_type = ('webloc' if sys.platform == 'darwin'
else 'desktop' if sys.platform.startswith('linux')
else 'url')
write_links[link_type] = True
if any(should_write and not _write_link_file(link_type)
for link_type, should_write in write_links.items()):
return
def replace_info_dict(new_info):
nonlocal info_dict
if new_info == info_dict:
return
info_dict.clear()
info_dict.update(new_info)
try:
new_info, files_to_move = self.pre_process(info_dict, 'before_dl', files_to_move)
replace_info_dict(new_info)
except PostProcessingError as err:
self.report_error('Preprocessing: %s' % str(err))
return
if self.params.get('skip_download'):
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
replace_info_dict(self.run_pp(MoveFilesAfterDownloadPP(self, False), info_dict))
info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
else:
# Download
info_dict.setdefault('__postprocessors', [])
try:
def existing_video_file(*filepaths):
ext = info_dict.get('ext')
converted = lambda file: replace_extension(file, self.params.get('final_ext') or ext, ext)
file = self.existing_file(itertools.chain(*zip(map(converted, filepaths), filepaths)),
default_overwrite=False)
if file:
info_dict['ext'] = os.path.splitext(file)[1][1:]
return file
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)
full_filename = correct_ext(full_filename)
temp_filename = correct_ext(temp_filename)
dl_filename = existing_video_file(full_filename, temp_filename)
info_dict['__real_download'] = False
downloaded = []
merger = FFmpegMergerPP(self)
fd = get_suitable_downloader(info_dict, self.params, to_stdout=temp_filename == '-')
if dl_filename is not None:
self.report_file_already_downloaded(dl_filename)
elif fd:
for f in requested_formats if fd != FFmpegFD else []:
f['filepath'] = fname = prepend_extension(
correct_ext(temp_filename, info_dict['ext']),
'f%s' % f['format_id'], info_dict['ext'])
downloaded.append(fname)
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:
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:
msg = 'You have requested merging of multiple formats but ffmpeg is not installed'
if not self.params.get('ignoreerrors'):
self.report_error(f'{msg}. Aborting due to --abort-on-error')
return
self.report_warning(f'{msg}. The formats won\'t be merged')
if temp_filename == '-':
reason = ('using a downloader other than ffmpeg' if FFmpegFD.can_merge_formats(info_dict, self.params)
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 downloaded and merger.available and not self.params.get('allow_unplayable_formats'):
info_dict['__postprocessors'].append(merger)
info_dict['__files_to_merge'] = downloaded
info_dict['__real_download'] = True
else:
for file in downloaded:
files_to_move[file] = None
else:
dl_filename = existing_video_file(full_filename, temp_filename)
if dl_filename is None or dl_filename == temp_filename:
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
if info_dict.get('requested_formats') is None:
ffmpeg_fixup(downloader == 'HlsFD',
'Possible MPEG-TS in MP4 container or malformed AAC timestamps',
FFmpegFixupM3u8PP)
ffmpeg_fixup(info_dict.get('is_live') and downloader == 'DashSegmentsFD',
'Possible duplicate MOOV atoms', FFmpegFixupDuplicateMoovPP)
ffmpeg_fixup(downloader == 'WebSocketFragmentFD', 'Malformed timestamps detected', FFmpegFixupTimestampPP)
ffmpeg_fixup(downloader == 'WebSocketFragmentFD', 'Malformed duration detected', FFmpegFixupDurationPP)
fixup()
try:
replace_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
info_dict['__write_download_archive'] = True
if self.params.get('force_write_download_archive'):
info_dict['__write_download_archive'] = True
assert info_dict is original_infodict
max_downloads = self.params.get('max_downloads')
if max_downloads is not None and self._num_downloads >= int(max_downloads):
raise MaxDownloadsReached()
def __download_wrapper(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
res = func(*args, **kwargs)
except UnavailableVideoError as e:
self.report_error(e)
except MaxDownloadsReached as e:
self.to_screen(f'[info] {e}')
raise
except DownloadCancelled as e:
self.to_screen(f'[info] {e}')
if not self.params.get('break_per_url'):
raise
else:
if self.params.get('dump_single_json', False):
self.post_extract(res)
self.to_stdout(json.dumps(self.sanitize_info(res)))
return wrapper
def download(self, url_list):
url_list = variadic(url_list)
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:
self.__download_wrapper(self.extract_info)(
url, force_generic_extractor=self.params.get('force_generic_extractor', False))
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:
info = self.sanitize_info(json.loads('\n'.join(f)), self.params.get('clean_infojson', True))
try:
self.__download_wrapper(self.process_ie_result)(info, download=True)
except (DownloadError, EntryNotInPlaylist, ReExtractInfo) as e:
if not isinstance(e, EntryNotInPlaylist):
self.to_stderr('\r')
webpage_url = info.get('webpage_url')
if webpage_url is not None:
self.report_warning(f'The info failed to download: {e}; trying with URL {webpage_url}')
return self.download([webpage_url])
else:
raise
return self._download_retcode
@staticmethod
def sanitize_info(info_dict, remove_private_keys=False):
if info_dict is None:
return info_dict
info_dict.setdefault('epoch', int(time.time()))
info_dict.setdefault('_type', 'video')
remove_keys = {'__original_infodict'}
keep_keys = ['_type']
if remove_private_keys:
remove_keys |= {
'requested_downloads', 'requested_formats', 'requested_subtitles', 'requested_entries',
'entries', 'filepath', 'infojson_filename', 'original_url', 'playlist_autonumber',
}
reject = lambda k, v: k not in keep_keys and (
k.startswith('_') or k in remove_keys or v is None)
else:
reject = lambda k, v: k in remove_keys
def filter_fn(obj):
if isinstance(obj, dict):
return {k: filter_fn(v) for k, v in obj.items() if not reject(k, v)}
elif isinstance(obj, (list, tuple, set, LazyList)):
return list(map(filter_fn, obj))
elif obj is None or isinstance(obj, (str, int, float, bool)):
return obj
else:
return repr(obj)
return filter_fn(info_dict)
@staticmethod
def filter_requested_info(info_dict, actually_filter=True):
return YoutubeDL.sanitize_info(info_dict, actually_filter)
@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 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:
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
def run_all_pps(self, key, info, *, additional_pps=None):
self._forceprint(key, info)
for pp in (additional_pps or []) + self._pps[key]:
info = self.run_pp(pp, info)
return info
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 {}
info = self.run_all_pps(key, info)
return info, info.pop('__files_to_move', None)
def post_process(self, filename, info, files_to_move=None):
info['filepath'] = filename
info['__files_to_move'] = files_to_move or {}
info = self.run_all_pps('post_process', info, additional_pps=info.get('__postprocessors'))
info = self.run_pp(MoveFilesAfterDownloadPP(self), info)
del info['__files_to_move']
return self.run_all_pps('after_move', info)
def _make_archive_id(self, info_dict):
video_id = info_dict.get('id')
if not video_id:
return
extractor = info_dict.get('extractor_key') or info_dict.get('ie_key')
if extractor is None:
url = str_or_none(info_dict.get('url'))
if not url:
return
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
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
self.write_debug(f'Adding to archive: {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'):
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'):
return '%dx%d' % (format['width'], format['height'])
elif format.get('height'):
return '%sp' % format['height']
elif format.get('width'):
return '%dx?' % format['width']
return default
def _list_format_headers(self, *headers):
if self.params.get('listformats_table', True) is not False:
return [self._format_screen(header, self.Styles.HEADERS) for header in headers]
return headers
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:
if res:
res += ' '
res += fdict['format_note']
if fdict.get('tbr') is not None:
if res:
res += ', '
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 render_formats_table(self, info_dict):
if not info_dict.get('formats') and not info_dict.get('url'):
return None
formats = info_dict.get('formats', [info_dict])
if not self.params.get('listformats_table', True) is not False:
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]
return render_table(['format code', 'extension', 'resolution', 'note'], table, extra_gap=1)
delim = self._format_screen('\u2502', self.Styles.DELIM, '|', test_encoding=True)
table = [
[
self._format_screen(format_field(f, 'format_id'), self.Styles.ID),
format_field(f, 'ext'),
format_field(f, func=self.format_resolution, ignore=('audio only', 'images')),
format_field(f, 'fps', '\t%d'),
format_field(f, 'dynamic_range', '%s', ignore=(None, 'SDR')).replace('HDR', ''),
delim,
format_field(f, 'filesize', ' \t%s', func=format_bytes) + format_field(f, 'filesize_approx', '~\t%s', func=format_bytes),
format_field(f, 'tbr', '\t%dk'),
shorten_protocol_name(f.get('protocol', '')),
delim,
format_field(f, 'vcodec', default='unknown').replace(
'none', 'images' if f.get('acodec') == 'none'
else self._format_screen('audio only', self.Styles.SUPPRESS)),
format_field(f, 'vbr', '\t%dk'),
format_field(f, 'acodec', default='unknown').replace(
'none', '' if f.get('vcodec') == 'none'
else self._format_screen('video only', self.Styles.SUPPRESS)),
format_field(f, 'abr', '\t%dk'),
format_field(f, 'asr', '\t%dHz'),
join_nonempty(
self._format_screen('UNSUPPORTED', 'light red') if f.get('ext') in ('f4f', 'f4m') else None,
format_field(f, 'language', '[%s]'),
join_nonempty(format_field(f, 'format_note'),
format_field(f, 'container', ignore=(None, f.get('ext'))),
delim=', '),
delim=' '),
] for f in formats if f.get('preference') is None or f['preference'] >= -1000]
header_line = self._list_format_headers(
'ID', 'EXT', 'RESOLUTION', '\tFPS', 'HDR', delim, '\tFILESIZE', '\tTBR', 'PROTO',
delim, 'VCODEC', '\tVBR', 'ACODEC', '\tABR', '\tASR', 'MORE INFO')
return render_table(
header_line, table, hide_empty=True,
delim=self._format_screen('\u2500', self.Styles.DELIM, '-', test_encoding=True))
def render_thumbnails_table(self, info_dict):
thumbnails = list(info_dict.get('thumbnails') or [])
if not thumbnails:
return None
return render_table(
self._list_format_headers('ID', 'Width', 'Height', 'URL'),
[[t.get('id'), t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails])
def render_subtitles_table(self, video_id, subtitles):
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)]
if not subtitles:
return None
return render_table(
self._list_format_headers('Language', 'Name', 'Formats'),
[_row(lang, formats) for lang, formats in subtitles.items()],
hide_empty=True)
def __list_table(self, video_id, name, func, *args):
table = func(*args)
if not table:
self.to_screen(f'{video_id} has no {name}')
return
self.to_screen(f'[info] Available {name} for {video_id}:')
self.to_stdout(table)
def list_formats(self, info_dict):
self.__list_table(info_dict['id'], 'formats', self.render_formats_table, info_dict)
def list_thumbnails(self, info_dict):
self.__list_table(info_dict['id'], 'thumbnails', self.render_thumbnails_table, info_dict)
def list_subtitles(self, video_id, subtitles, name='subtitles'):
self.__list_table(video_id, name, self.render_subtitles_table, video_id, subtitles)
def urlopen(self, req):
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
def get_encoding(stream):
ret = getattr(stream, 'encoding', 'missing (%s)' % type(stream).__name__)
if not supports_terminal_sequences(stream):
from .compat import WINDOWS_VT_MODE
ret += ' (No VT)' if WINDOWS_VT_MODE is False else ' (No ANSI)'
return ret
encoding_str = 'Encodings: locale %s, fs %s, out %s, err %s, pref %s' % (
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_string(f'[debug] {encoding_str}\n', encoding=None)
write_debug = lambda msg: self._write_string(f'[debug] {msg}\n')
source = detect_variant()
write_debug(join_nonempty(
'yt-dlp version', __version__,
f'[{RELEASE_GIT_HEAD}]' if RELEASE_GIT_HEAD else '',
'' if source == 'unknown' else f'({source})',
delim=' '))
if not _LAZY_LOADER:
if os.environ.get('YTDLP_NO_LAZY_EXTRACTORS'):
write_debug('Lazy loading extractors is forcibly disabled')
else:
write_debug('Lazy loading extractors is disabled')
if plugin_extractors or plugin_postprocessors:
write_debug('Plugins: %s' % [
'%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' % ', '.join(self.params.get('compat_opts')))
if source == 'source':
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' % 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' % (
platform.python_version(),
python_implementation(),
platform.architecture()[0],
platform_name()))
exe_versions, ffmpeg_features = FFmpegPostProcessor.get_versions_and_features(self)
ffmpeg_features = {key for key, val in ffmpeg_features.items() if val}
if ffmpeg_features:
exe_versions['ffmpeg'] += ' (%s)' % ','.join(ffmpeg_features)
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' % exe_str)
from .downloader.websocket import has_websockets
from .postprocessor.embedthumbnail import has_mutagen
from .cookies import SQLITE_AVAILABLE, SECRETSTORAGE_AVAILABLE
lib_str = join_nonempty(
compat_pycrypto_AES and compat_pycrypto_AES.__name__.split('.')[0],
SECRETSTORAGE_AVAILABLE and 'secretstorage',
has_mutagen and 'mutagen',
SQLITE_AVAILABLE and 'sqlite',
has_websockets and 'websockets',
delim=', ') or 'none'
write_debug('Optional libraries: %s' % lib_str)
proxy_map = {}
for handler in self._opener.handlers:
if hasattr(handler, 'proxies'):
proxy_map.update(handler.proxies)
write_debug(f'Proxy map: {proxy_map}')
if False and self.params.get('call_home'):
ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
write_debug('Public IP address: %s' % ipaddr)
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()
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()
# 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
opener.addheaders = []
self._opener = opener
def encode(self, s):
if isinstance(s, bytes):
return s
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, overwrite=None):
if overwrite is None:
overwrite = self.params.get('overwrites', True)
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 overwrite 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):
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):
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'))
existing_sub = self.existing_file((sub_filename_final, sub_filename))
if existing_sub:
self.to_screen(f'[info] Video subtitle {sub_lang}.{sub_format} is already present')
sub_info['filepath'] = existing_sub
ret.append((existing_sub, 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 (DownloadError, ExtractorError, IOError, OSError, ValueError) + network_exceptions as err:
if self.params.get('ignoreerrors') is not True: # False or 'only_download'
raise DownloadError(f'Unable to download video subtitles for {sub_lang!r}: {err}', err)
self.report_warning(f'Unable to download video subtitles for {sub_lang!r}: {err}')
return ret
def _write_thumbnails(self, label, info_dict, filename, thumb_filename_base=None):
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 idx, t in list(enumerate(thumbnails))[::-1]:
thumb_ext = (f'{t["id"]}.' if multiple else '') + determine_ext(t['url'], 'jpg')
thumb_display_id = f'{label} thumbnail {t["id"]}'
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'))
existing_thumb = self.existing_file((thumb_filename_final, thumb_filename))
if existing_thumb:
self.to_screen('[info] %s is already present' % (
thumb_display_id if multiple else f'{label} thumbnail').capitalize())
t['filepath'] = existing_thumb
ret.append((existing_thumb, thumb_filename_final))
else:
self.to_screen(f'[info] Downloading {thumb_display_id} ...')
try:
uf = self.urlopen(sanitized_Request(t['url'], headers=t.get('http_headers', {})))
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:
thumbnails.pop(idx)
self.report_warning(f'Unable to download {thumb_display_id}: {err}')
if ret and not write_all:
break
return ret
| true | true |
1c3f9ceeccd755232226fb4d68b02dcf4d5fb914 | 2,764 | py | Python | lib/rucio/api/dirac.py | faluchet/rucio | b8f3ebdc0748aeed022d8b789e7ef6e0f36e6dae | [
"Apache-2.0"
] | null | null | null | lib/rucio/api/dirac.py | faluchet/rucio | b8f3ebdc0748aeed022d8b789e7ef6e0f36e6dae | [
"Apache-2.0"
] | null | null | null | lib/rucio/api/dirac.py | faluchet/rucio | b8f3ebdc0748aeed022d8b789e7ef6e0f36e6dae | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# 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 print_function
from rucio.api.permission import has_permission
from rucio.api.scope import list_scopes
from rucio.core.rse import get_rse_id
from rucio.core import dirac
from rucio.common.exception import AccessDenied
from rucio.common.utils import extract_scope
def add_files(lfns, issuer, ignore_availability, vo='def'):
"""
Bulk add files :
- Create the file and replica.
- If doesn't exist create the dataset containing the file as well as a rule on the dataset on ANY sites.
- Create all the ascendants of the dataset if they do not exist
:param lfns: List of lfn (dictionary {'lfn': <lfn>, 'rse': <rse>, 'bytes': <bytes>, 'adler32': <adler32>, 'guid': <guid>, 'pfn': <pfn>}
:param issuer: The issuer account.
:param ignore_availability: A boolean to ignore blocked sites.
:param vo: The VO to act on.
"""
scopes = list_scopes(vo=vo)
dids = []
rses = {}
for lfn in lfns:
scope, name = extract_scope(lfn['lfn'], scopes)
dids.append({'scope': scope, 'name': name})
rse = lfn['rse']
if rse not in rses:
rse_id = get_rse_id(rse=rse, vo=vo)
rses[rse] = rse_id
lfn['rse_id'] = rses[rse]
# Check if the issuer can add dids and use skip_availabitlity
for rse in rses:
rse_id = rses[rse]
kwargs = {'rse': rse, 'rse_id': rse_id}
if not has_permission(issuer=issuer, action='add_replicas', kwargs=kwargs, vo=vo):
raise AccessDenied('Account %s can not add file replicas on %s for VO %s' % (issuer, rse, vo))
if not has_permission(issuer=issuer, action='skip_availability_check', kwargs=kwargs, vo=vo):
ignore_availability = False
# Check if the issuer can add the files
kwargs = {'issuer': issuer, 'dids': dids}
if not has_permission(issuer=issuer, action='add_dids', kwargs=kwargs, vo=vo):
raise AccessDenied('Account %s can not bulk add data identifier for VO %s' % (issuer, vo))
dirac.add_files(lfns=lfns, account=issuer, ignore_availability=ignore_availability, session=None, vo=vo)
| 41.253731 | 139 | 0.688495 |
from __future__ import print_function
from rucio.api.permission import has_permission
from rucio.api.scope import list_scopes
from rucio.core.rse import get_rse_id
from rucio.core import dirac
from rucio.common.exception import AccessDenied
from rucio.common.utils import extract_scope
def add_files(lfns, issuer, ignore_availability, vo='def'):
scopes = list_scopes(vo=vo)
dids = []
rses = {}
for lfn in lfns:
scope, name = extract_scope(lfn['lfn'], scopes)
dids.append({'scope': scope, 'name': name})
rse = lfn['rse']
if rse not in rses:
rse_id = get_rse_id(rse=rse, vo=vo)
rses[rse] = rse_id
lfn['rse_id'] = rses[rse]
for rse in rses:
rse_id = rses[rse]
kwargs = {'rse': rse, 'rse_id': rse_id}
if not has_permission(issuer=issuer, action='add_replicas', kwargs=kwargs, vo=vo):
raise AccessDenied('Account %s can not add file replicas on %s for VO %s' % (issuer, rse, vo))
if not has_permission(issuer=issuer, action='skip_availability_check', kwargs=kwargs, vo=vo):
ignore_availability = False
kwargs = {'issuer': issuer, 'dids': dids}
if not has_permission(issuer=issuer, action='add_dids', kwargs=kwargs, vo=vo):
raise AccessDenied('Account %s can not bulk add data identifier for VO %s' % (issuer, vo))
dirac.add_files(lfns=lfns, account=issuer, ignore_availability=ignore_availability, session=None, vo=vo)
| true | true |
1c3f9e4ebd21ad0606f2ffec97ee9773ddb7352f | 6,398 | py | Python | sphinxcontrib/confluencebuilder/exceptions.py | tsvi/confluencebuilder | 8a7577d5ca3afa095276dbe1e6f35821beae3f23 | [
"BSD-2-Clause"
] | null | null | null | sphinxcontrib/confluencebuilder/exceptions.py | tsvi/confluencebuilder | 8a7577d5ca3afa095276dbe1e6f35821beae3f23 | [
"BSD-2-Clause"
] | null | null | null | sphinxcontrib/confluencebuilder/exceptions.py | tsvi/confluencebuilder | 8a7577d5ca3afa095276dbe1e6f35821beae3f23 | [
"BSD-2-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""
:copyright: Copyright 2017-2020 Sphinx Confluence Builder Contributors (AUTHORS)
:license: BSD-2-Clause (LICENSE)
"""
from sphinx.errors import ConfigError
from sphinx.errors import SphinxError
class ConfluenceError(SphinxError):
category = 'sphinxcontrib.confluencebuilder error'
class ConfluenceAuthenticationFailedUrlError(ConfluenceError):
def __init__(self):
SphinxError.__init__(self,
"""---\n"""
"""Unable to authenticate with the Confluence server.\n"""
"""\n"""
"""Ensure your username and password are correct. If your """
"""username and password is correct, you may need to unlock """
"""your Confluence account be re-logging in with your browser """
"""or asking your Confluence administrator for help.\n"""
"""---\n"""
)
class ConfluenceBadApiError(ConfluenceError):
def __init__(self, details):
SphinxError.__init__(self,
"""---\n"""
"""An unsupported Confluence API call has been made.\n"""
"""\n"""
"""%s""" % details +
"""\n---\n"""
)
class ConfluenceBadSpaceError(ConfluenceError):
def __init__(self, space_name, uname, pw_set):
uname_value = uname if uname else '(empty)'
pw_value = '<set>' if pw_set else '(empty)'
SphinxError.__init__(self,
"""---\n"""
"""The configured Confluence space does not appear to be """
"""valid:\n\n"""
""" Space: {}\n"""
""" Username: {}\n"""
""" Password: {}\n"""
"""\n"""
"""Ensure the server is running or your Confluence URL is valid. """
"""Also ensure your authentication options are properly set.\n"""
"""\n"""
"""Note: Confluence space names are case-sensitive.\n"""
"""---\n""".format(space_name, uname_value, pw_value)
)
class ConfluenceBadServerUrlError(ConfluenceError):
def __init__(self, server_url, ex):
SphinxError.__init__(self,
"""---\n"""
"""An issue has been detected when trying to communicate with """
"""Confluence server.\n"""
"""\n"""
"""Ensure the server is running or your Confluence server URL """
"""is valid:\n\n"""
""" %s\n""" % server_url +
"""\n(details: %s""" % ex +
""")\n"""
"""---\n"""
)
class ConfluenceCertificateError(ConfluenceError):
def __init__(self, ex):
SphinxError.__init__(self,
"""---\n"""
"""An SSL issue has been detected when trying to load the """
"""the certificates provided.\n"""
"""details: %s\n""" % ex +
"""---\n"""
)
class ConfluenceConfigurationError(ConfluenceError, ConfigError):
pass
class ConfluencePermissionError(ConfluenceError):
def __init__(self, details):
SphinxError.__init__(self,
"""---\n"""
"""Do not have permission for this action on the Confluence """
"""server.\n\n"""
"""%s\n""" % details +
"""---\n"""
)
class ConfluenceProxyPermissionError(ConfluenceError):
def __init__(self):
SphinxError.__init__(self,
"""---\n"""
"""Unable to authenticate with the proxy server.\n"""
"""\n"""
"""Ensure your proxy's username and password are correct.\n"""
"""---\n"""
)
class ConfluenceSeraphAuthenticationFailedUrlError(ConfluenceError):
def __init__(self):
SphinxError.__init__(self,
"""---\n"""
"""Unable to authenticate with the Confluence server.\n"""
"""\n"""
"""While this could be your username or password being """
"""incorrect, this plugin as detected that the Atlassian """
"""Seraph instance has logged you out. This could be a """
"""result of a server-related issue. If this persisted, """
"""try contacting your Confluence administrator for help.\n"""
"""---\n"""
)
class ConfluenceSslError(ConfluenceError):
def __init__(self, server_url, ex):
SphinxError.__init__(self,
"""---\n"""
"""An SSL issue has been detected when trying to communicate """
"""with Confluence server.\n"""
"""\n"""
"""Ensure the server is running or your Confluence server URL """
"""is valid:\n\n"""
""" %s\n""" % server_url +
"""\n(details: %s""" % ex +
""")\n"""
"""---\n"""
)
class ConfluenceTimeoutError(ConfluenceError):
def __init__(self, server_url):
SphinxError.__init__(self,
"""---\n"""
"""A request to communicate with the Confluence server has """
"""timed out.\n"""
"""\n"""
"""Ensure the server is running or your Confluence server URL """
"""is valid:\n\n"""
""" %s\n""" % server_url +
"""---\n"""
)
class ConfluenceUnreconciledPageError(ConfluenceError):
def __init__(self, page_name, page_id, url, ex):
SphinxError.__init__(self,
"""---\n"""
"""Unable to update unreconciled page: %s """ % page_name +
"""(id: %s)\n""" % str(page_id) +
"""\n"""
"""Unable to update the target page due to the Confluence """
"""instance reporting an unreconciled page. A workaround for """
"""this is to manually browse the page using a browser which """
"""will force Confluence to reconcile the page. A link to the """
"""page is a follows:\n"""
"""\n"""
""" %spages/viewpage.action?pageId=%s""" % (url, str(page_id)) +
"""\n\n"""
"""If this is observed on Confluence v6.x, v7.3.3 or higher, """
"""please report this issue to the developers of the Confluence """
"""builder extension.\n"""
"""\n"""
"""See also: https://jira.atlassian.com/browse/CONFSERVER-59196\n"""
"""\n(details: %s""" % ex +
""")\n"""
"""---\n"""
)
| 37.857988 | 80 | 0.523914 |
from sphinx.errors import ConfigError
from sphinx.errors import SphinxError
class ConfluenceError(SphinxError):
category = 'sphinxcontrib.confluencebuilder error'
class ConfluenceAuthenticationFailedUrlError(ConfluenceError):
def __init__(self):
SphinxError.__init__(self,
"""---\n"""
"""Unable to authenticate with the Confluence server.\n"""
"""\n"""
"""Ensure your username and password are correct. If your """
"""username and password is correct, you may need to unlock """
"""your Confluence account be re-logging in with your browser """
"""or asking your Confluence administrator for help.\n"""
"""---\n"""
)
class ConfluenceBadApiError(ConfluenceError):
def __init__(self, details):
SphinxError.__init__(self,
"""---\n"""
"""An unsupported Confluence API call has been made.\n"""
"""\n"""
"""%s""" % details +
"""\n---\n"""
)
class ConfluenceBadSpaceError(ConfluenceError):
def __init__(self, space_name, uname, pw_set):
uname_value = uname if uname else '(empty)'
pw_value = '<set>' if pw_set else '(empty)'
SphinxError.__init__(self,
"""---\n"""
"""The configured Confluence space does not appear to be """
"""valid:\n\n"""
""" Space: {}\n"""
""" Username: {}\n"""
""" Password: {}\n"""
"""\n"""
"""Ensure the server is running or your Confluence URL is valid. """
"""Also ensure your authentication options are properly set.\n"""
"""\n"""
"""Note: Confluence space names are case-sensitive.\n"""
"""---\n""".format(space_name, uname_value, pw_value)
)
class ConfluenceBadServerUrlError(ConfluenceError):
def __init__(self, server_url, ex):
SphinxError.__init__(self,
"""---\n"""
"""An issue has been detected when trying to communicate with """
"""Confluence server.\n"""
"""\n"""
"""Ensure the server is running or your Confluence server URL """
"""is valid:\n\n"""
""" %s\n""" % server_url +
"""\n(details: %s""" % ex +
""")\n"""
"""---\n"""
)
class ConfluenceCertificateError(ConfluenceError):
def __init__(self, ex):
SphinxError.__init__(self,
"""---\n"""
"""An SSL issue has been detected when trying to load the """
"""the certificates provided.\n"""
"""details: %s\n""" % ex +
"""---\n"""
)
class ConfluenceConfigurationError(ConfluenceError, ConfigError):
pass
class ConfluencePermissionError(ConfluenceError):
def __init__(self, details):
SphinxError.__init__(self,
"""---\n"""
"""Do not have permission for this action on the Confluence """
"""server.\n\n"""
"""%s\n""" % details +
"""---\n"""
)
class ConfluenceProxyPermissionError(ConfluenceError):
def __init__(self):
SphinxError.__init__(self,
"""---\n"""
"""Unable to authenticate with the proxy server.\n"""
"""\n"""
"""Ensure your proxy's username and password are correct.\n"""
"""---\n"""
)
class ConfluenceSeraphAuthenticationFailedUrlError(ConfluenceError):
def __init__(self):
SphinxError.__init__(self,
"""---\n"""
"""Unable to authenticate with the Confluence server.\n"""
"""\n"""
"""While this could be your username or password being """
"""incorrect, this plugin as detected that the Atlassian """
"""Seraph instance has logged you out. This could be a """
"""result of a server-related issue. If this persisted, """
"""try contacting your Confluence administrator for help.\n"""
"""---\n"""
)
class ConfluenceSslError(ConfluenceError):
def __init__(self, server_url, ex):
SphinxError.__init__(self,
"""---\n"""
"""An SSL issue has been detected when trying to communicate """
"""with Confluence server.\n"""
"""\n"""
"""Ensure the server is running or your Confluence server URL """
"""is valid:\n\n"""
""" %s\n""" % server_url +
"""\n(details: %s""" % ex +
""")\n"""
"""---\n"""
)
class ConfluenceTimeoutError(ConfluenceError):
def __init__(self, server_url):
SphinxError.__init__(self,
"""---\n"""
"""A request to communicate with the Confluence server has """
"""timed out.\n"""
"""\n"""
"""Ensure the server is running or your Confluence server URL """
"""is valid:\n\n"""
""" %s\n""" % server_url +
"""---\n"""
)
class ConfluenceUnreconciledPageError(ConfluenceError):
def __init__(self, page_name, page_id, url, ex):
SphinxError.__init__(self,
"""---\n"""
"""Unable to update unreconciled page: %s """ % page_name +
"""(id: %s)\n""" % str(page_id) +
"""\n"""
"""Unable to update the target page due to the Confluence """
"""instance reporting an unreconciled page. A workaround for """
"""this is to manually browse the page using a browser which """
"""will force Confluence to reconcile the page. A link to the """
"""page is a follows:\n"""
"""\n"""
""" %spages/viewpage.action?pageId=%s""" % (url, str(page_id)) +
"""\n\n"""
"""If this is observed on Confluence v6.x, v7.3.3 or higher, """
"""please report this issue to the developers of the Confluence """
"""builder extension.\n"""
"""\n"""
"""See also: https://jira.atlassian.com/browse/CONFSERVER-59196\n"""
"""\n(details: %s""" % ex +
""")\n"""
"""---\n"""
)
| true | true |
1c3f9e5aea4eb42fa74686213dd3f580aeda7d65 | 10,183 | py | Python | 2018-2019/project/utils/preprocessing.py | Tudor67/Neural-Networks-Assignments | 7376e9d3b0059df2f2b21d56787c47d3c1ba6746 | [
"MIT"
] | 1 | 2019-04-07T03:50:57.000Z | 2019-04-07T03:50:57.000Z | 2018-2019/project/utils/preprocessing.py | Tudor67/Neural-Networks-Assignments | 7376e9d3b0059df2f2b21d56787c47d3c1ba6746 | [
"MIT"
] | 5 | 2018-10-16T22:46:33.000Z | 2019-02-04T20:11:41.000Z | 2018-2019/project/utils/preprocessing.py | Tudor67/Neural-Networks-Assignments | 7376e9d3b0059df2f2b21d56787c47d3c1ba6746 | [
"MIT"
] | 1 | 2019-04-07T03:50:42.000Z | 2019-04-07T03:50:42.000Z | import numpy as np
import os
import skimage
import sys
def resize_images(images, new_h, new_w, ch):
resized_images = np.zeros([len(images), new_h, new_w, ch])
for idx, img in enumerate(images):
resized_images[idx] = skimage.transform.resize(img,
[new_h, new_w, ch],
mode='constant',
anti_aliasing=False)
return resized_images
def crop_image(img, patch_h=256, patch_w=256):
patch_shape = (patch_h, patch_w, 3)
if img.ndim == 2:
img = img[:,:,np.newaxis]
patch_shape = (patch_h, patch_w, 1)
row_pad = (patch_shape[0] - (img.shape[0] % patch_shape[0])) % patch_shape[0]
col_pad = (patch_shape[1] - (img.shape[1] % patch_shape[1])) % patch_shape[1]
img_pad = np.pad(img, [(0, row_pad), (0, col_pad), (0, 0)], 'constant')
rows_start = range(0, img_pad.shape[0], patch_shape[0])
cols_start = range(0, img_pad.shape[1], patch_shape[1])
patches = np.zeros([len(rows_start), len(cols_start), *patch_shape],
dtype=np.uint8)
for i, row in enumerate(rows_start):
for j, col in enumerate(cols_start):
patches[i][j] = img_pad[row:row + patch_shape[0],
col:col + patch_shape[1],
:]
if patches.shape[4] == 1:
patches = patches.squeeze(axis=4)
return patches
def merge_patches(patches, img_h, img_w):
img_pad_h = patches.shape[0] * patches.shape[2]
img_pad_w = patches.shape[1] * patches.shape[3]
# combine patches
patches = np.moveaxis(patches, 2, 1)
img_pad = patches.reshape([img_pad_h, img_pad_w, -1])
# remove padding
img = img_pad[:img_h, :img_w, :].squeeze()
return img
def crop_images_and_save(images, img_names,
save_path, img_format,
patch_h, patch_w):
if not os.path.isdir(save_path):
os.makedirs(save_path)
for img, img_name in zip(images, img_names):
img_patches = crop_image(img, patch_h, patch_w)
for i in range(img_patches.shape[0]):
for j in range(img_patches.shape[1]):
filename = f'{save_path}/{img_name}_{i}_{j}.{img_format}'
skimage.io.imsave(filename, img_patches[i][j])
def crop_images_from_dir_and_save_all(images_path, save_path, patch_h, patch_w,
img_format, append_h_w=True):
img_names = os.listdir(images_path)
for img_name in img_names:
img = skimage.io.imread(f'{images_path}/{img_name}')
img_name_with_shape = None
if append_h_w:
img_name_with_shape = append_img_name_with_h_w(remove_img_formats([img_name]),
get_img_shapes([img]))[0]
else:
img_name_with_shape = remove_img_formats([img_name])[0]
crop_images_and_save([img], [img_name_with_shape],
save_path=save_path,
img_format=img_format,
patch_h=patch_h,
patch_w=patch_w)
def load_patches(img_name, patches_path):
patches_names_all = os.listdir(patches_path)
patches = []
max_row = 0
for patch_name in sorted(patches_names_all):
if patch_name.startswith(img_name):
patch = skimage.io.imread(f'{patches_path}/{patch_name}')
patches.append(patch)
# useful for patches.reshape
patch_shape = patch.shape
row = 1 + int(patch_name.split('_')[-2])
max_row = max(max_row, row)
patches = np.array(patches).astype(np.uint8).reshape(max_row, -1, *patch_shape)
return patches
def get_img_shapes(images):
return [img.shape for img in images]
def remove_img_formats(img_names):
return ['.'.join(img_name.split('.')[:-1]) for img_name in img_names]
def remove_grid_indices(img_names):
return ['_'.join(img_name.split('_')[:-2]) for img_name in img_names]
def append_img_name_with_h_w(img_names, img_shapes):
return [f'{img_name}_{img_shape[0]}_{img_shape[1]}'
for img_name, img_shape in zip(img_names, img_shapes)]
def get_img_shapes_from_strings(img_names):
img_shapes = []
for img_name in img_names:
h = int(img_name.split('_')[-4])
w = int(img_name.split('_')[-3])
img_shapes.append((h, w))
return img_shapes
def merge_patches_and_save(img_shapes, img_names, patches_path,
save_path, img_format):
if not os.path.isdir(save_path):
os.makedirs(save_path)
for img_shape, img_name in zip(img_shapes, img_names):
img_h, img_w = img_shape[:2]
patches = load_patches(img_name, patches_path)
img_from_patches = merge_patches(patches, img_h=img_h, img_w=img_w)
filename = f'{save_path}/{img_name}.{img_format}'
skimage.io.imsave(filename, img_from_patches)
def crop_images_and_save_all(dataset_with_img_names, dataset_path,
img_format='png', patch_h=256, patch_w=256,
append_img_h_w=False):
# dataset splits
train, train_img_names, val, val_img_names, test, test_img_names = dataset_with_img_names
train_images, train_masks = train
val_images, val_masks = val
test_images, test_masks = test
if append_img_h_w:
train_img_names = append_img_name_with_h_w(train_img_names, get_img_shapes(train_images))
val_img_names = append_img_name_with_h_w(val_img_names, get_img_shapes(val_images))
test_img_names = append_img_name_with_h_w(test_img_names, get_img_shapes(test_images))
d_splits = [(train_images, train_img_names, 'train_img'),
(train_masks, train_img_names, 'train_mask'),
(val_images, val_img_names, 'val_img'),
(val_masks, val_img_names, 'val_mask'),
(test_images, test_img_names, 'test_img'),
(test_masks, test_img_names, 'test_mask')]
for images, img_names, split_name in d_splits:
save_path=f'{dataset_path}/{split_name.split("_")[0]}/{split_name}_patches'
crop_images_and_save(images, img_names,
save_path=save_path,
img_format=img_format,
patch_h=patch_h,
patch_w=patch_w)
def merge_patches_and_save_all(dataset_with_img_names,
dataset_path,
img_format='png'):
# dataset splits
train, train_img_names, val, val_img_names, test, test_img_names = dataset_with_img_names
train_images, train_masks = train
val_images, val_masks = val
test_images, test_masks = test
d_splits = [(train_images, train_img_names, 'train_img'),
(train_masks, train_img_names, 'train_mask'),
(val_images, val_img_names, 'val_img'),
(val_masks, val_img_names, 'val_mask'),
(test_images, test_img_names, 'test_img'),
(test_masks, test_img_names, 'test_mask')]
for images, img_names, split_name in d_splits:
patches_path = f'{dataset_path}/{split_name.split("_")[0]}/{split_name}_patches'
save_path = f'{dataset_path}/{split_name.split("_")[0]}/{split_name}_from_patches'
img_shapes = get_img_shapes(images)
merge_patches_and_save(img_shapes, img_names,
patches_path=patches_path,
save_path=save_path,
img_format=img_format)
def merge_patches_directly_and_save_all(results_path,
split_types=['pred'],
img_format='png'):
for split_name in ['train', 'val', 'test']:
for split_type in split_types:
patches_path = f'{results_path}/{split_name}/{split_name}_{split_type}_patches'
save_path = f'{results_path}/{split_name}/{split_name}_{split_type}_from_patches'
img_names_full = os.listdir(patches_path)
img_names = remove_grid_indices(img_names_full)
img_shapes = get_img_shapes_from_strings(img_names_full)
# remove the same img_names (duplicates)
unique_img_names = []
unique_img_shapes = []
for img_name, img_shape in zip(img_names, img_shapes):
if img_name not in unique_img_names:
unique_img_names.append(img_name)
unique_img_shapes.append(img_shape)
merge_patches_and_save(unique_img_shapes,
unique_img_names,
patches_path=patches_path,
save_path=save_path,
img_format=img_format)
def merge_patches_from_dir_and_save_all(patches_path,
save_path,
img_format='png'):
img_names_full = os.listdir(patches_path)
img_names = remove_grid_indices(img_names_full)
img_shapes = get_img_shapes_from_strings(img_names_full)
# remove the same img_names (duplicates)
unique_img_names = []
unique_img_shapes = []
for img_name, img_shape in zip(img_names, img_shapes):
if img_name not in unique_img_names:
unique_img_names.append(img_name)
unique_img_shapes.append(img_shape)
merge_patches_and_save(unique_img_shapes,
unique_img_names,
patches_path=patches_path,
save_path=save_path,
img_format=img_format) | 41.060484 | 97 | 0.582343 | import numpy as np
import os
import skimage
import sys
def resize_images(images, new_h, new_w, ch):
resized_images = np.zeros([len(images), new_h, new_w, ch])
for idx, img in enumerate(images):
resized_images[idx] = skimage.transform.resize(img,
[new_h, new_w, ch],
mode='constant',
anti_aliasing=False)
return resized_images
def crop_image(img, patch_h=256, patch_w=256):
patch_shape = (patch_h, patch_w, 3)
if img.ndim == 2:
img = img[:,:,np.newaxis]
patch_shape = (patch_h, patch_w, 1)
row_pad = (patch_shape[0] - (img.shape[0] % patch_shape[0])) % patch_shape[0]
col_pad = (patch_shape[1] - (img.shape[1] % patch_shape[1])) % patch_shape[1]
img_pad = np.pad(img, [(0, row_pad), (0, col_pad), (0, 0)], 'constant')
rows_start = range(0, img_pad.shape[0], patch_shape[0])
cols_start = range(0, img_pad.shape[1], patch_shape[1])
patches = np.zeros([len(rows_start), len(cols_start), *patch_shape],
dtype=np.uint8)
for i, row in enumerate(rows_start):
for j, col in enumerate(cols_start):
patches[i][j] = img_pad[row:row + patch_shape[0],
col:col + patch_shape[1],
:]
if patches.shape[4] == 1:
patches = patches.squeeze(axis=4)
return patches
def merge_patches(patches, img_h, img_w):
img_pad_h = patches.shape[0] * patches.shape[2]
img_pad_w = patches.shape[1] * patches.shape[3]
patches = np.moveaxis(patches, 2, 1)
img_pad = patches.reshape([img_pad_h, img_pad_w, -1])
img = img_pad[:img_h, :img_w, :].squeeze()
return img
def crop_images_and_save(images, img_names,
save_path, img_format,
patch_h, patch_w):
if not os.path.isdir(save_path):
os.makedirs(save_path)
for img, img_name in zip(images, img_names):
img_patches = crop_image(img, patch_h, patch_w)
for i in range(img_patches.shape[0]):
for j in range(img_patches.shape[1]):
filename = f'{save_path}/{img_name}_{i}_{j}.{img_format}'
skimage.io.imsave(filename, img_patches[i][j])
def crop_images_from_dir_and_save_all(images_path, save_path, patch_h, patch_w,
img_format, append_h_w=True):
img_names = os.listdir(images_path)
for img_name in img_names:
img = skimage.io.imread(f'{images_path}/{img_name}')
img_name_with_shape = None
if append_h_w:
img_name_with_shape = append_img_name_with_h_w(remove_img_formats([img_name]),
get_img_shapes([img]))[0]
else:
img_name_with_shape = remove_img_formats([img_name])[0]
crop_images_and_save([img], [img_name_with_shape],
save_path=save_path,
img_format=img_format,
patch_h=patch_h,
patch_w=patch_w)
def load_patches(img_name, patches_path):
patches_names_all = os.listdir(patches_path)
patches = []
max_row = 0
for patch_name in sorted(patches_names_all):
if patch_name.startswith(img_name):
patch = skimage.io.imread(f'{patches_path}/{patch_name}')
patches.append(patch)
patch_shape = patch.shape
row = 1 + int(patch_name.split('_')[-2])
max_row = max(max_row, row)
patches = np.array(patches).astype(np.uint8).reshape(max_row, -1, *patch_shape)
return patches
def get_img_shapes(images):
return [img.shape for img in images]
def remove_img_formats(img_names):
return ['.'.join(img_name.split('.')[:-1]) for img_name in img_names]
def remove_grid_indices(img_names):
return ['_'.join(img_name.split('_')[:-2]) for img_name in img_names]
def append_img_name_with_h_w(img_names, img_shapes):
return [f'{img_name}_{img_shape[0]}_{img_shape[1]}'
for img_name, img_shape in zip(img_names, img_shapes)]
def get_img_shapes_from_strings(img_names):
img_shapes = []
for img_name in img_names:
h = int(img_name.split('_')[-4])
w = int(img_name.split('_')[-3])
img_shapes.append((h, w))
return img_shapes
def merge_patches_and_save(img_shapes, img_names, patches_path,
save_path, img_format):
if not os.path.isdir(save_path):
os.makedirs(save_path)
for img_shape, img_name in zip(img_shapes, img_names):
img_h, img_w = img_shape[:2]
patches = load_patches(img_name, patches_path)
img_from_patches = merge_patches(patches, img_h=img_h, img_w=img_w)
filename = f'{save_path}/{img_name}.{img_format}'
skimage.io.imsave(filename, img_from_patches)
def crop_images_and_save_all(dataset_with_img_names, dataset_path,
img_format='png', patch_h=256, patch_w=256,
append_img_h_w=False):
train, train_img_names, val, val_img_names, test, test_img_names = dataset_with_img_names
train_images, train_masks = train
val_images, val_masks = val
test_images, test_masks = test
if append_img_h_w:
train_img_names = append_img_name_with_h_w(train_img_names, get_img_shapes(train_images))
val_img_names = append_img_name_with_h_w(val_img_names, get_img_shapes(val_images))
test_img_names = append_img_name_with_h_w(test_img_names, get_img_shapes(test_images))
d_splits = [(train_images, train_img_names, 'train_img'),
(train_masks, train_img_names, 'train_mask'),
(val_images, val_img_names, 'val_img'),
(val_masks, val_img_names, 'val_mask'),
(test_images, test_img_names, 'test_img'),
(test_masks, test_img_names, 'test_mask')]
for images, img_names, split_name in d_splits:
save_path=f'{dataset_path}/{split_name.split("_")[0]}/{split_name}_patches'
crop_images_and_save(images, img_names,
save_path=save_path,
img_format=img_format,
patch_h=patch_h,
patch_w=patch_w)
def merge_patches_and_save_all(dataset_with_img_names,
dataset_path,
img_format='png'):
train, train_img_names, val, val_img_names, test, test_img_names = dataset_with_img_names
train_images, train_masks = train
val_images, val_masks = val
test_images, test_masks = test
d_splits = [(train_images, train_img_names, 'train_img'),
(train_masks, train_img_names, 'train_mask'),
(val_images, val_img_names, 'val_img'),
(val_masks, val_img_names, 'val_mask'),
(test_images, test_img_names, 'test_img'),
(test_masks, test_img_names, 'test_mask')]
for images, img_names, split_name in d_splits:
patches_path = f'{dataset_path}/{split_name.split("_")[0]}/{split_name}_patches'
save_path = f'{dataset_path}/{split_name.split("_")[0]}/{split_name}_from_patches'
img_shapes = get_img_shapes(images)
merge_patches_and_save(img_shapes, img_names,
patches_path=patches_path,
save_path=save_path,
img_format=img_format)
def merge_patches_directly_and_save_all(results_path,
split_types=['pred'],
img_format='png'):
for split_name in ['train', 'val', 'test']:
for split_type in split_types:
patches_path = f'{results_path}/{split_name}/{split_name}_{split_type}_patches'
save_path = f'{results_path}/{split_name}/{split_name}_{split_type}_from_patches'
img_names_full = os.listdir(patches_path)
img_names = remove_grid_indices(img_names_full)
img_shapes = get_img_shapes_from_strings(img_names_full)
unique_img_names = []
unique_img_shapes = []
for img_name, img_shape in zip(img_names, img_shapes):
if img_name not in unique_img_names:
unique_img_names.append(img_name)
unique_img_shapes.append(img_shape)
merge_patches_and_save(unique_img_shapes,
unique_img_names,
patches_path=patches_path,
save_path=save_path,
img_format=img_format)
def merge_patches_from_dir_and_save_all(patches_path,
save_path,
img_format='png'):
img_names_full = os.listdir(patches_path)
img_names = remove_grid_indices(img_names_full)
img_shapes = get_img_shapes_from_strings(img_names_full)
unique_img_names = []
unique_img_shapes = []
for img_name, img_shape in zip(img_names, img_shapes):
if img_name not in unique_img_names:
unique_img_names.append(img_name)
unique_img_shapes.append(img_shape)
merge_patches_and_save(unique_img_shapes,
unique_img_names,
patches_path=patches_path,
save_path=save_path,
img_format=img_format) | true | true |
1c3f9ecbc4cd49d29d84f283efcb137d3085b13f | 25,468 | py | Python | qa/rpc-tests/fundrawtransaction-hd.py | zevno/zevno-core | f546a48aaaf55c268633fcd8d04fc7c41c7b2bc8 | [
"MIT"
] | 1 | 2020-12-10T00:17:10.000Z | 2020-12-10T00:17:10.000Z | qa/rpc-tests/fundrawtransaction-hd.py | zevno/zevno-core | f546a48aaaf55c268633fcd8d04fc7c41c7b2bc8 | [
"MIT"
] | null | null | null | qa/rpc-tests/fundrawtransaction-hd.py | zevno/zevno-core | f546a48aaaf55c268633fcd8d04fc7c41c7b2bc8 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
# Create one-input, one-output, no-fee transaction:
class RawTransactionsTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 4
def setup_network(self, split=False):
self.nodes = start_nodes(4, self.options.tmpdir, [['-usehd=1']] * self.num_nodes, redirect_stderr=True)
connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2)
connect_nodes_bi(self.nodes,0,3)
self.is_network_split=False
self.sync_all()
def run_test(self):
self.log.info("Mining blocks...")
min_relay_tx_fee = self.nodes[0].getnetworkinfo()['relayfee']
# This test is not meant to test fee estimation and we'd like
# to be sure all txs are sent at a consistent desired feerate
for node in self.nodes:
node.settxfee(min_relay_tx_fee)
# if the fee's positive delta is higher than this value tests will fail,
# neg. delta always fail the tests.
# The size of the signature of every input may be at most 2 bytes larger
# than a minimum sized signature.
# = 2 bytes * minRelayTxFeePerByte
feeTolerance = 2 * min_relay_tx_fee/1000
self.nodes[2].generate(1)
self.sync_all()
self.nodes[0].generate(121)
self.sync_all()
watchonly_address = self.nodes[0].getnewaddress()
watchonly_pubkey = self.nodes[0].validateaddress(watchonly_address)["pubkey"]
watchonly_amount = Decimal(2000)
self.nodes[3].importpubkey(watchonly_pubkey, "", True)
watchonly_txid = self.nodes[0].sendtoaddress(watchonly_address, watchonly_amount)
self.nodes[0].sendtoaddress(self.nodes[3].getnewaddress(), watchonly_amount / 10)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 15)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 50)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
###############
# simple test #
###############
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0) #test if we have enought inputs
##############################
# simple test with two coins #
##############################
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 22 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0) #test if we have enough inputs
##############################
# simple test with two coins #
##############################
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 26 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0)
assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '')
################################
# simple test with two outputs #
################################
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 26, self.nodes[1].getnewaddress() : 25 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
for out in dec_tx['vout']:
totalOut += out['value']
assert(len(dec_tx['vin']) > 0)
assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '')
#########################################################################
# test a fundrawtransaction with a VIN greater than the required amount #
#########################################################################
utx = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 50:
utx = aUtx
break
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
for out in dec_tx['vout']:
totalOut += out['value']
assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee
#####################################################################
# test a fundrawtransaction with which will not get a change output #
#####################################################################
utx = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 50:
utx = aUtx
break
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : Decimal(50) - fee - feeTolerance }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
for out in dec_tx['vout']:
totalOut += out['value']
assert_equal(rawtxfund['changepos'], -1)
assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee
#########################################################################
# test a fundrawtransaction with a VIN smaller than the required amount #
#########################################################################
utx = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 10:
utx = aUtx
break
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
# 4-byte version + 1-byte vin count + 36-byte prevout then script_len
rawtx = rawtx[:82] + "0100" + rawtx[84:]
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
matchingOuts = 0
for i, out in enumerate(dec_tx['vout']):
totalOut += out['value']
if out['scriptPubKey']['addresses'][0] in outputs:
matchingOuts+=1
else:
assert_equal(i, rawtxfund['changepos'])
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex'])
assert_equal(matchingOuts, 1)
assert_equal(len(dec_tx['vout']), 2)
###########################################
# test a fundrawtransaction with two VINs #
###########################################
utx = False
utx2 = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 10:
utx = aUtx
if aUtx['amount'] == 50:
utx2 = aUtx
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ]
outputs = { self.nodes[0].getnewaddress() : 60 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
matchingOuts = 0
for out in dec_tx['vout']:
totalOut += out['value']
if out['scriptPubKey']['addresses'][0] in outputs:
matchingOuts+=1
assert_equal(matchingOuts, 1)
assert_equal(len(dec_tx['vout']), 2)
matchingIns = 0
for vinOut in dec_tx['vin']:
for vinIn in inputs:
if vinIn['txid'] == vinOut['txid']:
matchingIns+=1
assert_equal(matchingIns, 2) #we now must see two vins identical to vins given as params
#########################################################
# test a fundrawtransaction with two VINs and two vOUTs #
#########################################################
utx = False
utx2 = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 10:
utx = aUtx
if aUtx['amount'] == 50:
utx2 = aUtx
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ]
outputs = { self.nodes[0].getnewaddress() : 60, self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
matchingOuts = 0
for out in dec_tx['vout']:
totalOut += out['value']
if out['scriptPubKey']['addresses'][0] in outputs:
matchingOuts+=1
assert_equal(matchingOuts, 2)
assert_equal(len(dec_tx['vout']), 3)
##############################################
# test a fundrawtransaction with invalid vin #
##############################################
listunspent = self.nodes[2].listunspent()
inputs = [ {'txid' : "1c7f966dab21119bac53213a2bc7532bff1fa844c124fd750a7d0b1332440bd1", 'vout' : 0} ] #invalid vin!
outputs = { self.nodes[0].getnewaddress() : 10}
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
try:
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
raise AssertionError("Spent more than available")
except JSONRPCException as e:
assert("Insufficient" in e.error['message'])
############################################################
#compare fee of a standard pubkeyhash transaction
inputs = []
outputs = {self.nodes[1].getnewaddress():11}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 11)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
#compare fee of a standard pubkeyhash transaction with multiple outputs
inputs = []
outputs = {self.nodes[1].getnewaddress():11,self.nodes[1].getnewaddress():12,self.nodes[1].getnewaddress():1,self.nodes[1].getnewaddress():13,self.nodes[1].getnewaddress():2,self.nodes[1].getnewaddress():3}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendmany("", outputs)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
#compare fee of a 2of2 multisig p2sh transaction
# create 2of2 addr
addr1 = self.nodes[1].getnewaddress()
addr2 = self.nodes[1].getnewaddress()
addr1Obj = self.nodes[1].validateaddress(addr1)
addr2Obj = self.nodes[1].validateaddress(addr2)
mSigObj = self.nodes[1].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])
inputs = []
outputs = {mSigObj:11}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendtoaddress(mSigObj, 11)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
#compare fee of a standard pubkeyhash transaction
# create 4of5 addr
addr1 = self.nodes[1].getnewaddress()
addr2 = self.nodes[1].getnewaddress()
addr3 = self.nodes[1].getnewaddress()
addr4 = self.nodes[1].getnewaddress()
addr5 = self.nodes[1].getnewaddress()
addr1Obj = self.nodes[1].validateaddress(addr1)
addr2Obj = self.nodes[1].validateaddress(addr2)
addr3Obj = self.nodes[1].validateaddress(addr3)
addr4Obj = self.nodes[1].validateaddress(addr4)
addr5Obj = self.nodes[1].validateaddress(addr5)
mSigObj = self.nodes[1].addmultisigaddress(4, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey'], addr4Obj['pubkey'], addr5Obj['pubkey']])
inputs = []
outputs = {mSigObj:11}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendtoaddress(mSigObj, 11)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
# spend a 2of2 multisig transaction over fundraw
# create 2of2 addr
addr1 = self.nodes[2].getnewaddress()
addr2 = self.nodes[2].getnewaddress()
addr1Obj = self.nodes[2].validateaddress(addr1)
addr2Obj = self.nodes[2].validateaddress(addr2)
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])
# send 12 ZEV to msig addr
txId = self.nodes[0].sendtoaddress(mSigObj, 12)
self.sync_all()
self.nodes[1].generate(1)
self.sync_all()
oldBalance = self.nodes[1].getbalance()
inputs = []
outputs = {self.nodes[1].getnewaddress():11}
rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[2].fundrawtransaction(rawTx)
signedTx = self.nodes[2].signrawtransaction(fundedTx['hex'])
txId = self.nodes[2].sendrawtransaction(signedTx['hex'])
self.sync_all()
self.nodes[1].generate(1)
self.sync_all()
# make sure funds are received at node1
assert_equal(oldBalance+Decimal('11.0000000'), self.nodes[1].getbalance())
############################################################
# locked wallet test
self.nodes[1].encryptwallet("test")
self.nodes.pop(1)
stop_node(self.nodes[0], 0)
stop_node(self.nodes[1], 2)
stop_node(self.nodes[2], 3)
self.nodes = start_nodes(4, self.options.tmpdir, [['-usehd=1']] * self.num_nodes, redirect_stderr=True)
# This test is not meant to test fee estimation and we'd like
# to be sure all txs are sent at a consistent desired feerate
for node in self.nodes:
node.settxfee(min_relay_tx_fee)
connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2)
connect_nodes_bi(self.nodes,0,3)
self.is_network_split=False
self.sync_all()
# drain the keypool
self.nodes[1].getnewaddress()
self.nodes[1].getrawchangeaddress()
inputs = []
outputs = {self.nodes[0].getnewaddress():1.1}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
# fund a transaction that requires a new key for the change output
# creating the key must be impossible because the wallet is locked
try:
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
raise AssertionError("Wallet unlocked without passphrase")
except JSONRPCException as e:
assert('Keypool ran out' in e.error['message'])
#refill the keypool
self.nodes[1].walletpassphrase("test", 100)
self.nodes[1].keypoolrefill(2) #need to refill the keypool to get an internal change address
self.nodes[1].walletlock()
try:
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 12)
raise AssertionError("Wallet unlocked without passphrase")
except JSONRPCException as e:
assert('walletpassphrase' in e.error['message'])
oldBalance = self.nodes[0].getbalance()
inputs = []
outputs = {self.nodes[0].getnewaddress():11}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
#now we need to unlock
self.nodes[1].walletpassphrase("test", 100)
signedTx = self.nodes[1].signrawtransaction(fundedTx['hex'])
txId = self.nodes[1].sendrawtransaction(signedTx['hex'])
self.sync_all()
self.nodes[1].generate(1)
self.sync_all()
# make sure funds are received at node1
assert_equal(oldBalance+Decimal('511.0000000'), self.nodes[0].getbalance())
###############################################
# multiple (~19) inputs tx test | Compare fee #
###############################################
#empty node1, send some small coins from node0 to node1
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
for i in range(0,20):
self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
#fund a tx with ~20 small inputs
inputs = []
outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[1].sendmany("", outputs)
signedFee = self.nodes[1].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance*19) #~19 inputs
#############################################
# multiple (~19) inputs tx test | sign/send #
#############################################
#again, empty node1, send some small coins from node0 to node1
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
for i in range(0,20):
self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
#fund a tx with ~20 small inputs
oldBalance = self.nodes[0].getbalance()
inputs = []
outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
fundedAndSignedTx = self.nodes[1].signrawtransaction(fundedTx['hex'])
txId = self.nodes[1].sendrawtransaction(fundedAndSignedTx['hex'])
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
assert_equal(oldBalance+Decimal('500.19000000'), self.nodes[0].getbalance()) #0.19+block reward
#####################################################
# test fundrawtransaction with OP_RETURN and no vin #
#####################################################
rawtx = "0100000000010000000000000000066a047465737400000000"
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(len(dec_tx['vin']), 0)
assert_equal(len(dec_tx['vout']), 1)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert_greater_than(len(dec_tx['vin']), 0) # at least one vin
assert_equal(len(dec_tx['vout']), 2) # one change output added
##################################################
# test a fundrawtransaction using only watchonly #
##################################################
inputs = []
outputs = {self.nodes[2].getnewaddress() : watchonly_amount / 2}
rawtx = self.nodes[3].createrawtransaction(inputs, outputs)
result = self.nodes[3].fundrawtransaction(rawtx, True)
res_dec = self.nodes[0].decoderawtransaction(result["hex"])
assert_equal(len(res_dec["vin"]), 1)
assert_equal(res_dec["vin"][0]["txid"], watchonly_txid)
assert("fee" in result.keys())
assert_greater_than(result["changepos"], -1)
###############################################################
# test fundrawtransaction using the entirety of watched funds #
###############################################################
inputs = []
outputs = {self.nodes[2].getnewaddress() : watchonly_amount}
rawtx = self.nodes[3].createrawtransaction(inputs, outputs)
result = self.nodes[3].fundrawtransaction(rawtx, True)
res_dec = self.nodes[0].decoderawtransaction(result["hex"])
assert_equal(len(res_dec["vin"]), 2)
assert(res_dec["vin"][0]["txid"] == watchonly_txid or res_dec["vin"][1]["txid"] == watchonly_txid)
assert_greater_than(result["fee"], 0)
assert_greater_than(result["changepos"], -1)
assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10)
signedtx = self.nodes[3].signrawtransaction(result["hex"])
assert(not signedtx["complete"])
signedtx = self.nodes[0].signrawtransaction(signedtx["hex"])
assert(signedtx["complete"])
self.nodes[0].sendrawtransaction(signedtx["hex"])
if __name__ == '__main__':
RawTransactionsTest().main()
| 40.683706 | 214 | 0.558701 |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class RawTransactionsTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 4
def setup_network(self, split=False):
self.nodes = start_nodes(4, self.options.tmpdir, [['-usehd=1']] * self.num_nodes, redirect_stderr=True)
connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2)
connect_nodes_bi(self.nodes,0,3)
self.is_network_split=False
self.sync_all()
def run_test(self):
self.log.info("Mining blocks...")
min_relay_tx_fee = self.nodes[0].getnetworkinfo()['relayfee']
# to be sure all txs are sent at a consistent desired feerate
for node in self.nodes:
node.settxfee(min_relay_tx_fee)
# if the fee's positive delta is higher than this value tests will fail,
feeTolerance = 2 * min_relay_tx_fee/1000
self.nodes[2].generate(1)
self.sync_all()
self.nodes[0].generate(121)
self.sync_all()
watchonly_address = self.nodes[0].getnewaddress()
watchonly_pubkey = self.nodes[0].validateaddress(watchonly_address)["pubkey"]
watchonly_amount = Decimal(2000)
self.nodes[3].importpubkey(watchonly_pubkey, "", True)
watchonly_txid = self.nodes[0].sendtoaddress(watchonly_address, watchonly_amount)
self.nodes[0].sendtoaddress(self.nodes[3].getnewaddress(), watchonly_amount / 10)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 15)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 50)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
ansaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0)
| true | true |
1c3f9fa719865326ced95a5c8076ae6f9ef8fd6c | 296 | py | Python | cartelisands/models.py | austing/cartels | bfb5c3c333cfcbf62c2d8a5850794a3235d2ff87 | [
"MIT"
] | null | null | null | cartelisands/models.py | austing/cartels | bfb5c3c333cfcbf62c2d8a5850794a3235d2ff87 | [
"MIT"
] | null | null | null | cartelisands/models.py | austing/cartels | bfb5c3c333cfcbf62c2d8a5850794a3235d2ff87 | [
"MIT"
] | null | null | null | from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.contrib.gis.db.models import PointField
class Cartelisand(models.Model):
user = models.OneToOneField(User)
most_recent_place = PointField(blank=True, null=True)
| 29.6 | 57 | 0.807432 | from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.contrib.gis.db.models import PointField
class Cartelisand(models.Model):
user = models.OneToOneField(User)
most_recent_place = PointField(blank=True, null=True)
| true | true |
1c3fa04b967474e8b10e6fa7984f418a7281fc93 | 1,403 | py | Python | OrderSystem/utilities/Permissions.py | mattjt/OrderSystem | cbb433c1edb31527e77194d004cf408bd22a28ad | [
"MIT"
] | 1 | 2018-03-31T12:36:02.000Z | 2018-03-31T12:36:02.000Z | OrderSystem/utilities/Permissions.py | mattjt/OrderSystem | cbb433c1edb31527e77194d004cf408bd22a28ad | [
"MIT"
] | null | null | null | OrderSystem/utilities/Permissions.py | mattjt/OrderSystem | cbb433c1edb31527e77194d004cf408bd22a28ad | [
"MIT"
] | null | null | null | from functools import wraps
from flask import abort, redirect, url_for, request
from flask_login import current_user
def get_path():
return str(request.path).strip('/')
def admin_access_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
if current_user.is_authenticated:
if current_user.is_admin:
return func(*args, **kwargs)
else:
abort(403)
else:
return redirect(url_for('auth.login') + "?prev={0}".format(get_path()))
return wrapper
def update_order_status_access_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not current_user.is_authenticated:
return redirect(url_for('auth.login') + "?prev={0}".format(get_path()))
else:
if current_user.can_update_order_status or current_user.is_admin:
return func(*args, **kwargs)
else:
abort(403)
return wrapper
def approve_order_access_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not current_user.is_authenticated:
return redirect(url_for('auth.login') + "?prev={0}".format(get_path()))
else:
if current_user.can_approve_orders or current_user.is_admin:
return func(*args, **kwargs)
else:
abort(403)
return wrapper
| 27.509804 | 83 | 0.607983 | from functools import wraps
from flask import abort, redirect, url_for, request
from flask_login import current_user
def get_path():
return str(request.path).strip('/')
def admin_access_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
if current_user.is_authenticated:
if current_user.is_admin:
return func(*args, **kwargs)
else:
abort(403)
else:
return redirect(url_for('auth.login') + "?prev={0}".format(get_path()))
return wrapper
def update_order_status_access_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not current_user.is_authenticated:
return redirect(url_for('auth.login') + "?prev={0}".format(get_path()))
else:
if current_user.can_update_order_status or current_user.is_admin:
return func(*args, **kwargs)
else:
abort(403)
return wrapper
def approve_order_access_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not current_user.is_authenticated:
return redirect(url_for('auth.login') + "?prev={0}".format(get_path()))
else:
if current_user.can_approve_orders or current_user.is_admin:
return func(*args, **kwargs)
else:
abort(403)
return wrapper
| true | true |
1c3fa1697442963e61d94c3212fdaec06e8e6352 | 2,485 | py | Python | doctor/views.py | naitik2314/E-Health-Care | 246774d4abdc01d829effd58b6bebae947c9c9c5 | [
"MIT"
] | null | null | null | doctor/views.py | naitik2314/E-Health-Care | 246774d4abdc01d829effd58b6bebae947c9c9c5 | [
"MIT"
] | null | null | null | doctor/views.py | naitik2314/E-Health-Care | 246774d4abdc01d829effd58b6bebae947c9c9c5 | [
"MIT"
] | null | null | null | from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from doctor.models import DoctorInfo
from django.contrib import messages
from doctor.forms import UserForm
from django.db.models import Q
from django.contrib.auth.decorators import user_passes_test, login_required
from patient.models import Disease1, WhoPredictDisease
# Create your views here.
def doctor_login(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# if request.user.groups.filter(name='DOCTOR').exists():
return redirect('dashboard_doctor')
# else:
# messages.info(request, "Please login from valid panel")
# return render(request, 'docotor/login.html')
else:
messages.info(request, "Please enter valid credentials")
return render(request, 'doctor/login.html')
else:
return render(request, 'doctor/login.html')
def doctor_logout(request):
print("logout user")
logout(request)
return redirect("/")
# Decorators to check whether a user is doctor or not to access his assigned features
def is_doctor(user):
return user.groups.filter(name='DOCTOR').exists()
# def is_patient(user):
# return user.groups.filter(name='PATIENT').exists()
@login_required(login_url='doctor_login')
# @user_passes_test(is_doctor)
def dashboard_doctor(request):
search_term = request.GET.get('term')
# users=User.objects.filter(groups__name="PATIENT")
contex = {}
disease1 = Disease1.objects.filter(doctor__id=request.user.id)
disease = []
for d in disease1:
# print(d.name)
disease.append(d.name)
if search_term == None:
search_term = ""
new_predictions = WhoPredictDisease.objects.filter(
predicted_disease__in=disease).filter(Q(predicted_disease__icontains=search_term) | Q(predict_by__name__icontains=search_term) | Q(predict_by__name__icontains=search_term))
# print(new_predictions)
# for p in new_predictions:
# print(p.predict_by.address)
contex = {
'predictions': new_predictions
}
return render(request, 'doctor/dashboard_doctor.html', contex)
# return render(request,'doctor/dashboard_doctor.html', contex)
| 35 | 180 | 0.696982 | from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from doctor.models import DoctorInfo
from django.contrib import messages
from doctor.forms import UserForm
from django.db.models import Q
from django.contrib.auth.decorators import user_passes_test, login_required
from patient.models import Disease1, WhoPredictDisease
def doctor_login(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard_doctor')
else:
messages.info(request, "Please enter valid credentials")
return render(request, 'doctor/login.html')
else:
return render(request, 'doctor/login.html')
def doctor_logout(request):
print("logout user")
logout(request)
return redirect("/")
def is_doctor(user):
return user.groups.filter(name='DOCTOR').exists()
@login_required(login_url='doctor_login')
def dashboard_doctor(request):
search_term = request.GET.get('term')
contex = {}
disease1 = Disease1.objects.filter(doctor__id=request.user.id)
disease = []
for d in disease1:
disease.append(d.name)
if search_term == None:
search_term = ""
new_predictions = WhoPredictDisease.objects.filter(
predicted_disease__in=disease).filter(Q(predicted_disease__icontains=search_term) | Q(predict_by__name__icontains=search_term) | Q(predict_by__name__icontains=search_term))
contex = {
'predictions': new_predictions
}
return render(request, 'doctor/dashboard_doctor.html', contex)
| true | true |
1c3fa18e3a8be1afda0a727f003a3a985ab2d1d7 | 4,576 | py | Python | sdks/python/http_client/v1/polyaxon_sdk/models/v1_image_type.py | gregmbi/polyaxon | 8f24089fa9cb5df28fc7b70aec27d6d23ee81e8d | [
"Apache-2.0"
] | null | null | null | sdks/python/http_client/v1/polyaxon_sdk/models/v1_image_type.py | gregmbi/polyaxon | 8f24089fa9cb5df28fc7b70aec27d6d23ee81e8d | [
"Apache-2.0"
] | null | null | null | sdks/python/http_client/v1/polyaxon_sdk/models/v1_image_type.py | gregmbi/polyaxon | 8f24089fa9cb5df28fc7b70aec27d6d23ee81e8d | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, Inc.
#
# 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.
# coding: utf-8
"""
Polyaxon SDKs and REST API specification.
Polyaxon SDKs and REST API specification. # noqa: E501
The version of the OpenAPI document: 1.0.79
Contact: contact@polyaxon.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from polyaxon_sdk.configuration import Configuration
class V1ImageType(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {"name": "str", "connection": "str"}
attribute_map = {"name": "name", "connection": "connection"}
def __init__(
self, name=None, connection=None, local_vars_configuration=None
): # noqa: E501
"""V1ImageType - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._name = None
self._connection = None
self.discriminator = None
if name is not None:
self.name = name
if connection is not None:
self.connection = connection
@property
def name(self):
"""Gets the name of this V1ImageType. # noqa: E501
:return: The name of this V1ImageType. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this V1ImageType.
:param name: The name of this V1ImageType. # noqa: E501
:type: str
"""
self._name = name
@property
def connection(self):
"""Gets the connection of this V1ImageType. # noqa: E501
:return: The connection of this V1ImageType. # noqa: E501
:rtype: str
"""
return self._connection
@connection.setter
def connection(self, connection):
"""Sets the connection of this V1ImageType.
:param connection: The connection of this V1ImageType. # noqa: E501
:type: str
"""
self._connection = connection
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1ImageType):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1ImageType):
return True
return self.to_dict() != other.to_dict()
| 28.246914 | 85 | 0.590691 |
import pprint
import re
import six
from polyaxon_sdk.configuration import Configuration
class V1ImageType(object):
openapi_types = {"name": "str", "connection": "str"}
attribute_map = {"name": "name", "connection": "connection"}
def __init__(
self, name=None, connection=None, local_vars_configuration=None
):
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._name = None
self._connection = None
self.discriminator = None
if name is not None:
self.name = name
if connection is not None:
self.connection = connection
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def connection(self):
return self._connection
@connection.setter
def connection(self, connection):
self._connection = connection
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, V1ImageType):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
if not isinstance(other, V1ImageType):
return True
return self.to_dict() != other.to_dict()
| true | true |
1c3fa29f70d5302adfe320370e33ec19887b2f25 | 72 | py | Python | Testing Files/scheduler test.py | Butterparade/School-stuff | 0b92ca29c7c582727226bc18ac590a68d998f822 | [
"Apache-2.0"
] | null | null | null | Testing Files/scheduler test.py | Butterparade/School-stuff | 0b92ca29c7c582727226bc18ac590a68d998f822 | [
"Apache-2.0"
] | null | null | null | Testing Files/scheduler test.py | Butterparade/School-stuff | 0b92ca29c7c582727226bc18ac590a68d998f822 | [
"Apache-2.0"
] | null | null | null | emp1 = [8, 24]
emp2 = [8, 12]
totalhours = [0, 24]
filledhours = [0, 0]
| 14.4 | 20 | 0.555556 | emp1 = [8, 24]
emp2 = [8, 12]
totalhours = [0, 24]
filledhours = [0, 0]
| true | true |
1c3fa346c1495522249b91e4269ebedcf4b36dfd | 771 | py | Python | colordict/gradients.py | aleferna12/colordict | ee66c3695c755a1a8469f740980c53df0d74471d | [
"MIT"
] | 1 | 2020-05-30T22:01:55.000Z | 2020-05-30T22:01:55.000Z | colordict/gradients.py | aleferna12/colordict | ee66c3695c755a1a8469f740980c53df0d74471d | [
"MIT"
] | 1 | 2021-04-19T19:16:56.000Z | 2021-04-29T12:36:06.000Z | colordict/gradients.py | aleferna12/colordict | ee66c3695c755a1a8469f740980c53df0d74471d | [
"MIT"
] | null | null | null | """Module containing classes to create gradients between colors.
For now only the linear gradient is available.
"""
class LinearGrad(object):
def __init__(self, color_values):
color_values = tuple(color_values)
super().__init__()
self.colors = color_values
def __call__(self, p):
i = int(p * (len(self.colors) - 1))
return self._lin_interp(
self.colors[i],
self.colors[min([i + 1, len(self.colors) - 1])],
p * (len(self.colors) - 1) - i
)
def n_colors(self, n, stripped=True):
colors = []
sub = 1 if stripped else -1
for i in range(n):
p = (i + stripped) / (n + sub)
colors.append(self.__call__(p))
return colors
@staticmethod
def _lin_interp(c1, c2, t):
return tuple([c1[i] + (c2[i] - c1[i]) * t for i in range(len(c1))])
| 24.09375 | 69 | 0.647211 |
class LinearGrad(object):
def __init__(self, color_values):
color_values = tuple(color_values)
super().__init__()
self.colors = color_values
def __call__(self, p):
i = int(p * (len(self.colors) - 1))
return self._lin_interp(
self.colors[i],
self.colors[min([i + 1, len(self.colors) - 1])],
p * (len(self.colors) - 1) - i
)
def n_colors(self, n, stripped=True):
colors = []
sub = 1 if stripped else -1
for i in range(n):
p = (i + stripped) / (n + sub)
colors.append(self.__call__(p))
return colors
@staticmethod
def _lin_interp(c1, c2, t):
return tuple([c1[i] + (c2[i] - c1[i]) * t for i in range(len(c1))])
| true | true |
1c3fa3fc380272b6633e8325e6b5de0740f11444 | 4,539 | py | Python | .history/src/Simulador_20200707141954.py | eduardodut/Trabalho_final_estatistica_cd | fbedbbea6bdd7a79e1d62030cde0fab4e93fc338 | [
"MIT"
] | null | null | null | .history/src/Simulador_20200707141954.py | eduardodut/Trabalho_final_estatistica_cd | fbedbbea6bdd7a79e1d62030cde0fab4e93fc338 | [
"MIT"
] | null | null | null | .history/src/Simulador_20200707141954.py | eduardodut/Trabalho_final_estatistica_cd | fbedbbea6bdd7a79e1d62030cde0fab4e93fc338 | [
"MIT"
] | null | null | null | import pandas as pd
import numpy as np
from Matriz_esferica import Matriz_esferica
from Individuo import Individuo
import random
class Simulador():
def __init__(
self,
tamanho_matriz, #numero de linhas e colunas da matriz esférica
densidade_populacional_inicial): #percentual de ocupação inicial da matriz
self.num_iteracoes = 0
self.indices_infectados_tipo_2 = []
self.indices_infectados_tipo_1 = []
self.densidade_populacional_inicial = densidade_populacional_inicial
self.matriz_individuos = []
self.fabrica_individuo = None
self.num_max_individuos = tamanho_matriz^2
#objeto que é responsável por validar a movimentação no grid n x n
self.matriz_esferica = Matriz_esferica(tamanho_matriz)
#dataframe que guardará os resultados de cada atualização
self.dataframe = pd.DataFrame(columns= ['num_sadios', 'num_infect_t1', 'num_infect_t2', 'num_curados', 'num_mortos'])
def set_condicoes_iniciais(
chance_infeccao, #chance que um infectado tipo 2 tem de infectar um indivíduo saudável
chance_infeccao_tipo2, #chance de um indivíduo infectado se tornar contagioso
chance_morte, #chance de um indivíduo tipo 2 morrer ao fim de uma atualização
atualizacoes_cura, #número de atualizações necessárias para a cura de um indivíduo tipo 1 ou 2
percentual_inicial_tipo1, #percentual inicial da população que será infectada tipo 1
percentual_inicial_tipo2): #percentual inicial da população que será infectada tipo 2
self.fabrica_individuo = Fabrica_individuo(
chance_infeccao,
chance_infeccao_tipo2,
chance_morte,
atualizacoes_cura,
percentual_inicial_tipo1,
percentual_inicial_tipo2 )
class Fabrica_individuo():
def __init__(
chance_infeccao, #chance que um infectado tipo 2 tem de infectar um indivíduo saudável
chance_infeccao_tipo2, #chance de um indivíduo infectado se tornar contagioso
chance_morte, #chance de um indivíduo tipo 2 morrer ao fim de uma atualização
atualizacoes_cura, #número de atualizações necessárias para a cura de um indivíduo tipo 1 ou 2
percentual_inicial_tipo1, #percentual inicial da população que será infectada tipo 1
percentual_inicial_tipo2): #percentual inicial da população que será infectada tipo 2
self.chance_infeccao = chance_infeccao
self.chance_infeccao_tipo2 = chance_infeccao_tipo2
self.chance_morte = chance_morte
self.atualizacoes_cura = atualizacoes_cura
self.percentual_inicial_tipo1 = percentual_inicial_tipo1 + percentual_inicial_tipo2
self.percentual_inicial_tipo2 = percentual_inicial_tipo2
def criar_individuo():
rng_status_inicial = random.random()
status_inicial = Individuo.SADIO
if rng_status_inicial <= percentual_inicial_tipo2:
status_inicial = Individuo.INFECTADO_TIPO_2
elif rng_status_inicial <= percentual_inicial_tipo1:
status_inicial = Individuo.INFECTADO_TIPO_1
return Individuo(
status_inicial,
self.chance_infeccao,
self.chance_infeccao_tipo2,
self.chance_morte,
self.atualizacoes_cura)
def cria_individuo_tipo_2():
return Individuo(
Individuo.INFECTADO_TIPO_2,
self.chance_infeccao,
self.chance_infeccao_tipo2,
self.chance_morte,
self.atualizacoes_cura)
sim = Simulador(100, 0.5)
chance_infeccao = 0.3
chance_infeccao_tipo2 = 0.2
chance_morte = 0.2
atualizacoes_cura = 10
percentual_inicial_tipo1 = 0.05
percentual_inicial_tipo2 = 0.01
sim.set_condicoes_iniciais(
chance_infeccao,
chance_infeccao_tipo2,
chance_morte,
atualizacoes_cura,
percentual_inicial_tipo1,
percentual_inicial_tipo2 )
sim.fabrica_individuo.cria_individuo_tipo_2()
#print(sim.matriz_individuos) | 40.526786 | 125 | 0.638907 | import pandas as pd
import numpy as np
from Matriz_esferica import Matriz_esferica
from Individuo import Individuo
import random
class Simulador():
def __init__(
self,
tamanho_matriz,
densidade_populacional_inicial):
self.num_iteracoes = 0
self.indices_infectados_tipo_2 = []
self.indices_infectados_tipo_1 = []
self.densidade_populacional_inicial = densidade_populacional_inicial
self.matriz_individuos = []
self.fabrica_individuo = None
self.num_max_individuos = tamanho_matriz^2
self.matriz_esferica = Matriz_esferica(tamanho_matriz)
self.dataframe = pd.DataFrame(columns= ['num_sadios', 'num_infect_t1', 'num_infect_t2', 'num_curados', 'num_mortos'])
def set_condicoes_iniciais(
chance_infeccao,
chance_infeccao_tipo2,
chance_morte,
atualizacoes_cura,
percentual_inicial_tipo1,
percentual_inicial_tipo2):
self.fabrica_individuo = Fabrica_individuo(
chance_infeccao,
chance_infeccao_tipo2,
chance_morte,
atualizacoes_cura,
percentual_inicial_tipo1,
percentual_inicial_tipo2 )
class Fabrica_individuo():
def __init__(
chance_infeccao,
chance_infeccao_tipo2,
chance_morte,
atualizacoes_cura,
percentual_inicial_tipo1,
percentual_inicial_tipo2):
self.chance_infeccao = chance_infeccao
self.chance_infeccao_tipo2 = chance_infeccao_tipo2
self.chance_morte = chance_morte
self.atualizacoes_cura = atualizacoes_cura
self.percentual_inicial_tipo1 = percentual_inicial_tipo1 + percentual_inicial_tipo2
self.percentual_inicial_tipo2 = percentual_inicial_tipo2
def criar_individuo():
rng_status_inicial = random.random()
status_inicial = Individuo.SADIO
if rng_status_inicial <= percentual_inicial_tipo2:
status_inicial = Individuo.INFECTADO_TIPO_2
elif rng_status_inicial <= percentual_inicial_tipo1:
status_inicial = Individuo.INFECTADO_TIPO_1
return Individuo(
status_inicial,
self.chance_infeccao,
self.chance_infeccao_tipo2,
self.chance_morte,
self.atualizacoes_cura)
def cria_individuo_tipo_2():
return Individuo(
Individuo.INFECTADO_TIPO_2,
self.chance_infeccao,
self.chance_infeccao_tipo2,
self.chance_morte,
self.atualizacoes_cura)
sim = Simulador(100, 0.5)
chance_infeccao = 0.3
chance_infeccao_tipo2 = 0.2
chance_morte = 0.2
atualizacoes_cura = 10
percentual_inicial_tipo1 = 0.05
percentual_inicial_tipo2 = 0.01
sim.set_condicoes_iniciais(
chance_infeccao,
chance_infeccao_tipo2,
chance_morte,
atualizacoes_cura,
percentual_inicial_tipo1,
percentual_inicial_tipo2 )
sim.fabrica_individuo.cria_individuo_tipo_2()
| true | true |
1c3fa4b7f383bfaa1a5f9c469da3e85bd03e3a35 | 907 | py | Python | tests/test_apps.py | alairock/integromat | 4fd50531e4934d24a726e91d4885658026ff96a5 | [
"Apache-2.0"
] | null | null | null | tests/test_apps.py | alairock/integromat | 4fd50531e4934d24a726e91d4885658026ff96a5 | [
"Apache-2.0"
] | null | null | null | tests/test_apps.py | alairock/integromat | 4fd50531e4934d24a726e91d4885658026ff96a5 | [
"Apache-2.0"
] | null | null | null | import pytest
from integromat_wrapper.integromat import Apps, AioApps
def test_get_apps(api_key):
# test connection to integromat api
imt_apps = Apps(api_key)
# create a new app
created_app = imt_apps.create_app('test-app-1-hw', 'Test App 1')
newapp_name = created_app.get('name')
newapp_version = created_app.get('version')
assert newapp_version is not None
# delete the above created app (cleanup)
deleted_app = imt_apps.delete_app(newapp_name, newapp_version)
assert deleted_app == {}
# test list apps
response = imt_apps.list_apps()
assert len(response) > 0
@pytest.mark.asyncio
async def test_async_get_apps(api_key):
imt_apps = AioApps(api_key)
response = await imt_apps.list_apps()
assert len(response) > 0
def test_get_imtapp_fixture(imtapp):
name, version = imtapp
assert 'test-app-1' in name
assert version == 1
| 25.914286 | 68 | 0.712238 | import pytest
from integromat_wrapper.integromat import Apps, AioApps
def test_get_apps(api_key):
imt_apps = Apps(api_key)
created_app = imt_apps.create_app('test-app-1-hw', 'Test App 1')
newapp_name = created_app.get('name')
newapp_version = created_app.get('version')
assert newapp_version is not None
deleted_app = imt_apps.delete_app(newapp_name, newapp_version)
assert deleted_app == {}
response = imt_apps.list_apps()
assert len(response) > 0
@pytest.mark.asyncio
async def test_async_get_apps(api_key):
imt_apps = AioApps(api_key)
response = await imt_apps.list_apps()
assert len(response) > 0
def test_get_imtapp_fixture(imtapp):
name, version = imtapp
assert 'test-app-1' in name
assert version == 1
| true | true |
1c3fa4fb0b6c6e1f32cb36842725ad128397a212 | 9,624 | py | Python | libs/metrics/social_distancing.py | dok529/smart-social-distancing | fd054c92cf478cefd5326c7beaa288b24dd5110f | [
"Apache-2.0"
] | null | null | null | libs/metrics/social_distancing.py | dok529/smart-social-distancing | fd054c92cf478cefd5326c7beaa288b24dd5110f | [
"Apache-2.0"
] | 1 | 2021-08-25T16:13:56.000Z | 2021-08-25T16:15:19.000Z | libs/metrics/social_distancing.py | myunyui22/smart-social-distancing-dev | 2b71c4330420758a3ff6833923cf2ef81cdebdb1 | [
"Apache-2.0"
] | 1 | 2021-01-13T15:48:56.000Z | 2021-01-13T15:48:56.000Z | import csv
import ast
import numpy as np
import os
from collections import deque
from datetime import datetime, date, timedelta
from typing import Dict, List, Iterator, Tuple
from libs.utils.loggers import get_source_log_directory
from .base import BaseMetric
class SocialDistancingMetric(BaseMetric):
reports_folder = "social-distancing"
csv_headers = ["DetectedObjects", "NoInfringement", "LowInfringement", "HighInfringement",
"CriticalInfringement"]
@classmethod
def procces_csv_row(cls, csv_row: Dict, objects_logs: Dict):
row_time = datetime.strptime(csv_row["Timestamp"], "%Y-%m-%d %H:%M:%S")
detections = ast.literal_eval(csv_row["Detections"])
row_hour = row_time.hour
if not objects_logs.get(row_hour):
objects_logs[row_hour] = {}
for index, d in enumerate(detections):
if not objects_logs[row_hour].get(d["tracking_id"]):
objects_logs[row_hour][d["tracking_id"]] = {"distance_violations": []}
# Append social distancing violations
objects_logs[row_hour][d["tracking_id"]]["distance_violations"].append(
{
"time": row_time,
"infrigement": index in ast.literal_eval(csv_row["ViolationsIndexes"])
}
)
@classmethod
def generate_hourly_metric_data(cls, objects_logs, entity=None):
summary = np.zeros((len(objects_logs), 5), dtype=np.long)
for index, hour in enumerate(sorted(objects_logs)):
hour_objects_detections = objects_logs[hour]
for detection_object in hour_objects_detections.values():
summary[index] += cls.process_distance_violation_for_object(
detection_object["distance_violations"])
return summary
@classmethod
def process_distance_violation_for_object(cls, distance_violations: List[dict]) -> Tuple[int, int]:
"""
Receives a list with the "social distancing detections" (for a single person) and returns a
tuple with the summary of detections and violations (grouped by severity). Consecutive detections in
the same state are grouped and returned as a single one. Detections lower than the constant
PROCESSING_COUNT_THRESHOLD are ignored.
The infrigement categories are :
- Low: Between 10 seconds 30 seconds
- High: Between 30 and 60 seconds
- Critical: More than 60 seconds
"""
# TODO: The categories values defined need to be updated taking into account the OMS recommendations.
# The current values only have demo purposes
current_status = None
processing_status = None
processing_count = 0
current_status_start_time = None
processing_start_time = None
CRITICAL_THRESHOLD = 60
HIGH_THRESHOLD = 30
LOW_TRESHOLD = 10
detections = []
if distance_violations:
for dist_violation in distance_violations:
status = dist_violation["infrigement"]
if processing_status != status:
processing_status = status
processing_start_time = dist_violation["time"]
processing_count = 0
processing_count += 1
if current_status != processing_status and processing_count >= cls.processing_count_threshold:
# Object was enouth time in the same state, change it
if current_status is not None:
# Append the previous status in the detections list
seconds_in_status = (processing_start_time - current_status_start_time).seconds
detections.append({"status": status, "seconds": seconds_in_status})
current_status = processing_status
current_status_start_time = processing_start_time
if current_status:
# Append the latest status
seconds_in_status = (distance_violations[-1]["time"] - current_status_start_time).seconds
detections.append({"status": status, "seconds": seconds_in_status})
detected_objects, no_infringements, low_infringements, high_infringements, critical_infringements = 0, 0, 0, 0, 0
for detection in detections:
detected_objects += 1
if not detection["status"] or detection["seconds"] < LOW_TRESHOLD:
no_infringements += 1
elif LOW_TRESHOLD <= detection["seconds"] < HIGH_THRESHOLD:
low_infringements += 1
elif HIGH_THRESHOLD <= detection["seconds"] < CRITICAL_THRESHOLD:
high_infringements += 1
else:
# CRITICAL_THRESHOLD <= detection["time"]
critical_infringements += 1
return detected_objects, no_infringements, low_infringements, high_infringements, critical_infringements
@classmethod
def generate_daily_csv_data(cls, yesterday_hourly_file):
detected_objects, no_infringements, low_infringements, high_infringements, critical_infringements = 0, 0, 0, 0, 0
with open(yesterday_hourly_file, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
detected_objects += int(row["DetectedObjects"])
no_infringements += int(row["NoInfringement"])
low_infringements += int(row["LowInfringement"])
high_infringements += int(row["HighInfringement"])
critical_infringements += int(row["CriticalInfringement"])
return detected_objects, no_infringements, low_infringements, high_infringements, critical_infringements
@classmethod
def create_heatmap_report(cls, config, yesterday_csv, heatmap_file, column):
heatmap_resolution = config.get_section_dict("App")["HeatmapResolution"].split(",")
heatmap_x = int(heatmap_resolution[0])
heatmap_y = int(heatmap_resolution[1])
heatmap_grid = np.zeros((heatmap_x, heatmap_y))
with open(yesterday_csv, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
detections = ast.literal_eval(row['Detections'])
if column == 'Violations':
violations_indexes = ast.literal_eval(row['ViolationsIndexes'])
# Get bounding boxes of violations
detections = [detections[object_id] for object_id in violations_indexes]
for detection in detections:
bbox = detection.get('bbox')
x = int((np.floor((bbox[0] + bbox[2]) * heatmap_x / 2)).item())
y = int((np.floor((bbox[1] + bbox[3]) * heatmap_y / 2)).item())
heatmap_grid[x][y] += 1 / (1 + heatmap_grid[x][y])
np.save(heatmap_file, heatmap_grid)
@classmethod
def compute_daily_metrics(cls, config):
super().compute_daily_metrics(config)
base_directory = get_source_log_directory(config)
entities = config.get_video_sources()
for entity in entities:
entity_directory = os.path.join(base_directory, entity["id"])
objects_log_directory = os.path.join(entity_directory, "objects_log")
heatmaps_directory = os.path.join(entity_directory, "heatmaps")
# Create missing directories
os.makedirs(objects_log_directory, exist_ok=True)
os.makedirs(heatmaps_directory, exist_ok=True)
yesterday = str(date.today() - timedelta(days=1))
yesterday_csv = os.path.join(objects_log_directory, yesterday + ".csv")
if os.path.isfile(yesterday_csv):
detection_heatmap_file = os.path.join(heatmaps_directory, "detections_heatmap_" + yesterday)
violation_heatmap_file = os.path.join(heatmaps_directory, "violations_heatmap_" + yesterday)
cls.create_heatmap_report(config, yesterday_csv, detection_heatmap_file, "Detections")
cls.create_heatmap_report(config, yesterday_csv, violation_heatmap_file, "Violations")
@classmethod
def generate_live_csv_data(cls, today_entity_csv, entity, entries_in_interval):
"""
Generates the live report using the `today_entity_csv` file received.
"""
with open(today_entity_csv, "r") as log:
objects_logs = {}
lastest_entries = deque(csv.DictReader(log), entries_in_interval)
for entry in lastest_entries:
cls.procces_csv_row(entry, objects_logs)
return np.sum(cls.generate_hourly_metric_data(objects_logs), axis=0)
@classmethod
def get_trend_live_values(cls, live_report_paths: Iterator[str]) -> Iterator[int]:
latest_social_distancing_results = {}
for n in range(10):
latest_social_distancing_results[n] = None
for live_path in live_report_paths:
with open(live_path, "r") as live_file:
lastest_10_entries = deque(csv.DictReader(live_file), 10)
for index, item in enumerate(lastest_10_entries):
if not latest_social_distancing_results[index]:
latest_social_distancing_results[index] = 0
latest_social_distancing_results[index] += int(item["DetectedObjects"]) - int(item["NoInfringement"])
return [item for item in latest_social_distancing_results.values() if item is not None]
| 50.387435 | 121 | 0.64256 | import csv
import ast
import numpy as np
import os
from collections import deque
from datetime import datetime, date, timedelta
from typing import Dict, List, Iterator, Tuple
from libs.utils.loggers import get_source_log_directory
from .base import BaseMetric
class SocialDistancingMetric(BaseMetric):
reports_folder = "social-distancing"
csv_headers = ["DetectedObjects", "NoInfringement", "LowInfringement", "HighInfringement",
"CriticalInfringement"]
@classmethod
def procces_csv_row(cls, csv_row: Dict, objects_logs: Dict):
row_time = datetime.strptime(csv_row["Timestamp"], "%Y-%m-%d %H:%M:%S")
detections = ast.literal_eval(csv_row["Detections"])
row_hour = row_time.hour
if not objects_logs.get(row_hour):
objects_logs[row_hour] = {}
for index, d in enumerate(detections):
if not objects_logs[row_hour].get(d["tracking_id"]):
objects_logs[row_hour][d["tracking_id"]] = {"distance_violations": []}
objects_logs[row_hour][d["tracking_id"]]["distance_violations"].append(
{
"time": row_time,
"infrigement": index in ast.literal_eval(csv_row["ViolationsIndexes"])
}
)
@classmethod
def generate_hourly_metric_data(cls, objects_logs, entity=None):
summary = np.zeros((len(objects_logs), 5), dtype=np.long)
for index, hour in enumerate(sorted(objects_logs)):
hour_objects_detections = objects_logs[hour]
for detection_object in hour_objects_detections.values():
summary[index] += cls.process_distance_violation_for_object(
detection_object["distance_violations"])
return summary
@classmethod
def process_distance_violation_for_object(cls, distance_violations: List[dict]) -> Tuple[int, int]:
current_status = None
processing_status = None
processing_count = 0
current_status_start_time = None
processing_start_time = None
CRITICAL_THRESHOLD = 60
HIGH_THRESHOLD = 30
LOW_TRESHOLD = 10
detections = []
if distance_violations:
for dist_violation in distance_violations:
status = dist_violation["infrigement"]
if processing_status != status:
processing_status = status
processing_start_time = dist_violation["time"]
processing_count = 0
processing_count += 1
if current_status != processing_status and processing_count >= cls.processing_count_threshold:
if current_status is not None:
seconds_in_status = (processing_start_time - current_status_start_time).seconds
detections.append({"status": status, "seconds": seconds_in_status})
current_status = processing_status
current_status_start_time = processing_start_time
if current_status:
seconds_in_status = (distance_violations[-1]["time"] - current_status_start_time).seconds
detections.append({"status": status, "seconds": seconds_in_status})
detected_objects, no_infringements, low_infringements, high_infringements, critical_infringements = 0, 0, 0, 0, 0
for detection in detections:
detected_objects += 1
if not detection["status"] or detection["seconds"] < LOW_TRESHOLD:
no_infringements += 1
elif LOW_TRESHOLD <= detection["seconds"] < HIGH_THRESHOLD:
low_infringements += 1
elif HIGH_THRESHOLD <= detection["seconds"] < CRITICAL_THRESHOLD:
high_infringements += 1
else:
critical_infringements += 1
return detected_objects, no_infringements, low_infringements, high_infringements, critical_infringements
@classmethod
def generate_daily_csv_data(cls, yesterday_hourly_file):
detected_objects, no_infringements, low_infringements, high_infringements, critical_infringements = 0, 0, 0, 0, 0
with open(yesterday_hourly_file, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
detected_objects += int(row["DetectedObjects"])
no_infringements += int(row["NoInfringement"])
low_infringements += int(row["LowInfringement"])
high_infringements += int(row["HighInfringement"])
critical_infringements += int(row["CriticalInfringement"])
return detected_objects, no_infringements, low_infringements, high_infringements, critical_infringements
@classmethod
def create_heatmap_report(cls, config, yesterday_csv, heatmap_file, column):
heatmap_resolution = config.get_section_dict("App")["HeatmapResolution"].split(",")
heatmap_x = int(heatmap_resolution[0])
heatmap_y = int(heatmap_resolution[1])
heatmap_grid = np.zeros((heatmap_x, heatmap_y))
with open(yesterday_csv, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
detections = ast.literal_eval(row['Detections'])
if column == 'Violations':
violations_indexes = ast.literal_eval(row['ViolationsIndexes'])
detections = [detections[object_id] for object_id in violations_indexes]
for detection in detections:
bbox = detection.get('bbox')
x = int((np.floor((bbox[0] + bbox[2]) * heatmap_x / 2)).item())
y = int((np.floor((bbox[1] + bbox[3]) * heatmap_y / 2)).item())
heatmap_grid[x][y] += 1 / (1 + heatmap_grid[x][y])
np.save(heatmap_file, heatmap_grid)
@classmethod
def compute_daily_metrics(cls, config):
super().compute_daily_metrics(config)
base_directory = get_source_log_directory(config)
entities = config.get_video_sources()
for entity in entities:
entity_directory = os.path.join(base_directory, entity["id"])
objects_log_directory = os.path.join(entity_directory, "objects_log")
heatmaps_directory = os.path.join(entity_directory, "heatmaps")
os.makedirs(objects_log_directory, exist_ok=True)
os.makedirs(heatmaps_directory, exist_ok=True)
yesterday = str(date.today() - timedelta(days=1))
yesterday_csv = os.path.join(objects_log_directory, yesterday + ".csv")
if os.path.isfile(yesterday_csv):
detection_heatmap_file = os.path.join(heatmaps_directory, "detections_heatmap_" + yesterday)
violation_heatmap_file = os.path.join(heatmaps_directory, "violations_heatmap_" + yesterday)
cls.create_heatmap_report(config, yesterday_csv, detection_heatmap_file, "Detections")
cls.create_heatmap_report(config, yesterday_csv, violation_heatmap_file, "Violations")
@classmethod
def generate_live_csv_data(cls, today_entity_csv, entity, entries_in_interval):
with open(today_entity_csv, "r") as log:
objects_logs = {}
lastest_entries = deque(csv.DictReader(log), entries_in_interval)
for entry in lastest_entries:
cls.procces_csv_row(entry, objects_logs)
return np.sum(cls.generate_hourly_metric_data(objects_logs), axis=0)
@classmethod
def get_trend_live_values(cls, live_report_paths: Iterator[str]) -> Iterator[int]:
latest_social_distancing_results = {}
for n in range(10):
latest_social_distancing_results[n] = None
for live_path in live_report_paths:
with open(live_path, "r") as live_file:
lastest_10_entries = deque(csv.DictReader(live_file), 10)
for index, item in enumerate(lastest_10_entries):
if not latest_social_distancing_results[index]:
latest_social_distancing_results[index] = 0
latest_social_distancing_results[index] += int(item["DetectedObjects"]) - int(item["NoInfringement"])
return [item for item in latest_social_distancing_results.values() if item is not None]
| true | true |
1c3fa86adc535b5ca59895af3f30fbc046c4133f | 152 | py | Python | adet/modeling/DTMRInst_backup/__init__.py | shuaiqi361/AdelaiDet | 35d944033a8d2f7aa623ad607b57bd8a1fe88b43 | [
"BSD-2-Clause"
] | null | null | null | adet/modeling/DTMRInst_backup/__init__.py | shuaiqi361/AdelaiDet | 35d944033a8d2f7aa623ad607b57bd8a1fe88b43 | [
"BSD-2-Clause"
] | null | null | null | adet/modeling/DTMRInst_backup/__init__.py | shuaiqi361/AdelaiDet | 35d944033a8d2f7aa623ad607b57bd8a1fe88b43 | [
"BSD-2-Clause"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .DTMRInst import DTMRInst
from .DTMREncode import DistanceTransformEncoding
| 38 | 70 | 0.822368 |
from .DTMRInst import DTMRInst
from .DTMREncode import DistanceTransformEncoding
| true | true |
1c3faad72af69451caa228795765f6467ec6e1c0 | 10,382 | py | Python | game/level.py | Magicalbat/Spooktober-Jam-2021 | ba652c0aa3b479f35ea08e26d6f0725bd1706ebd | [
"Unlicense"
] | null | null | null | game/level.py | Magicalbat/Spooktober-Jam-2021 | ba652c0aa3b479f35ea08e26d6f0725bd1706ebd | [
"Unlicense"
] | null | null | null | game/level.py | Magicalbat/Spooktober-Jam-2021 | ba652c0aa3b479f35ea08e26d6f0725bd1706ebd | [
"Unlicense"
] | null | null | null | import pygame
import random
from engine.gamescreen import GameScreen
from engine.tilemap import Tilemap
from engine.text import Text
from engine.menu import Menu
from engine.particles import Particles
from engine.common import *
from game.player import Player
from game.pumpkin import Pumpkin
from game.ghost import Ghost
from game.audiosettings import AudioSettings
class Level(GameScreen):
def setup(self):
super().setup()
self.tilemap = Tilemap(12)
extraMapData = self.tilemap.loadFromJson(f"data/maps/level{self.levelNum}.json", True)
#level{self.levelNum}.json
playerSpawn = [20,100]
if 'playerSpawn' in extraMapData:
playerSpawn = extraMapData['playerSpawn'][0]
self.player = Player(playerSpawn[0], playerSpawn[1], 12, 12)
self.ghost = Ghost(0, 0, 12, 12, self.player.gravity)
self.levelExitImg = pygame.image.load("data/images/tiles/candles.png").convert()
self.levelExitImg.set_colorkey((0,0,0))
self.levelExitParticles = Particles([2,4], [-4, 4, -1, 1], [-15, 15, -35, -40], 100, True, 4, colors=((250, 192, 0), (255, 117, 0), (255,255,0), (255,128,0)))
if 'levelExit' in extraMapData:
self.levelExit = pygame.Rect((extraMapData['levelExit'][0][0], extraMapData['levelExit'][0][1], 12, 12))
else:
self.levelExit = pygame.Rect((0,0,0,0))
self.spikeImg = pygame.image.load("data/images/tiles/spikes.png").convert()
self.spikeImg.set_colorkey((0,0,0))
self.spikes = []
if 'spikes' in extraMapData:
for pos in extraMapData['spikes']:
self.spikes.append(pygame.Rect((pos[0], pos[1] + 8, 12, 4)))
self.jackOLanternImg = pygame.image.load("data/images/characters/jack_o_lantern.png").convert()
self.jackOLanternImg.set_colorkey((0,0,0))
self.pumpkinImgs = loadSpriteSheet("data/images/characters/Pumpkin.png", (14,14), (4,2), (1,1), 8, (0,0,0))
self.pumpkinImgs = [self.pumpkinImgs[0], self.pumpkinImgs[4], self.pumpkinImgs[5]]
self.pumpkins = []
self.pumpkinSpawnSound = pygame.mixer.Sound("data/sounds/pumpkin.wav")
self.maxPumpkins = 1
if 'maxPumpkins' in extraMapData:
self.maxPumpkins = extraMapData['maxPumpkins']
self.wind = []
self.windSpeed = self.player.gravity
self.windParticles = Particles((5, 6), (0, 12, -2, 2), (-.1, .1, -10, -25), 1000, True, 6, colors=((255,255,255),(225,225,225),(200,200,200)))
if 'wind' in extraMapData:
for pos in extraMapData['wind']:
self.wind.append(pygame.Rect((pos[0], pos[1], 12, 12)))
self.text = Text()
self.text.loadFontImg("data/images/text.png", scale=(2,2), color=(255, 229, 127))
self.levelText = None
self.levelTextPos = [0,0]
if 'text' in extraMapData:
if isinstance(extraMapData['text'][1],str):
self.levelTextPos = extraMapData['text'][0]
self.levelText = self.text.createTextSurf(extraMapData['text'][1]).copy()
self.text.loadFontImg("data/images/text.png", scale=(2,2))
self.fps = 0
self.scroll = [0,0]
self.cameraBounds = ((0,0),(0,0))
if 'cameraBounds' in extraMapData:
if len(extraMapData['cameraBounds']) == 1:
self.cameraBound = ((0,0), extraMapData['cameraBounds'][0])
else:
self.cameraBounds = (sorted((extraMapData['cameraBounds'][0], extraMapData['cameraBounds'][1])))
self.pauseMenu = Menu(["Resume", "Restart", "Back"], 2, (0, 20), (5, 25), {0:self.togglePause, 1:self.screenManager.reloadCurrentScreenWithTransition, 2:self.screenManager.changeScreenWithTransition}, {2:self.prevScreen})
self.paused = False
self.alphaSurf = pygame.Surface((320,180))
self.alphaSurf.fill((0,0,0))
self.alphaSurf.set_alpha(128)
self.lightningTimer = 0
self.lightningSound = pygame.mixer.Sound("data/sounds/thunder.wav")
self.lightningSound.set_volume(0.25)
def __init__(self, levelNum=1, prevScreen=None):
self.levelNum = levelNum
self.prevScreen = prevScreen
super().__init__()
def togglePause(self):
self.paused = not self.paused
def draw(self, win):
#if abs(((self.player.pos.x - win.get_width() / 2) - self.scroll[0]) - self.scroll[0]) > 25:
self.scroll[0] += ((self.player.pos.x - win.get_width() / 2) - self.scroll[0]) / 20
self.scroll[0] = clamp(self.scroll[0], self.cameraBounds[0][0], self.cameraBounds[1][0])
self.scroll[1] += ((self.player.pos.y - win.get_height() / 2) - self.scroll[1]) / 20
self.scroll[1] = clamp(self.scroll[1], self.cameraBounds[0][1], self.cameraBounds[1][1])
if self.lightningTimer > 0:
self.scroll[0] += random.randint(0,8) - 4
self.scroll[1] += random.randint(0,8) - 4
self.tilemap.draw(win, self.scroll)
for s in self.spikes:
#pygame.draw.rect(win, (255,0,0), (s.x - self.scroll[0], s.y - self.scroll[1], s.w, s.h))
win.blit(self.spikeImg, (s.x - self.scroll[0], s.y - self.scroll[1] - 4))
if self.levelExit != pygame.Rect((0,0,0,0)):
win.blit(self.levelExitImg, (self.levelExit.x - self.scroll[0], self.levelExit.y - self.scroll[1]))
self.levelExitParticles.draw(win, self.scroll)
for w in self.wind:
self.windParticles.emit((w.x, w.y + 12), .2)
#pygame.draw.rect(win, (0,128,128), (w.x - self.scroll[0], w.y - self.scroll[1], w.w, w.h))
self.windParticles.draw(win, self.scroll)
if self.levelText is not None:
win.blit(self.levelText, (self.levelTextPos[0] - self.scroll[0], self.levelTextPos[1] - self.scroll[1]))
if self.ghost.active:
win.blit(self.alphaSurf, (0,0))
self.player.draw(win, self.scroll)
self.ghost.draw(win, self.scroll)
for p in self.pumpkins:
p.draw(win, self.scroll)
if self.lightningTimer > 0.15:
win.fill((225,225,225))
win.blit(self.pumpkinImgs[0], (4,4))
win.blit(self.text.createTextSurf(f': {self.maxPumpkins - len(self.pumpkins)}'), (20,4))
if self.paused:
win.blit(self.alphaSurf, (0,0))
self.pauseMenu.draw(win)
def update(self, delta, inp):
if delta:
self.fps = int(1 / delta)
delta = min(delta, 0.1)
if self.lightningTimer > 0:
self.lightningTimer -= delta
if inp.keyJustPressed(pygame.K_ESCAPE):
self.togglePause()
if not self.paused:
entityRects = [p.rect for p in self.pumpkins]
self.windParticles.update(delta)
self.player.update(delta, inp, entityRects, self.tilemap.chunks)
if self.player.rect.collidelist(self.wind) != -1:
dist = abs(self.player.pos.y) % 12
if dist < 1:
self.player.velocity.y -= self.windSpeed * delta * 1.4
self.player.velocity.y -= self.windSpeed * delta * ((max(dist, 2) / 12) * 5)
entityRects.append(self.player.rect)
for p in self.pumpkins:
if p.rect.collidelist(self.wind) != -1:
dist = abs(p.pos.y) % 12
p.velocity.y -= self.windSpeed * delta * ((max(dist, 2) / 12) * 5)
p.update(delta, entityRects, self.tilemap.chunks)
if p.stopping:
p.stopping = False
self.pumpkins.sort(key=lambda p:(p.rect.x, p.rect.y))
if inp.keyJustPressed(pygame.K_x):
if len(self.pumpkins) + 1 <= self.maxPumpkins:
self.pumpkins.append(Pumpkin(self.player.rect.x, self.player.rect.y, self.player.rect.w, self.player.rect.h, self.player.velocity, self.player.gravity, self.pumpkinImgs[random.randint(0,2)], self.jackOLanternImg))
self.player.reset()
hitlist = getCollidingRects(self.player.rect, [p.rect for p in self.pumpkins])
for rect in hitlist:
self.pumpkins.remove(rect)
if AudioSettings().sfx:
self.pumpkinSpawnSound.play()
if self.player.rect.collidelist(self.spikes) != -1:
self.player.reset()
if self.levelExit != pygame.Rect((0,0,0,0)):
self.levelExitParticles.update(delta)
self.levelExitParticles.emit((self.levelExit.x+1, self.levelExit.y+5), 0.025)
self.levelExitParticles.emit((self.levelExit.x+5, self.levelExit.y+4), 0.025)
self.levelExitParticles.emit((self.levelExit.x+7, self.levelExit.y+6), 0.025)
self.levelExitParticles.emit((self.levelExit.x+10, self.levelExit.y+3), 0.025)
if self.player.rect.colliderect(self.levelExit) and not self.ghost.active:
self.ghost.activate(self.player.pos, (self.player.pos.x < 320 / 2) * 2 - 1)
self.player.applyGravity = False
self.player.applyVelocity = False
self.player.handleCollision = False
for p in self.pumpkins:
p.changeToJackOLantern()
self.lightningTimer = .25
if AudioSettings().sfx:
self.lightningSound.play()
if self.ghost.active:
self.player.pos = pygame.math.Vector2(self.ghost.pos.x, self.ghost.pos.y + 10)
self.player.updateRect()
if self.ghost.finished:
#from game.startscreen import StartScreen
self.screenManager.changeScreenWithTransition(Level(self.levelNum + 1, self.prevScreen))
self.ghost.update(delta)
if inp.keyJustPressed(pygame.K_r):
self.screenManager.reloadCurrentScreenWithTransition()
else:
self.pauseMenu.update(inp, delta) | 42.203252 | 233 | 0.574648 | import pygame
import random
from engine.gamescreen import GameScreen
from engine.tilemap import Tilemap
from engine.text import Text
from engine.menu import Menu
from engine.particles import Particles
from engine.common import *
from game.player import Player
from game.pumpkin import Pumpkin
from game.ghost import Ghost
from game.audiosettings import AudioSettings
class Level(GameScreen):
def setup(self):
super().setup()
self.tilemap = Tilemap(12)
extraMapData = self.tilemap.loadFromJson(f"data/maps/level{self.levelNum}.json", True)
playerSpawn = [20,100]
if 'playerSpawn' in extraMapData:
playerSpawn = extraMapData['playerSpawn'][0]
self.player = Player(playerSpawn[0], playerSpawn[1], 12, 12)
self.ghost = Ghost(0, 0, 12, 12, self.player.gravity)
self.levelExitImg = pygame.image.load("data/images/tiles/candles.png").convert()
self.levelExitImg.set_colorkey((0,0,0))
self.levelExitParticles = Particles([2,4], [-4, 4, -1, 1], [-15, 15, -35, -40], 100, True, 4, colors=((250, 192, 0), (255, 117, 0), (255,255,0), (255,128,0)))
if 'levelExit' in extraMapData:
self.levelExit = pygame.Rect((extraMapData['levelExit'][0][0], extraMapData['levelExit'][0][1], 12, 12))
else:
self.levelExit = pygame.Rect((0,0,0,0))
self.spikeImg = pygame.image.load("data/images/tiles/spikes.png").convert()
self.spikeImg.set_colorkey((0,0,0))
self.spikes = []
if 'spikes' in extraMapData:
for pos in extraMapData['spikes']:
self.spikes.append(pygame.Rect((pos[0], pos[1] + 8, 12, 4)))
self.jackOLanternImg = pygame.image.load("data/images/characters/jack_o_lantern.png").convert()
self.jackOLanternImg.set_colorkey((0,0,0))
self.pumpkinImgs = loadSpriteSheet("data/images/characters/Pumpkin.png", (14,14), (4,2), (1,1), 8, (0,0,0))
self.pumpkinImgs = [self.pumpkinImgs[0], self.pumpkinImgs[4], self.pumpkinImgs[5]]
self.pumpkins = []
self.pumpkinSpawnSound = pygame.mixer.Sound("data/sounds/pumpkin.wav")
self.maxPumpkins = 1
if 'maxPumpkins' in extraMapData:
self.maxPumpkins = extraMapData['maxPumpkins']
self.wind = []
self.windSpeed = self.player.gravity
self.windParticles = Particles((5, 6), (0, 12, -2, 2), (-.1, .1, -10, -25), 1000, True, 6, colors=((255,255,255),(225,225,225),(200,200,200)))
if 'wind' in extraMapData:
for pos in extraMapData['wind']:
self.wind.append(pygame.Rect((pos[0], pos[1], 12, 12)))
self.text = Text()
self.text.loadFontImg("data/images/text.png", scale=(2,2), color=(255, 229, 127))
self.levelText = None
self.levelTextPos = [0,0]
if 'text' in extraMapData:
if isinstance(extraMapData['text'][1],str):
self.levelTextPos = extraMapData['text'][0]
self.levelText = self.text.createTextSurf(extraMapData['text'][1]).copy()
self.text.loadFontImg("data/images/text.png", scale=(2,2))
self.fps = 0
self.scroll = [0,0]
self.cameraBounds = ((0,0),(0,0))
if 'cameraBounds' in extraMapData:
if len(extraMapData['cameraBounds']) == 1:
self.cameraBound = ((0,0), extraMapData['cameraBounds'][0])
else:
self.cameraBounds = (sorted((extraMapData['cameraBounds'][0], extraMapData['cameraBounds'][1])))
self.pauseMenu = Menu(["Resume", "Restart", "Back"], 2, (0, 20), (5, 25), {0:self.togglePause, 1:self.screenManager.reloadCurrentScreenWithTransition, 2:self.screenManager.changeScreenWithTransition}, {2:self.prevScreen})
self.paused = False
self.alphaSurf = pygame.Surface((320,180))
self.alphaSurf.fill((0,0,0))
self.alphaSurf.set_alpha(128)
self.lightningTimer = 0
self.lightningSound = pygame.mixer.Sound("data/sounds/thunder.wav")
self.lightningSound.set_volume(0.25)
def __init__(self, levelNum=1, prevScreen=None):
self.levelNum = levelNum
self.prevScreen = prevScreen
super().__init__()
def togglePause(self):
self.paused = not self.paused
def draw(self, win):
self.scroll[0] += ((self.player.pos.x - win.get_width() / 2) - self.scroll[0]) / 20
self.scroll[0] = clamp(self.scroll[0], self.cameraBounds[0][0], self.cameraBounds[1][0])
self.scroll[1] += ((self.player.pos.y - win.get_height() / 2) - self.scroll[1]) / 20
self.scroll[1] = clamp(self.scroll[1], self.cameraBounds[0][1], self.cameraBounds[1][1])
if self.lightningTimer > 0:
self.scroll[0] += random.randint(0,8) - 4
self.scroll[1] += random.randint(0,8) - 4
self.tilemap.draw(win, self.scroll)
for s in self.spikes:
win.blit(self.spikeImg, (s.x - self.scroll[0], s.y - self.scroll[1] - 4))
if self.levelExit != pygame.Rect((0,0,0,0)):
win.blit(self.levelExitImg, (self.levelExit.x - self.scroll[0], self.levelExit.y - self.scroll[1]))
self.levelExitParticles.draw(win, self.scroll)
for w in self.wind:
self.windParticles.emit((w.x, w.y + 12), .2)
self.windParticles.draw(win, self.scroll)
if self.levelText is not None:
win.blit(self.levelText, (self.levelTextPos[0] - self.scroll[0], self.levelTextPos[1] - self.scroll[1]))
if self.ghost.active:
win.blit(self.alphaSurf, (0,0))
self.player.draw(win, self.scroll)
self.ghost.draw(win, self.scroll)
for p in self.pumpkins:
p.draw(win, self.scroll)
if self.lightningTimer > 0.15:
win.fill((225,225,225))
win.blit(self.pumpkinImgs[0], (4,4))
win.blit(self.text.createTextSurf(f': {self.maxPumpkins - len(self.pumpkins)}'), (20,4))
if self.paused:
win.blit(self.alphaSurf, (0,0))
self.pauseMenu.draw(win)
def update(self, delta, inp):
if delta:
self.fps = int(1 / delta)
delta = min(delta, 0.1)
if self.lightningTimer > 0:
self.lightningTimer -= delta
if inp.keyJustPressed(pygame.K_ESCAPE):
self.togglePause()
if not self.paused:
entityRects = [p.rect for p in self.pumpkins]
self.windParticles.update(delta)
self.player.update(delta, inp, entityRects, self.tilemap.chunks)
if self.player.rect.collidelist(self.wind) != -1:
dist = abs(self.player.pos.y) % 12
if dist < 1:
self.player.velocity.y -= self.windSpeed * delta * 1.4
self.player.velocity.y -= self.windSpeed * delta * ((max(dist, 2) / 12) * 5)
entityRects.append(self.player.rect)
for p in self.pumpkins:
if p.rect.collidelist(self.wind) != -1:
dist = abs(p.pos.y) % 12
p.velocity.y -= self.windSpeed * delta * ((max(dist, 2) / 12) * 5)
p.update(delta, entityRects, self.tilemap.chunks)
if p.stopping:
p.stopping = False
self.pumpkins.sort(key=lambda p:(p.rect.x, p.rect.y))
if inp.keyJustPressed(pygame.K_x):
if len(self.pumpkins) + 1 <= self.maxPumpkins:
self.pumpkins.append(Pumpkin(self.player.rect.x, self.player.rect.y, self.player.rect.w, self.player.rect.h, self.player.velocity, self.player.gravity, self.pumpkinImgs[random.randint(0,2)], self.jackOLanternImg))
self.player.reset()
hitlist = getCollidingRects(self.player.rect, [p.rect for p in self.pumpkins])
for rect in hitlist:
self.pumpkins.remove(rect)
if AudioSettings().sfx:
self.pumpkinSpawnSound.play()
if self.player.rect.collidelist(self.spikes) != -1:
self.player.reset()
if self.levelExit != pygame.Rect((0,0,0,0)):
self.levelExitParticles.update(delta)
self.levelExitParticles.emit((self.levelExit.x+1, self.levelExit.y+5), 0.025)
self.levelExitParticles.emit((self.levelExit.x+5, self.levelExit.y+4), 0.025)
self.levelExitParticles.emit((self.levelExit.x+7, self.levelExit.y+6), 0.025)
self.levelExitParticles.emit((self.levelExit.x+10, self.levelExit.y+3), 0.025)
if self.player.rect.colliderect(self.levelExit) and not self.ghost.active:
self.ghost.activate(self.player.pos, (self.player.pos.x < 320 / 2) * 2 - 1)
self.player.applyGravity = False
self.player.applyVelocity = False
self.player.handleCollision = False
for p in self.pumpkins:
p.changeToJackOLantern()
self.lightningTimer = .25
if AudioSettings().sfx:
self.lightningSound.play()
if self.ghost.active:
self.player.pos = pygame.math.Vector2(self.ghost.pos.x, self.ghost.pos.y + 10)
self.player.updateRect()
if self.ghost.finished:
self.screenManager.changeScreenWithTransition(Level(self.levelNum + 1, self.prevScreen))
self.ghost.update(delta)
if inp.keyJustPressed(pygame.K_r):
self.screenManager.reloadCurrentScreenWithTransition()
else:
self.pauseMenu.update(inp, delta) | true | true |
1c3fad66793c87698591fd8a85a8f83a19bd9c05 | 14,295 | py | Python | bin/Python27/Lib/site-packages/numpy/lib/arraysetops.py | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | null | null | null | bin/Python27/Lib/site-packages/numpy/lib/arraysetops.py | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | null | null | null | bin/Python27/Lib/site-packages/numpy/lib/arraysetops.py | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | 1 | 2020-08-08T12:44:48.000Z | 2020-08-08T12:44:48.000Z | """
Set operations for 1D numeric arrays based on sorting.
:Contains:
ediff1d,
unique,
intersect1d,
setxor1d,
in1d,
union1d,
setdiff1d
:Notes:
For floating point arrays, inaccurate results may appear due to usual round-off
and floating point comparison issues.
Speed could be gained in some operations by an implementation of
sort(), that can provide directly the permutation vectors, avoiding
thus calls to argsort().
To do: Optionally return indices analogously to unique for all functions.
:Author: Robert Cimrman
"""
from __future__ import division, absolute_import, print_function
import numpy as np
__all__ = [
'ediff1d', 'intersect1d', 'setxor1d', 'union1d', 'setdiff1d', 'unique',
'in1d'
]
def ediff1d(ary, to_end=None, to_begin=None):
"""
The differences between consecutive elements of an array.
Parameters
----------
ary : array_like
If necessary, will be flattened before the differences are taken.
to_end : array_like, optional
Number(s) to append at the end of the returned differences.
to_begin : array_like, optional
Number(s) to prepend at the beginning of the returned differences.
Returns
-------
ediff1d : ndarray
The differences. Loosely, this is ``ary.flat[1:] - ary.flat[:-1]``.
See Also
--------
diff, gradient
Notes
-----
When applied to masked arrays, this function drops the mask information
if the `to_begin` and/or `to_end` parameters are used.
Examples
--------
>>> x = np.array([1, 2, 4, 7, 0])
>>> np.ediff1d(x)
array([ 1, 2, 3, -7])
>>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99]))
array([-99, 1, 2, 3, -7, 88, 99])
The returned array is always 1D.
>>> y = [[1, 2, 4], [1, 6, 24]]
>>> np.ediff1d(y)
array([ 1, 2, -3, 5, 18])
"""
ary = np.asanyarray(ary).flat
ed = ary[1:] - ary[:-1]
arrays = [ed]
if to_begin is not None:
arrays.insert(0, to_begin)
if to_end is not None:
arrays.append(to_end)
if len(arrays) != 1:
# We'll save ourselves a copy of a potentially large array in
# the common case where neither to_begin or to_end was given.
ed = np.hstack(arrays)
return ed
def unique(ar, return_index=False, return_inverse=False, return_counts=False):
"""
Find the unique elements of an array.
Returns the sorted unique elements of an array. There are three optional
outputs in addition to the unique elements: the indices of the input array
that give the unique values, the indices of the unique array that
reconstruct the input array, and the number of times each unique value
comes up in the input array.
Parameters
----------
ar : array_like
Input array. This will be flattened if it is not already 1-D.
return_index : bool, optional
If True, also return the indices of `ar` that result in the unique
array.
return_inverse : bool, optional
If True, also return the indices of the unique array that can be used
to reconstruct `ar`.
return_counts : bool, optional
If True, also return the number of times each unique value comes up
in `ar`.
.. versionadded:: 1.9.0
Returns
-------
unique : ndarray
The sorted unique values.
unique_indices : ndarray, optional
The indices of the first occurrences of the unique values in the
(flattened) original array. Only provided if `return_index` is True.
unique_inverse : ndarray, optional
The indices to reconstruct the (flattened) original array from the
unique array. Only provided if `return_inverse` is True.
unique_counts : ndarray, optional
The number of times each of the unique values comes up in the
original array. Only provided if `return_counts` is True.
.. versionadded:: 1.9.0
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
Examples
--------
>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])
Return the indices of the original array that give the unique values:
>>> a = np.array(['a', 'b', 'b', 'c', 'a'])
>>> u, indices = np.unique(a, return_index=True)
>>> u
array(['a', 'b', 'c'],
dtype='|S1')
>>> indices
array([0, 1, 3])
>>> a[indices]
array(['a', 'b', 'c'],
dtype='|S1')
Reconstruct the input array from the unique values:
>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = np.unique(a, return_inverse=True)
>>> u
array([1, 2, 3, 4, 6])
>>> indices
array([0, 1, 4, 3, 1, 2, 1])
>>> u[indices]
array([1, 2, 6, 4, 2, 3, 2])
"""
ar = np.asanyarray(ar).flatten()
optional_indices = return_index or return_inverse
optional_returns = optional_indices or return_counts
if ar.size == 0:
if not optional_returns:
ret = ar
else:
ret = (ar,)
if return_index:
ret += (np.empty(0, np.bool),)
if return_inverse:
ret += (np.empty(0, np.bool),)
if return_counts:
ret += (np.empty(0, np.intp),)
return ret
if optional_indices:
perm = ar.argsort(kind='mergesort' if return_index else 'quicksort')
aux = ar[perm]
else:
ar.sort()
aux = ar
flag = np.concatenate(([True], aux[1:] != aux[:-1]))
if not optional_returns:
ret = aux[flag]
else:
ret = (aux[flag],)
if return_index:
ret += (perm[flag],)
if return_inverse:
iflag = np.cumsum(flag) - 1
inv_idx = np.empty(ar.shape, dtype=np.intp)
inv_idx[perm] = iflag
ret += (inv_idx,)
if return_counts:
idx = np.concatenate(np.nonzero(flag) + ([ar.size],))
ret += (np.diff(idx),)
return ret
def intersect1d(ar1, ar2, assume_unique=False):
"""
Find the intersection of two arrays.
Return the sorted, unique values that are in both of the input arrays.
Parameters
----------
ar1, ar2 : array_like
Input arrays.
assume_unique : bool
If True, the input arrays are both assumed to be unique, which
can speed up the calculation. Default is False.
Returns
-------
intersect1d : ndarray
Sorted 1D array of common and unique elements.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
Examples
--------
>>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])
array([1, 3])
To intersect more than two arrays, use functools.reduce:
>>> from functools import reduce
>>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
array([3])
"""
if not assume_unique:
# Might be faster than unique( intersect1d( ar1, ar2 ) )?
ar1 = unique(ar1)
ar2 = unique(ar2)
aux = np.concatenate((ar1, ar2))
aux.sort()
return aux[:-1][aux[1:] == aux[:-1]]
def setxor1d(ar1, ar2, assume_unique=False):
"""
Find the set exclusive-or of two arrays.
Return the sorted, unique values that are in only one (not both) of the
input arrays.
Parameters
----------
ar1, ar2 : array_like
Input arrays.
assume_unique : bool
If True, the input arrays are both assumed to be unique, which
can speed up the calculation. Default is False.
Returns
-------
setxor1d : ndarray
Sorted 1D array of unique values that are in only one of the input
arrays.
Examples
--------
>>> a = np.array([1, 2, 3, 2, 4])
>>> b = np.array([2, 3, 5, 7, 5])
>>> np.setxor1d(a,b)
array([1, 4, 5, 7])
"""
if not assume_unique:
ar1 = unique(ar1)
ar2 = unique(ar2)
aux = np.concatenate((ar1, ar2))
if aux.size == 0:
return aux
aux.sort()
# flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0
flag = np.concatenate(([True], aux[1:] != aux[:-1], [True]))
# flag2 = ediff1d( flag ) == 0
flag2 = flag[1:] == flag[:-1]
return aux[flag2]
def in1d(ar1, ar2, assume_unique=False, invert=False):
"""
Test whether each element of a 1-D array is also present in a second array.
Returns a boolean array the same length as `ar1` that is True
where an element of `ar1` is in `ar2` and False otherwise.
Parameters
----------
ar1 : (M,) array_like
Input array.
ar2 : array_like
The values against which to test each value of `ar1`.
assume_unique : bool, optional
If True, the input arrays are both assumed to be unique, which
can speed up the calculation. Default is False.
invert : bool, optional
If True, the values in the returned array are inverted (that is,
False where an element of `ar1` is in `ar2` and True otherwise).
Default is False. ``np.in1d(a, b, invert=True)`` is equivalent
to (but is faster than) ``np.invert(in1d(a, b))``.
.. versionadded:: 1.8.0
Returns
-------
in1d : (M,) ndarray, bool
The values `ar1[in1d]` are in `ar2`.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
Notes
-----
`in1d` can be considered as an element-wise function version of the
python keyword `in`, for 1-D sequences. ``in1d(a, b)`` is roughly
equivalent to ``np.array([item in b for item in a])``.
However, this idea fails if `ar2` is a set, or similar (non-sequence)
container: As ``ar2`` is converted to an array, in those cases
``asarray(ar2)`` is an object array rather than the expected array of
contained values.
.. versionadded:: 1.4.0
Examples
--------
>>> test = np.array([0, 1, 2, 5, 0])
>>> states = [0, 2]
>>> mask = np.in1d(test, states)
>>> mask
array([ True, False, True, False, True], dtype=bool)
>>> test[mask]
array([0, 2, 0])
>>> mask = np.in1d(test, states, invert=True)
>>> mask
array([False, True, False, True, False], dtype=bool)
>>> test[mask]
array([1, 5])
"""
# Ravel both arrays, behavior for the first array could be different
ar1 = np.asarray(ar1).ravel()
ar2 = np.asarray(ar2).ravel()
# This code is significantly faster when the condition is satisfied.
if len(ar2) < 10 * len(ar1) ** 0.145:
if invert:
mask = np.ones(len(ar1), dtype=np.bool)
for a in ar2:
mask &= (ar1 != a)
else:
mask = np.zeros(len(ar1), dtype=np.bool)
for a in ar2:
mask |= (ar1 == a)
return mask
# Otherwise use sorting
if not assume_unique:
ar1, rev_idx = np.unique(ar1, return_inverse=True)
ar2 = np.unique(ar2)
ar = np.concatenate((ar1, ar2))
# We need this to be a stable sort, so always use 'mergesort'
# here. The values from the first array should always come before
# the values from the second array.
order = ar.argsort(kind='mergesort')
sar = ar[order]
if invert:
bool_ar = (sar[1:] != sar[:-1])
else:
bool_ar = (sar[1:] == sar[:-1])
flag = np.concatenate((bool_ar, [invert]))
ret = np.empty(ar.shape, dtype=bool)
ret[order] = flag
if assume_unique:
return ret[:len(ar1)]
else:
return ret[rev_idx]
def union1d(ar1, ar2):
"""
Find the union of two arrays.
Return the unique, sorted array of values that are in either of the two
input arrays.
Parameters
----------
ar1, ar2 : array_like
Input arrays. They are flattened if they are not already 1D.
Returns
-------
union1d : ndarray
Unique, sorted union of the input arrays.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
Examples
--------
>>> np.union1d([-1, 0, 1], [-2, 0, 2])
array([-2, -1, 0, 1, 2])
To find the union of more than two arrays, use functools.reduce:
>>> from functools import reduce
>>> reduce(np.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
array([1, 2, 3, 4, 6])
"""
return unique(np.concatenate((ar1, ar2)))
def setdiff1d(ar1, ar2, assume_unique=False):
"""
Find the set difference of two arrays.
Return the sorted, unique values in `ar1` that are not in `ar2`.
Parameters
----------
ar1 : array_like
Input array.
ar2 : array_like
Input comparison array.
assume_unique : bool
If True, the input arrays are both assumed to be unique, which
can speed up the calculation. Default is False.
Returns
-------
setdiff1d : ndarray
Sorted 1D array of values in `ar1` that are not in `ar2`.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
Examples
--------
>>> a = np.array([1, 2, 3, 2, 4, 1])
>>> b = np.array([3, 4, 5, 6])
>>> np.setdiff1d(a, b)
array([1, 2])
"""
if assume_unique:
ar1 = np.asarray(ar1).ravel()
else:
ar1 = unique(ar1)
ar2 = unique(ar2)
return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)]
| 29.719335 | 80 | 0.561525 | from __future__ import division, absolute_import, print_function
import numpy as np
__all__ = [
'ediff1d', 'intersect1d', 'setxor1d', 'union1d', 'setdiff1d', 'unique',
'in1d'
]
def ediff1d(ary, to_end=None, to_begin=None):
ary = np.asanyarray(ary).flat
ed = ary[1:] - ary[:-1]
arrays = [ed]
if to_begin is not None:
arrays.insert(0, to_begin)
if to_end is not None:
arrays.append(to_end)
if len(arrays) != 1:
# the common case where neither to_begin or to_end was given.
ed = np.hstack(arrays)
return ed
def unique(ar, return_index=False, return_inverse=False, return_counts=False):
ar = np.asanyarray(ar).flatten()
optional_indices = return_index or return_inverse
optional_returns = optional_indices or return_counts
if ar.size == 0:
if not optional_returns:
ret = ar
else:
ret = (ar,)
if return_index:
ret += (np.empty(0, np.bool),)
if return_inverse:
ret += (np.empty(0, np.bool),)
if return_counts:
ret += (np.empty(0, np.intp),)
return ret
if optional_indices:
perm = ar.argsort(kind='mergesort' if return_index else 'quicksort')
aux = ar[perm]
else:
ar.sort()
aux = ar
flag = np.concatenate(([True], aux[1:] != aux[:-1]))
if not optional_returns:
ret = aux[flag]
else:
ret = (aux[flag],)
if return_index:
ret += (perm[flag],)
if return_inverse:
iflag = np.cumsum(flag) - 1
inv_idx = np.empty(ar.shape, dtype=np.intp)
inv_idx[perm] = iflag
ret += (inv_idx,)
if return_counts:
idx = np.concatenate(np.nonzero(flag) + ([ar.size],))
ret += (np.diff(idx),)
return ret
def intersect1d(ar1, ar2, assume_unique=False):
if not assume_unique:
# Might be faster than unique( intersect1d( ar1, ar2 ) )?
ar1 = unique(ar1)
ar2 = unique(ar2)
aux = np.concatenate((ar1, ar2))
aux.sort()
return aux[:-1][aux[1:] == aux[:-1]]
def setxor1d(ar1, ar2, assume_unique=False):
if not assume_unique:
ar1 = unique(ar1)
ar2 = unique(ar2)
aux = np.concatenate((ar1, ar2))
if aux.size == 0:
return aux
aux.sort()
# flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0
flag = np.concatenate(([True], aux[1:] != aux[:-1], [True]))
# flag2 = ediff1d( flag ) == 0
flag2 = flag[1:] == flag[:-1]
return aux[flag2]
def in1d(ar1, ar2, assume_unique=False, invert=False):
# Ravel both arrays, behavior for the first array could be different
ar1 = np.asarray(ar1).ravel()
ar2 = np.asarray(ar2).ravel()
# This code is significantly faster when the condition is satisfied.
if len(ar2) < 10 * len(ar1) ** 0.145:
if invert:
mask = np.ones(len(ar1), dtype=np.bool)
for a in ar2:
mask &= (ar1 != a)
else:
mask = np.zeros(len(ar1), dtype=np.bool)
for a in ar2:
mask |= (ar1 == a)
return mask
# Otherwise use sorting
if not assume_unique:
ar1, rev_idx = np.unique(ar1, return_inverse=True)
ar2 = np.unique(ar2)
ar = np.concatenate((ar1, ar2))
# We need this to be a stable sort, so always use 'mergesort'
# here. The values from the first array should always come before
# the values from the second array.
order = ar.argsort(kind='mergesort')
sar = ar[order]
if invert:
bool_ar = (sar[1:] != sar[:-1])
else:
bool_ar = (sar[1:] == sar[:-1])
flag = np.concatenate((bool_ar, [invert]))
ret = np.empty(ar.shape, dtype=bool)
ret[order] = flag
if assume_unique:
return ret[:len(ar1)]
else:
return ret[rev_idx]
def union1d(ar1, ar2):
return unique(np.concatenate((ar1, ar2)))
def setdiff1d(ar1, ar2, assume_unique=False):
if assume_unique:
ar1 = np.asarray(ar1).ravel()
else:
ar1 = unique(ar1)
ar2 = unique(ar2)
return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)]
| true | true |
1c3fadb18ea5a35b1a6c384aad3f988c75251fce | 1,398 | py | Python | 10_path.py | akfmdl/testdome-python-solutions | f4a2dd2831bc9b11c3374f41c84abc53ff79c01b | [
"MIT"
] | 2 | 2022-02-09T17:30:49.000Z | 2022-02-27T17:25:53.000Z | 10_path.py | akfmdl/testdome-python-solutions | f4a2dd2831bc9b11c3374f41c84abc53ff79c01b | [
"MIT"
] | null | null | null | 10_path.py | akfmdl/testdome-python-solutions | f4a2dd2831bc9b11c3374f41c84abc53ff79c01b | [
"MIT"
] | null | null | null | """
30 min
Write a function that provides change directory (cd) function for an abstract file system.
Notes:
* Root path is '/'.
* Path separator is '/'.
* Parent directory is addressable as '..'.
* Directory names consist only of English alphabet letters (A-Z and a-z).
* The function should support both relative and absolute paths.
* The function will not be passed any invalid paths.
* Do not use built-in path-related functions.
For example:
path = Path('/a/b/c/d')
path.cd('../x')
print(path.current_path)
should display '/a/b/c/x'.
class Path:
def __init__(self, path):
self.current_path = path
def cd(self, new_path):
pass
path = Path('/a/b/c/d')
path.cd('../x')
print(path.current_path)
"""
class Path:
def __init__(self, path):
self.current_path = path
def cd(self, new_path):
if new_path.startswith('/'):
self.current_path = new_path
else:
orig = self.current_path.split('/')
for part in new_path.split('/'):
if part == '..':
orig.pop()
else:
orig.append(part)
if orig == ['']:
self.current_path = '/'
else:
self.current_path = '/'.join(orig)
path = Path('/a/b/c/d')
path.cd('../x')
print(path.current_path)
| 22.918033 | 90 | 0.55794 |
class Path:
def __init__(self, path):
self.current_path = path
def cd(self, new_path):
if new_path.startswith('/'):
self.current_path = new_path
else:
orig = self.current_path.split('/')
for part in new_path.split('/'):
if part == '..':
orig.pop()
else:
orig.append(part)
if orig == ['']:
self.current_path = '/'
else:
self.current_path = '/'.join(orig)
path = Path('/a/b/c/d')
path.cd('../x')
print(path.current_path)
| true | true |
1c3fafdd497f21f0c7a44fed0e588a194ae3989e | 12,454 | py | Python | pyserializer/serialize.py | deptofdefense/pyserializer | 2f52664ed96b2640f24d4312b2a93db6c75d0b53 | [
"MIT"
] | 1 | 2022-03-05T01:18:08.000Z | 2022-03-05T01:18:08.000Z | pyserializer/serialize.py | deptofdefense/pyserializer | 2f52664ed96b2640f24d4312b2a93db6c75d0b53 | [
"MIT"
] | null | null | null | pyserializer/serialize.py | deptofdefense/pyserializer | 2f52664ed96b2640f24d4312b2a93db6c75d0b53 | [
"MIT"
] | null | null | null | # =================================================================
#
# Work of the U.S. Department of Defense, Defense Digital Service.
# Released as open source under the MIT License. See LICENSE file.
#
# =================================================================
import csv
import json
import pyarrow as pa
import pandas as pd
from pyserializer.cleaner import clean
from pyserializer.encoder import Encoder
from pyserializer.parquet import DatasetWriter, PartitionWriter
from pyserializer.writer import create_writer
def write_jsonl_tuples(drop_blanks=None, drop_nulls=None, f=None, limit=None, tuples=None, kwargs=None):
if limit is not None and limit > 0 and limit < len(tuples):
if drop_nulls or drop_blanks:
count = 0
for item in tuples:
f.write(
json.dumps(
clean(
item._asdict(),
drop_nulls=drop_nulls,
drop_blanks=drop_blanks
),
**kwargs
)+"\n"
)
count += 1
if count >= limit:
break
else:
count = 0
for item in tuples:
f.write(json.dumps(item._asdict(), **kwargs)+"\n")
count += 1
if count >= limit:
break
else:
if drop_nulls or drop_blanks:
for item in tuples:
f.write(
json.dumps(
clean(
item._asdict(),
drop_nulls=drop_nulls,
drop_blanks=drop_blanks
),
**kwargs
)+"\n"
)
else:
for item in tuples:
f.write(json.dumps(item._asdict(), **kwargs)+"\n")
def write_csv_tuples(drop_blanks=None, drop_nulls=None, cw=None, limit=None, tuples=None):
if limit is not None and limit > 0 and limit < len(tuples):
if drop_nulls or drop_blanks:
count = 0
for item in tuples:
cw.writerow(clean(
item._asdict(),
drop_nulls=drop_nulls,
drop_blanks=drop_blanks
))
count += 1
if count >= limit:
break
else:
count = 0
for item in tuples:
cw.writerow(item._asdict())
count += 1
if count >= limit:
break
else:
if drop_nulls or drop_blanks:
for item in tuples:
cw.writerow(clean(
item._asdict(),
drop_nulls=drop_nulls,
drop_blanks=drop_blanks
))
else:
for item in tuples:
cw.writerow(item._asdict())
def serialize(
allow_nan=False,
ctx=None,
dest=None,
data=None,
drop_blanks=None,
drop_nulls=None,
encoder=None,
format=None,
compression=None,
columns=None,
limit=None,
partition_columns=None,
row_group_columns=None,
row_group_size=None,
fs=None,
schema=None,
makedirs=False,
index=False,
safe=True,
timeout=None,
zero_copy_only=False,
pretty=False
):
if format == "json":
kwargs = {
"allow_nan": allow_nan,
"cls": (encoder if encoder is not None else Encoder),
"separators": ((', ', ': ') if pretty else (',', ':'))
}
if fs is not None:
with fs.open(dest, 'wb') as f:
with create_writer(f=f, compression=compression) as w:
w.write(json.dumps(data, **kwargs))
else:
with create_writer(f=dest, compression=compression) as w:
w.write(json.dumps(data, **kwargs))
elif format == "jsonl":
if (not isinstance(data, pa.Table)) and (not isinstance(data, pd.DataFrame)) and (not isinstance(data, list)):
raise Exception("unknown data type {}".format(type(data)))
if len(data) == 0:
return
kwargs = {
"allow_nan": allow_nan,
"cls": (encoder if encoder is not None else Encoder),
"separators": ((', ', ': ') if pretty else (',', ':'))
}
if fs is not None:
with fs.open(dest, 'wb') as f:
with create_writer(f=f, compression=compression) as w:
# if list, then slice the list all at once, since already in memory
if isinstance(data, list):
json.dump(data[0], w, **kwargs)
for item in (data[1:limit] if limit is not None and limit > 0 else data[1:]):
w.write("\n")
json.dump(item, w, **kwargs)
# if dataframe, then iterate through the data time.
if isinstance(data, pd.DataFrame):
write_jsonl_tuples(
drop_blanks=drop_blanks,
drop_nulls=drop_nulls,
f=w,
limit=limit,
tuples=data.itertuples(index=index),
kwargs=kwargs
)
else:
with create_writer(f=dest, compression=compression) as w:
# if list, then slice the list all at once, since already in memory
if isinstance(data, list):
json.dump(data[0], w, **kwargs)
for item in (data[1:limit] if limit is not None and limit > 0 else data[1:]):
w.write("\n")
json.dump(item, w, **kwargs)
# if dataframe, then iterate through the data time.
if isinstance(data, pd.DataFrame):
write_jsonl_tuples(
drop_blanks=drop_blanks,
drop_nulls=drop_nulls,
f=w,
limit=limit,
tuples=data.itertuples(index=index),
kwargs=kwargs
)
elif format == "csv" or format == "tsv":
if (not isinstance(data, pa.Table)) and (not isinstance(data, pd.DataFrame)) and (not isinstance(data, list)):
raise Exception("unknown data type {}".format(type(data)))
if len(data) == 0:
return
if fs is not None:
with fs.open(dest, 'wb') as f:
with create_writer(f=f, compression=compression) as w:
# if list, then slice the list all at once, since already in memory
if isinstance(data, list):
fieldnames = columns or sorted(list({k for d in data for k in d.keys()}))
if limit is not None and limit > 0 and limit < len(data):
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
count = 0
for r in data:
cw.writerow(r)
count += 1
if count >= limit:
break
else:
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
for r in data:
cw.writerow(r)
# if dataframe, then iterate through the data time.
if isinstance(data, pd.DataFrame):
fieldnames = sorted(list(data.columns))
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
if limit is not None and limit > 0 and limit < len(data):
data = data.head(limit)
else:
write_csv_tuples(
drop_blanks=drop_blanks,
drop_nulls=drop_nulls,
cw=cw,
limit=limit,
tuples=data.itertuples(index=index)
)
else:
with create_writer(f=dest, compression=compression) as w:
# if list, then slice the list all at once, since already in memory
if isinstance(data, list):
fieldnames = columns or sorted(list({k for d in data for k in d.keys()}))
if limit is not None and limit > 0 and limit < len(data):
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
count = 0
for r in data:
cw.writerow(r)
count += 1
if count >= limit:
break
else:
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
for r in data:
cw.writerow(r)
# if dataframe, then iterate through the data time.
if isinstance(data, pd.DataFrame):
fieldnames = sorted(list(data.columns))
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
if limit is not None and limit > 0 and limit < len(data):
data = data.head(limit)
else:
write_csv_tuples(
drop_blanks=drop_blanks,
drop_nulls=drop_nulls,
cw=cw,
limit=limit,
tuples=data.itertuples(index=index)
)
elif format == "parquet":
if (not isinstance(data, pa.Table)) and (not isinstance(data, pd.DataFrame)) and (not isinstance(data, list)):
raise Exception("unknown dataset type")
if len(data) == 0:
return
if partition_columns is not None and len(partition_columns) > 0:
dw = DatasetWriter(
dest,
partition_columns,
compression=compression.upper() if compression in ['gzip', 'snappy'] else None,
filesystem=fs,
makedirs=makedirs,
nthreads=None,
preserve_index=index,
schema=schema,
timeout=timeout
)
dw.write_dataset(
data,
ctx=ctx,
row_group_columns=row_group_columns,
row_group_size=row_group_size,
safe=True,
limit=limit
)
else:
table = None
if isinstance(data, pd.DataFrame):
table = pa.Table.from_pandas(data, preserve_index=index)
elif isinstance(data, pa.Table):
table = data
elif isinstance(data, list):
table = pa.Table.from_pandas(pd.DataFrame(data), preserve_index=index)
pw = PartitionWriter(
dest,
table.schema,
compression=compression.upper() if compression in ['gzip', 'snappy'] else None,
filesystem=fs)
pw.write_partition(
table,
row_group_size=row_group_size,
row_group_columns=row_group_columns,
preserve_index=index,
safe=safe,
limit=limit)
pw.close()
else:
raise Exception("invalid format {}".format(format))
| 38.085627 | 119 | 0.453027 |
import csv
import json
import pyarrow as pa
import pandas as pd
from pyserializer.cleaner import clean
from pyserializer.encoder import Encoder
from pyserializer.parquet import DatasetWriter, PartitionWriter
from pyserializer.writer import create_writer
def write_jsonl_tuples(drop_blanks=None, drop_nulls=None, f=None, limit=None, tuples=None, kwargs=None):
if limit is not None and limit > 0 and limit < len(tuples):
if drop_nulls or drop_blanks:
count = 0
for item in tuples:
f.write(
json.dumps(
clean(
item._asdict(),
drop_nulls=drop_nulls,
drop_blanks=drop_blanks
),
**kwargs
)+"\n"
)
count += 1
if count >= limit:
break
else:
count = 0
for item in tuples:
f.write(json.dumps(item._asdict(), **kwargs)+"\n")
count += 1
if count >= limit:
break
else:
if drop_nulls or drop_blanks:
for item in tuples:
f.write(
json.dumps(
clean(
item._asdict(),
drop_nulls=drop_nulls,
drop_blanks=drop_blanks
),
**kwargs
)+"\n"
)
else:
for item in tuples:
f.write(json.dumps(item._asdict(), **kwargs)+"\n")
def write_csv_tuples(drop_blanks=None, drop_nulls=None, cw=None, limit=None, tuples=None):
if limit is not None and limit > 0 and limit < len(tuples):
if drop_nulls or drop_blanks:
count = 0
for item in tuples:
cw.writerow(clean(
item._asdict(),
drop_nulls=drop_nulls,
drop_blanks=drop_blanks
))
count += 1
if count >= limit:
break
else:
count = 0
for item in tuples:
cw.writerow(item._asdict())
count += 1
if count >= limit:
break
else:
if drop_nulls or drop_blanks:
for item in tuples:
cw.writerow(clean(
item._asdict(),
drop_nulls=drop_nulls,
drop_blanks=drop_blanks
))
else:
for item in tuples:
cw.writerow(item._asdict())
def serialize(
allow_nan=False,
ctx=None,
dest=None,
data=None,
drop_blanks=None,
drop_nulls=None,
encoder=None,
format=None,
compression=None,
columns=None,
limit=None,
partition_columns=None,
row_group_columns=None,
row_group_size=None,
fs=None,
schema=None,
makedirs=False,
index=False,
safe=True,
timeout=None,
zero_copy_only=False,
pretty=False
):
if format == "json":
kwargs = {
"allow_nan": allow_nan,
"cls": (encoder if encoder is not None else Encoder),
"separators": ((', ', ': ') if pretty else (',', ':'))
}
if fs is not None:
with fs.open(dest, 'wb') as f:
with create_writer(f=f, compression=compression) as w:
w.write(json.dumps(data, **kwargs))
else:
with create_writer(f=dest, compression=compression) as w:
w.write(json.dumps(data, **kwargs))
elif format == "jsonl":
if (not isinstance(data, pa.Table)) and (not isinstance(data, pd.DataFrame)) and (not isinstance(data, list)):
raise Exception("unknown data type {}".format(type(data)))
if len(data) == 0:
return
kwargs = {
"allow_nan": allow_nan,
"cls": (encoder if encoder is not None else Encoder),
"separators": ((', ', ': ') if pretty else (',', ':'))
}
if fs is not None:
with fs.open(dest, 'wb') as f:
with create_writer(f=f, compression=compression) as w:
if isinstance(data, list):
json.dump(data[0], w, **kwargs)
for item in (data[1:limit] if limit is not None and limit > 0 else data[1:]):
w.write("\n")
json.dump(item, w, **kwargs)
if isinstance(data, pd.DataFrame):
write_jsonl_tuples(
drop_blanks=drop_blanks,
drop_nulls=drop_nulls,
f=w,
limit=limit,
tuples=data.itertuples(index=index),
kwargs=kwargs
)
else:
with create_writer(f=dest, compression=compression) as w:
if isinstance(data, list):
json.dump(data[0], w, **kwargs)
for item in (data[1:limit] if limit is not None and limit > 0 else data[1:]):
w.write("\n")
json.dump(item, w, **kwargs)
if isinstance(data, pd.DataFrame):
write_jsonl_tuples(
drop_blanks=drop_blanks,
drop_nulls=drop_nulls,
f=w,
limit=limit,
tuples=data.itertuples(index=index),
kwargs=kwargs
)
elif format == "csv" or format == "tsv":
if (not isinstance(data, pa.Table)) and (not isinstance(data, pd.DataFrame)) and (not isinstance(data, list)):
raise Exception("unknown data type {}".format(type(data)))
if len(data) == 0:
return
if fs is not None:
with fs.open(dest, 'wb') as f:
with create_writer(f=f, compression=compression) as w:
if isinstance(data, list):
fieldnames = columns or sorted(list({k for d in data for k in d.keys()}))
if limit is not None and limit > 0 and limit < len(data):
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
count = 0
for r in data:
cw.writerow(r)
count += 1
if count >= limit:
break
else:
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
for r in data:
cw.writerow(r)
if isinstance(data, pd.DataFrame):
fieldnames = sorted(list(data.columns))
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
if limit is not None and limit > 0 and limit < len(data):
data = data.head(limit)
else:
write_csv_tuples(
drop_blanks=drop_blanks,
drop_nulls=drop_nulls,
cw=cw,
limit=limit,
tuples=data.itertuples(index=index)
)
else:
with create_writer(f=dest, compression=compression) as w:
if isinstance(data, list):
fieldnames = columns or sorted(list({k for d in data for k in d.keys()}))
if limit is not None and limit > 0 and limit < len(data):
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
count = 0
for r in data:
cw.writerow(r)
count += 1
if count >= limit:
break
else:
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
for r in data:
cw.writerow(r)
if isinstance(data, pd.DataFrame):
fieldnames = sorted(list(data.columns))
cw = csv.DictWriter(w, delimiter=("\t" if format == "tsv" else ","), fieldnames=fieldnames)
cw.writeheader()
if limit is not None and limit > 0 and limit < len(data):
data = data.head(limit)
else:
write_csv_tuples(
drop_blanks=drop_blanks,
drop_nulls=drop_nulls,
cw=cw,
limit=limit,
tuples=data.itertuples(index=index)
)
elif format == "parquet":
if (not isinstance(data, pa.Table)) and (not isinstance(data, pd.DataFrame)) and (not isinstance(data, list)):
raise Exception("unknown dataset type")
if len(data) == 0:
return
if partition_columns is not None and len(partition_columns) > 0:
dw = DatasetWriter(
dest,
partition_columns,
compression=compression.upper() if compression in ['gzip', 'snappy'] else None,
filesystem=fs,
makedirs=makedirs,
nthreads=None,
preserve_index=index,
schema=schema,
timeout=timeout
)
dw.write_dataset(
data,
ctx=ctx,
row_group_columns=row_group_columns,
row_group_size=row_group_size,
safe=True,
limit=limit
)
else:
table = None
if isinstance(data, pd.DataFrame):
table = pa.Table.from_pandas(data, preserve_index=index)
elif isinstance(data, pa.Table):
table = data
elif isinstance(data, list):
table = pa.Table.from_pandas(pd.DataFrame(data), preserve_index=index)
pw = PartitionWriter(
dest,
table.schema,
compression=compression.upper() if compression in ['gzip', 'snappy'] else None,
filesystem=fs)
pw.write_partition(
table,
row_group_size=row_group_size,
row_group_columns=row_group_columns,
preserve_index=index,
safe=safe,
limit=limit)
pw.close()
else:
raise Exception("invalid format {}".format(format))
| true | true |
1c3fb030ac5b90d523c816d4c4a496444658a784 | 1,368 | py | Python | trench/urls/base.py | eriol/django-trench | 27b61479e6d494d7c2e94732c1d186247dac8dd9 | [
"MIT"
] | 190 | 2018-10-26T09:48:26.000Z | 2022-03-31T14:09:28.000Z | trench/urls/base.py | eriol/django-trench | 27b61479e6d494d7c2e94732c1d186247dac8dd9 | [
"MIT"
] | 116 | 2018-10-26T13:04:58.000Z | 2022-03-28T13:51:21.000Z | trench/urls/base.py | eriol/django-trench | 27b61479e6d494d7c2e94732c1d186247dac8dd9 | [
"MIT"
] | 29 | 2018-11-14T07:15:21.000Z | 2022-03-19T08:13:16.000Z | from django.urls import path
__all__ = [
"urlpatterns",
]
from trench.views import (
MFAConfigView,
MFAListActiveUserMethodsView,
MFAMethodActivationView,
MFAMethodBackupCodesRegenerationView,
MFAMethodConfirmActivationView,
MFAMethodDeactivationView,
MFAMethodRequestCodeView,
MFAPrimaryMethodChangeView,
)
urlpatterns = (
path(
"<str:method>/activate/",
MFAMethodActivationView.as_view(),
name="mfa-activate",
),
path(
"<str:method>/activate/confirm/",
MFAMethodConfirmActivationView.as_view(),
name="mfa-activate-confirm",
),
path(
"<str:method>/deactivate/",
MFAMethodDeactivationView.as_view(),
name="mfa-deactivate",
),
path(
"<str:method>/codes/regenerate/",
MFAMethodBackupCodesRegenerationView.as_view(),
name="mfa-regenerate-codes",
),
path("code/request/", MFAMethodRequestCodeView.as_view(), name="mfa-request-code"),
path("mfa/config/", MFAConfigView.as_view(), name="mfa-config-info"),
path(
"mfa/user-active-methods/",
MFAListActiveUserMethodsView.as_view(),
name="mfa-list-user-active-methods",
),
path(
"mfa/change-primary-method/",
MFAPrimaryMethodChangeView.as_view(),
name="mfa-change-primary-method",
),
)
| 25.333333 | 87 | 0.645468 | from django.urls import path
__all__ = [
"urlpatterns",
]
from trench.views import (
MFAConfigView,
MFAListActiveUserMethodsView,
MFAMethodActivationView,
MFAMethodBackupCodesRegenerationView,
MFAMethodConfirmActivationView,
MFAMethodDeactivationView,
MFAMethodRequestCodeView,
MFAPrimaryMethodChangeView,
)
urlpatterns = (
path(
"<str:method>/activate/",
MFAMethodActivationView.as_view(),
name="mfa-activate",
),
path(
"<str:method>/activate/confirm/",
MFAMethodConfirmActivationView.as_view(),
name="mfa-activate-confirm",
),
path(
"<str:method>/deactivate/",
MFAMethodDeactivationView.as_view(),
name="mfa-deactivate",
),
path(
"<str:method>/codes/regenerate/",
MFAMethodBackupCodesRegenerationView.as_view(),
name="mfa-regenerate-codes",
),
path("code/request/", MFAMethodRequestCodeView.as_view(), name="mfa-request-code"),
path("mfa/config/", MFAConfigView.as_view(), name="mfa-config-info"),
path(
"mfa/user-active-methods/",
MFAListActiveUserMethodsView.as_view(),
name="mfa-list-user-active-methods",
),
path(
"mfa/change-primary-method/",
MFAPrimaryMethodChangeView.as_view(),
name="mfa-change-primary-method",
),
)
| true | true |
1c3fb038214eb4d85d24f39d10adf779811cd5c4 | 891 | py | Python | common/utils/time_series.py | shapeshift-legacy/watchtower | c9cd5150f8549145f7de9b1ea820d548959350fe | [
"MIT"
] | null | null | null | common/utils/time_series.py | shapeshift-legacy/watchtower | c9cd5150f8549145f7de9b1ea820d548959350fe | [
"MIT"
] | null | null | null | common/utils/time_series.py | shapeshift-legacy/watchtower | c9cd5150f8549145f7de9b1ea820d548959350fe | [
"MIT"
] | null | null | null | INTERVALS = {
'weekly': {
'unit': 'weeks',
'amount': 1,
'seconds': 60 * 60 * 24 * 7
},
'daily': {
'unit': 'days',
'amount': 1,
'seconds': 60 * 60 * 24
},
'hourly': {
'unit': 'hours',
'amount': 1,
'seconds': 60 * 60
},
'minutely': {
'unit': 'minutes',
'amount': 1,
'seconds': 60
},
'30min': {
'unit': 'minutes',
'amount': 30,
'seconds': 60 * 30
},
'15min': {
'unit': 'minutes',
'amount': 15,
'seconds': 60 * 15
},
'10min': {
'unit': 'minutes',
'amount': 10,
'seconds': 60 * 10
},
'5min': {
'unit': 'minutes',
'amount': 5,
'seconds': 60 * 5
},
'1min': {
'unit': 'minutes',
'amount': 1,
'seconds': 60
},
}
| 18.5625 | 35 | 0.352413 | INTERVALS = {
'weekly': {
'unit': 'weeks',
'amount': 1,
'seconds': 60 * 60 * 24 * 7
},
'daily': {
'unit': 'days',
'amount': 1,
'seconds': 60 * 60 * 24
},
'hourly': {
'unit': 'hours',
'amount': 1,
'seconds': 60 * 60
},
'minutely': {
'unit': 'minutes',
'amount': 1,
'seconds': 60
},
'30min': {
'unit': 'minutes',
'amount': 30,
'seconds': 60 * 30
},
'15min': {
'unit': 'minutes',
'amount': 15,
'seconds': 60 * 15
},
'10min': {
'unit': 'minutes',
'amount': 10,
'seconds': 60 * 10
},
'5min': {
'unit': 'minutes',
'amount': 5,
'seconds': 60 * 5
},
'1min': {
'unit': 'minutes',
'amount': 1,
'seconds': 60
},
}
| true | true |
1c3fb16926f14de180ad561de64021de40c453a9 | 936 | py | Python | django_ajax/mixins.py | skhaylov/django-ajax | d513975e536fc4feff5d710bb17d96b2ef80b28c | [
"MIT"
] | null | null | null | django_ajax/mixins.py | skhaylov/django-ajax | d513975e536fc4feff5d710bb17d96b2ef80b28c | [
"MIT"
] | null | null | null | django_ajax/mixins.py | skhaylov/django-ajax | d513975e536fc4feff5d710bb17d96b2ef80b28c | [
"MIT"
] | null | null | null | # coding=utf-8;
__author__ = 'skhaylov'
import json
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from json_response import JSONResponse
class JSONMixin(object):
response_class = JSONResponse
def get_json_context(self):
context = super(JSONMixin, self).get_json_context()
return context
def get_json_request(self, request_key):
data = getattr(self.request, self.request.method)
return json.loads(data[request_key])
def render_to_response(self, context, **kwargs):
return self.response_class(context, **kwargs)
class JSONUpdateMixin(object):
def process(self):
super(JSONUpdateMixin, self).process()
class CSRFExemptMixin(object):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(CSRFExemptMixin, self).dispatch(request, *args, **kwargs)
| 24.631579 | 78 | 0.724359 |
__author__ = 'skhaylov'
import json
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from json_response import JSONResponse
class JSONMixin(object):
response_class = JSONResponse
def get_json_context(self):
context = super(JSONMixin, self).get_json_context()
return context
def get_json_request(self, request_key):
data = getattr(self.request, self.request.method)
return json.loads(data[request_key])
def render_to_response(self, context, **kwargs):
return self.response_class(context, **kwargs)
class JSONUpdateMixin(object):
def process(self):
super(JSONUpdateMixin, self).process()
class CSRFExemptMixin(object):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(CSRFExemptMixin, self).dispatch(request, *args, **kwargs)
| true | true |
1c3fb1b1e0e6fa6147508ca62535516c9e779138 | 4,396 | py | Python | test/Fortran/SHF03.py | jcassagnol-public/scons | 8eaf585a893757e68c9e4a6e25d375021fa5eab7 | [
"MIT"
] | 1,403 | 2017-11-23T14:24:01.000Z | 2022-03-30T20:59:39.000Z | test/Fortran/SHF03.py | jcassagnol-public/scons | 8eaf585a893757e68c9e4a6e25d375021fa5eab7 | [
"MIT"
] | 3,708 | 2017-11-27T13:47:12.000Z | 2022-03-29T17:21:17.000Z | test/Fortran/SHF03.py | jcassagnol-public/scons | 8eaf585a893757e68c9e4a6e25d375021fa5eab7 | [
"MIT"
] | 281 | 2017-12-01T23:48:38.000Z | 2022-03-31T15:25:44.000Z | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import TestSCons
_python_ = TestSCons._python_
_obj = TestSCons._shobj
obj_ = TestSCons.shobj_
test = TestSCons.TestSCons()
test.file_fixture(['fixture', 'myfortran.py'])
test.write('SConstruct', """
env = Environment(SHF03 = r'%(_python_)s myfortran.py g03',
SHFORTRAN = r'%(_python_)s myfortran.py fortran')
env.SharedObject(target = 'test01', source = 'test01.f')
env.SharedObject(target = 'test02', source = 'test02.F')
env.SharedObject(target = 'test03', source = 'test03.for')
env.SharedObject(target = 'test04', source = 'test04.FOR')
env.SharedObject(target = 'test05', source = 'test05.ftn')
env.SharedObject(target = 'test06', source = 'test06.FTN')
env.SharedObject(target = 'test07', source = 'test07.fpp')
env.SharedObject(target = 'test08', source = 'test08.FPP')
env.SharedObject(target = 'test13', source = 'test13.f03')
env.SharedObject(target = 'test14', source = 'test14.F03')
""" % locals())
test.write('test01.f', "This is a .f file.\n#fortran\n")
test.write('test02.F', "This is a .F file.\n#fortran\n")
test.write('test03.for', "This is a .for file.\n#fortran\n")
test.write('test04.FOR', "This is a .FOR file.\n#fortran\n")
test.write('test05.ftn', "This is a .ftn file.\n#fortran\n")
test.write('test06.FTN', "This is a .FTN file.\n#fortran\n")
test.write('test07.fpp', "This is a .fpp file.\n#fortran\n")
test.write('test08.FPP', "This is a .FPP file.\n#fortran\n")
test.write('test13.f03', "This is a .f03 file.\n#g03\n")
test.write('test14.F03', "This is a .F03 file.\n#g03\n")
test.run(arguments = '.', stderr = None)
test.must_match(obj_ + 'test01' + _obj, "This is a .f file.\n")
test.must_match(obj_ + 'test02' + _obj, "This is a .F file.\n")
test.must_match(obj_ + 'test03' + _obj, "This is a .for file.\n")
test.must_match(obj_ + 'test04' + _obj, "This is a .FOR file.\n")
test.must_match(obj_ + 'test05' + _obj, "This is a .ftn file.\n")
test.must_match(obj_ + 'test06' + _obj, "This is a .FTN file.\n")
test.must_match(obj_ + 'test07' + _obj, "This is a .fpp file.\n")
test.must_match(obj_ + 'test08' + _obj, "This is a .FPP file.\n")
test.must_match(obj_ + 'test13' + _obj, "This is a .f03 file.\n")
test.must_match(obj_ + 'test14' + _obj, "This is a .F03 file.\n")
fc = 'f03'
g03 = test.detect_tool(fc)
if g03:
test.file_fixture('wrapper.py')
test.write('SConstruct', """
foo = Environment(SHF03 = '%(fc)s')
shf03 = foo.Dictionary('SHF03')
bar = foo.Clone(SHF03 = r'%(_python_)s wrapper.py ' + shf03)
foo.SharedObject(target = 'foo/foo', source = 'foo.f03')
bar.SharedObject(target = 'bar/bar', source = 'bar.f03')
""" % locals())
test.write('foo.f03', r"""
PROGRAM FOO
PRINT *,'foo.f03'
STOP
END
""")
test.write('bar.f03', r"""
PROGRAM BAR
PRINT *,'bar.f03'
STOP
END
""")
test.run(arguments = 'foo', stderr = None)
test.must_not_exist('wrapper.out')
import sys
if sys.platform[:5] == 'sunos':
test.run(arguments = 'bar', stderr = None)
else:
test.run(arguments = 'bar')
test.must_match('wrapper.out', "wrapper.py\n")
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| 35.168 | 73 | 0.682439 |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import TestSCons
_python_ = TestSCons._python_
_obj = TestSCons._shobj
obj_ = TestSCons.shobj_
test = TestSCons.TestSCons()
test.file_fixture(['fixture', 'myfortran.py'])
test.write('SConstruct', """
env = Environment(SHF03 = r'%(_python_)s myfortran.py g03',
SHFORTRAN = r'%(_python_)s myfortran.py fortran')
env.SharedObject(target = 'test01', source = 'test01.f')
env.SharedObject(target = 'test02', source = 'test02.F')
env.SharedObject(target = 'test03', source = 'test03.for')
env.SharedObject(target = 'test04', source = 'test04.FOR')
env.SharedObject(target = 'test05', source = 'test05.ftn')
env.SharedObject(target = 'test06', source = 'test06.FTN')
env.SharedObject(target = 'test07', source = 'test07.fpp')
env.SharedObject(target = 'test08', source = 'test08.FPP')
env.SharedObject(target = 'test13', source = 'test13.f03')
env.SharedObject(target = 'test14', source = 'test14.F03')
""" % locals())
test.write('test01.f', "This is a .f file.\n#fortran\n")
test.write('test02.F', "This is a .F file.\n#fortran\n")
test.write('test03.for', "This is a .for file.\n#fortran\n")
test.write('test04.FOR', "This is a .FOR file.\n#fortran\n")
test.write('test05.ftn', "This is a .ftn file.\n#fortran\n")
test.write('test06.FTN', "This is a .FTN file.\n#fortran\n")
test.write('test07.fpp', "This is a .fpp file.\n#fortran\n")
test.write('test08.FPP', "This is a .FPP file.\n#fortran\n")
test.write('test13.f03', "This is a .f03 file.\n#g03\n")
test.write('test14.F03', "This is a .F03 file.\n#g03\n")
test.run(arguments = '.', stderr = None)
test.must_match(obj_ + 'test01' + _obj, "This is a .f file.\n")
test.must_match(obj_ + 'test02' + _obj, "This is a .F file.\n")
test.must_match(obj_ + 'test03' + _obj, "This is a .for file.\n")
test.must_match(obj_ + 'test04' + _obj, "This is a .FOR file.\n")
test.must_match(obj_ + 'test05' + _obj, "This is a .ftn file.\n")
test.must_match(obj_ + 'test06' + _obj, "This is a .FTN file.\n")
test.must_match(obj_ + 'test07' + _obj, "This is a .fpp file.\n")
test.must_match(obj_ + 'test08' + _obj, "This is a .FPP file.\n")
test.must_match(obj_ + 'test13' + _obj, "This is a .f03 file.\n")
test.must_match(obj_ + 'test14' + _obj, "This is a .F03 file.\n")
fc = 'f03'
g03 = test.detect_tool(fc)
if g03:
test.file_fixture('wrapper.py')
test.write('SConstruct', """
foo = Environment(SHF03 = '%(fc)s')
shf03 = foo.Dictionary('SHF03')
bar = foo.Clone(SHF03 = r'%(_python_)s wrapper.py ' + shf03)
foo.SharedObject(target = 'foo/foo', source = 'foo.f03')
bar.SharedObject(target = 'bar/bar', source = 'bar.f03')
""" % locals())
test.write('foo.f03', r"""
PROGRAM FOO
PRINT *,'foo.f03'
STOP
END
""")
test.write('bar.f03', r"""
PROGRAM BAR
PRINT *,'bar.f03'
STOP
END
""")
test.run(arguments = 'foo', stderr = None)
test.must_not_exist('wrapper.out')
import sys
if sys.platform[:5] == 'sunos':
test.run(arguments = 'bar', stderr = None)
else:
test.run(arguments = 'bar')
test.must_match('wrapper.out', "wrapper.py\n")
test.pass_test()
| true | true |
1c3fb3bcdf36a09a0d89dedb18d20ebbe20b866f | 4,466 | py | Python | fuxictr/pytorch/models/HOFM.py | w32zhong/FuxiCTR | f9cac1c5b0a977d6a7dfd16c0ffb524811470f97 | [
"Apache-2.0"
] | null | null | null | fuxictr/pytorch/models/HOFM.py | w32zhong/FuxiCTR | f9cac1c5b0a977d6a7dfd16c0ffb524811470f97 | [
"Apache-2.0"
] | null | null | null | fuxictr/pytorch/models/HOFM.py | w32zhong/FuxiCTR | f9cac1c5b0a977d6a7dfd16c0ffb524811470f97 | [
"Apache-2.0"
] | null | null | null | # =========================================================================
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# 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 torch import nn
import torch
from .base_model import BaseModel
from ..layers import LR_Layer, EmbeddingLayer, InnerProductLayer
from itertools import combinations
class HOFM(BaseModel):
def __init__(self,
feature_map,
model_id="HOFM",
gpu=-1,
task="binary_classification",
learning_rate=1e-3,
order=3,
embedding_dim=10,
reuse_embedding=False,
embedding_dropout=0,
regularizer=None,
**kwargs):
super(HOFM, self).__init__(feature_map,
model_id=model_id,
gpu=gpu,
embedding_regularizer=regularizer,
net_regularizer=regularizer,
**kwargs)
self.order = order
assert order >= 2, "order >= 2 is required in HOFM!"
self.reuse_embedding = reuse_embedding
if reuse_embedding:
assert isinstance(embedding_dim, int), "embedding_dim should be an integer when reuse_embedding=True."
self.embedding_layer = EmbeddingLayer(feature_map, embedding_dim)
else:
if not isinstance(embedding_dim, list):
embedding_dim = [embedding_dim] * (order - 1)
self.embedding_layers = nn.ModuleList([EmbeddingLayer(feature_map, embedding_dim[i]) \
for i in range(order - 1)])
self.inner_product_layer = InnerProductLayer(feature_map.num_fields)
self.lr_layer = LR_Layer(feature_map, use_bias=True)
self.final_activation = self.get_final_activation(task)
self.compile(kwargs["optimizer"], loss=kwargs["loss"], lr=learning_rate)
self.apply(self.init_weights)
self.field_conjunction_dict = dict()
for order_i in range(3, self.order + 1):
order_i_conjunction = zip(*list(combinations(range(feature_map.num_fields), order_i)))
for k, field_index in enumerate(order_i_conjunction):
self.field_conjunction_dict[(order_i, k)] = torch.LongTensor(field_index)
def forward(self, inputs):
"""
Inputs: [X, y]
"""
X, y = self.inputs_to_device(inputs)
y_pred = self.lr_layer(X)
if self.reuse_embedding:
feature_emb = self.embedding_layer(X)
for i in range(2, self.order + 1):
order_i_out = self.high_order_interaction(feature_emb if self.reuse_embedding \
else self.embedding_layers[i - 2](X), order_i=i)
y_pred += order_i_out
if self.final_activation is not None:
y_pred = self.final_activation(y_pred)
return_dict = {"y_true": y, "y_pred": y_pred}
return return_dict
def high_order_interaction(self, feature_emb, order_i):
if order_i == 2:
interaction_out = self.inner_product_layer(feature_emb)
elif order_i > 2:
index = self.field_conjunction_dict[(order_i, 0)].to(self.device)
hadamard_product = torch.index_select(feature_emb, 1, index)
for k in range(1, order_i):
index = self.field_conjunction_dict[(order_i, k)].to(self.device)
hadamard_product = hadamard_product * torch.index_select(feature_emb, 1, index)
interaction_out = hadamard_product.sum((1, 2)).view(-1, 1)
return interaction_out
| 48.021505 | 115 | 0.576131 |
from torch import nn
import torch
from .base_model import BaseModel
from ..layers import LR_Layer, EmbeddingLayer, InnerProductLayer
from itertools import combinations
class HOFM(BaseModel):
def __init__(self,
feature_map,
model_id="HOFM",
gpu=-1,
task="binary_classification",
learning_rate=1e-3,
order=3,
embedding_dim=10,
reuse_embedding=False,
embedding_dropout=0,
regularizer=None,
**kwargs):
super(HOFM, self).__init__(feature_map,
model_id=model_id,
gpu=gpu,
embedding_regularizer=regularizer,
net_regularizer=regularizer,
**kwargs)
self.order = order
assert order >= 2, "order >= 2 is required in HOFM!"
self.reuse_embedding = reuse_embedding
if reuse_embedding:
assert isinstance(embedding_dim, int), "embedding_dim should be an integer when reuse_embedding=True."
self.embedding_layer = EmbeddingLayer(feature_map, embedding_dim)
else:
if not isinstance(embedding_dim, list):
embedding_dim = [embedding_dim] * (order - 1)
self.embedding_layers = nn.ModuleList([EmbeddingLayer(feature_map, embedding_dim[i]) \
for i in range(order - 1)])
self.inner_product_layer = InnerProductLayer(feature_map.num_fields)
self.lr_layer = LR_Layer(feature_map, use_bias=True)
self.final_activation = self.get_final_activation(task)
self.compile(kwargs["optimizer"], loss=kwargs["loss"], lr=learning_rate)
self.apply(self.init_weights)
self.field_conjunction_dict = dict()
for order_i in range(3, self.order + 1):
order_i_conjunction = zip(*list(combinations(range(feature_map.num_fields), order_i)))
for k, field_index in enumerate(order_i_conjunction):
self.field_conjunction_dict[(order_i, k)] = torch.LongTensor(field_index)
def forward(self, inputs):
X, y = self.inputs_to_device(inputs)
y_pred = self.lr_layer(X)
if self.reuse_embedding:
feature_emb = self.embedding_layer(X)
for i in range(2, self.order + 1):
order_i_out = self.high_order_interaction(feature_emb if self.reuse_embedding \
else self.embedding_layers[i - 2](X), order_i=i)
y_pred += order_i_out
if self.final_activation is not None:
y_pred = self.final_activation(y_pred)
return_dict = {"y_true": y, "y_pred": y_pred}
return return_dict
def high_order_interaction(self, feature_emb, order_i):
if order_i == 2:
interaction_out = self.inner_product_layer(feature_emb)
elif order_i > 2:
index = self.field_conjunction_dict[(order_i, 0)].to(self.device)
hadamard_product = torch.index_select(feature_emb, 1, index)
for k in range(1, order_i):
index = self.field_conjunction_dict[(order_i, k)].to(self.device)
hadamard_product = hadamard_product * torch.index_select(feature_emb, 1, index)
interaction_out = hadamard_product.sum((1, 2)).view(-1, 1)
return interaction_out
| true | true |
1c3fb3cedd17e4c492cf2192f069b0c0863eee6d | 2,129 | py | Python | src/robust_deid/ner_datasets/distribution/print_distribution.py | obi-ml-public/ehr_deidentification | c9deaf30b8317689d28a4267d15ec13baa9791cd | [
"MIT"
] | null | null | null | src/robust_deid/ner_datasets/distribution/print_distribution.py | obi-ml-public/ehr_deidentification | c9deaf30b8317689d28a4267d15ec13baa9791cd | [
"MIT"
] | null | null | null | src/robust_deid/ner_datasets/distribution/print_distribution.py | obi-ml-public/ehr_deidentification | c9deaf30b8317689d28a4267d15ec13baa9791cd | [
"MIT"
] | null | null | null | from collections import Counter
from typing import Sequence, NoReturn
from .ner_distribution import NERDistribution
class PrintDistribution(object):
"""
This class is used to print the distribution of NER types
"""
def __init__(self, ner_distribution: NERDistribution, key_counts: Counter) -> NoReturn:
"""
Initialize
Args:
ner_distribution (NERDistribution): NERDistribution object that keeps track of the NER type distributions
key_counts (Counter): Number of keys/groups (e.g note_ids, patient ids etc)
"""
self._ner_distribution = ner_distribution
self._key_counts = key_counts
def split_distribution(self, split: str, split_info: Sequence[str]) -> NoReturn:
"""
Print NER type distribution
Args:
split (str): The dataset split
split_info (Sequence[str]): The keys belonging to that split
"""
split_distribution = Counter()
number_of_notes = 0
for key in split_info:
number_of_notes += self._key_counts[key]
split_distribution.update(self._ner_distribution.get_group_distribution(key))
total_ner = sum(split_distribution.values())
percentages = {ner_type: float(count) / total_ner * 100 if total_ner else 0
for ner_type, count in split_distribution.items()}
print('{:^70}'.format('============ ' + split.upper() + ' NER Distribution ============='))
print('{:<20}{:<10}'.format('Number of Notes: ', number_of_notes))
print('{:<20}{:<10}\n'.format('Number of Groups: ', len(split_info)))
for ner_type, count in split_distribution.most_common():
print('{:<10}{:<10}{:<5}{:<10}{:<5}{:<10}'.format(
'NER Type: ', ner_type,
'Count: ', count,
'Percentage: ', '{:0.2f}'.format(percentages[ner_type]))
)
print('{:<10}{:<10}{:<5}{:<10}{:<5}{:<10}'.format(
'NER Type:', 'TOTALS', 'Count: ', total_ner, 'Percentage: ', '{:0.2f}'.format(100))
)
print('\n')
| 42.58 | 117 | 0.591827 | from collections import Counter
from typing import Sequence, NoReturn
from .ner_distribution import NERDistribution
class PrintDistribution(object):
def __init__(self, ner_distribution: NERDistribution, key_counts: Counter) -> NoReturn:
self._ner_distribution = ner_distribution
self._key_counts = key_counts
def split_distribution(self, split: str, split_info: Sequence[str]) -> NoReturn:
split_distribution = Counter()
number_of_notes = 0
for key in split_info:
number_of_notes += self._key_counts[key]
split_distribution.update(self._ner_distribution.get_group_distribution(key))
total_ner = sum(split_distribution.values())
percentages = {ner_type: float(count) / total_ner * 100 if total_ner else 0
for ner_type, count in split_distribution.items()}
print('{:^70}'.format('============ ' + split.upper() + ' NER Distribution ============='))
print('{:<20}{:<10}'.format('Number of Notes: ', number_of_notes))
print('{:<20}{:<10}\n'.format('Number of Groups: ', len(split_info)))
for ner_type, count in split_distribution.most_common():
print('{:<10}{:<10}{:<5}{:<10}{:<5}{:<10}'.format(
'NER Type: ', ner_type,
'Count: ', count,
'Percentage: ', '{:0.2f}'.format(percentages[ner_type]))
)
print('{:<10}{:<10}{:<5}{:<10}{:<5}{:<10}'.format(
'NER Type:', 'TOTALS', 'Count: ', total_ner, 'Percentage: ', '{:0.2f}'.format(100))
)
print('\n')
| true | true |
1c3fb48f7768e1c691f56a6ad1099f95405463d3 | 569 | py | Python | Dataset/Leetcode/test/8/125.py | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/8/125.py | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/8/125.py | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution:
def XXX(self, str: str) -> int:
sign=1
str=str.strip()
if not str:
return 0
if str[0]=="+" or str[0]=="-":
if str[0]=="-":
sign=-1
str=str[1:]
ans=0
for i in str:
if i.isdigit():
ans=ans*10+int(i)
else:
break
ans*=sign
if ans>2147483647:
return 2147483647
elif ans<-2147483648:
return -2147483648
else:
return ans
| 21.074074 | 38 | 0.388401 | class Solution:
def XXX(self, str: str) -> int:
sign=1
str=str.strip()
if not str:
return 0
if str[0]=="+" or str[0]=="-":
if str[0]=="-":
sign=-1
str=str[1:]
ans=0
for i in str:
if i.isdigit():
ans=ans*10+int(i)
else:
break
ans*=sign
if ans>2147483647:
return 2147483647
elif ans<-2147483648:
return -2147483648
else:
return ans
| true | true |
1c3fb526e37a26eea6f0226f05b415ad6d775a8e | 72,404 | py | Python | python/ray/serve/tests/test_deployment_state.py | jianoaix/ray | 1701b923bc83905f8961c06a6a173e3eba46a936 | [
"Apache-2.0"
] | null | null | null | python/ray/serve/tests/test_deployment_state.py | jianoaix/ray | 1701b923bc83905f8961c06a6a173e3eba46a936 | [
"Apache-2.0"
] | null | null | null | python/ray/serve/tests/test_deployment_state.py | jianoaix/ray | 1701b923bc83905f8961c06a6a173e3eba46a936 | [
"Apache-2.0"
] | null | null | null | from dataclasses import dataclass
import os
import sys
import time
from typing import Any, Dict, List, Optional, Tuple
from unittest.mock import patch, Mock
import pytest
import ray
from ray.actor import ActorHandle
from ray.serve.common import (
DeploymentConfig,
DeploymentInfo,
DeploymentStatus,
ReplicaConfig,
ReplicaTag,
ReplicaName,
)
from ray.serve.deployment_state import (
DeploymentState,
DeploymentStateManager,
DeploymentVersion,
DeploymentReplica,
ReplicaStartupStatus,
ReplicaState,
ReplicaStateContainer,
VersionedReplica,
CHECKPOINT_KEY,
rank_replicas_for_stopping,
)
from ray.serve.storage.kv_store import RayLocalKVStore
from ray.serve.utils import get_random_letters
class MockReplicaActorWrapper:
def __init__(
self,
actor_name: str,
detached: bool,
controller_name: str,
replica_tag: ReplicaTag,
deployment_name: str,
):
self._actor_name = actor_name
self._replica_tag = replica_tag
self._deployment_name = deployment_name
# Will be set when `start()` is called.
self.started = False
# Will be set when `recover()` is called.
self.recovering = False
# Will be set when `start()` is called.
self.version = None
# Initial state for a replica is PENDING_ALLOCATION.
self.ready = ReplicaStartupStatus.PENDING_ALLOCATION
# Will be set when `graceful_stop()` is called.
self.stopped = False
# Expected to be set in the test.
self.done_stopping = False
# Will be set when `force_stop()` is called.
self.force_stopped_counter = 0
# Will be cleaned up when `cleanup()` is called.
self.cleaned_up = False
# Will be set when `check_health()` is called.
self.health_check_called = False
# Returned by the health check.
self.healthy = True
@property
def replica_tag(self) -> str:
return str(self._replica_tag)
@property
def deployment_name(self) -> str:
return self._deployment_name
@property
def actor_handle(self) -> ActorHandle:
return None
@property
def max_concurrent_queries(self) -> int:
return 100
@property
def node_id(self) -> Optional[str]:
if self.ready == ReplicaStartupStatus.SUCCEEDED or self.started:
return "node-id"
return None
def set_ready(self):
self.ready = ReplicaStartupStatus.SUCCEEDED
def set_failed_to_start(self):
self.ready = ReplicaStartupStatus.FAILED
def set_done_stopping(self):
self.done_stopping = True
def set_unhealthy(self):
self.healthy = False
def set_starting_version(self, version: DeploymentVersion):
"""Mocked deployment_worker return version from reconfigure()"""
self.starting_version = version
def start(self, deployment_info: DeploymentInfo, version: DeploymentVersion):
self.started = True
self.version = version
self.deployment_info = deployment_info
def update_user_config(self, user_config: Any):
self.started = True
self.version = DeploymentVersion(
self.version.code_version, user_config=user_config
)
def recover(self):
self.recovering = True
self.started = False
self.version = None
def check_ready(self) -> ReplicaStartupStatus:
ready = self.ready
self.ready = ReplicaStartupStatus.PENDING_INITIALIZATION
if ready == ReplicaStartupStatus.SUCCEEDED and self.recovering:
self.recovering = False
self.started = True
self.version = self.starting_version
return ready, self.version
def resource_requirements(self) -> Tuple[str, str]:
assert self.started
return str({"REQUIRED_RESOURCE": 1.0}), str({"AVAILABLE_RESOURCE": 1.0})
@property
def actor_resources(self) -> Dict[str, float]:
return {"CPU": 0.1}
@property
def available_resources(self) -> Dict[str, float]:
# Only used to print a warning.
return {}
def graceful_stop(self) -> None:
assert self.started
self.stopped = True
return self.deployment_info.deployment_config.graceful_shutdown_timeout_s
def check_stopped(self) -> bool:
return self.done_stopping
def force_stop(self):
self.force_stopped_counter += 1
def cleanup(self):
self.cleaned_up = True
def check_health(self):
self.health_check_called = True
return self.healthy
def deployment_info(
version: Optional[str] = None,
num_replicas: Optional[int] = 1,
user_config: Optional[Any] = None,
**config_opts,
) -> Tuple[DeploymentInfo, DeploymentVersion]:
info = DeploymentInfo(
version=version,
start_time_ms=0,
deployment_config=DeploymentConfig(
num_replicas=num_replicas, user_config=user_config, **config_opts
),
replica_config=ReplicaConfig.create(lambda x: x),
deployer_job_id=ray.JobID.nil(),
)
if version is not None:
code_version = version
else:
code_version = get_random_letters()
version = DeploymentVersion(code_version, info.deployment_config.user_config)
return info, version
class MockTimer:
def __init__(self, start_time=None):
if start_time is None:
start_time = time.time()
self._curr = start_time
def time(self):
return self._curr
def advance(self, by):
self._curr += by
@pytest.fixture
def mock_deployment_state() -> Tuple[DeploymentState, Mock, Mock]:
timer = MockTimer()
with patch(
"ray.serve.deployment_state.ActorReplicaWrapper", new=MockReplicaActorWrapper
), patch("time.time", new=timer.time), patch(
"ray.serve.long_poll.LongPollHost"
) as mock_long_poll:
deployment_state = DeploymentState(
"name", "name", True, mock_long_poll, lambda: None
)
yield deployment_state, timer
def replica(version: Optional[DeploymentVersion] = None) -> VersionedReplica:
if version is None:
version = DeploymentVersion(get_random_letters(), None)
class MockVersionedReplica(VersionedReplica):
def __init__(self, version: DeploymentVersion):
self._version = version
@property
def version(self):
return self._version
return MockVersionedReplica(version)
class TestReplicaStateContainer:
def test_count(self):
c = ReplicaStateContainer()
r1, r2, r3 = (
replica(DeploymentVersion("1")),
replica(DeploymentVersion("2")),
replica(DeploymentVersion("2")),
)
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert c.count() == 3
# Test filtering by state.
assert c.count() == c.count(
states=[ReplicaState.STARTING, ReplicaState.STOPPING]
)
assert c.count(states=[ReplicaState.STARTING]) == 2
assert c.count(states=[ReplicaState.STOPPING]) == 1
# Test filtering by version.
assert c.count(version=DeploymentVersion("1")) == 1
assert c.count(version=DeploymentVersion("2")) == 2
assert c.count(version=DeploymentVersion("3")) == 0
assert c.count(exclude_version=DeploymentVersion("1")) == 2
assert c.count(exclude_version=DeploymentVersion("2")) == 1
assert c.count(exclude_version=DeploymentVersion("3")) == 3
# Test filtering by state and version.
assert (
c.count(version=DeploymentVersion("1"), states=[ReplicaState.STARTING]) == 1
)
assert (
c.count(version=DeploymentVersion("3"), states=[ReplicaState.STARTING]) == 0
)
assert (
c.count(
version=DeploymentVersion("2"),
states=[ReplicaState.STARTING, ReplicaState.STOPPING],
)
== 2
)
assert (
c.count(
exclude_version=DeploymentVersion("1"), states=[ReplicaState.STARTING]
)
== 1
)
assert (
c.count(
exclude_version=DeploymentVersion("3"), states=[ReplicaState.STARTING]
)
== 2
)
assert (
c.count(
exclude_version=DeploymentVersion("2"),
states=[ReplicaState.STARTING, ReplicaState.STOPPING],
)
== 1
)
def test_get(self):
c = ReplicaStateContainer()
r1, r2, r3 = replica(), replica(), replica()
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert c.get() == [r1, r2, r3]
assert c.get() == c.get([ReplicaState.STARTING, ReplicaState.STOPPING])
assert c.get([ReplicaState.STARTING]) == [r1, r2]
assert c.get([ReplicaState.STOPPING]) == [r3]
def test_pop_basic(self):
c = ReplicaStateContainer()
r1, r2, r3 = replica(), replica(), replica()
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert c.pop() == [r1, r2, r3]
assert not c.pop()
def test_pop_exclude_version(self):
c = ReplicaStateContainer()
r1, r2, r3 = (
replica(DeploymentVersion("1")),
replica(DeploymentVersion("1")),
replica(DeploymentVersion("2")),
)
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STARTING, r3)
assert c.pop(exclude_version=DeploymentVersion("1")) == [r3]
assert not c.pop(exclude_version=DeploymentVersion("1"))
assert c.pop(exclude_version=DeploymentVersion("2")) == [r1, r2]
assert not c.pop(exclude_version=DeploymentVersion("2"))
assert not c.pop()
def test_pop_max_replicas(self):
c = ReplicaStateContainer()
r1, r2, r3 = replica(), replica(), replica()
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert not c.pop(max_replicas=0)
assert len(c.pop(max_replicas=1)) == 1
assert len(c.pop(max_replicas=2)) == 2
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert len(c.pop(max_replicas=10)) == 3
def test_pop_states(self):
c = ReplicaStateContainer()
r1, r2, r3, r4 = replica(), replica(), replica(), replica()
# Check popping single state.
c.add(ReplicaState.STOPPING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert c.pop(states=[ReplicaState.STARTING]) == [r2]
assert not c.pop(states=[ReplicaState.STARTING])
assert c.pop(states=[ReplicaState.STOPPING]) == [r1, r3]
assert not c.pop(states=[ReplicaState.STOPPING])
# Check popping multiple states. Ordering of states should be
# preserved.
c.add(ReplicaState.STOPPING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
c.add(ReplicaState.STARTING, r4)
assert c.pop(states=[ReplicaState.STOPPING, ReplicaState.STARTING]) == [
r1,
r3,
r2,
r4,
]
assert not c.pop(states=[ReplicaState.STOPPING, ReplicaState.STARTING])
assert not c.pop(states=[ReplicaState.STOPPING])
assert not c.pop(states=[ReplicaState.STARTING])
assert not c.pop()
def test_pop_integration(self):
c = ReplicaStateContainer()
r1, r2, r3, r4 = (
replica(DeploymentVersion("1")),
replica(DeploymentVersion("2")),
replica(DeploymentVersion("2")),
replica(DeploymentVersion("3")),
)
c.add(ReplicaState.STOPPING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.RUNNING, r3)
c.add(ReplicaState.RUNNING, r4)
assert not c.pop(
exclude_version=DeploymentVersion("1"), states=[ReplicaState.STOPPING]
)
assert (
c.pop(
exclude_version=DeploymentVersion("1"),
states=[ReplicaState.RUNNING],
max_replicas=1,
)
== [r3]
)
assert (
c.pop(
exclude_version=DeploymentVersion("1"),
states=[ReplicaState.RUNNING],
max_replicas=1,
)
== [r4]
)
c.add(ReplicaState.RUNNING, r3)
c.add(ReplicaState.RUNNING, r4)
assert c.pop(
exclude_version=DeploymentVersion("1"), states=[ReplicaState.RUNNING]
) == [r3, r4]
assert c.pop(
exclude_version=DeploymentVersion("1"), states=[ReplicaState.STARTING]
) == [r2]
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.RUNNING, r3)
c.add(ReplicaState.RUNNING, r4)
assert (
c.pop(
exclude_version=DeploymentVersion("1"),
states=[ReplicaState.RUNNING, ReplicaState.STARTING],
)
== [r3, r4, r2]
)
assert (
c.pop(
exclude_version=DeploymentVersion("nonsense"),
states=[ReplicaState.STOPPING],
)
== [r1]
)
def check_counts(
deployment_state: DeploymentState,
total: Optional[int] = None,
version: Optional[str] = None,
by_state: Optional[List[Tuple[ReplicaState, int]]] = None,
):
if total is not None:
assert deployment_state._replicas.count(version=version) == total
if by_state is not None:
for state, count in by_state:
assert isinstance(state, ReplicaState)
assert isinstance(count, int) and count >= 0
curr_count = deployment_state._replicas.count(
version=version, states=[state]
)
msg = f"Expected {count} for state {state} but got {curr_count}."
assert curr_count == count, msg
def test_create_delete_single_replica(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info()
updating = deployment_state.deploy(b_info_1)
assert updating
# Single replica should be created.
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
# update() should not transition the state if the replica isn't ready.
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
deployment_state._replicas.get()[0]._actor.set_ready()
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Now the replica should be marked running.
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Removing the replica should transition it to stopping.
deployment_state.delete()
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
assert deployment_state._replicas.get()[0]._actor.stopped
assert not deployment_state._replicas.get()[0]._actor.cleaned_up
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Once it's done stopping, replica should be removed.
replica = deployment_state._replicas.get()[0]
replica._actor.set_done_stopping()
deleted = deployment_state.update()
assert deleted
check_counts(deployment_state, total=0)
assert replica._actor.cleaned_up
def test_force_kill(mock_deployment_state):
deployment_state, timer = mock_deployment_state
grace_period_s = 10
b_info_1, b_version_1 = deployment_info(graceful_shutdown_timeout_s=grace_period_s)
# Create and delete the deployment.
deployment_state.deploy(b_info_1)
deployment_state.update()
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state.update()
deployment_state.delete()
deployment_state.update()
# Replica should remain in STOPPING until it finishes.
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
assert deployment_state._replicas.get()[0]._actor.stopped
for _ in range(10):
deployment_state.update()
# force_stop shouldn't be called until after the timer.
assert not deployment_state._replicas.get()[0]._actor.force_stopped_counter
assert not deployment_state._replicas.get()[0]._actor.cleaned_up
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
# Advance the timer, now the replica should be force stopped.
timer.advance(grace_period_s + 0.1)
deployment_state.update()
assert deployment_state._replicas.get()[0]._actor.force_stopped_counter == 1
assert not deployment_state._replicas.get()[0]._actor.cleaned_up
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Force stop should be called repeatedly until the replica stops.
deployment_state.update()
assert deployment_state._replicas.get()[0]._actor.force_stopped_counter == 2
assert not deployment_state._replicas.get()[0]._actor.cleaned_up
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Once the replica is done stopping, it should be removed.
replica = deployment_state._replicas.get()[0]
replica._actor.set_done_stopping()
deleted = deployment_state.update()
assert deleted
check_counts(deployment_state, total=0)
assert replica._actor.cleaned_up
def test_redeploy_same_version(mock_deployment_state):
# Redeploying with the same version and code should do nothing.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Test redeploying while the initial deployment is still pending.
updating = deployment_state.deploy(b_info_1)
assert not updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
# Mark the replica ready. After this, the initial goal should be complete.
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Test redeploying after the initial deployment has finished.
updating = deployment_state.deploy(b_info_1)
assert not updating
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_redeploy_no_version(mock_deployment_state):
# Redeploying with no version specified (`None`) should always redeploy
# the replicas.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(version=None)
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Test redeploying while the initial deployment is still pending.
updating = deployment_state.deploy(b_info_1)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# The initial replica should be stopping. The new replica shouldn't start
# until the old one has completely stopped.
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=0)
# Now that the old replica has stopped, the new replica should be started.
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Check that the new replica has started.
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
deployment_state.update()
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Now deploy a third version after the transition has finished.
b_info_3, b_version_3 = deployment_info(version="3")
updating = deployment_state.deploy(b_info_3)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=0)
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deleted = deployment_state.update()
assert not deleted
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_redeploy_new_version(mock_deployment_state):
# Redeploying with a new version should start a new replica.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Test redeploying while the initial deployment is still pending.
b_info_2, b_version_2 = deployment_info(version="2")
updating = deployment_state.deploy(b_info_2)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# The initial replica should be stopping. The new replica shouldn't start
# until the old one has completely stopped.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=0)
# Now that the old replica has stopped, the new replica should be started.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
# Check that the new replica has started.
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
deployment_state.update()
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Now deploy a third version after the transition has finished.
b_info_3, b_version_3 = deployment_info(version="3")
updating = deployment_state.deploy(b_info_3)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=0)
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
check_counts(
deployment_state,
version=b_version_3,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
deleted = deployment_state.update()
assert not deleted
check_counts(
deployment_state,
version=b_version_3,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_deploy_new_config_same_version(mock_deployment_state):
# Deploying a new config with the same version should not deploy a new
# replica.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(version="1")
updated = deployment_state.deploy(b_info_1)
assert updated
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Create the replica initially.
deployment_state.update()
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Update to a new config without changing the version.
b_info_2, b_version_2 = deployment_info(version="1", user_config={"hello": "world"})
updated = deployment_state.deploy(b_info_2)
assert updated
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.UPDATING, 1)],
)
# Mark the replica as ready.
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_deploy_new_config_new_version(mock_deployment_state):
# Deploying a new config with a new version should deploy a new replica.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
# Create the replica initially.
deployment_state.update()
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Update to a new config and a new version.
b_info_2, b_version_2 = deployment_info(version="2", user_config={"hello": "world"})
updating = deployment_state.deploy(b_info_2)
assert updating
# New version shouldn't start until old version is stopped.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
assert deployment_state._replicas.count() == 0
check_counts(deployment_state, total=0)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Now the new version should be started.
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
# Check that the new version is now running.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_initial_deploy_no_throttling(mock_deployment_state):
# All replicas should be started at once for a new deployment.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=10, version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.STARTING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
# Check that the new replicas have started.
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.RUNNING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_new_version_deploy_throttling(mock_deployment_state):
# All replicas should be started at once for a new deployment.
# When the version is updated, it should be throttled. The throttling
# should apply to both code version and user config updates.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(
num_replicas=10, version="1", user_config="1"
)
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.STARTING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
# Check that the new replicas have started.
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.RUNNING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Now deploy a new version. Two old replicas should be stopped.
b_info_2, b_version_2 = deployment_info(
num_replicas=10, version="2", user_config="2"
)
updating = deployment_state.deploy(b_info_2)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=10,
by_state=[(ReplicaState.RUNNING, 8), (ReplicaState.STOPPING, 2)],
)
# Mark only one of the replicas as done stopping.
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=9,
by_state=[(ReplicaState.RUNNING, 8), (ReplicaState.STOPPING, 1)],
)
# Now one of the new version replicas should start up.
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=9,
by_state=[(ReplicaState.RUNNING, 8), (ReplicaState.STOPPING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
# Mark the new version replica as ready. Another old version replica
# should subsequently be stopped.
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
deployment_state.update()
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=9,
by_state=[(ReplicaState.RUNNING, 7), (ReplicaState.STOPPING, 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
# Mark the old replicas as done stopping.
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
1
]._actor.set_done_stopping()
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Old replicas should be stopped and new versions started in batches of 2.
new_replicas = 1
old_replicas = 9
while old_replicas > 3:
deployment_state.update()
check_counts(deployment_state, total=8)
check_counts(
deployment_state,
version=b_version_1,
total=old_replicas - 2,
by_state=[(ReplicaState.RUNNING, old_replicas - 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=new_replicas,
by_state=[(ReplicaState.RUNNING, new_replicas)],
)
# Replicas starting up.
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=old_replicas - 2,
by_state=[(ReplicaState.RUNNING, old_replicas - 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=new_replicas + 2,
by_state=[(ReplicaState.RUNNING, new_replicas), (ReplicaState.STARTING, 2)],
)
# Set both ready.
deployment_state._replicas.get(states=[ReplicaState.STARTING])[
0
]._actor.set_ready()
deployment_state._replicas.get(states=[ReplicaState.STARTING])[
1
]._actor.set_ready()
new_replicas += 2
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=old_replicas - 2,
by_state=[(ReplicaState.RUNNING, old_replicas - 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=new_replicas,
by_state=[(ReplicaState.RUNNING, new_replicas)],
)
# Two more old replicas should be stopped.
old_replicas -= 2
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=old_replicas,
by_state=[
(ReplicaState.RUNNING, old_replicas - 2),
(ReplicaState.STOPPING, 2),
],
)
check_counts(
deployment_state,
version=b_version_2,
total=new_replicas,
by_state=[(ReplicaState.RUNNING, new_replicas)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
1
]._actor.set_done_stopping()
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# 2 left to update.
deployment_state.update()
check_counts(deployment_state, total=8)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=new_replicas,
by_state=[(ReplicaState.RUNNING, 7)],
)
# Replicas starting up.
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=9,
by_state=[(ReplicaState.RUNNING, 7), (ReplicaState.STARTING, 2)],
)
# Set both ready.
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
deployment_state._replicas.get(states=[ReplicaState.STARTING])[1]._actor.set_ready()
# One replica remaining to update.
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=9,
by_state=[(ReplicaState.RUNNING, 9)],
)
# The last replica should be stopped.
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=9,
by_state=[(ReplicaState.RUNNING, 9)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=9)
check_counts(
deployment_state,
version=b_version_2,
total=9,
by_state=[(ReplicaState.RUNNING, 9)],
)
# The last replica should start up.
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_2,
total=10,
by_state=[(ReplicaState.RUNNING, 9), (ReplicaState.STARTING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Set both ready.
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_2,
total=10,
by_state=[(ReplicaState.RUNNING, 10)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_reconfigure_throttling(mock_deployment_state):
# All replicas should be started at once for a new deployment.
# When the version is updated, it should be throttled.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(
num_replicas=2, version="1", user_config="1"
)
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
# Check that the new replicas have started.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Now deploy a new user_config. One replica should be updated.
b_info_2, b_version_2 = deployment_info(
num_replicas=2, version="1", user_config="2"
)
updating = deployment_state.deploy(b_info_2)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.UPDATING, 1)],
)
# Mark the updating replica as ready.
deployment_state._replicas.get(states=[ReplicaState.UPDATING])[0]._actor.set_ready()
# The updated replica should now be RUNNING.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# The second replica should now be updated.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.UPDATING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Mark the updating replica as ready.
deployment_state._replicas.get(states=[ReplicaState.UPDATING])[0]._actor.set_ready()
# Both replicas should now be RUNNING.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_new_version_and_scale_down(mock_deployment_state):
# Test the case when we reduce the number of replicas and change the
# version at the same time. First the number of replicas should be
# turned down, then the rolling update should happen.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=10, version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.STARTING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
# Check that the new replicas have started.
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.RUNNING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Now deploy a new version and scale down the number of replicas to 2.
# First, 8 old replicas should be stopped to bring it down to the target.
b_info_2, b_version_2 = deployment_info(num_replicas=2, version="2")
updating = deployment_state.deploy(b_info_2)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=10,
by_state=[(ReplicaState.RUNNING, 2), (ReplicaState.STOPPING, 8)],
)
# Mark only one of the replicas as done stopping.
# This should not yet trigger the rolling update because there are still
# stopping replicas.
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=9)
check_counts(
deployment_state,
version=b_version_1,
total=9,
by_state=[(ReplicaState.RUNNING, 2), (ReplicaState.STOPPING, 7)],
)
# Stop the remaining replicas.
for replica in deployment_state._replicas.get(states=[ReplicaState.STOPPING]):
replica._actor.set_done_stopping()
# Now the rolling update should trigger, stopping one of the old replicas.
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_1,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_1,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.STOPPING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
# Old version stopped, new version should start up.
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
# New version is started, final old version replica should be stopped.
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
# Final old version replica is stopped, final new version replica
# should be started.
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.STARTING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_new_version_and_scale_up(mock_deployment_state):
# Test the case when we increase the number of replicas and change the
# version at the same time. The new replicas should all immediately be
# turned up. When they're up, rolling update should trigger.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2, version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
# Check that the new replicas have started.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Now deploy a new version and scale up the number of replicas to 10.
# 8 new replicas should be started.
b_info_2, b_version_2 = deployment_info(num_replicas=10, version="2")
updating = deployment_state.deploy(b_info_2)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=8,
by_state=[(ReplicaState.STARTING, 8)],
)
# Mark the new replicas as ready.
for replica in deployment_state._replicas.get(states=[ReplicaState.STARTING]):
replica._actor.set_ready()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=8,
by_state=[(ReplicaState.RUNNING, 8)],
)
# Now that the new version replicas are up, rolling update should start.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=2,
by_state=[(ReplicaState.RUNNING, 0), (ReplicaState.STOPPING, 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=8,
by_state=[(ReplicaState.RUNNING, 8)],
)
# Mark the replicas as done stopping.
for replica in deployment_state._replicas.get(states=[ReplicaState.STOPPING]):
replica._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=8)
check_counts(
deployment_state,
version=b_version_2,
total=8,
by_state=[(ReplicaState.RUNNING, 8)],
)
# The remaining replicas should be started.
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_2,
total=10,
by_state=[(ReplicaState.RUNNING, 8), (ReplicaState.STARTING, 2)],
)
# Mark the remaining replicas as ready.
for replica in deployment_state._replicas.get(states=[ReplicaState.STARTING]):
replica._actor.set_ready()
# All new replicas should be up and running.
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_2,
total=10,
by_state=[(ReplicaState.RUNNING, 10)],
)
deployment_state.update()
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_health_check(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2, version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
# Health check shouldn't be called until it's ready.
assert not replica._actor.health_check_called
# Check that the new replicas have started.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
deployment_state.update()
for replica in deployment_state._replicas.get():
# Health check shouldn't be called until it's ready.
assert replica._actor.health_check_called
# Mark one replica unhealthy. It should be stopped.
deployment_state._replicas.get()[0]._actor.set_unhealthy()
deployment_state.update()
check_counts(
deployment_state,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.STOPPING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
replica = deployment_state._replicas.get(states=[ReplicaState.STOPPING])[0]
replica._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
deployment_state.update()
check_counts(
deployment_state,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.STARTING, 1)],
)
replica = deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]
replica._actor.set_ready()
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_update_while_unhealthy(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2, version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
# Health check shouldn't be called until it's ready.
assert not replica._actor.health_check_called
# Check that the new replicas have started.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
deployment_state.update()
for replica in deployment_state._replicas.get():
# Health check shouldn't be called until it's ready.
assert replica._actor.health_check_called
# Mark one replica unhealthy. It should be stopped.
deployment_state._replicas.get()[0]._actor.set_unhealthy()
deployment_state.update()
check_counts(
deployment_state,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.STOPPING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
replica = deployment_state._replicas.get(states=[ReplicaState.STOPPING])[0]
replica._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
# Now deploy a new version (e.g., a rollback). This should update the status
# to UPDATING and then it should eventually become healthy.
b_info_2, b_version_2 = deployment_info(num_replicas=2, version="2")
updating = deployment_state.deploy(b_info_2)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Check that a failure in the old version replica does not mark the
# deployment as UNHEALTHY.
deployment_state._replicas.get(states=[ReplicaState.RUNNING])[
0
]._actor.set_unhealthy()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
replica = deployment_state._replicas.get(states=[ReplicaState.STOPPING])[0]
replica._actor.set_done_stopping()
# Another replica of the new version should get started.
deployment_state.update()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.STARTING, 2)],
)
# Mark new version replicas as ready.
for replica in deployment_state._replicas.get(states=[ReplicaState.STARTING]):
replica._actor.set_ready()
# Both replicas should be RUNNING, deployment should be HEALTHY.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def _constructor_failure_loop_two_replica(deployment_state, num_loops):
"""Helper function to exact constructor failure loops."""
for i in range(num_loops):
# Single replica should be created.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state._replica_constructor_retry_counter == i * 2
replica_1 = deployment_state._replicas.get()[0]
replica_2 = deployment_state._replicas.get()[1]
replica_1._actor.set_failed_to_start()
replica_2._actor.set_failed_to_start()
# Now the replica should be marked SHOULD_STOP after failure.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STOPPING, 2)])
# Once it's done stopping, replica should be removed.
replica_1._actor.set_done_stopping()
replica_2._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=0)
def test_deploy_with_consistent_constructor_failure(mock_deployment_state):
"""
Test deploy() multiple replicas with consistent constructor failure.
The deployment should get marked FAILED.
"""
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2)
updating = deployment_state.deploy(b_info_1)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
_constructor_failure_loop_two_replica(deployment_state, 3)
assert deployment_state._replica_constructor_retry_counter == 6
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
check_counts(deployment_state, total=0)
assert deployment_state.curr_status_info.message != ""
def test_deploy_with_partial_constructor_failure(mock_deployment_state):
"""
Test deploy() multiple replicas with constructor failure exceedining
pre-set limit but achieved partial success with at least 1 running replica.
Ensures:
1) Deployment status doesn't get marked FAILED.
2) There should be expected # of RUNNING replicas eventually that
matches user intent
3) Replica counter set as -1 to stop tracking current goal as it's
already completed
Same testing for same test case in test_deploy.py.
"""
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2)
updating = deployment_state.deploy(b_info_1)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
_constructor_failure_loop_two_replica(deployment_state, 2)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state._replica_constructor_retry_counter == 4
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Let one replica reach RUNNING state while the other still fails
replica_1 = deployment_state._replicas.get()[0]
replica_2 = deployment_state._replicas.get()[1]
replica_1._actor.set_ready()
replica_2._actor.set_failed_to_start()
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STOPPING, 1)])
# Ensure failed to start replica is removed
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STOPPING, 1)])
replica_2._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 0)])
# New update cycle should spawn new replica after previous one is removed
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 1)])
# Set the starting one to fail again and trigger retry limit
starting_replica = deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]
starting_replica._actor.set_failed_to_start()
deployment_state.update()
# Ensure our goal returned with construtor start counter reset
assert deployment_state._replica_constructor_retry_counter == -1
# Deployment should NOT be considered complete yet
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STOPPING, 1)])
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STOPPING, 1)])
starting_replica = deployment_state._replicas.get(states=[ReplicaState.STOPPING])[0]
starting_replica._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 0)])
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 1)])
starting_replica = deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]
starting_replica._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
# Deployment should be considered complete
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_deploy_with_transient_constructor_failure(mock_deployment_state):
"""
Test deploy() multiple replicas with transient constructor failure.
Ensures:
1) Deployment status gets marked as RUNNING.
2) There should be expected # of RUNNING replicas eventually that
matches user intent.
3) Replica counter set as -1 to stop tracking current goal as it's
already completed.
Same testing for same test case in test_deploy.py.
"""
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2)
updating = deployment_state.deploy(b_info_1)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Burn 4 retries from both replicas.
_constructor_failure_loop_two_replica(deployment_state, 2)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Let both replicas succeed in last try.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
assert deployment_state._replica_constructor_retry_counter == 4
replica_1 = deployment_state._replicas.get()[0]
replica_2 = deployment_state._replicas.get()[1]
replica_1._actor.set_ready()
replica_2._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state._replica_constructor_retry_counter == 4
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
@pytest.fixture
def mock_deployment_state_manager() -> Tuple[DeploymentStateManager, Mock]:
timer = MockTimer()
with patch(
"ray.serve.deployment_state.ActorReplicaWrapper", new=MockReplicaActorWrapper
), patch("time.time", new=timer.time), patch(
"ray.serve.long_poll.LongPollHost"
) as mock_long_poll:
kv_store = RayLocalKVStore("TEST_DB", "test_kv_store.db")
all_current_actor_names = []
deployment_state_manager = DeploymentStateManager(
"name",
True,
kv_store,
mock_long_poll,
all_current_actor_names,
)
yield deployment_state_manager, timer
# Clear checkpoint at the end of each test
kv_store.delete(CHECKPOINT_KEY)
if sys.platform != "win32":
# This line fails on windows with a PermissionError.
os.remove("test_kv_store.db")
def test_shutdown(mock_deployment_state_manager):
"""
Test that shutdown waits for all deployments to be deleted and they
are force-killed without a grace period.
"""
deployment_state_manager, timer = mock_deployment_state_manager
tag = "test"
grace_period_s = 10
b_info_1, b_version_1 = deployment_info(graceful_shutdown_timeout_s=grace_period_s)
updating = deployment_state_manager.deploy(tag, b_info_1)
assert updating
deployment_state = deployment_state_manager._deployment_states[tag]
# Single replica should be created.
deployment_state_manager.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
deployment_state._replicas.get()[0]._actor.set_ready()
# Now the replica should be marked running.
deployment_state_manager.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
# Test shutdown flow
assert not deployment_state._replicas.get()[0]._actor.stopped
deployment_state_manager.shutdown()
timer.advance(grace_period_s + 0.1)
deployment_state_manager.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
assert deployment_state._replicas.get()[0]._actor.stopped
assert not deployment_state._replicas.get()[0]._actor.cleaned_up
assert len(deployment_state_manager.get_deployment_statuses()) > 0
# Once it's done stopping, replica should be removed.
replica = deployment_state._replicas.get()[0]
replica._actor.set_done_stopping()
deployment_state_manager.update()
check_counts(deployment_state, total=0)
assert replica._actor.cleaned_up
assert len(deployment_state_manager.get_deployment_statuses()) == 0
def test_resume_deployment_state_from_replica_tags(mock_deployment_state_manager):
deployment_state_manager, timer = mock_deployment_state_manager
tag = "test"
# Step 1: Create some deployment info with actors in running state
b_info_1, b_version_1 = deployment_info(version="1")
updating = deployment_state_manager.deploy(tag, b_info_1)
assert updating
deployment_state = deployment_state_manager._deployment_states[tag]
# Single replica should be created.
deployment_state_manager.update()
check_counts(
deployment_state,
total=1,
version=b_version_1,
by_state=[(ReplicaState.STARTING, 1)],
)
deployment_state._replicas.get()[0]._actor.set_ready()
# Now the replica should be marked running.
deployment_state_manager.update()
check_counts(
deployment_state,
total=1,
version=b_version_1,
by_state=[(ReplicaState.RUNNING, 1)],
)
mocked_replica = deployment_state._replicas.get(states=[ReplicaState.RUNNING])[0]
# Step 2: Delete _replicas from deployment_state
deployment_state._replicas = ReplicaStateContainer()
# Step 3: Create new deployment_state by resuming from passed in replicas
deployment_state_manager._recover_from_checkpoint(
[ReplicaName.prefix + mocked_replica.replica_tag]
)
# Step 4: Ensure new deployment_state is correct
# deployment state behind "test" is re-created in recovery flow
deployment_state = deployment_state_manager._deployment_states[tag]
# Ensure recovering replica begin with no version assigned
check_counts(
deployment_state, total=1, version=None, by_state=[(ReplicaState.RECOVERING, 1)]
)
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state._replicas.get()[0]._actor.set_starting_version(b_version_1)
# Now the replica should be marked running.
deployment_state_manager.update()
check_counts(
deployment_state,
total=1,
version=b_version_1,
by_state=[(ReplicaState.RUNNING, 1)],
)
# Ensure same replica name is used
assert deployment_state._replicas.get()[0].replica_tag == mocked_replica.replica_tag
def test_stopping_replicas_ranking():
@dataclass
class MockReplica:
actor_node_id: str
def compare(before, after):
before_replicas = [MockReplica(item) for item in before]
after_replicas = [MockReplica(item) for item in after]
result_replicas = rank_replicas_for_stopping(before_replicas)
assert result_replicas == after_replicas
compare(
[None, 1, None], [None, None, 1]
) # replicas not allocated should be stopped first
compare(
[3, 3, 3, 2, 2, 1], [1, 2, 2, 3, 3, 3]
) # prefer to stop dangling replicas first
compare([2, 2, 3, 3], [2, 2, 3, 3]) # if equal, ordering should be kept
def test_resource_requirements_none(mock_deployment_state):
"""Ensure resource_requirements doesn't break if a requirement is None"""
class FakeActor:
actor_resources = {"num_cpus": 2, "fake": None}
available_resources = {}
# Make a DeploymentReplica just to accesss its resource_requirement function
replica = DeploymentReplica(None, None, None, None, None)
replica._actor = FakeActor()
# resource_requirements() should not error
replica.resource_requirements()
if __name__ == "__main__":
sys.exit(pytest.main(["-v", "-s", __file__]))
| 34.36355 | 88 | 0.688788 | from dataclasses import dataclass
import os
import sys
import time
from typing import Any, Dict, List, Optional, Tuple
from unittest.mock import patch, Mock
import pytest
import ray
from ray.actor import ActorHandle
from ray.serve.common import (
DeploymentConfig,
DeploymentInfo,
DeploymentStatus,
ReplicaConfig,
ReplicaTag,
ReplicaName,
)
from ray.serve.deployment_state import (
DeploymentState,
DeploymentStateManager,
DeploymentVersion,
DeploymentReplica,
ReplicaStartupStatus,
ReplicaState,
ReplicaStateContainer,
VersionedReplica,
CHECKPOINT_KEY,
rank_replicas_for_stopping,
)
from ray.serve.storage.kv_store import RayLocalKVStore
from ray.serve.utils import get_random_letters
class MockReplicaActorWrapper:
def __init__(
self,
actor_name: str,
detached: bool,
controller_name: str,
replica_tag: ReplicaTag,
deployment_name: str,
):
self._actor_name = actor_name
self._replica_tag = replica_tag
self._deployment_name = deployment_name
self.started = False
self.recovering = False
self.version = None
self.ready = ReplicaStartupStatus.PENDING_ALLOCATION
self.stopped = False
self.done_stopping = False
self.force_stopped_counter = 0
self.cleaned_up = False
self.health_check_called = False
self.healthy = True
@property
def replica_tag(self) -> str:
return str(self._replica_tag)
@property
def deployment_name(self) -> str:
return self._deployment_name
@property
def actor_handle(self) -> ActorHandle:
return None
@property
def max_concurrent_queries(self) -> int:
return 100
@property
def node_id(self) -> Optional[str]:
if self.ready == ReplicaStartupStatus.SUCCEEDED or self.started:
return "node-id"
return None
def set_ready(self):
self.ready = ReplicaStartupStatus.SUCCEEDED
def set_failed_to_start(self):
self.ready = ReplicaStartupStatus.FAILED
def set_done_stopping(self):
self.done_stopping = True
def set_unhealthy(self):
self.healthy = False
def set_starting_version(self, version: DeploymentVersion):
self.starting_version = version
def start(self, deployment_info: DeploymentInfo, version: DeploymentVersion):
self.started = True
self.version = version
self.deployment_info = deployment_info
def update_user_config(self, user_config: Any):
self.started = True
self.version = DeploymentVersion(
self.version.code_version, user_config=user_config
)
def recover(self):
self.recovering = True
self.started = False
self.version = None
def check_ready(self) -> ReplicaStartupStatus:
ready = self.ready
self.ready = ReplicaStartupStatus.PENDING_INITIALIZATION
if ready == ReplicaStartupStatus.SUCCEEDED and self.recovering:
self.recovering = False
self.started = True
self.version = self.starting_version
return ready, self.version
def resource_requirements(self) -> Tuple[str, str]:
assert self.started
return str({"REQUIRED_RESOURCE": 1.0}), str({"AVAILABLE_RESOURCE": 1.0})
@property
def actor_resources(self) -> Dict[str, float]:
return {"CPU": 0.1}
@property
def available_resources(self) -> Dict[str, float]:
return {}
def graceful_stop(self) -> None:
assert self.started
self.stopped = True
return self.deployment_info.deployment_config.graceful_shutdown_timeout_s
def check_stopped(self) -> bool:
return self.done_stopping
def force_stop(self):
self.force_stopped_counter += 1
def cleanup(self):
self.cleaned_up = True
def check_health(self):
self.health_check_called = True
return self.healthy
def deployment_info(
version: Optional[str] = None,
num_replicas: Optional[int] = 1,
user_config: Optional[Any] = None,
**config_opts,
) -> Tuple[DeploymentInfo, DeploymentVersion]:
info = DeploymentInfo(
version=version,
start_time_ms=0,
deployment_config=DeploymentConfig(
num_replicas=num_replicas, user_config=user_config, **config_opts
),
replica_config=ReplicaConfig.create(lambda x: x),
deployer_job_id=ray.JobID.nil(),
)
if version is not None:
code_version = version
else:
code_version = get_random_letters()
version = DeploymentVersion(code_version, info.deployment_config.user_config)
return info, version
class MockTimer:
def __init__(self, start_time=None):
if start_time is None:
start_time = time.time()
self._curr = start_time
def time(self):
return self._curr
def advance(self, by):
self._curr += by
@pytest.fixture
def mock_deployment_state() -> Tuple[DeploymentState, Mock, Mock]:
timer = MockTimer()
with patch(
"ray.serve.deployment_state.ActorReplicaWrapper", new=MockReplicaActorWrapper
), patch("time.time", new=timer.time), patch(
"ray.serve.long_poll.LongPollHost"
) as mock_long_poll:
deployment_state = DeploymentState(
"name", "name", True, mock_long_poll, lambda: None
)
yield deployment_state, timer
def replica(version: Optional[DeploymentVersion] = None) -> VersionedReplica:
if version is None:
version = DeploymentVersion(get_random_letters(), None)
class MockVersionedReplica(VersionedReplica):
def __init__(self, version: DeploymentVersion):
self._version = version
@property
def version(self):
return self._version
return MockVersionedReplica(version)
class TestReplicaStateContainer:
def test_count(self):
c = ReplicaStateContainer()
r1, r2, r3 = (
replica(DeploymentVersion("1")),
replica(DeploymentVersion("2")),
replica(DeploymentVersion("2")),
)
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert c.count() == 3
assert c.count() == c.count(
states=[ReplicaState.STARTING, ReplicaState.STOPPING]
)
assert c.count(states=[ReplicaState.STARTING]) == 2
assert c.count(states=[ReplicaState.STOPPING]) == 1
assert c.count(version=DeploymentVersion("1")) == 1
assert c.count(version=DeploymentVersion("2")) == 2
assert c.count(version=DeploymentVersion("3")) == 0
assert c.count(exclude_version=DeploymentVersion("1")) == 2
assert c.count(exclude_version=DeploymentVersion("2")) == 1
assert c.count(exclude_version=DeploymentVersion("3")) == 3
assert (
c.count(version=DeploymentVersion("1"), states=[ReplicaState.STARTING]) == 1
)
assert (
c.count(version=DeploymentVersion("3"), states=[ReplicaState.STARTING]) == 0
)
assert (
c.count(
version=DeploymentVersion("2"),
states=[ReplicaState.STARTING, ReplicaState.STOPPING],
)
== 2
)
assert (
c.count(
exclude_version=DeploymentVersion("1"), states=[ReplicaState.STARTING]
)
== 1
)
assert (
c.count(
exclude_version=DeploymentVersion("3"), states=[ReplicaState.STARTING]
)
== 2
)
assert (
c.count(
exclude_version=DeploymentVersion("2"),
states=[ReplicaState.STARTING, ReplicaState.STOPPING],
)
== 1
)
def test_get(self):
c = ReplicaStateContainer()
r1, r2, r3 = replica(), replica(), replica()
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert c.get() == [r1, r2, r3]
assert c.get() == c.get([ReplicaState.STARTING, ReplicaState.STOPPING])
assert c.get([ReplicaState.STARTING]) == [r1, r2]
assert c.get([ReplicaState.STOPPING]) == [r3]
def test_pop_basic(self):
c = ReplicaStateContainer()
r1, r2, r3 = replica(), replica(), replica()
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert c.pop() == [r1, r2, r3]
assert not c.pop()
def test_pop_exclude_version(self):
c = ReplicaStateContainer()
r1, r2, r3 = (
replica(DeploymentVersion("1")),
replica(DeploymentVersion("1")),
replica(DeploymentVersion("2")),
)
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STARTING, r3)
assert c.pop(exclude_version=DeploymentVersion("1")) == [r3]
assert not c.pop(exclude_version=DeploymentVersion("1"))
assert c.pop(exclude_version=DeploymentVersion("2")) == [r1, r2]
assert not c.pop(exclude_version=DeploymentVersion("2"))
assert not c.pop()
def test_pop_max_replicas(self):
c = ReplicaStateContainer()
r1, r2, r3 = replica(), replica(), replica()
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert not c.pop(max_replicas=0)
assert len(c.pop(max_replicas=1)) == 1
assert len(c.pop(max_replicas=2)) == 2
c.add(ReplicaState.STARTING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert len(c.pop(max_replicas=10)) == 3
def test_pop_states(self):
c = ReplicaStateContainer()
r1, r2, r3, r4 = replica(), replica(), replica(), replica()
c.add(ReplicaState.STOPPING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
assert c.pop(states=[ReplicaState.STARTING]) == [r2]
assert not c.pop(states=[ReplicaState.STARTING])
assert c.pop(states=[ReplicaState.STOPPING]) == [r1, r3]
assert not c.pop(states=[ReplicaState.STOPPING])
c.add(ReplicaState.STOPPING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.STOPPING, r3)
c.add(ReplicaState.STARTING, r4)
assert c.pop(states=[ReplicaState.STOPPING, ReplicaState.STARTING]) == [
r1,
r3,
r2,
r4,
]
assert not c.pop(states=[ReplicaState.STOPPING, ReplicaState.STARTING])
assert not c.pop(states=[ReplicaState.STOPPING])
assert not c.pop(states=[ReplicaState.STARTING])
assert not c.pop()
def test_pop_integration(self):
c = ReplicaStateContainer()
r1, r2, r3, r4 = (
replica(DeploymentVersion("1")),
replica(DeploymentVersion("2")),
replica(DeploymentVersion("2")),
replica(DeploymentVersion("3")),
)
c.add(ReplicaState.STOPPING, r1)
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.RUNNING, r3)
c.add(ReplicaState.RUNNING, r4)
assert not c.pop(
exclude_version=DeploymentVersion("1"), states=[ReplicaState.STOPPING]
)
assert (
c.pop(
exclude_version=DeploymentVersion("1"),
states=[ReplicaState.RUNNING],
max_replicas=1,
)
== [r3]
)
assert (
c.pop(
exclude_version=DeploymentVersion("1"),
states=[ReplicaState.RUNNING],
max_replicas=1,
)
== [r4]
)
c.add(ReplicaState.RUNNING, r3)
c.add(ReplicaState.RUNNING, r4)
assert c.pop(
exclude_version=DeploymentVersion("1"), states=[ReplicaState.RUNNING]
) == [r3, r4]
assert c.pop(
exclude_version=DeploymentVersion("1"), states=[ReplicaState.STARTING]
) == [r2]
c.add(ReplicaState.STARTING, r2)
c.add(ReplicaState.RUNNING, r3)
c.add(ReplicaState.RUNNING, r4)
assert (
c.pop(
exclude_version=DeploymentVersion("1"),
states=[ReplicaState.RUNNING, ReplicaState.STARTING],
)
== [r3, r4, r2]
)
assert (
c.pop(
exclude_version=DeploymentVersion("nonsense"),
states=[ReplicaState.STOPPING],
)
== [r1]
)
def check_counts(
deployment_state: DeploymentState,
total: Optional[int] = None,
version: Optional[str] = None,
by_state: Optional[List[Tuple[ReplicaState, int]]] = None,
):
if total is not None:
assert deployment_state._replicas.count(version=version) == total
if by_state is not None:
for state, count in by_state:
assert isinstance(state, ReplicaState)
assert isinstance(count, int) and count >= 0
curr_count = deployment_state._replicas.count(
version=version, states=[state]
)
msg = f"Expected {count} for state {state} but got {curr_count}."
assert curr_count == count, msg
def test_create_delete_single_replica(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info()
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
deployment_state._replicas.get()[0]._actor.set_ready()
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Now the replica should be marked running.
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Removing the replica should transition it to stopping.
deployment_state.delete()
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
assert deployment_state._replicas.get()[0]._actor.stopped
assert not deployment_state._replicas.get()[0]._actor.cleaned_up
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Once it's done stopping, replica should be removed.
replica = deployment_state._replicas.get()[0]
replica._actor.set_done_stopping()
deleted = deployment_state.update()
assert deleted
check_counts(deployment_state, total=0)
assert replica._actor.cleaned_up
def test_force_kill(mock_deployment_state):
deployment_state, timer = mock_deployment_state
grace_period_s = 10
b_info_1, b_version_1 = deployment_info(graceful_shutdown_timeout_s=grace_period_s)
deployment_state.deploy(b_info_1)
deployment_state.update()
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state.update()
deployment_state.delete()
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
assert deployment_state._replicas.get()[0]._actor.stopped
for _ in range(10):
deployment_state.update()
assert not deployment_state._replicas.get()[0]._actor.force_stopped_counter
assert not deployment_state._replicas.get()[0]._actor.cleaned_up
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
# Advance the timer, now the replica should be force stopped.
timer.advance(grace_period_s + 0.1)
deployment_state.update()
assert deployment_state._replicas.get()[0]._actor.force_stopped_counter == 1
assert not deployment_state._replicas.get()[0]._actor.cleaned_up
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Force stop should be called repeatedly until the replica stops.
deployment_state.update()
assert deployment_state._replicas.get()[0]._actor.force_stopped_counter == 2
assert not deployment_state._replicas.get()[0]._actor.cleaned_up
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Once the replica is done stopping, it should be removed.
replica = deployment_state._replicas.get()[0]
replica._actor.set_done_stopping()
deleted = deployment_state.update()
assert deleted
check_counts(deployment_state, total=0)
assert replica._actor.cleaned_up
def test_redeploy_same_version(mock_deployment_state):
# Redeploying with the same version and code should do nothing.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Test redeploying while the initial deployment is still pending.
updating = deployment_state.deploy(b_info_1)
assert not updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
# Mark the replica ready. After this, the initial goal should be complete.
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Test redeploying after the initial deployment has finished.
updating = deployment_state.deploy(b_info_1)
assert not updating
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_redeploy_no_version(mock_deployment_state):
# Redeploying with no version specified (`None`) should always redeploy
# the replicas.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(version=None)
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Test redeploying while the initial deployment is still pending.
updating = deployment_state.deploy(b_info_1)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# The initial replica should be stopping. The new replica shouldn't start
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=0)
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
deployment_state.update()
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
b_info_3, b_version_3 = deployment_info(version="3")
updating = deployment_state.deploy(b_info_3)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=0)
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deleted = deployment_state.update()
assert not deleted
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_redeploy_new_version(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
b_info_2, b_version_2 = deployment_info(version="2")
updating = deployment_state.deploy(b_info_2)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# until the old one has completely stopped.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=0)
# Now that the old replica has stopped, the new replica should be started.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
# Check that the new replica has started.
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
deployment_state.update()
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Now deploy a third version after the transition has finished.
b_info_3, b_version_3 = deployment_info(version="3")
updating = deployment_state.deploy(b_info_3)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=0)
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
check_counts(
deployment_state,
version=b_version_3,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
deleted = deployment_state.update()
assert not deleted
check_counts(
deployment_state,
version=b_version_3,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_deploy_new_config_same_version(mock_deployment_state):
# Deploying a new config with the same version should not deploy a new
# replica.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(version="1")
updated = deployment_state.deploy(b_info_1)
assert updated
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Create the replica initially.
deployment_state.update()
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Update to a new config without changing the version.
b_info_2, b_version_2 = deployment_info(version="1", user_config={"hello": "world"})
updated = deployment_state.deploy(b_info_2)
assert updated
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.UPDATING, 1)],
)
# Mark the replica as ready.
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_deploy_new_config_new_version(mock_deployment_state):
# Deploying a new config with a new version should deploy a new replica.
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
# Create the replica initially.
deployment_state.update()
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Update to a new config and a new version.
b_info_2, b_version_2 = deployment_info(version="2", user_config={"hello": "world"})
updating = deployment_state.deploy(b_info_2)
assert updating
# New version shouldn't start until old version is stopped.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
assert deployment_state._replicas.count() == 0
check_counts(deployment_state, total=0)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_initial_deploy_no_throttling(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=10, version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.STARTING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.RUNNING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_new_version_deploy_throttling(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(
num_replicas=10, version="1", user_config="1"
)
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.STARTING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.RUNNING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
b_info_2, b_version_2 = deployment_info(
num_replicas=10, version="2", user_config="2"
)
updating = deployment_state.deploy(b_info_2)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=10,
by_state=[(ReplicaState.RUNNING, 8), (ReplicaState.STOPPING, 2)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=9,
by_state=[(ReplicaState.RUNNING, 8), (ReplicaState.STOPPING, 1)],
)
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=9,
by_state=[(ReplicaState.RUNNING, 8), (ReplicaState.STOPPING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
deployment_state.update()
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=9,
by_state=[(ReplicaState.RUNNING, 7), (ReplicaState.STOPPING, 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
1
]._actor.set_done_stopping()
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
new_replicas = 1
old_replicas = 9
while old_replicas > 3:
deployment_state.update()
check_counts(deployment_state, total=8)
check_counts(
deployment_state,
version=b_version_1,
total=old_replicas - 2,
by_state=[(ReplicaState.RUNNING, old_replicas - 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=new_replicas,
by_state=[(ReplicaState.RUNNING, new_replicas)],
)
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=old_replicas - 2,
by_state=[(ReplicaState.RUNNING, old_replicas - 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=new_replicas + 2,
by_state=[(ReplicaState.RUNNING, new_replicas), (ReplicaState.STARTING, 2)],
)
deployment_state._replicas.get(states=[ReplicaState.STARTING])[
0
]._actor.set_ready()
deployment_state._replicas.get(states=[ReplicaState.STARTING])[
1
]._actor.set_ready()
new_replicas += 2
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=old_replicas - 2,
by_state=[(ReplicaState.RUNNING, old_replicas - 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=new_replicas,
by_state=[(ReplicaState.RUNNING, new_replicas)],
)
old_replicas -= 2
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=old_replicas,
by_state=[
(ReplicaState.RUNNING, old_replicas - 2),
(ReplicaState.STOPPING, 2),
],
)
check_counts(
deployment_state,
version=b_version_2,
total=new_replicas,
by_state=[(ReplicaState.RUNNING, new_replicas)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
1
]._actor.set_done_stopping()
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(deployment_state, total=8)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=new_replicas,
by_state=[(ReplicaState.RUNNING, 7)],
)
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=9,
by_state=[(ReplicaState.RUNNING, 7), (ReplicaState.STARTING, 2)],
)
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
deployment_state._replicas.get(states=[ReplicaState.STARTING])[1]._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=9,
by_state=[(ReplicaState.RUNNING, 9)],
)
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=9,
by_state=[(ReplicaState.RUNNING, 9)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=9)
check_counts(
deployment_state,
version=b_version_2,
total=9,
by_state=[(ReplicaState.RUNNING, 9)],
)
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_2,
total=10,
by_state=[(ReplicaState.RUNNING, 9), (ReplicaState.STARTING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_2,
total=10,
by_state=[(ReplicaState.RUNNING, 10)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_reconfigure_throttling(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(
num_replicas=2, version="1", user_config="1"
)
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
b_info_2, b_version_2 = deployment_info(
num_replicas=2, version="1", user_config="2"
)
updating = deployment_state.deploy(b_info_2)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.UPDATING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.UPDATING])[0]._actor.set_ready()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.UPDATING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state._replicas.get(states=[ReplicaState.UPDATING])[0]._actor.set_ready()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_new_version_and_scale_down(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=10, version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.STARTING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=10, by_state=[(ReplicaState.RUNNING, 10)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
b_info_2, b_version_2 = deployment_info(num_replicas=2, version="2")
updating = deployment_state.deploy(b_info_2)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=10,
by_state=[(ReplicaState.RUNNING, 2), (ReplicaState.STOPPING, 8)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=9)
check_counts(
deployment_state,
version=b_version_1,
total=9,
by_state=[(ReplicaState.RUNNING, 2), (ReplicaState.STOPPING, 7)],
)
for replica in deployment_state._replicas.get(states=[ReplicaState.STOPPING]):
replica._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_1,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_1,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.STOPPING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STOPPING])[
0
]._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.STARTING, 1)],
)
deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=2)
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_new_version_and_scale_up(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2, version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
# Check that the new replicas have started.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
# Now deploy a new version and scale up the number of replicas to 10.
# 8 new replicas should be started.
b_info_2, b_version_2 = deployment_info(num_replicas=10, version="2")
updating = deployment_state.deploy(b_info_2)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=8,
by_state=[(ReplicaState.STARTING, 8)],
)
# Mark the new replicas as ready.
for replica in deployment_state._replicas.get(states=[ReplicaState.STARTING]):
replica._actor.set_ready()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=8,
by_state=[(ReplicaState.RUNNING, 8)],
)
# Now that the new version replicas are up, rolling update should start.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=2,
by_state=[(ReplicaState.RUNNING, 0), (ReplicaState.STOPPING, 2)],
)
check_counts(
deployment_state,
version=b_version_2,
total=8,
by_state=[(ReplicaState.RUNNING, 8)],
)
# Mark the replicas as done stopping.
for replica in deployment_state._replicas.get(states=[ReplicaState.STOPPING]):
replica._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=8)
check_counts(
deployment_state,
version=b_version_2,
total=8,
by_state=[(ReplicaState.RUNNING, 8)],
)
# The remaining replicas should be started.
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_2,
total=10,
by_state=[(ReplicaState.RUNNING, 8), (ReplicaState.STARTING, 2)],
)
# Mark the remaining replicas as ready.
for replica in deployment_state._replicas.get(states=[ReplicaState.STARTING]):
replica._actor.set_ready()
# All new replicas should be up and running.
deployment_state.update()
check_counts(deployment_state, total=10)
check_counts(
deployment_state,
version=b_version_2,
total=10,
by_state=[(ReplicaState.RUNNING, 10)],
)
deployment_state.update()
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_health_check(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2, version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
# Health check shouldn't be called until it's ready.
assert not replica._actor.health_check_called
# Check that the new replicas have started.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
deployment_state.update()
for replica in deployment_state._replicas.get():
# Health check shouldn't be called until it's ready.
assert replica._actor.health_check_called
# Mark one replica unhealthy. It should be stopped.
deployment_state._replicas.get()[0]._actor.set_unhealthy()
deployment_state.update()
check_counts(
deployment_state,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.STOPPING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
replica = deployment_state._replicas.get(states=[ReplicaState.STOPPING])[0]
replica._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
deployment_state.update()
check_counts(
deployment_state,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.STARTING, 1)],
)
replica = deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]
replica._actor.set_ready()
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_update_while_unhealthy(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2, version="1")
updating = deployment_state.deploy(b_info_1)
assert updating
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
for replica in deployment_state._replicas.get():
replica._actor.set_ready()
# Health check shouldn't be called until it's ready.
assert not replica._actor.health_check_called
# Check that the new replicas have started.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
deployment_state.update()
for replica in deployment_state._replicas.get():
# Health check shouldn't be called until it's ready.
assert replica._actor.health_check_called
# Mark one replica unhealthy. It should be stopped.
deployment_state._replicas.get()[0]._actor.set_unhealthy()
deployment_state.update()
check_counts(
deployment_state,
total=2,
by_state=[(ReplicaState.RUNNING, 1), (ReplicaState.STOPPING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
replica = deployment_state._replicas.get(states=[ReplicaState.STOPPING])[0]
replica._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
# Now deploy a new version (e.g., a rollback). This should update the status
# to UPDATING and then it should eventually become healthy.
b_info_2, b_version_2 = deployment_info(num_replicas=2, version="2")
updating = deployment_state.deploy(b_info_2)
assert updating
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.RUNNING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
# Check that a failure in the old version replica does not mark the
# deployment as UNHEALTHY.
deployment_state._replicas.get(states=[ReplicaState.RUNNING])[
0
]._actor.set_unhealthy()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_1,
total=1,
by_state=[(ReplicaState.STOPPING, 1)],
)
check_counts(
deployment_state,
version=b_version_2,
total=1,
by_state=[(ReplicaState.STARTING, 1)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
replica = deployment_state._replicas.get(states=[ReplicaState.STOPPING])[0]
replica._actor.set_done_stopping()
# Another replica of the new version should get started.
deployment_state.update()
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.STARTING, 2)],
)
# Mark new version replicas as ready.
for replica in deployment_state._replicas.get(states=[ReplicaState.STARTING]):
replica._actor.set_ready()
# Both replicas should be RUNNING, deployment should be HEALTHY.
deployment_state.update()
check_counts(
deployment_state,
version=b_version_2,
total=2,
by_state=[(ReplicaState.RUNNING, 2)],
)
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def _constructor_failure_loop_two_replica(deployment_state, num_loops):
for i in range(num_loops):
# Single replica should be created.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state._replica_constructor_retry_counter == i * 2
replica_1 = deployment_state._replicas.get()[0]
replica_2 = deployment_state._replicas.get()[1]
replica_1._actor.set_failed_to_start()
replica_2._actor.set_failed_to_start()
# Now the replica should be marked SHOULD_STOP after failure.
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STOPPING, 2)])
# Once it's done stopping, replica should be removed.
replica_1._actor.set_done_stopping()
replica_2._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=0)
def test_deploy_with_consistent_constructor_failure(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2)
updating = deployment_state.deploy(b_info_1)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
_constructor_failure_loop_two_replica(deployment_state, 3)
assert deployment_state._replica_constructor_retry_counter == 6
assert deployment_state.curr_status_info.status == DeploymentStatus.UNHEALTHY
check_counts(deployment_state, total=0)
assert deployment_state.curr_status_info.message != ""
def test_deploy_with_partial_constructor_failure(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2)
updating = deployment_state.deploy(b_info_1)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
_constructor_failure_loop_two_replica(deployment_state, 2)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state._replica_constructor_retry_counter == 4
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
replica_1 = deployment_state._replicas.get()[0]
replica_2 = deployment_state._replicas.get()[1]
replica_1._actor.set_ready()
replica_2._actor.set_failed_to_start()
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STOPPING, 1)])
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STOPPING, 1)])
replica_2._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 0)])
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 1)])
starting_replica = deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]
starting_replica._actor.set_failed_to_start()
deployment_state.update()
assert deployment_state._replica_constructor_retry_counter == -1
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STOPPING, 1)])
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STOPPING, 1)])
starting_replica = deployment_state._replicas.get(states=[ReplicaState.STOPPING])[0]
starting_replica._actor.set_done_stopping()
deployment_state.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 0)])
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 1)])
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 1)])
starting_replica = deployment_state._replicas.get(states=[ReplicaState.STARTING])[0]
starting_replica._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
def test_deploy_with_transient_constructor_failure(mock_deployment_state):
deployment_state, timer = mock_deployment_state
b_info_1, b_version_1 = deployment_info(num_replicas=2)
updating = deployment_state.deploy(b_info_1)
assert updating
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
_constructor_failure_loop_two_replica(deployment_state, 2)
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.STARTING, 2)])
assert deployment_state.curr_status_info.status == DeploymentStatus.UPDATING
assert deployment_state._replica_constructor_retry_counter == 4
replica_1 = deployment_state._replicas.get()[0]
replica_2 = deployment_state._replicas.get()[1]
replica_1._actor.set_ready()
replica_2._actor.set_ready()
deployment_state.update()
check_counts(deployment_state, total=2, by_state=[(ReplicaState.RUNNING, 2)])
assert deployment_state._replica_constructor_retry_counter == 4
assert deployment_state.curr_status_info.status == DeploymentStatus.HEALTHY
@pytest.fixture
def mock_deployment_state_manager() -> Tuple[DeploymentStateManager, Mock]:
timer = MockTimer()
with patch(
"ray.serve.deployment_state.ActorReplicaWrapper", new=MockReplicaActorWrapper
), patch("time.time", new=timer.time), patch(
"ray.serve.long_poll.LongPollHost"
) as mock_long_poll:
kv_store = RayLocalKVStore("TEST_DB", "test_kv_store.db")
all_current_actor_names = []
deployment_state_manager = DeploymentStateManager(
"name",
True,
kv_store,
mock_long_poll,
all_current_actor_names,
)
yield deployment_state_manager, timer
kv_store.delete(CHECKPOINT_KEY)
if sys.platform != "win32":
os.remove("test_kv_store.db")
def test_shutdown(mock_deployment_state_manager):
deployment_state_manager, timer = mock_deployment_state_manager
tag = "test"
grace_period_s = 10
b_info_1, b_version_1 = deployment_info(graceful_shutdown_timeout_s=grace_period_s)
updating = deployment_state_manager.deploy(tag, b_info_1)
assert updating
deployment_state = deployment_state_manager._deployment_states[tag]
deployment_state_manager.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STARTING, 1)])
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state_manager.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.RUNNING, 1)])
assert not deployment_state._replicas.get()[0]._actor.stopped
deployment_state_manager.shutdown()
timer.advance(grace_period_s + 0.1)
deployment_state_manager.update()
check_counts(deployment_state, total=1, by_state=[(ReplicaState.STOPPING, 1)])
assert deployment_state._replicas.get()[0]._actor.stopped
assert not deployment_state._replicas.get()[0]._actor.cleaned_up
assert len(deployment_state_manager.get_deployment_statuses()) > 0
replica = deployment_state._replicas.get()[0]
replica._actor.set_done_stopping()
deployment_state_manager.update()
check_counts(deployment_state, total=0)
assert replica._actor.cleaned_up
assert len(deployment_state_manager.get_deployment_statuses()) == 0
def test_resume_deployment_state_from_replica_tags(mock_deployment_state_manager):
deployment_state_manager, timer = mock_deployment_state_manager
tag = "test"
# Step 1: Create some deployment info with actors in running state
b_info_1, b_version_1 = deployment_info(version="1")
updating = deployment_state_manager.deploy(tag, b_info_1)
assert updating
deployment_state = deployment_state_manager._deployment_states[tag]
# Single replica should be created.
deployment_state_manager.update()
check_counts(
deployment_state,
total=1,
version=b_version_1,
by_state=[(ReplicaState.STARTING, 1)],
)
deployment_state._replicas.get()[0]._actor.set_ready()
# Now the replica should be marked running.
deployment_state_manager.update()
check_counts(
deployment_state,
total=1,
version=b_version_1,
by_state=[(ReplicaState.RUNNING, 1)],
)
mocked_replica = deployment_state._replicas.get(states=[ReplicaState.RUNNING])[0]
# Step 2: Delete _replicas from deployment_state
deployment_state._replicas = ReplicaStateContainer()
# Step 3: Create new deployment_state by resuming from passed in replicas
deployment_state_manager._recover_from_checkpoint(
[ReplicaName.prefix + mocked_replica.replica_tag]
)
# Step 4: Ensure new deployment_state is correct
# deployment state behind "test" is re-created in recovery flow
deployment_state = deployment_state_manager._deployment_states[tag]
# Ensure recovering replica begin with no version assigned
check_counts(
deployment_state, total=1, version=None, by_state=[(ReplicaState.RECOVERING, 1)]
)
deployment_state._replicas.get()[0]._actor.set_ready()
deployment_state._replicas.get()[0]._actor.set_starting_version(b_version_1)
# Now the replica should be marked running.
deployment_state_manager.update()
check_counts(
deployment_state,
total=1,
version=b_version_1,
by_state=[(ReplicaState.RUNNING, 1)],
)
# Ensure same replica name is used
assert deployment_state._replicas.get()[0].replica_tag == mocked_replica.replica_tag
def test_stopping_replicas_ranking():
@dataclass
class MockReplica:
actor_node_id: str
def compare(before, after):
before_replicas = [MockReplica(item) for item in before]
after_replicas = [MockReplica(item) for item in after]
result_replicas = rank_replicas_for_stopping(before_replicas)
assert result_replicas == after_replicas
compare(
[None, 1, None], [None, None, 1]
) # replicas not allocated should be stopped first
compare(
[3, 3, 3, 2, 2, 1], [1, 2, 2, 3, 3, 3]
) # prefer to stop dangling replicas first
compare([2, 2, 3, 3], [2, 2, 3, 3]) # if equal, ordering should be kept
def test_resource_requirements_none(mock_deployment_state):
class FakeActor:
actor_resources = {"num_cpus": 2, "fake": None}
available_resources = {}
# Make a DeploymentReplica just to accesss its resource_requirement function
replica = DeploymentReplica(None, None, None, None, None)
replica._actor = FakeActor()
# resource_requirements() should not error
replica.resource_requirements()
if __name__ == "__main__":
sys.exit(pytest.main(["-v", "-s", __file__]))
| true | true |
1c3fb6b30b996ff5765cfd6f146b4a0a3f563ca6 | 769 | py | Python | providers/caching/DiskCacheProvider.py | Prouser123/xbl-web-api | eb49032edb34cfbfda7f4cfda7aa1eecc7ea7eb3 | [
"MIT"
] | 16 | 2019-09-30T11:30:56.000Z | 2022-01-28T12:42:53.000Z | providers/caching/DiskCacheProvider.py | Prouser123/xbl-web-api | eb49032edb34cfbfda7f4cfda7aa1eecc7ea7eb3 | [
"MIT"
] | 13 | 2019-05-24T14:34:46.000Z | 2022-02-23T15:35:39.000Z | providers/caching/DiskCacheProvider.py | Prouser123/xbl-web-api | eb49032edb34cfbfda7f4cfda7aa1eecc7ea7eb3 | [
"MIT"
] | 1 | 2021-07-30T23:34:31.000Z | 2021-07-30T23:34:31.000Z | import diskcache
from providers.caching.CacheProvider import CacheProvider
class DiskCacheProvider(CacheProvider):
def __init__(self, path):
self.cache = diskcache.Cache(path)
self.cache.clear() # Clear all items
def get(self, key):
return self.cache.get(key)
def set(self, key, value, expire):
return self.cache.set(key, value, expire)
def has(self, key):
return self.cache.__contains__(key)
def len(self):
return self.cache.__len__()
def remove_expired(self):
return self.cache.expire()
def shutdown(self):
self.cache.close()
def cached(self, timeout):
def dec(func):
return diskcache.memoize(self.cache, timeout)(func)
return dec
| 22.617647 | 63 | 0.639792 | import diskcache
from providers.caching.CacheProvider import CacheProvider
class DiskCacheProvider(CacheProvider):
def __init__(self, path):
self.cache = diskcache.Cache(path)
self.cache.clear()
def get(self, key):
return self.cache.get(key)
def set(self, key, value, expire):
return self.cache.set(key, value, expire)
def has(self, key):
return self.cache.__contains__(key)
def len(self):
return self.cache.__len__()
def remove_expired(self):
return self.cache.expire()
def shutdown(self):
self.cache.close()
def cached(self, timeout):
def dec(func):
return diskcache.memoize(self.cache, timeout)(func)
return dec
| true | true |
1c3fb705945f1d44f80d75cdcf2b417407d28418 | 5,511 | py | Python | huaweicloud-sdk-cce/huaweicloudsdkcce/v3/model/update_node_pool_response.py | handsome-baby/huaweicloud-sdk-python-v3 | 6cdcf1da8b098427e58fc3335a387c14df7776d0 | [
"Apache-2.0"
] | 1 | 2021-04-16T07:59:28.000Z | 2021-04-16T07:59:28.000Z | huaweicloud-sdk-cce/huaweicloudsdkcce/v3/model/update_node_pool_response.py | Lencof/huaweicloud-sdk-python-v3 | d13dc4e2830a83e295be6e4de021999b3376e34e | [
"Apache-2.0"
] | null | null | null | huaweicloud-sdk-cce/huaweicloudsdkcce/v3/model/update_node_pool_response.py | Lencof/huaweicloud-sdk-python-v3 | d13dc4e2830a83e295be6e4de021999b3376e34e | [
"Apache-2.0"
] | 1 | 2022-01-17T02:24:18.000Z | 2022-01-17T02:24:18.000Z | # coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class UpdateNodePoolResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'api_version': 'str',
'kind': 'str',
'metadata': 'NodePoolMetadata',
'spec': 'NodePoolSpec',
'status': 'NodePoolStatus'
}
attribute_map = {
'api_version': 'apiVersion',
'kind': 'kind',
'metadata': 'metadata',
'spec': 'spec',
'status': 'status'
}
def __init__(self, api_version=None, kind=None, metadata=None, spec=None, status=None):
"""UpdateNodePoolResponse - a model defined in huaweicloud sdk"""
super().__init__()
self._api_version = None
self._kind = None
self._metadata = None
self._spec = None
self._status = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
if spec is not None:
self.spec = spec
if status is not None:
self.status = status
@property
def api_version(self):
"""Gets the api_version of this UpdateNodePoolResponse.
API版本,固定值“v3”。
:return: The api_version of this UpdateNodePoolResponse.
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this UpdateNodePoolResponse.
API版本,固定值“v3”。
:param api_version: The api_version of this UpdateNodePoolResponse.
:type: str
"""
self._api_version = api_version
@property
def kind(self):
"""Gets the kind of this UpdateNodePoolResponse.
API类型,固定值“NodePool”。
:return: The kind of this UpdateNodePoolResponse.
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this UpdateNodePoolResponse.
API类型,固定值“NodePool”。
:param kind: The kind of this UpdateNodePoolResponse.
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this UpdateNodePoolResponse.
:return: The metadata of this UpdateNodePoolResponse.
:rtype: NodePoolMetadata
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this UpdateNodePoolResponse.
:param metadata: The metadata of this UpdateNodePoolResponse.
:type: NodePoolMetadata
"""
self._metadata = metadata
@property
def spec(self):
"""Gets the spec of this UpdateNodePoolResponse.
:return: The spec of this UpdateNodePoolResponse.
:rtype: NodePoolSpec
"""
return self._spec
@spec.setter
def spec(self, spec):
"""Sets the spec of this UpdateNodePoolResponse.
:param spec: The spec of this UpdateNodePoolResponse.
:type: NodePoolSpec
"""
self._spec = spec
@property
def status(self):
"""Gets the status of this UpdateNodePoolResponse.
:return: The status of this UpdateNodePoolResponse.
:rtype: NodePoolStatus
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this UpdateNodePoolResponse.
:param status: The status of this UpdateNodePoolResponse.
:type: NodePoolStatus
"""
self._status = status
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, UpdateNodePoolResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 25.873239 | 91 | 0.569044 |
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class UpdateNodePoolResponse(SdkResponse):
sensitive_list = []
openapi_types = {
'api_version': 'str',
'kind': 'str',
'metadata': 'NodePoolMetadata',
'spec': 'NodePoolSpec',
'status': 'NodePoolStatus'
}
attribute_map = {
'api_version': 'apiVersion',
'kind': 'kind',
'metadata': 'metadata',
'spec': 'spec',
'status': 'status'
}
def __init__(self, api_version=None, kind=None, metadata=None, spec=None, status=None):
super().__init__()
self._api_version = None
self._kind = None
self._metadata = None
self._spec = None
self._status = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
if spec is not None:
self.spec = spec
if status is not None:
self.status = status
@property
def api_version(self):
return self._api_version
@api_version.setter
def api_version(self, api_version):
self._api_version = api_version
@property
def kind(self):
return self._kind
@kind.setter
def kind(self, kind):
self._kind = kind
@property
def metadata(self):
return self._metadata
@metadata.setter
def metadata(self, metadata):
self._metadata = metadata
@property
def spec(self):
return self._spec
@spec.setter
def spec(self, spec):
self._spec = spec
@property
def status(self):
return self._status
@status.setter
def status(self, status):
self._status = status
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, UpdateNodePoolResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
1c3fb724b82955a9d93f2abdc023952c315d892a | 778 | py | Python | mayan/apps/autoadmin/models.py | nattangwiwat/Mayan-EDMS-recitation | fcf16afb56eae812fb99144d65ae1ae6749de0b7 | [
"Apache-2.0"
] | 343 | 2015-01-05T14:19:35.000Z | 2018-12-10T19:07:48.000Z | mayan/apps/autoadmin/models.py | nattangwiwat/Mayan-EDMS-recitation | fcf16afb56eae812fb99144d65ae1ae6749de0b7 | [
"Apache-2.0"
] | 191 | 2015-01-03T00:48:19.000Z | 2018-11-30T09:10:25.000Z | mayan/apps/autoadmin/models.py | nattangwiwat/Mayan-EDMS-recitation | fcf16afb56eae812fb99144d65ae1ae6749de0b7 | [
"Apache-2.0"
] | 257 | 2019-05-14T10:26:37.000Z | 2022-03-30T03:37:36.000Z | from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from solo.models import SingletonModel
from .managers import AutoAdminSingletonManager
class AutoAdminSingleton(SingletonModel):
account = models.ForeignKey(
blank=True, null=True, on_delete=models.CASCADE,
to=settings.AUTH_USER_MODEL, verbose_name=_('Account'),
)
password = models.CharField(
blank=True, max_length=128, null=True, verbose_name=_('Password')
)
password_hash = models.CharField(
blank=True, max_length=128, null=True, verbose_name=_('Password hash')
)
objects = AutoAdminSingletonManager()
class Meta:
verbose_name = verbose_name_plural = _('Autoadmin properties')
| 29.923077 | 78 | 0.732648 | from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from solo.models import SingletonModel
from .managers import AutoAdminSingletonManager
class AutoAdminSingleton(SingletonModel):
account = models.ForeignKey(
blank=True, null=True, on_delete=models.CASCADE,
to=settings.AUTH_USER_MODEL, verbose_name=_('Account'),
)
password = models.CharField(
blank=True, max_length=128, null=True, verbose_name=_('Password')
)
password_hash = models.CharField(
blank=True, max_length=128, null=True, verbose_name=_('Password hash')
)
objects = AutoAdminSingletonManager()
class Meta:
verbose_name = verbose_name_plural = _('Autoadmin properties')
| true | true |
1c3fb7d69830be9fe5752e67677b4eb12326bb8e | 3,618 | py | Python | calculaIpv4.py | Werberty/Calculando-Redes_IPV4 | c86ef00248c998b74cb6af377989c6f824d37ae4 | [
"MIT"
] | 1 | 2022-03-06T11:37:46.000Z | 2022-03-06T11:37:46.000Z | calculaIpv4.py | Werberty/Calculando-Redes_IPV4 | c86ef00248c998b74cb6af377989c6f824d37ae4 | [
"MIT"
] | null | null | null | calculaIpv4.py | Werberty/Calculando-Redes_IPV4 | c86ef00248c998b74cb6af377989c6f824d37ae4 | [
"MIT"
] | null | null | null | import re
class CalculaIpv4:
def __init__(self, ip, mascara) -> None:
self.ip = ip
self.mascara = mascara
self.prefixo = self.calc_prefixo(mascara)
self.rede = self.calc_ip_rede(ip, mascara)
self.broadcast = self.calc_broadcast(ip, mascara)
self.numero_ips = self.calc_numero_de_ips(mascara)
self.ips_usaveis = self.calc_ips_usaveis(self.rede, self.broadcast)
@property
def ip(self):
return self._ip
@property
def mascara(self):
return self._mascara
@ip.setter
def ip(self, valor):
if not self.validar_ip(valor):
raise ValueError('Ip inválido!')
self._ip = valor
@mascara.setter
def mascara(self, valor):
if not self.validar_ip(valor):
raise ValueError('Máscara inválida!')
self._mascara = valor
@staticmethod
def validar_ip(ip):
regexp = re.compile(
r'^([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})$')
if regexp.search(ip):
return True
def calc_ips_usaveis(self, rede, broadcast):
rede = self.remover_caracteres(rede)
broadcast = self.remover_caracteres(broadcast)
rede[3] += 1
broadcast[3] -= 1
return f'{self.formatar_ip(rede)} - {self.formatar_ip(broadcast)}'
def calc_numero_de_ips(self, mascara):
bits_da_mascara = self.decimal_para_binario(mascara)[3]
b = 0
for n in bits_da_mascara:
if n == '0':
b += 1
return 2**b - 2
def calc_broadcast(self, ip, mascara):
ip = self.decimal_para_binario(ip)
mascara = self.decimal_para_binario(mascara)
for byte in range(4):
byte_mascara = list(mascara[byte])
byte_ip = list(ip[byte])
for bit in range(8):
if byte_mascara[bit] == '0':
byte_ip[bit] = '1'
ip[byte] = ''.join(byte_ip)
ip = self.binario_para_decimal(ip)
return self.formatar_ip(ip)
def calc_ip_rede(self, ip, mascara):
ip = self.decimal_para_binario(ip)
mascara = self.decimal_para_binario(mascara)
for byte in range(4):
byte_mascara = list(mascara[byte])
byte_ip = list(ip[byte])
for bit in range(8):
if byte_mascara[bit] == '0':
byte_ip[bit] = '0'
ip[byte] = ''.join(byte_ip)
ip = self.binario_para_decimal(ip)
return self.formatar_ip(ip)
def calc_prefixo(self, mascara):
mascara = self.decimal_para_binario(mascara)
prefixo = 0
for valor in mascara:
for n in list(valor):
if n == '1':
prefixo += 1
return prefixo
def binario_para_decimal(self, ip):
if not isinstance(ip, list):
ip = self.remover_caracteres(ip)
ip_decimal = []
for binario in ip:
binario_dec = int(binario, 2)
ip_decimal.append(binario_dec)
return ip_decimal
def decimal_para_binario(self, ip):
if not isinstance(ip, list):
ip = self.remover_caracteres(ip)
ip_binario = []
for decimal in ip:
dec_binario = format(decimal, 'b')
dec_binario = dec_binario.zfill(8)
ip_binario.append(dec_binario)
return ip_binario
@staticmethod
def formatar_ip(ip):
return '.'.join(map(str, ip))
@staticmethod
def remover_caracteres(ip):
ip = [int(n) for n in ip.split('.')]
return ip
| 30.661017 | 75 | 0.564677 | import re
class CalculaIpv4:
def __init__(self, ip, mascara) -> None:
self.ip = ip
self.mascara = mascara
self.prefixo = self.calc_prefixo(mascara)
self.rede = self.calc_ip_rede(ip, mascara)
self.broadcast = self.calc_broadcast(ip, mascara)
self.numero_ips = self.calc_numero_de_ips(mascara)
self.ips_usaveis = self.calc_ips_usaveis(self.rede, self.broadcast)
@property
def ip(self):
return self._ip
@property
def mascara(self):
return self._mascara
@ip.setter
def ip(self, valor):
if not self.validar_ip(valor):
raise ValueError('Ip inválido!')
self._ip = valor
@mascara.setter
def mascara(self, valor):
if not self.validar_ip(valor):
raise ValueError('Máscara inválida!')
self._mascara = valor
@staticmethod
def validar_ip(ip):
regexp = re.compile(
r'^([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})$')
if regexp.search(ip):
return True
def calc_ips_usaveis(self, rede, broadcast):
rede = self.remover_caracteres(rede)
broadcast = self.remover_caracteres(broadcast)
rede[3] += 1
broadcast[3] -= 1
return f'{self.formatar_ip(rede)} - {self.formatar_ip(broadcast)}'
def calc_numero_de_ips(self, mascara):
bits_da_mascara = self.decimal_para_binario(mascara)[3]
b = 0
for n in bits_da_mascara:
if n == '0':
b += 1
return 2**b - 2
def calc_broadcast(self, ip, mascara):
ip = self.decimal_para_binario(ip)
mascara = self.decimal_para_binario(mascara)
for byte in range(4):
byte_mascara = list(mascara[byte])
byte_ip = list(ip[byte])
for bit in range(8):
if byte_mascara[bit] == '0':
byte_ip[bit] = '1'
ip[byte] = ''.join(byte_ip)
ip = self.binario_para_decimal(ip)
return self.formatar_ip(ip)
def calc_ip_rede(self, ip, mascara):
ip = self.decimal_para_binario(ip)
mascara = self.decimal_para_binario(mascara)
for byte in range(4):
byte_mascara = list(mascara[byte])
byte_ip = list(ip[byte])
for bit in range(8):
if byte_mascara[bit] == '0':
byte_ip[bit] = '0'
ip[byte] = ''.join(byte_ip)
ip = self.binario_para_decimal(ip)
return self.formatar_ip(ip)
def calc_prefixo(self, mascara):
mascara = self.decimal_para_binario(mascara)
prefixo = 0
for valor in mascara:
for n in list(valor):
if n == '1':
prefixo += 1
return prefixo
def binario_para_decimal(self, ip):
if not isinstance(ip, list):
ip = self.remover_caracteres(ip)
ip_decimal = []
for binario in ip:
binario_dec = int(binario, 2)
ip_decimal.append(binario_dec)
return ip_decimal
def decimal_para_binario(self, ip):
if not isinstance(ip, list):
ip = self.remover_caracteres(ip)
ip_binario = []
for decimal in ip:
dec_binario = format(decimal, 'b')
dec_binario = dec_binario.zfill(8)
ip_binario.append(dec_binario)
return ip_binario
@staticmethod
def formatar_ip(ip):
return '.'.join(map(str, ip))
@staticmethod
def remover_caracteres(ip):
ip = [int(n) for n in ip.split('.')]
return ip
| true | true |
1c3fb7e4d49e191f28457af06cee9b503f582ccc | 5,190 | py | Python | src/sqlTools/ReaderTools.py | XPH0904/Library-management-system | 9990654070caa9f757af9a6f4771ce4b1b484083 | [
"Apache-2.0"
] | null | null | null | src/sqlTools/ReaderTools.py | XPH0904/Library-management-system | 9990654070caa9f757af9a6f4771ce4b1b484083 | [
"Apache-2.0"
] | null | null | null | src/sqlTools/ReaderTools.py | XPH0904/Library-management-system | 9990654070caa9f757af9a6f4771ce4b1b484083 | [
"Apache-2.0"
] | null | null | null | import traceback
import mysql.connector
from ..model.Reader import Reader
from ..database.database import DatabaseTools
class ReaderTools:
#return for Special ID
def ReaderDataId(self, idReader):
db = DatabaseTools()
conn = db.getConn()
result_set = None
ls = []
try :
sql = "select idReader,nameReader,kind,sex,password from Reader where idReader = %s"
answer = (str(idReader),)
mycursor = conn.cursor()
mycursor.execute(sql,answer)
result_set = mycursor.fetchall()
for row in result_set:
reader = Reader()
reader.setIdReader(row[0])
reader.setNameReader(row[1])
reader.setLevel(row[2])
reader.setSex(row[3])
reader.setPassword(row[4])
ls.append(reader.list_return())
mycursor.close()
conn.close()
except Exception as e :
traceback.print_exc()
return ls
#return for Special name
def ReaderDataSearch(self, nameReader):
db = DatabaseTools()
conn = db.getConn()
result_set = None
ls = []
try :
sql = "select idReader,nameReader,kind,sex,password from Reader where nameReader like %s"
answer = str("'%"+nameReader+"%'")
mycursor = conn.cursor()
mycursor.execute(sql%answer)
result_set =(mycursor.fetchall())
for row in result_set:
reader = Reader()
reader.setIdReader(row[0])
reader.setNameReader(row[1])
reader.setLevel(row[2])
reader.setSex(row[3])
reader.setPassword(row[4])
ls.append(reader.list_return())
mycursor.close()
conn.close()
except Exception as e :
traceback.print_exc()
return ls
def ReaderData(self):
db = DatabaseTools()
conn = db.getConn()
result_set = None
ls = []
try:
sql = "select idReader,nameReader,kind,sex,password from Reader"
mycursor = conn.cursor()
mycursor.execute(sql)
result_set = mycursor.fetchall()
for row in result_set:
reader = Reader()
reader.setIdReader(row[0])
reader.setNameReader(row[1])
reader.setLevel(row[2])
reader.setSex(row[3])
reader.setPassword(row[4])
ls.append(reader.list_return())
mycursor.close()
conn.close()
except Exception as e:
traceback.print_exc()
return ls
def ReaderLogin(self, idReader , password):
db = DatabaseTools()
conn = db.getConn()
try:
sql = "select idReader,password from reader where idReader= %s and password= %s "
answer = (str(idReader),str(password))
mycursor = conn.cursor()
mycursor.execute(sql,answer)
result = mycursor.fetchone()
if(result != None):
return True
mycursor.close()
conn.close()
except Exception as e:
traceback.print_exc()
return False
def addReader(self, Reader):
i = 0
db = DatabaseTools()
conn = db.getConn()
try :
sql = "insert into reader (idReader,nameReader,kind,sex,password) values (%s,%s,%s,%s,%s)"
answer = (str(Reader.idReader),str(Reader.nameReader),str(Reader.level),str(Reader.sex),str(Reader.password))
mycursor = conn.cursor()
mycursor.execute(sql,answer)
i = mycursor.rowcount
mycursor.close()
conn.commit()
conn.close()
except Exception as e :
traceback.print_exc()
return i
def UpdateReader(self, Reader):
i = 0
db = DatabaseTools()
conn = db.getConn()
try :
sql = "update reader set idReader=%s,nameReader=%s,kind=%s,sex=%s,password=%s where idReader=%s"
answer = (str(Reader.idReader),str(Reader.nameReader),str(Reader.level),str(Reader.sex),str(Reader.password),str(Reader.idReader))
mycursor = conn.cursor()
mycursor.execute(sql,answer)
i = mycursor.rowcount
mycursor.close()
conn.commit()
conn.close()
except Exception as e :
traceback.print_exc()
return i
def DeleteReader(self, idreader):
i = 0
db = DatabaseTools()
conn = db.getConn()
try :
sql = "delete from reader where idReader = %s"
answer = (str(idreader),)
mycursor = conn.cursor()
mycursor.execute(sql,answer)
i = mycursor.rowcount
mycursor.close()
conn.commit()
conn.close()
except Exception as e :
traceback.print_exc()
return i
| 27.315789 | 142 | 0.522351 | import traceback
import mysql.connector
from ..model.Reader import Reader
from ..database.database import DatabaseTools
class ReaderTools:
def ReaderDataId(self, idReader):
db = DatabaseTools()
conn = db.getConn()
result_set = None
ls = []
try :
sql = "select idReader,nameReader,kind,sex,password from Reader where idReader = %s"
answer = (str(idReader),)
mycursor = conn.cursor()
mycursor.execute(sql,answer)
result_set = mycursor.fetchall()
for row in result_set:
reader = Reader()
reader.setIdReader(row[0])
reader.setNameReader(row[1])
reader.setLevel(row[2])
reader.setSex(row[3])
reader.setPassword(row[4])
ls.append(reader.list_return())
mycursor.close()
conn.close()
except Exception as e :
traceback.print_exc()
return ls
def ReaderDataSearch(self, nameReader):
db = DatabaseTools()
conn = db.getConn()
result_set = None
ls = []
try :
sql = "select idReader,nameReader,kind,sex,password from Reader where nameReader like %s"
answer = str("'%"+nameReader+"%'")
mycursor = conn.cursor()
mycursor.execute(sql%answer)
result_set =(mycursor.fetchall())
for row in result_set:
reader = Reader()
reader.setIdReader(row[0])
reader.setNameReader(row[1])
reader.setLevel(row[2])
reader.setSex(row[3])
reader.setPassword(row[4])
ls.append(reader.list_return())
mycursor.close()
conn.close()
except Exception as e :
traceback.print_exc()
return ls
def ReaderData(self):
db = DatabaseTools()
conn = db.getConn()
result_set = None
ls = []
try:
sql = "select idReader,nameReader,kind,sex,password from Reader"
mycursor = conn.cursor()
mycursor.execute(sql)
result_set = mycursor.fetchall()
for row in result_set:
reader = Reader()
reader.setIdReader(row[0])
reader.setNameReader(row[1])
reader.setLevel(row[2])
reader.setSex(row[3])
reader.setPassword(row[4])
ls.append(reader.list_return())
mycursor.close()
conn.close()
except Exception as e:
traceback.print_exc()
return ls
def ReaderLogin(self, idReader , password):
db = DatabaseTools()
conn = db.getConn()
try:
sql = "select idReader,password from reader where idReader= %s and password= %s "
answer = (str(idReader),str(password))
mycursor = conn.cursor()
mycursor.execute(sql,answer)
result = mycursor.fetchone()
if(result != None):
return True
mycursor.close()
conn.close()
except Exception as e:
traceback.print_exc()
return False
def addReader(self, Reader):
i = 0
db = DatabaseTools()
conn = db.getConn()
try :
sql = "insert into reader (idReader,nameReader,kind,sex,password) values (%s,%s,%s,%s,%s)"
answer = (str(Reader.idReader),str(Reader.nameReader),str(Reader.level),str(Reader.sex),str(Reader.password))
mycursor = conn.cursor()
mycursor.execute(sql,answer)
i = mycursor.rowcount
mycursor.close()
conn.commit()
conn.close()
except Exception as e :
traceback.print_exc()
return i
def UpdateReader(self, Reader):
i = 0
db = DatabaseTools()
conn = db.getConn()
try :
sql = "update reader set idReader=%s,nameReader=%s,kind=%s,sex=%s,password=%s where idReader=%s"
answer = (str(Reader.idReader),str(Reader.nameReader),str(Reader.level),str(Reader.sex),str(Reader.password),str(Reader.idReader))
mycursor = conn.cursor()
mycursor.execute(sql,answer)
i = mycursor.rowcount
mycursor.close()
conn.commit()
conn.close()
except Exception as e :
traceback.print_exc()
return i
def DeleteReader(self, idreader):
i = 0
db = DatabaseTools()
conn = db.getConn()
try :
sql = "delete from reader where idReader = %s"
answer = (str(idreader),)
mycursor = conn.cursor()
mycursor.execute(sql,answer)
i = mycursor.rowcount
mycursor.close()
conn.commit()
conn.close()
except Exception as e :
traceback.print_exc()
return i
| true | true |
1c3fb92f9cfb2eda4e23250f74cc254577012884 | 533 | py | Python | 4_Tran_Thi_Nhu_Huong_LOCAL/bai4.1.py | lpython2006e/exercies | 84343eae57d86708a7984aa02f77183a4688a508 | [
"MIT"
] | null | null | null | 4_Tran_Thi_Nhu_Huong_LOCAL/bai4.1.py | lpython2006e/exercies | 84343eae57d86708a7984aa02f77183a4688a508 | [
"MIT"
] | null | null | null | 4_Tran_Thi_Nhu_Huong_LOCAL/bai4.1.py | lpython2006e/exercies | 84343eae57d86708a7984aa02f77183a4688a508 | [
"MIT"
] | 8 | 2020-07-10T14:13:54.000Z | 2020-08-03T08:17:50.000Z | """Create Student class with attributes like (Name, Nickname, birthday, class)"""
class Student:
def __init__(self, name, nickname, birthday, class_num):
self.name = name
self.nickname = nickname
self.birthday = birthday
self.class_num = class_num
def show_info(self):
print("Name is {}, nickname is {}, birthday is {},class is {}.".format(self.name, self.nickname, self.birthday, self.class_num))
first_student = Student("Name", "Boy", "03/12/99", "1")
first_student.show_info()
| 31.352941 | 136 | 0.660413 |
class Student:
def __init__(self, name, nickname, birthday, class_num):
self.name = name
self.nickname = nickname
self.birthday = birthday
self.class_num = class_num
def show_info(self):
print("Name is {}, nickname is {}, birthday is {},class is {}.".format(self.name, self.nickname, self.birthday, self.class_num))
first_student = Student("Name", "Boy", "03/12/99", "1")
first_student.show_info()
| true | true |
1c3fb995b1da3003ba9e6ca50446edc20caf3fae | 532 | py | Python | 100 Python Exercises/Day 3/12.py | elipopovadev/Tournament-Tracker | 5b0acbd460257869438e27d3db770ff269ac6d40 | [
"MIT"
] | null | null | null | 100 Python Exercises/Day 3/12.py | elipopovadev/Tournament-Tracker | 5b0acbd460257869438e27d3db770ff269ac6d40 | [
"MIT"
] | 1 | 2022-02-21T12:40:21.000Z | 2022-02-21T12:40:21.000Z | 100 Python Exercises/Day 3/12.py | elipopovadev/Complete-Python-Developer | 5b0acbd460257869438e27d3db770ff269ac6d40 | [
"MIT"
] | null | null | null | import numpy as np
'''Question 12:
Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit
of the number is an even number.The numbers obtained should be printed in a comma-separated sequence on a single line.'''
sample_list = []
sample_array = range(1000, 3001)
for variable in sample_array:
var = str(variable)
if int(var[0]) % 2 == 0 and int(var[1]) % 2 == 0 and int(var[2]) % 2 and int(var[3]) % 2 == 0:
sample_list.append(var)
print(",".join(sample_list))
| 38 | 121 | 0.693609 | import numpy as np
sample_list = []
sample_array = range(1000, 3001)
for variable in sample_array:
var = str(variable)
if int(var[0]) % 2 == 0 and int(var[1]) % 2 == 0 and int(var[2]) % 2 and int(var[3]) % 2 == 0:
sample_list.append(var)
print(",".join(sample_list))
| true | true |
1c3fbabd96e05b2650f95dc93074ba84d8a33b06 | 381 | py | Python | tools/gen_interrupts.py | Narasimha1997/r3 | fbeea8de1c7b07bad3a30c511a1085c8dd0c4495 | [
"MIT"
] | 65 | 2022-01-22T11:23:33.000Z | 2022-03-29T12:12:50.000Z | tools/gen_interrupts.py | Narasimha1997/r3 | fbeea8de1c7b07bad3a30c511a1085c8dd0c4495 | [
"MIT"
] | 2 | 2022-01-22T10:49:59.000Z | 2022-01-23T05:50:00.000Z | tools/gen_interrupts.py | Narasimha1997/r3 | fbeea8de1c7b07bad3a30c511a1085c8dd0c4495 | [
"MIT"
] | 3 | 2022-01-22T17:30:19.000Z | 2022-03-12T03:25:37.000Z |
LEGACY_INTERRUPTS_BASE = 0x20
MAX_ARCH_INTERRUPTS = 256
entries = []
writer = open('entries.txt', 'w')
for idx in range(1, MAX_ARCH_INTERRUPTS - LEGACY_INTERRUPTS_BASE):
entry = "IDT.lock().interrupts[LEGACY_HARDWARE_INTERRUPTS_BASE + {}] = prepare_no_irq_handler!(no_irq_fn, {});\n".format(
hex(idx), hex(LEGACY_INTERRUPTS_BASE + idx)
)
writer.write(entry) | 29.307692 | 125 | 0.713911 |
LEGACY_INTERRUPTS_BASE = 0x20
MAX_ARCH_INTERRUPTS = 256
entries = []
writer = open('entries.txt', 'w')
for idx in range(1, MAX_ARCH_INTERRUPTS - LEGACY_INTERRUPTS_BASE):
entry = "IDT.lock().interrupts[LEGACY_HARDWARE_INTERRUPTS_BASE + {}] = prepare_no_irq_handler!(no_irq_fn, {});\n".format(
hex(idx), hex(LEGACY_INTERRUPTS_BASE + idx)
)
writer.write(entry) | true | true |
1c3fbbb4b422fedd696e2428da5fa8fa8df82664 | 633 | py | Python | Utopian_Tree.py | Quarantinex/Hackerrank_Python_Algorithm | 4a5fc532bfbdac02e66e9d0d9ae279c4e33ca017 | [
"MIT"
] | null | null | null | Utopian_Tree.py | Quarantinex/Hackerrank_Python_Algorithm | 4a5fc532bfbdac02e66e9d0d9ae279c4e33ca017 | [
"MIT"
] | null | null | null | Utopian_Tree.py | Quarantinex/Hackerrank_Python_Algorithm | 4a5fc532bfbdac02e66e9d0d9ae279c4e33ca017 | [
"MIT"
] | null | null | null | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the utopianTree function below.
def utopianTree(n):
temp = 1
if n == 0:
return temp
else:
for i in range(1,n+1):
if i%2 != 0:
temp = temp*2
elif i%2 == 0:
temp = temp+1
return temp
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
result = utopianTree(n)
fptr.write(str(result) + '\n')
fptr.close()
| 17.583333 | 47 | 0.491311 |
import math
import os
import random
import re
import sys
def utopianTree(n):
temp = 1
if n == 0:
return temp
else:
for i in range(1,n+1):
if i%2 != 0:
temp = temp*2
elif i%2 == 0:
temp = temp+1
return temp
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
result = utopianTree(n)
fptr.write(str(result) + '\n')
fptr.close()
| true | true |
1c3fbc5ca16d62fb96a83ee2f7d3e8ca38a8082a | 3,170 | py | Python | qiskit/result/models.py | ismaila-at-za-ibm/qiskit-terra | 08303ec98ac7b33fde55266dc3a74466fbdcae95 | [
"Apache-2.0"
] | 2 | 2021-09-06T19:25:36.000Z | 2021-11-17T10:46:12.000Z | qiskit/result/models.py | ismaila-at-za-ibm/qiskit-terra | 08303ec98ac7b33fde55266dc3a74466fbdcae95 | [
"Apache-2.0"
] | null | null | null | qiskit/result/models.py | ismaila-at-za-ibm/qiskit-terra | 08303ec98ac7b33fde55266dc3a74466fbdcae95 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Schema and helper models for schema-conformant Results."""
from marshmallow.validate import Length, OneOf, Regexp, Range
from qiskit.validation.base import BaseModel, BaseSchema, ObjSchema, bind_schema
from qiskit.validation.fields import Complex, ByType
from qiskit.validation.fields import Boolean, DateTime, Integer, List, Nested, Raw, String
from qiskit.validation.validate import PatternProperties
class ExperimentResultDataSchema(BaseSchema):
"""Schema for ExperimentResultData."""
counts = Nested(ObjSchema,
validate=PatternProperties(
{Regexp('^0x([0-9A-Fa-f])+$'): Integer()}))
snapshots = Nested(ObjSchema)
memory = List(Raw(),
validate=Length(min=1))
statevector = List(Complex(),
validate=Length(min=1))
unitary = List(List(Complex(),
validate=Length(min=1)),
validate=Length(min=1))
class ExperimentResultSchema(BaseSchema):
"""Schema for ExperimentResult."""
# Required fields.
shots = ByType([Integer(), List(Integer(validate=Range(min=1)),
validate=Length(equal=2))],
required=True)
success = Boolean(required=True)
data = Nested(ExperimentResultDataSchema, required=True)
# Optional fields.
status = String()
seed = Integer()
meas_return = String(validate=OneOf(['single', 'avg']))
header = Nested(ObjSchema)
class ResultSchema(BaseSchema):
"""Schema for Result."""
# Required fields.
backend_name = String(required=True)
backend_version = String(required=True,
validate=Regexp('[0-9]+.[0-9]+.[0-9]+$'))
qobj_id = String(required=True)
job_id = String(required=True)
success = Boolean(required=True)
results = Nested(ExperimentResultSchema, required=True, many=True)
# Optional fields.
date = DateTime()
status = String()
header = Nested(ObjSchema)
@bind_schema(ExperimentResultDataSchema)
class ExperimentResultData(BaseModel):
"""Model for ExperimentResultData.
Please note that this class only describes the required fields. For the
full description of the model, please check
``ExperimentResultDataSchema``.
"""
pass
@bind_schema(ExperimentResultSchema)
class ExperimentResult(BaseModel):
"""Model for ExperimentResult.
Please note that this class only describes the required fields. For the
full description of the model, please check ``ExperimentResultSchema``.
Attributes:
shots (int or tuple): the starting and ending shot for this data.
success (bool): if true, we can trust results for this experiment.
data (ExperimentResultData): results information.
"""
def __init__(self, shots, success, data, **kwargs):
self.shots = shots
self.success = success
self.data = data
super().__init__(**kwargs)
| 32.020202 | 90 | 0.66183 |
from marshmallow.validate import Length, OneOf, Regexp, Range
from qiskit.validation.base import BaseModel, BaseSchema, ObjSchema, bind_schema
from qiskit.validation.fields import Complex, ByType
from qiskit.validation.fields import Boolean, DateTime, Integer, List, Nested, Raw, String
from qiskit.validation.validate import PatternProperties
class ExperimentResultDataSchema(BaseSchema):
counts = Nested(ObjSchema,
validate=PatternProperties(
{Regexp('^0x([0-9A-Fa-f])+$'): Integer()}))
snapshots = Nested(ObjSchema)
memory = List(Raw(),
validate=Length(min=1))
statevector = List(Complex(),
validate=Length(min=1))
unitary = List(List(Complex(),
validate=Length(min=1)),
validate=Length(min=1))
class ExperimentResultSchema(BaseSchema):
shots = ByType([Integer(), List(Integer(validate=Range(min=1)),
validate=Length(equal=2))],
required=True)
success = Boolean(required=True)
data = Nested(ExperimentResultDataSchema, required=True)
status = String()
seed = Integer()
meas_return = String(validate=OneOf(['single', 'avg']))
header = Nested(ObjSchema)
class ResultSchema(BaseSchema):
backend_name = String(required=True)
backend_version = String(required=True,
validate=Regexp('[0-9]+.[0-9]+.[0-9]+$'))
qobj_id = String(required=True)
job_id = String(required=True)
success = Boolean(required=True)
results = Nested(ExperimentResultSchema, required=True, many=True)
date = DateTime()
status = String()
header = Nested(ObjSchema)
@bind_schema(ExperimentResultDataSchema)
class ExperimentResultData(BaseModel):
pass
@bind_schema(ExperimentResultSchema)
class ExperimentResult(BaseModel):
def __init__(self, shots, success, data, **kwargs):
self.shots = shots
self.success = success
self.data = data
super().__init__(**kwargs)
| true | true |
1c3fbcaba55e7177584dc605a776aa7a815b290f | 7,249 | py | Python | google/cloud/container_v1/__init__.py | sid-dinesh94/python-container | 8870b0000fc859407f7a8eac391ae06e528b3aae | [
"Apache-2.0"
] | null | null | null | google/cloud/container_v1/__init__.py | sid-dinesh94/python-container | 8870b0000fc859407f7a8eac391ae06e528b3aae | [
"Apache-2.0"
] | null | null | null | google/cloud/container_v1/__init__.py | sid-dinesh94/python-container | 8870b0000fc859407f7a8eac391ae06e528b3aae | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# 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.
#
from .services.cluster_manager import ClusterManagerClient
from .types.cluster_service import AcceleratorConfig
from .types.cluster_service import AddonsConfig
from .types.cluster_service import AuthenticatorGroupsConfig
from .types.cluster_service import AutoUpgradeOptions
from .types.cluster_service import AutoprovisioningNodePoolDefaults
from .types.cluster_service import BinaryAuthorization
from .types.cluster_service import CancelOperationRequest
from .types.cluster_service import ClientCertificateConfig
from .types.cluster_service import CloudRunConfig
from .types.cluster_service import Cluster
from .types.cluster_service import ClusterAutoscaling
from .types.cluster_service import ClusterUpdate
from .types.cluster_service import CompleteIPRotationRequest
from .types.cluster_service import CreateClusterRequest
from .types.cluster_service import CreateNodePoolRequest
from .types.cluster_service import DailyMaintenanceWindow
from .types.cluster_service import DatabaseEncryption
from .types.cluster_service import DeleteClusterRequest
from .types.cluster_service import DeleteNodePoolRequest
from .types.cluster_service import GetClusterRequest
from .types.cluster_service import GetNodePoolRequest
from .types.cluster_service import GetOperationRequest
from .types.cluster_service import GetServerConfigRequest
from .types.cluster_service import HorizontalPodAutoscaling
from .types.cluster_service import HttpLoadBalancing
from .types.cluster_service import IPAllocationPolicy
from .types.cluster_service import IntraNodeVisibilityConfig
from .types.cluster_service import KubernetesDashboard
from .types.cluster_service import LegacyAbac
from .types.cluster_service import ListClustersRequest
from .types.cluster_service import ListClustersResponse
from .types.cluster_service import ListNodePoolsRequest
from .types.cluster_service import ListNodePoolsResponse
from .types.cluster_service import ListOperationsRequest
from .types.cluster_service import ListOperationsResponse
from .types.cluster_service import ListUsableSubnetworksRequest
from .types.cluster_service import ListUsableSubnetworksResponse
from .types.cluster_service import MaintenancePolicy
from .types.cluster_service import MaintenanceWindow
from .types.cluster_service import MasterAuth
from .types.cluster_service import MasterAuthorizedNetworksConfig
from .types.cluster_service import MaxPodsConstraint
from .types.cluster_service import NetworkConfig
from .types.cluster_service import NetworkPolicy
from .types.cluster_service import NetworkPolicyConfig
from .types.cluster_service import NodeConfig
from .types.cluster_service import NodeManagement
from .types.cluster_service import NodePool
from .types.cluster_service import NodePoolAutoscaling
from .types.cluster_service import NodeTaint
from .types.cluster_service import Operation
from .types.cluster_service import PrivateClusterConfig
from .types.cluster_service import RecurringTimeWindow
from .types.cluster_service import ResourceLimit
from .types.cluster_service import ResourceUsageExportConfig
from .types.cluster_service import RollbackNodePoolUpgradeRequest
from .types.cluster_service import ServerConfig
from .types.cluster_service import SetAddonsConfigRequest
from .types.cluster_service import SetLabelsRequest
from .types.cluster_service import SetLegacyAbacRequest
from .types.cluster_service import SetLocationsRequest
from .types.cluster_service import SetLoggingServiceRequest
from .types.cluster_service import SetMaintenancePolicyRequest
from .types.cluster_service import SetMasterAuthRequest
from .types.cluster_service import SetMonitoringServiceRequest
from .types.cluster_service import SetNetworkPolicyRequest
from .types.cluster_service import SetNodePoolAutoscalingRequest
from .types.cluster_service import SetNodePoolManagementRequest
from .types.cluster_service import SetNodePoolSizeRequest
from .types.cluster_service import ShieldedInstanceConfig
from .types.cluster_service import StartIPRotationRequest
from .types.cluster_service import StatusCondition
from .types.cluster_service import TimeWindow
from .types.cluster_service import UpdateClusterRequest
from .types.cluster_service import UpdateMasterRequest
from .types.cluster_service import UpdateNodePoolRequest
from .types.cluster_service import UsableSubnetwork
from .types.cluster_service import UsableSubnetworkSecondaryRange
from .types.cluster_service import VerticalPodAutoscaling
__all__ = (
"AcceleratorConfig",
"AddonsConfig",
"AuthenticatorGroupsConfig",
"AutoUpgradeOptions",
"AutoprovisioningNodePoolDefaults",
"BinaryAuthorization",
"CancelOperationRequest",
"ClientCertificateConfig",
"CloudRunConfig",
"Cluster",
"ClusterAutoscaling",
"ClusterUpdate",
"CompleteIPRotationRequest",
"CreateClusterRequest",
"CreateNodePoolRequest",
"DailyMaintenanceWindow",
"DatabaseEncryption",
"DeleteClusterRequest",
"DeleteNodePoolRequest",
"GetClusterRequest",
"GetNodePoolRequest",
"GetOperationRequest",
"GetServerConfigRequest",
"HorizontalPodAutoscaling",
"HttpLoadBalancing",
"IPAllocationPolicy",
"IntraNodeVisibilityConfig",
"KubernetesDashboard",
"LegacyAbac",
"ListClustersRequest",
"ListClustersResponse",
"ListNodePoolsRequest",
"ListNodePoolsResponse",
"ListOperationsRequest",
"ListOperationsResponse",
"ListUsableSubnetworksRequest",
"ListUsableSubnetworksResponse",
"MaintenancePolicy",
"MaintenanceWindow",
"MasterAuth",
"MasterAuthorizedNetworksConfig",
"MaxPodsConstraint",
"NetworkConfig",
"NetworkPolicy",
"NetworkPolicyConfig",
"NodeConfig",
"NodeManagement",
"NodePool",
"NodePoolAutoscaling",
"NodeTaint",
"Operation",
"PrivateClusterConfig",
"RecurringTimeWindow",
"ResourceLimit",
"ResourceUsageExportConfig",
"RollbackNodePoolUpgradeRequest",
"ServerConfig",
"SetAddonsConfigRequest",
"SetLabelsRequest",
"SetLegacyAbacRequest",
"SetLocationsRequest",
"SetLoggingServiceRequest",
"SetMaintenancePolicyRequest",
"SetMasterAuthRequest",
"SetMonitoringServiceRequest",
"SetNetworkPolicyRequest",
"SetNodePoolAutoscalingRequest",
"SetNodePoolManagementRequest",
"SetNodePoolSizeRequest",
"ShieldedInstanceConfig",
"StartIPRotationRequest",
"StatusCondition",
"TimeWindow",
"UpdateClusterRequest",
"UpdateMasterRequest",
"UpdateNodePoolRequest",
"UsableSubnetwork",
"UsableSubnetworkSecondaryRange",
"VerticalPodAutoscaling",
"ClusterManagerClient",
)
| 39.82967 | 74 | 0.82301 |
from .services.cluster_manager import ClusterManagerClient
from .types.cluster_service import AcceleratorConfig
from .types.cluster_service import AddonsConfig
from .types.cluster_service import AuthenticatorGroupsConfig
from .types.cluster_service import AutoUpgradeOptions
from .types.cluster_service import AutoprovisioningNodePoolDefaults
from .types.cluster_service import BinaryAuthorization
from .types.cluster_service import CancelOperationRequest
from .types.cluster_service import ClientCertificateConfig
from .types.cluster_service import CloudRunConfig
from .types.cluster_service import Cluster
from .types.cluster_service import ClusterAutoscaling
from .types.cluster_service import ClusterUpdate
from .types.cluster_service import CompleteIPRotationRequest
from .types.cluster_service import CreateClusterRequest
from .types.cluster_service import CreateNodePoolRequest
from .types.cluster_service import DailyMaintenanceWindow
from .types.cluster_service import DatabaseEncryption
from .types.cluster_service import DeleteClusterRequest
from .types.cluster_service import DeleteNodePoolRequest
from .types.cluster_service import GetClusterRequest
from .types.cluster_service import GetNodePoolRequest
from .types.cluster_service import GetOperationRequest
from .types.cluster_service import GetServerConfigRequest
from .types.cluster_service import HorizontalPodAutoscaling
from .types.cluster_service import HttpLoadBalancing
from .types.cluster_service import IPAllocationPolicy
from .types.cluster_service import IntraNodeVisibilityConfig
from .types.cluster_service import KubernetesDashboard
from .types.cluster_service import LegacyAbac
from .types.cluster_service import ListClustersRequest
from .types.cluster_service import ListClustersResponse
from .types.cluster_service import ListNodePoolsRequest
from .types.cluster_service import ListNodePoolsResponse
from .types.cluster_service import ListOperationsRequest
from .types.cluster_service import ListOperationsResponse
from .types.cluster_service import ListUsableSubnetworksRequest
from .types.cluster_service import ListUsableSubnetworksResponse
from .types.cluster_service import MaintenancePolicy
from .types.cluster_service import MaintenanceWindow
from .types.cluster_service import MasterAuth
from .types.cluster_service import MasterAuthorizedNetworksConfig
from .types.cluster_service import MaxPodsConstraint
from .types.cluster_service import NetworkConfig
from .types.cluster_service import NetworkPolicy
from .types.cluster_service import NetworkPolicyConfig
from .types.cluster_service import NodeConfig
from .types.cluster_service import NodeManagement
from .types.cluster_service import NodePool
from .types.cluster_service import NodePoolAutoscaling
from .types.cluster_service import NodeTaint
from .types.cluster_service import Operation
from .types.cluster_service import PrivateClusterConfig
from .types.cluster_service import RecurringTimeWindow
from .types.cluster_service import ResourceLimit
from .types.cluster_service import ResourceUsageExportConfig
from .types.cluster_service import RollbackNodePoolUpgradeRequest
from .types.cluster_service import ServerConfig
from .types.cluster_service import SetAddonsConfigRequest
from .types.cluster_service import SetLabelsRequest
from .types.cluster_service import SetLegacyAbacRequest
from .types.cluster_service import SetLocationsRequest
from .types.cluster_service import SetLoggingServiceRequest
from .types.cluster_service import SetMaintenancePolicyRequest
from .types.cluster_service import SetMasterAuthRequest
from .types.cluster_service import SetMonitoringServiceRequest
from .types.cluster_service import SetNetworkPolicyRequest
from .types.cluster_service import SetNodePoolAutoscalingRequest
from .types.cluster_service import SetNodePoolManagementRequest
from .types.cluster_service import SetNodePoolSizeRequest
from .types.cluster_service import ShieldedInstanceConfig
from .types.cluster_service import StartIPRotationRequest
from .types.cluster_service import StatusCondition
from .types.cluster_service import TimeWindow
from .types.cluster_service import UpdateClusterRequest
from .types.cluster_service import UpdateMasterRequest
from .types.cluster_service import UpdateNodePoolRequest
from .types.cluster_service import UsableSubnetwork
from .types.cluster_service import UsableSubnetworkSecondaryRange
from .types.cluster_service import VerticalPodAutoscaling
__all__ = (
"AcceleratorConfig",
"AddonsConfig",
"AuthenticatorGroupsConfig",
"AutoUpgradeOptions",
"AutoprovisioningNodePoolDefaults",
"BinaryAuthorization",
"CancelOperationRequest",
"ClientCertificateConfig",
"CloudRunConfig",
"Cluster",
"ClusterAutoscaling",
"ClusterUpdate",
"CompleteIPRotationRequest",
"CreateClusterRequest",
"CreateNodePoolRequest",
"DailyMaintenanceWindow",
"DatabaseEncryption",
"DeleteClusterRequest",
"DeleteNodePoolRequest",
"GetClusterRequest",
"GetNodePoolRequest",
"GetOperationRequest",
"GetServerConfigRequest",
"HorizontalPodAutoscaling",
"HttpLoadBalancing",
"IPAllocationPolicy",
"IntraNodeVisibilityConfig",
"KubernetesDashboard",
"LegacyAbac",
"ListClustersRequest",
"ListClustersResponse",
"ListNodePoolsRequest",
"ListNodePoolsResponse",
"ListOperationsRequest",
"ListOperationsResponse",
"ListUsableSubnetworksRequest",
"ListUsableSubnetworksResponse",
"MaintenancePolicy",
"MaintenanceWindow",
"MasterAuth",
"MasterAuthorizedNetworksConfig",
"MaxPodsConstraint",
"NetworkConfig",
"NetworkPolicy",
"NetworkPolicyConfig",
"NodeConfig",
"NodeManagement",
"NodePool",
"NodePoolAutoscaling",
"NodeTaint",
"Operation",
"PrivateClusterConfig",
"RecurringTimeWindow",
"ResourceLimit",
"ResourceUsageExportConfig",
"RollbackNodePoolUpgradeRequest",
"ServerConfig",
"SetAddonsConfigRequest",
"SetLabelsRequest",
"SetLegacyAbacRequest",
"SetLocationsRequest",
"SetLoggingServiceRequest",
"SetMaintenancePolicyRequest",
"SetMasterAuthRequest",
"SetMonitoringServiceRequest",
"SetNetworkPolicyRequest",
"SetNodePoolAutoscalingRequest",
"SetNodePoolManagementRequest",
"SetNodePoolSizeRequest",
"ShieldedInstanceConfig",
"StartIPRotationRequest",
"StatusCondition",
"TimeWindow",
"UpdateClusterRequest",
"UpdateMasterRequest",
"UpdateNodePoolRequest",
"UsableSubnetwork",
"UsableSubnetworkSecondaryRange",
"VerticalPodAutoscaling",
"ClusterManagerClient",
)
| true | true |
1c3fbcd19b3ffbf3c6cb89409faf0751e9908e1d | 5,110 | py | Python | soft/lib.hdf5/customize.py | G4V/ck-env | b882480b00b9dbd88f15eef58440772e09414f64 | [
"BSD-3-Clause"
] | 80 | 2015-03-03T14:27:39.000Z | 2022-01-04T15:37:01.000Z | soft/lib.hdf5/customize.py | G4V/ck-env | b882480b00b9dbd88f15eef58440772e09414f64 | [
"BSD-3-Clause"
] | 78 | 2016-02-20T07:47:05.000Z | 2021-05-01T13:33:31.000Z | soft/lib.hdf5/customize.py | G4V/ck-env | b882480b00b9dbd88f15eef58440772e09414f64 | [
"BSD-3-Clause"
] | 22 | 2016-07-29T07:25:11.000Z | 2021-02-08T16:18:26.000Z | #
# Collective Knowledge (individual environment - setup)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net
#
import os
##############################################################################
# limit directories
def limit(i):
dr=i.get('list',[])
drx=[]
for q in dr:
if q.find('.libs')<0 and q.find('anaconda')<0:
drx.append(q)
# Anaconda installation and libraries often conflict with existing OS installations
return {'return':0, 'list':drx}
##############################################################################
# get version from path
def version_cmd(i):
ck=i['ck_kernel']
fp=i['full_path']
ver=''
r = ck.access({'action': 'search_version',
'module_uoa': 'soft',
'path': fp})
if r['return']>0: return r
ver=r.get('version','')
if ver=='':
if len(fp)>0:
j=fp.rfind('.')
if j>0:
fps=fp[:j]+'.settings'
if os.path.isfile(fps):
# Load file and find setting
r=ck.load_text_file({'text_file':fps, 'split_to_list':'yes'})
if r['return']>0: return r
for l in r['lst']:
l=l.strip()
if l.startswith('HDF5 Version:'):
ver=l[14:].strip()
break
return {'return':0, 'cmd':'', 'version':ver}
##############################################################################
# setup environment setup
def setup(i):
"""
Input: {
cfg - meta of this soft entry
self_cfg - meta of module soft
ck_kernel - import CK kernel module (to reuse functions)
host_os_uoa - host OS UOA
host_os_uid - host OS UID
host_os_dict - host OS meta
target_os_uoa - target OS UOA
target_os_uid - target OS UID
target_os_dict - target OS meta
target_device_id - target device ID (if via ADB)
tags - list of tags used to search this entry
env - updated environment vars from meta
customize - updated customize vars from meta
deps - resolved dependencies for this soft
interactive - if 'yes', can ask questions, otherwise quiet
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
bat - prepared string for bat file
}
"""
import os
# Get variables
ck=i['ck_kernel']
s=''
iv=i.get('interactive','')
cus=i.get('customize',{})
fp=cus.get('full_path','')
hosd=i['host_os_dict']
tosd=i['target_os_dict']
win=tosd.get('windows_base','')
winh=hosd.get('windows_base','')
# Check platform
hplat=hosd.get('ck_name','')
tplat=tosd.get('ck_name','')
hproc=hosd.get('processor','')
tproc=tosd.get('processor','')
remote=tosd.get('remote','')
tbits=tosd.get('bits','')
env=i['env']
ep=cus['env_prefix']
fi=cus.get('include_file','')
pinc=fp
fpinc=''
found=False
while True:
fpinc=os.path.join(pinc,'include', fi)
if os.path.isfile(fpinc):
found=True
break
fpinc=os.path.join(pinc,'include','hdf5', 'serial', fi)
if os.path.isfile(fpinc):
found=True
break
pincx=os.path.dirname(pinc)
if pincx==pinc:
break
pinc=pincx
if not found:
return {'return':1, 'error':'can\'t find include directory for HDF5'}
pi=os.path.realpath(os.path.dirname(fpinc))
pii=os.path.dirname(pi)
lb=os.path.basename(fp)
lbs=lb
if lbs.endswith('.so'):
lbs=lbs[:-3]+'.a'
elif lbs.endswith('.lib'):
lbs=lbs[:-4]+'.dll'
pl=os.path.realpath(os.path.dirname(fp))
cus['path_lib']=pl
pl1=os.path.dirname(pl)
pl2=os.path.dirname(pl1)
cus['path_include']=pi
cus['include_name']=fi
cus['static_lib']=lb
cus['dynamic_lib']=lbs
r = ck.access({'action': 'lib_path_export_script', 'module_uoa': 'os', 'host_os_dict': hosd,
'lib_path': cus.get('path_lib','')})
if r['return']>0: return r
s += r['script']
env[ep]=pii
pb=os.path.join(pii,'bin')
if os.path.isdir(pb):
env[ep+'_BIN']=pb
cus['path_bin']=pb
if tplat=='win':
s+='\nset PATH='+pb+';%PATH%\n\n'
env[ep+'_LFLAG']=os.path.join(pl,'hdf5.lib')
env[ep+'_LFLAG_HL']=os.path.join(pl,'hdf5_hl.lib')
env[ep+'_INCLUDE_NAME']=cus.get('include_name','')
env[ep+'_STATIC_NAME']=cus.get('static_lib','')
env[ep+'_DYNAMIC_NAME']=cus.get('dynamic_lib','')
return {'return':0, 'bat':s}
| 25.55 | 97 | 0.501957 |
import os
| true | true |
1c3fbd449f724a0f3dc9619c6e39da5f11648aac | 6,009 | py | Python | python/oneflow/compatible/single_client/test/ops/test_clip_by_value.py | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 3,285 | 2020-07-31T05:51:22.000Z | 2022-03-31T15:20:16.000Z | python/oneflow/compatible/single_client/test/ops/test_clip_by_value.py | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 2,417 | 2020-07-31T06:28:58.000Z | 2022-03-31T23:04:14.000Z | python/oneflow/compatible/single_client/test/ops/test_clip_by_value.py | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 520 | 2020-07-31T05:52:42.000Z | 2022-03-29T02:38:11.000Z | """
Copyright 2020 The OneFlow Authors. All rights reserved.
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 unittest
from collections import OrderedDict
import numpy as np
import tensorflow as tf
from test_util import GenArgList
import oneflow.compatible.single_client.unittest
from oneflow.compatible import single_client as flow
from oneflow.compatible.single_client import typing as oft
gpus = tf.config.experimental.list_physical_devices("GPU")
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
def _np_dtype_to_of_dtype(np_dtype):
if np_dtype == np.float32:
return flow.float
else:
raise NotImplementedError
def _of_clip_by_value(values, min, max, device_type="gpu", dynamic=False, grad_cb=None):
data_type = _np_dtype_to_of_dtype(values.dtype)
if callable(grad_cb):
def clip(values_blob):
with flow.scope.placement(device_type, "0:0"):
x = flow.get_variable(
"values",
shape=values.shape,
dtype=data_type,
initializer=flow.constant_initializer(0),
)
x = flow.cast_to_current_logical_view(x)
x = x + values_blob
y = flow.clip_by_value(x, min, max)
flow.optimizer.SGD(
flow.optimizer.PiecewiseConstantScheduler([], [0.001]), momentum=0
).minimize(y)
flow.watch_diff(x, grad_cb)
return y
else:
def clip(values_blob):
with flow.scope.placement(device_type, "0:0"):
return flow.clip_by_value(values_blob, min, max, name="Clip")
flow.clear_default_session()
func_config = flow.FunctionConfig()
func_config.default_data_type(data_type)
if grad_cb is not None:
func_config_type = "train"
else:
func_config_type = "predict"
if dynamic:
func_config.default_logical_view(flow.scope.mirrored_view())
@flow.global_function(type=func_config_type, function_config=func_config)
def clip_fn(
values_def: oft.ListNumpy.Placeholder(values.shape, dtype=data_type)
):
return clip(values_def)
return clip_fn([values]).get().numpy_list()[0]
else:
func_config.default_logical_view(flow.scope.consistent_view())
@flow.global_function(type=func_config_type, function_config=func_config)
def clip_fn(values_def: oft.Numpy.Placeholder(values.shape, dtype=data_type)):
return clip(values_def)
return clip_fn(values).get().numpy()
def _compare_with_tf(test_case, values, min, max, device_type, dynamic):
with tf.GradientTape() as t:
x = tf.Variable(values)
y = tf.clip_by_value(x, min, max)
dy = t.gradient(y, x)
def compare_dy(dy_blob):
test_case.assertTrue(
np.array_equal(
dy.numpy(), dy_blob.numpy_list()[0] if dynamic else dy_blob.numpy()
)
)
of_y = _of_clip_by_value(
values=values,
min=min,
max=max,
device_type=device_type,
dynamic=dynamic,
grad_cb=compare_dy,
)
test_case.assertTrue(np.array_equal(y.numpy(), of_y))
@flow.unittest.skip_unless_1n1d()
class TestClipByValue(flow.unittest.TestCase):
def test_clip_by_value(test_case):
values = np.random.randint(low=-100, high=100, size=(8, 512, 4)).astype(
np.float32
)
np_out = np.clip(values, -50, 50)
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "gpu"]
arg_dict["dynamic"] = [True, False]
for arg in GenArgList(arg_dict):
of_out = _of_clip_by_value(values, -50, 50, *arg)
test_case.assertTrue(np.array_equal(np_out, of_out))
def test_clip_by_min(test_case):
values = np.random.standard_normal((100, 30)).astype(np.float32)
np_out = np.clip(values, a_min=0, a_max=None)
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "gpu"]
arg_dict["dynamic"] = [True, False]
for arg in GenArgList(arg_dict):
of_out = _of_clip_by_value(values, 0, None, *arg)
test_case.assertTrue(np.array_equal(np_out, of_out))
def test_clip_by_max(test_case):
values = np.random.standard_normal((2, 64, 800, 1088)).astype(np.float32)
np_out = np.clip(values, a_min=None, a_max=0.2)
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "gpu"]
arg_dict["dynamic"] = [True, False]
for arg in GenArgList(arg_dict):
of_out = _of_clip_by_value(values, None, 0.2, *arg)
test_case.assertTrue(np.allclose(np_out, of_out))
def test_clip_by_value_grad(test_case):
values = np.random.standard_normal(1024).astype(np.float32)
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "gpu"]
arg_dict["dynamic"] = [True, False]
for arg in GenArgList(arg_dict):
_compare_with_tf(test_case, values, 0, 0.5, *arg)
def test_clip_by_value_grad_case_1(test_case):
values = np.random.standard_normal((128, 10, 27)).astype(np.float32)
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "gpu"]
arg_dict["dynamic"] = [True, False]
for arg in GenArgList(arg_dict):
_compare_with_tf(test_case, values, -0.2, 0.2, *arg)
if __name__ == "__main__":
unittest.main()
| 35.140351 | 88 | 0.644533 |
import unittest
from collections import OrderedDict
import numpy as np
import tensorflow as tf
from test_util import GenArgList
import oneflow.compatible.single_client.unittest
from oneflow.compatible import single_client as flow
from oneflow.compatible.single_client import typing as oft
gpus = tf.config.experimental.list_physical_devices("GPU")
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
def _np_dtype_to_of_dtype(np_dtype):
if np_dtype == np.float32:
return flow.float
else:
raise NotImplementedError
def _of_clip_by_value(values, min, max, device_type="gpu", dynamic=False, grad_cb=None):
data_type = _np_dtype_to_of_dtype(values.dtype)
if callable(grad_cb):
def clip(values_blob):
with flow.scope.placement(device_type, "0:0"):
x = flow.get_variable(
"values",
shape=values.shape,
dtype=data_type,
initializer=flow.constant_initializer(0),
)
x = flow.cast_to_current_logical_view(x)
x = x + values_blob
y = flow.clip_by_value(x, min, max)
flow.optimizer.SGD(
flow.optimizer.PiecewiseConstantScheduler([], [0.001]), momentum=0
).minimize(y)
flow.watch_diff(x, grad_cb)
return y
else:
def clip(values_blob):
with flow.scope.placement(device_type, "0:0"):
return flow.clip_by_value(values_blob, min, max, name="Clip")
flow.clear_default_session()
func_config = flow.FunctionConfig()
func_config.default_data_type(data_type)
if grad_cb is not None:
func_config_type = "train"
else:
func_config_type = "predict"
if dynamic:
func_config.default_logical_view(flow.scope.mirrored_view())
@flow.global_function(type=func_config_type, function_config=func_config)
def clip_fn(
values_def: oft.ListNumpy.Placeholder(values.shape, dtype=data_type)
):
return clip(values_def)
return clip_fn([values]).get().numpy_list()[0]
else:
func_config.default_logical_view(flow.scope.consistent_view())
@flow.global_function(type=func_config_type, function_config=func_config)
def clip_fn(values_def: oft.Numpy.Placeholder(values.shape, dtype=data_type)):
return clip(values_def)
return clip_fn(values).get().numpy()
def _compare_with_tf(test_case, values, min, max, device_type, dynamic):
with tf.GradientTape() as t:
x = tf.Variable(values)
y = tf.clip_by_value(x, min, max)
dy = t.gradient(y, x)
def compare_dy(dy_blob):
test_case.assertTrue(
np.array_equal(
dy.numpy(), dy_blob.numpy_list()[0] if dynamic else dy_blob.numpy()
)
)
of_y = _of_clip_by_value(
values=values,
min=min,
max=max,
device_type=device_type,
dynamic=dynamic,
grad_cb=compare_dy,
)
test_case.assertTrue(np.array_equal(y.numpy(), of_y))
@flow.unittest.skip_unless_1n1d()
class TestClipByValue(flow.unittest.TestCase):
def test_clip_by_value(test_case):
values = np.random.randint(low=-100, high=100, size=(8, 512, 4)).astype(
np.float32
)
np_out = np.clip(values, -50, 50)
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "gpu"]
arg_dict["dynamic"] = [True, False]
for arg in GenArgList(arg_dict):
of_out = _of_clip_by_value(values, -50, 50, *arg)
test_case.assertTrue(np.array_equal(np_out, of_out))
def test_clip_by_min(test_case):
values = np.random.standard_normal((100, 30)).astype(np.float32)
np_out = np.clip(values, a_min=0, a_max=None)
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "gpu"]
arg_dict["dynamic"] = [True, False]
for arg in GenArgList(arg_dict):
of_out = _of_clip_by_value(values, 0, None, *arg)
test_case.assertTrue(np.array_equal(np_out, of_out))
def test_clip_by_max(test_case):
values = np.random.standard_normal((2, 64, 800, 1088)).astype(np.float32)
np_out = np.clip(values, a_min=None, a_max=0.2)
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "gpu"]
arg_dict["dynamic"] = [True, False]
for arg in GenArgList(arg_dict):
of_out = _of_clip_by_value(values, None, 0.2, *arg)
test_case.assertTrue(np.allclose(np_out, of_out))
def test_clip_by_value_grad(test_case):
values = np.random.standard_normal(1024).astype(np.float32)
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "gpu"]
arg_dict["dynamic"] = [True, False]
for arg in GenArgList(arg_dict):
_compare_with_tf(test_case, values, 0, 0.5, *arg)
def test_clip_by_value_grad_case_1(test_case):
values = np.random.standard_normal((128, 10, 27)).astype(np.float32)
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "gpu"]
arg_dict["dynamic"] = [True, False]
for arg in GenArgList(arg_dict):
_compare_with_tf(test_case, values, -0.2, 0.2, *arg)
if __name__ == "__main__":
unittest.main()
| true | true |
1c3fbd972582e7814d0ea0aca085c77b85fb4860 | 5,189 | py | Python | metrics/functional/cls_acc_f1.py | ShannonAI/dice_loss_for_NLP | d437bb999185535df46fdb74d1f2f57161331b44 | [
"Apache-2.0"
] | 143 | 2020-04-25T11:23:10.000Z | 2022-03-30T14:49:21.000Z | metrics/functional/cls_acc_f1.py | ShannonAI/dice_loss_for_NLP | d437bb999185535df46fdb74d1f2f57161331b44 | [
"Apache-2.0"
] | 17 | 2021-04-12T19:11:58.000Z | 2022-02-21T02:42:56.000Z | metrics/functional/cls_acc_f1.py | ShannonAI/dice_loss_for_NLP | d437bb999185535df46fdb74d1f2f57161331b44 | [
"Apache-2.0"
] | 26 | 2021-03-26T08:05:37.000Z | 2022-03-15T07:28:38.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# file: cls_acc_f1.py
# description:
# compute acc and f1 scores for text classification task.
import torch
import torch.nn.functional as F
def collect_confusion_matrix(y_pred_labels, y_gold_labels, num_classes=2):
"""
compute accuracy and f1 scores for text classification task.
Args:
pred_labels: [batch_size] index of labels.
gold_labels: [batch_size] index of labels.
Returns:
A LongTensor composed by [true_positive, false_positive, false_negative]
"""
if num_classes <= 0:
raise ValueError
if num_classes == 1 or num_classes == 2:
num_classes = 1
y_true_onehot = y_gold_labels.bool()
y_pred_onehot = y_pred_labels.bool()
else:
y_true_onehot = F.one_hot(y_gold_labels, num_classes=num_classes)
y_pred_onehot = F.one_hot(y_pred_labels, num_classes=num_classes)
if num_classes == 1:
y_true_onehot = y_true_onehot.bool()
y_pred_onehot = y_pred_onehot.bool()
true_positive = (y_true_onehot & y_pred_onehot).long().sum()
false_positive = (y_pred_onehot & ~ y_true_onehot).long().sum()
false_negative = (~ y_pred_onehot & y_true_onehot).long().sum()
stack_confusion_matrix = torch.stack([true_positive, false_positive, false_negative])
return stack_confusion_matrix
multi_label_confusion_matrix = []
for idx in range(num_classes):
index_item = torch.tensor([idx], dtype=torch.long).cuda()
y_true_item_onehot = torch.index_select(y_true_onehot, 1, index_item)
y_pred_item_onehot = torch.index_select(y_pred_onehot, 1, index_item)
true_sum_item = torch.sum(y_true_item_onehot)
pred_sum_item = torch.sum(y_pred_item_onehot)
true_positive_item = torch.sum(y_true_item_onehot.multiply(y_pred_item_onehot))
false_positive_item = pred_sum_item - true_positive_item
false_negative_item = true_sum_item - true_positive_item
confusion_matrix_item = torch.tensor([true_positive_item, false_positive_item, false_negative_item],
dtype=torch.long)
multi_label_confusion_matrix.append(confusion_matrix_item)
stack_confusion_matrix = torch.stack(multi_label_confusion_matrix, dim=0)
return stack_confusion_matrix
def compute_precision_recall_f1_scores(confusion_matrix, num_classes=2, f1_type="micro"):
"""
compute precision, recall and f1 scores.
Description:
f1: 2 * precision * recall / (precision + recall)
- precision = true_positive / true_positive + false_positive
- recall = true_positive / true_positive + false_negative
Returns:
precision, recall, f1
"""
if num_classes == 2 or num_classes == 1:
confusion_matrix = confusion_matrix.to("cpu").numpy().tolist()
true_positive, false_positive, false_negative = tuple(confusion_matrix)
precision = true_positive / (true_positive + false_positive + 1e-10)
recall = true_positive / (true_positive + false_negative + 1e-10)
f1 = 2 * precision * recall / (precision + recall + 1e-10)
precision, recall, f1 = round(precision, 5), round(recall, 5), round(f1, 5)
return precision, recall, f1
if f1_type == "micro":
precision, recall, f1 = micro_precision_recall_f1(confusion_matrix, num_classes)
elif f1_type == "macro":
precision, recall, f1 = macro_precision_recall_f1(confusion_matrix)
else:
raise ValueError
return precision, recall, f1
def micro_precision_recall_f1(all_confusion_matrix, num_classes):
precision_lst = []
recall_lst = []
all_confusion_matrix_lst = all_confusion_matrix.to("cpu").numpy().tolist()
for idx in range(num_classes):
matrix_item = all_confusion_matrix_lst[idx]
true_positive_item, false_positive_item, false_negative_item = tuple(matrix_item)
precision_item = true_positive_item / (true_positive_item + false_positive_item + 1e-10)
recall_item = true_positive_item / (true_positive_item + false_negative_item + 1e-10)
precision_lst.append(precision_item)
recall_lst.append(recall_item)
avg_precision = sum(precision_lst) / num_classes
avg_recall = sum(recall_lst) / num_classes
avg_f1 = 2 * avg_recall * avg_precision / (avg_recall + avg_precision + 1e-10)
avg_precision, avg_recall, avg_f1 = round(avg_precision, 5), round(avg_recall, 5), round(avg_f1, 5)
return avg_precision, avg_recall, avg_f1
def macro_precision_recall_f1(all_confusion_matrix, ):
confusion_matrix = torch.sum(all_confusion_matrix, 1, keepdim=False)
confusion_matrix_lst = confusion_matrix.to("cpu").numpy().tolist()
true_positive, false_positive, false_negative = tuple(confusion_matrix_lst)
precision = true_positive / (true_positive + false_positive + 1e-10)
recall = true_positive / (true_positive + false_negative + 1e-10)
f1 = 2 * precision * recall / (precision + recall + 1e-10)
precision, recall, f1 = round(precision, 5), round(recall, 5), round(f1, 5)
return precision, recall, f1 | 39.310606 | 108 | 0.70264 |
import torch
import torch.nn.functional as F
def collect_confusion_matrix(y_pred_labels, y_gold_labels, num_classes=2):
if num_classes <= 0:
raise ValueError
if num_classes == 1 or num_classes == 2:
num_classes = 1
y_true_onehot = y_gold_labels.bool()
y_pred_onehot = y_pred_labels.bool()
else:
y_true_onehot = F.one_hot(y_gold_labels, num_classes=num_classes)
y_pred_onehot = F.one_hot(y_pred_labels, num_classes=num_classes)
if num_classes == 1:
y_true_onehot = y_true_onehot.bool()
y_pred_onehot = y_pred_onehot.bool()
true_positive = (y_true_onehot & y_pred_onehot).long().sum()
false_positive = (y_pred_onehot & ~ y_true_onehot).long().sum()
false_negative = (~ y_pred_onehot & y_true_onehot).long().sum()
stack_confusion_matrix = torch.stack([true_positive, false_positive, false_negative])
return stack_confusion_matrix
multi_label_confusion_matrix = []
for idx in range(num_classes):
index_item = torch.tensor([idx], dtype=torch.long).cuda()
y_true_item_onehot = torch.index_select(y_true_onehot, 1, index_item)
y_pred_item_onehot = torch.index_select(y_pred_onehot, 1, index_item)
true_sum_item = torch.sum(y_true_item_onehot)
pred_sum_item = torch.sum(y_pred_item_onehot)
true_positive_item = torch.sum(y_true_item_onehot.multiply(y_pred_item_onehot))
false_positive_item = pred_sum_item - true_positive_item
false_negative_item = true_sum_item - true_positive_item
confusion_matrix_item = torch.tensor([true_positive_item, false_positive_item, false_negative_item],
dtype=torch.long)
multi_label_confusion_matrix.append(confusion_matrix_item)
stack_confusion_matrix = torch.stack(multi_label_confusion_matrix, dim=0)
return stack_confusion_matrix
def compute_precision_recall_f1_scores(confusion_matrix, num_classes=2, f1_type="micro"):
if num_classes == 2 or num_classes == 1:
confusion_matrix = confusion_matrix.to("cpu").numpy().tolist()
true_positive, false_positive, false_negative = tuple(confusion_matrix)
precision = true_positive / (true_positive + false_positive + 1e-10)
recall = true_positive / (true_positive + false_negative + 1e-10)
f1 = 2 * precision * recall / (precision + recall + 1e-10)
precision, recall, f1 = round(precision, 5), round(recall, 5), round(f1, 5)
return precision, recall, f1
if f1_type == "micro":
precision, recall, f1 = micro_precision_recall_f1(confusion_matrix, num_classes)
elif f1_type == "macro":
precision, recall, f1 = macro_precision_recall_f1(confusion_matrix)
else:
raise ValueError
return precision, recall, f1
def micro_precision_recall_f1(all_confusion_matrix, num_classes):
precision_lst = []
recall_lst = []
all_confusion_matrix_lst = all_confusion_matrix.to("cpu").numpy().tolist()
for idx in range(num_classes):
matrix_item = all_confusion_matrix_lst[idx]
true_positive_item, false_positive_item, false_negative_item = tuple(matrix_item)
precision_item = true_positive_item / (true_positive_item + false_positive_item + 1e-10)
recall_item = true_positive_item / (true_positive_item + false_negative_item + 1e-10)
precision_lst.append(precision_item)
recall_lst.append(recall_item)
avg_precision = sum(precision_lst) / num_classes
avg_recall = sum(recall_lst) / num_classes
avg_f1 = 2 * avg_recall * avg_precision / (avg_recall + avg_precision + 1e-10)
avg_precision, avg_recall, avg_f1 = round(avg_precision, 5), round(avg_recall, 5), round(avg_f1, 5)
return avg_precision, avg_recall, avg_f1
def macro_precision_recall_f1(all_confusion_matrix, ):
confusion_matrix = torch.sum(all_confusion_matrix, 1, keepdim=False)
confusion_matrix_lst = confusion_matrix.to("cpu").numpy().tolist()
true_positive, false_positive, false_negative = tuple(confusion_matrix_lst)
precision = true_positive / (true_positive + false_positive + 1e-10)
recall = true_positive / (true_positive + false_negative + 1e-10)
f1 = 2 * precision * recall / (precision + recall + 1e-10)
precision, recall, f1 = round(precision, 5), round(recall, 5), round(f1, 5)
return precision, recall, f1 | true | true |
1c3fbdcd48e631b7ec93438b03f953b85ecdf799 | 32,297 | py | Python | app/maingame.py | diegoag30/ScrabbleAr | e309b21ec60148b290c45f4edc6bf90d391d144a | [
"MIT"
] | 3 | 2020-05-26T21:02:48.000Z | 2020-08-06T03:19:54.000Z | app/maingame.py | diegoag30/ScrabbleAr | e309b21ec60148b290c45f4edc6bf90d391d144a | [
"MIT"
] | null | null | null | app/maingame.py | diegoag30/ScrabbleAr | e309b21ec60148b290c45f4edc6bf90d391d144a | [
"MIT"
] | null | null | null | import PySimpleGUI as sg
import random
from itertools import combinations
import time
import clasificarPalabra
import IA
import os.path
import config_tablero
from Bolsa import Bolsa
from Configuracion import Configuracion
from puntajes import Puntaje
base_path=os.path.dirname(os.path.abspath(__file__))
"""
gestiona todas las operacions necesarias para generar el tablero y modificar su estado
."""
def main_game(num_tablero, configuracion):
#Inicializacion de variables e imagenes
conf = configuracion
bolsa = Bolsa(conf.getConfiguracionLetras())
PC=IA
clasificar=clasificarPalabra
"""
ruta absoluta para utilizar recursos
."""
blank = {'letra':'', 'imagen': os.path.join(base_path,'images/fondo.png')}
a={'letra':'A','imagen': os.path.join(base_path,'images/a.png')} #(r'img.png')
b={'letra':'B','imagen': os.path.join(base_path,'images/b.png')}
c={'letra':'C','imagen': os.path.join(base_path,'images/c.png')}
d={'letra':'D','imagen': os.path.join(base_path,'images/d.png')}
e={'letra':'E','imagen': os.path.join(base_path,'images/e.png')}
f={'letra':'F','imagen': os.path.join(base_path,'images/f.png')}
g={'letra':'G','imagen': os.path.join(base_path,'images/g.png')}
h={'letra':'H','imagen': os.path.join(base_path,'images/h.png')}
i={'letra':'I','imagen': os.path.join(base_path,'images/i.png')}
j={'letra':'J','imagen': os.path.join(base_path,'images/j.png')}
k={'letra':'K','imagen': os.path.join(base_path,'images/k.png')}
l={'letra':'L','imagen': os.path.join(base_path,'images/l.png')}
m={'letra':'M','imagen': os.path.join(base_path,'images/m.png')}
n={'letra':'N','imagen': os.path.join(base_path,'images/n.png')}
o={'letra':'O','imagen': os.path.join(base_path,'images/o.png')}
p={'letra':'P','imagen': os.path.join(base_path,'images/p.png')}
q={'letra':'Q','imagen': os.path.join(base_path,'images/q.png')}
r={'letra':'R','imagen': os.path.join(base_path,'images/r.png')}
s={'letra':'S','imagen': os.path.join(base_path,'images/s.png')}
t={'letra':'T','imagen': os.path.join(base_path,'images/t.png')}
u={'letra':'U','imagen': os.path.join(base_path,'images/u.png')}
v={'letra':'V','imagen': os.path.join(base_path,'images/v.png')}
w={'letra':'W','imagen': os.path.join(base_path,'images/w.png')}
x={'letra':'X','imagen': os.path.join(base_path,'images/x.png')}
y={'letra':'Y','imagen': os.path.join(base_path,'images/y.png')}
z={'letra':'Z','imagen': os.path.join(base_path,'images/z.png')}
"""
son los diccionarios que contienen las imagenes para cada tablero del juego
."""
images_PuntosTablero2={'centro':os.path.join(base_path,'images/centro.png'), 'fondo':os.path.join(base_path,'images/fond2.png'), 'green' :os.path.join(base_path,'images/LX2.png') ,'red':os.path.join(base_path,'images/PX3.png'),'orange':os.path.join(base_path,'images/PX-2.png'),'blue':os.path.join(base_path,'images/LX3.png')}
images_PuntosTablero3={'centro':os.path.join(base_path,'images/corona1.png'),'fondo':os.path.join(base_path,'images/fond3.png'),'red':os.path.join(base_path,'images/PX3ESC.png'),'orange':os.path.join(base_path,'images/PX2ESC.png'),'blue':os.path.join(base_path,'images/LX-3Cr.png'),'green':os.path.join(base_path,'images/LX-2Cr.png')}
images_PuntosTablero1={'centro':os.path.join(base_path,'images/corona.png'),'fondo':os.path.join(base_path,'images/fondo.png'),'red':os.path.join(base_path,'images/PX3.png'),'orange':os.path.join(base_path,'images/PX2.png'),'blue':os.path.join(base_path,'images/LX3.png'),'green':os.path.join(base_path,'images/LX2.png')}
images_PuntosTablero={}
fichasIA=[]
color_button=('white','white')
images = {'BLANK':blank,'A': a, 'B': b, 'C': c, 'D': d, 'E': e, 'F': f, 'G': g, 'H': h, 'I': i, 'J': j, 'K': k, 'L': l, 'M': m, 'N': n, 'O': o, 'P': p, 'Q': q, 'R': r, 'S': s, 'T': t, 'U': u, 'V': v, 'W': w, 'X': x, 'Y': y, 'Z': z}
images_keys= bolsa ### Se recibe las letras configuradas por el usuario, y se eliminan las que estan en 0
print(images_keys)
random.shuffle(images_keys.get_letras(),random.random)
initial_atril=[]
initial_atril2=[]
PC.atrilPalabrasValidas(images_keys,initial_atril2, conf)
initial_atril=initial_atril2[:]
## SE Restan las fichas cuando se crea el atril del jugador, ademas se quitan las fichas que quedaron en 0
'''
for ficha in initial_atril:
if ficha in bolsa.get_fichas():
bolsa.quitar_fichas(ficha,1)
images_keys = list(bolsa.letras_validas().keys())
#print(bolsa.letras_validas().keys())
'''
def actualizar_layout_bolsa():
for ficha in bolsa.get_fichas().keys():
window.FindElement(ficha).update(bolsa.cant_letras(ficha))
def get_name():
'''Pop up inicial, que obtiene el nombre del jugador, para poder agregarlo al ranking en caso de ser necesario '''
layout = [[sg.Text('Bienvenido a ScrabbleAR. Por favor introduce tu nombre:',background_color='#00796B'),],
[sg.InputText(key='-IN-')],
[sg.Submit(), sg.Cancel()]]
window = sg.Window('Window Title', layout)
event, values = window.read()
window.close()
text_input = values['-IN-']
return text_input
"""
clase padre que hereda un metodo para generar botones
."""
class Tablero():
def render_square(self, image ,key , texto= '',color_button=('white','white')):
#return sg.RButton(texto,image_filename=image,image_size=(50, 50), pad=(2,2),key=key,button_color=color_button)
return sg.RButton(texto,image_filename=image,image_size=(50, 50), pad=(2,2),key=key,button_color=color_button)
"""
genera los tres tablero necesarios para el juego
segun una configuaracion dada por un objeto (boardConfig) se contiene el estado segun el tablero que se pida
."""
class Tablero(Tablero):
def Tab(self,images):
tamaño=(50,50)
tablero1=[]
for i in range(15):
row=[]
for j in range(15):
piece_image=images_PuntosTablero['fondo']
valor=boardConfig[i][j].get_valor()
color=boardConfig[i][j].get_color()
if color == 'green':
piece_image=images_PuntosTablero['green']
row.append(self.render_square(piece_image,key =(i,j),texto='', color_button=('white','green')))
elif color == 'red':
piece_image=images_PuntosTablero['red']
row.append(self.render_square(piece_image,key =(i,j),texto='', color_button=('white','red')))
elif color == 'blue':
piece_image=images_PuntosTablero['blue']
row.append(self.render_square(piece_image,key =(i,j),texto='', color_button=('white','blue')))
elif color == 'violet':
#piece_image=os.path.join(base_path,'images/corona.png')
piece_image=images_PuntosTablero['centro']
row.append(self.render_square(piece_image,key =(i,j),texto='', color_button=('white','Dark violet')))
elif color == 'orange':
#piece_image=os.path.join(base_path,'images/PX2.png')
#piece_image = images_PuntosNv1['PX2']
piece_image=images_PuntosTablero['orange']
row.append(self.render_square(piece_image,key =(i,j),texto='', color_button=('white','orange')))
else:
color_button=('white','white')
row.append(self.render_square(piece_image,key =(i,j),texto=''))
tablero1.append(row)
return (tablero1,tamaño)
""" genera dos atriles que contienen las palabras del jugador y de simbolos que representan las palabras de la pc ."""
class atril1():
'''Clase que controla la UI del atril'''
def __init__(self,T=True):
self._T= T
def crearAtril(self):
def render1(image, key, texto='',color_button=('white','white')):
return sg.RButton(texto,image_filename=image,image_size=(50, 50), pad=(2,2),key=key,button_color=color_button)
atril=[]
#Si se pasa true como parametro, los botones del atril se rellenan con letras
if self._T:
for i in range(7):
row=[]
piece_image = images[initial_atril[i]]
row.append(render1(piece_image['imagen'],key =(i),texto='', color_button=('white','white')))
atril.append(row)
#En caso de que se pase false, se mostraran signos de interrogacion en el atril(atril de la computadora)
else:
img=os.path.join(base_path,'images/interrogacion.png')
for i in range(7):
row=[]
row.append(render1(img,key =(i),texto='', color_button=('white','white')))
atril.append(row)
return atril
def modificarBoton(valores):
''' modificartBoton () cambia el estado del boton , cambia la imagen de una pieza del tablero y consta que esta ocupado'''
#if boardConfig[button[0]][button[1]].get_estado() == True:
#print('')
if boardConfig[button[0]][button[1]].get_estado() == False:
img=''
window[i].update(image_filename=img,image_size=(50, 50), button_color=('',''))
valores.append(boardConfig[button[0]][button[1]].get_valor())
piece_image = images[initial_atril[i]]
img=piece_image['imagen']
window[button].update(image_filename=img, image_size= tamaño_img ,button_color=('white','grey'))
listadoPosicionLetrasTablero.append(button)
p2=palabra[0]
p2=p2+letra
palabra[0]=p2
initial_atril[i]='' ## relacionar con la bolsa
listadoPosicionLetrasAtril.append(i)
boardConfig[button[0]][button[1]].set_estado(True)
print('los valores de las letras son: ', valores)
""" devuelve las letras ivalidas ingresadas en el tablero al atril respetando el orden en que fueron ingresadas ."""
def devolverLetras():
#images_PuntosTablero3
p=palabra[0]
print(p)
cont=0
#if opc==3:
for i in listadoPosicionLetrasAtril:
piece_image = images[p[cont]]
img=piece_image['imagen']
window[i].update(image_filename=img,image_size=(50, 50), button_color=('',''))
initial_atril[i]=p[cont]
img=images_PuntosTablero['fondo']
boardConfig[listadoPosicionLetrasTablero[cont][0]][listadoPosicionLetrasTablero[cont][1]].set_estado(False)
#color=boardConfig[listadoPosicionLetrasTablero[cont][0][listadoPosicionLetrasTablero[cont][1]].get_color()
color=boardConfig[listadoPosicionLetrasTablero[cont][0]][listadoPosicionLetrasTablero[cont][1]].get_color()
if color == 'violet':
piece_image=images_PuntosTablero['centro']
window[listadoPosicionLetrasTablero[cont]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','Dark violet'))
elif color == 'green':
piece_image=images_PuntosTablero['green']
window[listadoPosicionLetrasTablero[cont]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','green'))
elif color == 'red':
piece_image=images_PuntosTablero['red']
window[listadoPosicionLetrasTablero[cont]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','red'))
elif color == 'blue':
piece_image=images_PuntosTablero['blue']
window[listadoPosicionLetrasTablero[cont]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','blue'))
elif color == 'orange':
piece_image=images_PuntosTablero['orange']
window[listadoPosicionLetrasTablero[cont]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','orange'))
else:
window[listadoPosicionLetrasTablero[cont]].update(image_filename=img, image_size= tamaño_img ,button_color=('white','white'))
cont=cont+1
print(initial_atril)
"""actualiza el atril del jugador despues de comprobar que la palabra ingresada es correcta con el boton FINALIZAR TURNO."""
def actualizarAtrilJugador():
initial_atril2=[]
PC.atrilPalabrasValidas(images_keys,initial_atril2, conf)
for i in range(0,7):
if initial_atril[i]=='':
# initial_atril[i]=random.choice(initial_atril2)
initial_atril[i]=initial_atril2[i]
piece_image = images[initial_atril[i]]
img=piece_image['imagen']
window[i].update(image_filename=img,image_size=(50, 50), button_color=('',''))
print(initial_atril)
""" actualiza el atril y limpia del tablero las palabras ingresadas en se turno ."""
def PasarTurno(initial_atril):
if len(listadoPosicionLetrasTablero)>0:
for i in range(0,len(listadoPosicionLetrasTablero)):
img=images_PuntosTablero['fondo']
boardConfig[listadoPosicionLetrasTablero[i][0]][listadoPosicionLetrasTablero[i][1]].set_estado(False)
#color=boardConfig[listadoPosicionLetrasTablero[cont][0][listadoPosicionLetrasTablero[cont][1]].get_color()
color=boardConfig[listadoPosicionLetrasTablero[i][0]][listadoPosicionLetrasTablero[i][1]].get_color()
if color == 'violet':
piece_image=images_PuntosTablero['centro']
window[listadoPosicionLetrasTablero[i]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','Dark violet'))
elif color == 'green':
piece_image=images_PuntosTablero['green']
window[listadoPosicionLetrasTablero[i]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','green'))
elif color == 'red':
piece_image=images_PuntosTablero['red']
window[listadoPosicionLetrasTablero[i]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','red'))
elif color == 'blue':
piece_image=images_PuntosTablero['blue']
window[listadoPosicionLetrasTablero[i]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','blue'))
elif color == 'orange':
piece_image=images_PuntosTablero['orange']
window[listadoPosicionLetrasTablero[i]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','orange'))
else:
window[listadoPosicionLetrasTablero[i]].update(image_filename=img, image_size= tamaño_img ,button_color=('white','white'))
initial_atril2=[]
PC.atrilPalabrasValidas(images_keys,initial_atril2, conf)
initial_atril=[]
initial_atril=initial_atril2[:]
print(initial_atril,'Final')
for i in range(7):
#window[i].update(initial_atril[i])
piece_image = images[initial_atril[i]]
img=piece_image['imagen']
window[i].update(image_filename=img,image_size=(50, 50), button_color=('',''))
return initial_atril
""" cada vez que se termine una partida se limpia del tablero todas las palabras ingresadas ."""
def BorrarTablerGeneral():
def BorrarTablero(color):
piece_image=images_PuntosTablero['fondo']
if color == 'green':
piece_image=images_PuntosTablero['green']
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','green'))
elif color == 'red':
piece_image=images_PuntosTablero['red']
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','red'))
elif color == 'blue':
piece_image=images_PuntosTablero['blue']
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','blue'))
elif color == 'violet':
piece_image=images_PuntosTablero['centro']
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','Dark violet'))
elif color == 'orange':
piece_image=images_PuntosTablero['orange']
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','orange'))
else:
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','white'))
for i in range(15):
for j in range(15):
window[(i,j)].update('')
boardConfig[i][j].set_estado(False)
color=boardConfig[i][j].get_color()
BorrarTablero(color)
""" actualizad el listado que contiene el historial de casillas con premios del jugador y la PC."""
def actualizar_listado(listbox):
listbox.Update(listado) ## accedo a la tupla
"""se crea el atril del jugador y la Pc."""
####################
#inteligencia1.saludo()
nombre = get_name()
word_values = []
print(nombre)
atr1=atril1(True).crearAtril()
atr2=atril1(False).crearAtril()
""" en base a una opcion ingresada por la configuracion se instancia un objeto tablero y se elige una configuracion para crear el tablero."""
if num_tablero ==1:
images_PuntosTablero=images_PuntosTablero1
boardConfig=config_tablero.Config1()
obj = Tablero()
opc=1
elif num_tablero == 2:
#obj = Tablero2()
images_PuntosTablero=images_PuntosTablero2
boardConfig=config_tablero.Config2()
obj = Tablero()
#opc=2
elif num_tablero ==3:
images_PuntosTablero=images_PuntosTablero3
boardConfig=config_tablero.Config3()
obj = Tablero()
#bolsa.sacar_fichas(14)
""""""""""""""""""""""" interfaz grafica del panel del juego ."""""""""""""""""""""
elementos=obj.Tab(images) ##### estaria para conectarlo con una opcion para elegir el tablero
tablero= elementos[0]
tamaño_img = elementos[1]
columna_2 = [ [sg.Text('PUNTOS MAQUINA', background_color='#00796B')],[sg.Listbox(values =[], key='datosm', font='Courier 18' ,size=(20,10))],[sg.Text('TOTAL PUNTOS', background_color='#00796B')],[sg.Column(bolsa.get_layout(),key="BOLSA")]]
columna_1 = [ [sg.Text('PUNTOS JUGADOR', background_color='#00796B')],[sg.Listbox(values =[], key='datosj', font='Courier 18',size=(20,10))],[sg.Text('TOTAL PUNTOS', background_color='#00796B'), sg.Text(background_color='#00796B', size=(5,1), key='puntaje')],[sg.Text('00:00:00', background_color=('#01a9b4'),key='reloj')]]
columna_3 = [ [sg.Text('Total Puntos: '), sg.Text(size=(12,1), key='puntaje')]]
"""se agregar las columnas a una estructura que esta contenida dentro del layout."""
board_tab=[[sg.Button('FINALIZAR TURNO', size=(10,0), button_color=('#FFFFFF', '#004A79'), disabled=True)],[sg.Column(columna_1), sg.Column(atr1),sg.Column(tablero),sg.Column(atr2),sg.Column(columna_2)],[sg.Button('COMENZAR',button_color=('white','green')),sg.Button('PASAR',disabled=True),sg.Button('GUARDAR',disabled=True),sg.Button('FINALIZAR PARTIDA', size=(10,0), button_color=('#FFFFFF', '#F74343'))]]
window = sg.Window('ScrabbleAr',default_button_element_size=(12,1), auto_size_buttons=False).Layout(board_tab)
cantPasadas=0
#palabra=''
controlAt=[7,7,0,0]
palabra=['']
#i=0
""" condicionales para elegir y seguir una orientacion , para las palabras del jugador ."""
cant=2
T1=True
T2= True
T3= True
T4= True
F=0
C=0
#x=0
puntosCasilla=[]
putosL=0
"""listas necesarias para controlar el estado de las palabras ingresadas al tablero ."""
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
listadoPc=[]
listado=[]
#inicio=time.time()
wait=True
wait2=True
window.Finalize()
""" temporizador del juego."""
inicio=time.time()
iniciar=True
puntaje_jugador = 0
while ((True and iniciar)and (not bolsa.check_bolsa_vacia())):
while True:
if wait:
button , value = window.Read()
if button in (None , 'FINALIZAR PARTIDA'):
exit()
if button=='COMENZAR' and wait:
###
inicio=time.time()
"""
bolsa.quitar_fichas("A",8)
window.FindElement("AA").update(bolsa.cant_letras("A"))
if bolsa.bolsa_vacia():
break
"""
#VARIABLES USADAS PARA MOSTRAR EL CRONOMETRO EN PANTALLA
current_time = 0
paused = False
start_time = int(round(time.time() * 100))
window.FindElement('PASAR').update(disabled=False)
window.FindElement('GUARDAR').update(disabled=False)
window.FindElement('FINALIZAR TURNO').update(disabled=False)
#window.FindElement('PASAR TURNO').update(disabled=False)
window.FindElement('COMENZAR').update(disabled=True)
window['COMENZAR'].update( button_color=('white','red'))
wait=False
opc2=random.randint(0,1)
if opc2==1:
print('empieza el jugador')
if not(wait):
if (opc2==0)and wait2:
PC.inteligencia(controlAt,window,boardConfig,images,listadoPc,clasificar,images_keys,conf,fichasIA)
actualizar_layout_bolsa()
print('IA INICIAL')
wait2=False
### Depues del turno de la IA, si ya no quedan fichas se termina el juego.
if(bolsa.check_bolsa_vacia()):
sg.Popup('No quedan mas fichas')
print('la bolsa esta vacia:')
break
while True:
current_time = int(round(time.time() * 100)) - start_time
# minu = current_time // 100 // 60
# seg = current_time // 100 % 60
# mil = current_time % 100
window['reloj'].update('{:02d}:{:02d}.{:02d}'.format((current_time // 100) // 60,
(current_time // 100) % 60,
current_time % 100),background_color=('red'))
if conf.getConfiguracionesSeleccionadas()['tiempo'] == 'minimo':
if (current_time // 100) // 60 == 5:
print('=============================================5 MINUTOS====================================')
print('=============================================5 MINUTOS====================================')
print('=============================================5 MINUTOS====================================')
print('=============================================5 MINUTOS====================================')
sg.Popup('SE ACABO EL TIEMPO!!! PUNTAJE GUARDADO')
##Una vez que el tiempo termino, se guardan los puntajes
puntaje_final_jugador = Puntaje()
puntaje_final_jugador.agregar_nuevo_puntaje(nombre,puntaje_jugador,configuracion.getConfiguracionesSeleccionadas()['dificultad'])
window.close()
if conf.getConfiguracionesSeleccionadas()['tiempo'] == 'medio':
if (current_time // 100) // 60 == 15:
print('=============================================15 MINUTOS====================================')
print('=============================================15 MINUTOS====================================')
print('=============================================15 MINUTOS====================================')
print('=============================================15 MINUTOS====================================')
sg.Popup('SE ACABO EL TIEMPO!!! PUNTAJE GUARDADO')
##Una vez que el tiempo termino, se guardan los puntajes
puntaje_final_jugador = Puntaje()
puntaje_final_jugador.agregar_nuevo_puntaje(nombre,puntaje_jugador,configuracion.getConfiguracionesSeleccionadas()['dificultad'])
window.close()
if conf.getConfiguracionesSeleccionadas()['tiempo'] == 'maximo':
if (current_time // 100) // 60 == 30:
print('=============================================30 MINUTOS====================================')
print('=============================================30 MINUTOS====================================')
print('=============================================30 MINUTOS====================================')
print('=============================================30 MINUTOS====================================')
sg.Popup('SE ACABO EL TIEMPO!!! PUNTAJE GUARDADO')
##Una vez que el tiempo termino, se guardan los puntajes
puntaje_final_jugador = Puntaje()
puntaje_final_jugador.agregar_nuevo_puntaje(nombre,puntaje_jugador,configuracion.getConfiguracionesSeleccionadas()['dificultad'])
window.close()
puntosP=0
puntosL=0
#letra=''
l=-1
button , value = window.Read(timeout=10)
#type(button) is tuple
# if button == 'PASAR TURNO':
# wait2=True
# break
if button == 'FINALIZAR TURNO':
p = ""
p = p.join(palabra)
j
if palabra == '':
sg.Popup('todavia no formo una palabra')
elif len(palabra[0])>1:
if (clasificar.comprobarPalabraEnBaseAlNivel(palabra[0], conf)):
#print(palabra[0])
sg.Popup('PALABRA FORMADA : ' ,palabra)
print(clasificar.comprobarPalabraEnBaseAlNivel(palabra[0], conf))
#palabra[0]=''
T2= True
T1=True
T3= True
F=0
C=0
#cant=cant+1
#x=0
T4=True
if (clasificar.comprobarPalabraEnBaseAlNivel(palabra[0], conf)):
palabra[0]=''
actualizarAtrilJugador()
wait2=True
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
### se agrega el puntaje a la lista
listado.append(p + " " + str(bolsa.calcular_puntos(p,word_values)) + " Puntos")
actualizar_listado(window.FindElement('datosj'))
puntaje_jugador = puntaje_jugador + bolsa.calcular_puntos(p,word_values)
print(puntaje_jugador)
window['puntaje'].update(puntaje_jugador)
#####
actualizar_layout_bolsa()
del word_values[:]
break
#####
else:
sg.Popup('PALABRA INVALIDA')
devolverLetras()
T2=True
T3=True
T1=True
T4=True
palabra[0]=''
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
del word_values[:]
##window[]
# if len(word)>= 2 and len(word) <=7:
elif len(palabra[0])<2:
sg.Popup('la palabra es menor de 2')
#break
if button in (None , 'FINALIZAR PARTIDA'):
exit()
if button =='PASAR':
cantPasadas=cantPasadas+1
controlAt=[7,7,0,0]
# if cantPasadas==3:
# window.FindElement('PASAR').update(disabled=True)
if cantPasadas<4:
initial_atril=PasarTurno(initial_atril)
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
palabra=['']
T1=True
T2=True
#T3=True
T4=True
listado=[]
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
PC.inteligencia(controlAt,window,boardConfig,images,listadoPc,clasificar,images_keys,conf,fichasIA)
actualizar_layout_bolsa()
else:
sg.Popup('se supero la cantidad de pasadas')
if type(button) is int:
print(button)
if initial_atril[button] !='':
i=button
letra= initial_atril[button]
#####hoy palabra += letra
button , value = window.Read()
while(type(button)is not(tuple)):
button , value = window.Read()
#button , value = window.Read()
if type(button) is tuple:
if not(boardConfig[7][7].get_estado()):
print('posicion central no ocupada')
if not(boardConfig[7][7].get_estado()):
print('posicion central no ocupada')
if (button[0]==7 and button[1]==7)and T3 :
print(button)
modificarBoton(word_values)
T3=False
F=button[0]
C=button[1]
cant=0
#print(type(lista[1]))
if not(T3):
if(button[0]==F)and T1:
if C<button[1]and(button[1]==C+1):
T2=False
modificarBoton(word_values)
C=button[1]
if(button[1]==C)and T2:
if F<button[0]and(button[0]==F+1):
print(button)
T1=False
modificarBoton(word_values)
F=button[0]
#cant=4
else:
#if cant<10: ## la cantidad de palabras formadas con 7 letras
if T4:
modificarBoton(word_values)
F=button[0]
C=button[1]
T4=False
else:
if(button[0]==F)and T1 :
if C<button[1]and(button[1]==C+1):
T2=False
modificarBoton(word_values)
C=button[1]
if(button[1]==C)and T2:
if F<button[0]and(button[0]==F+1):
T1=False
modificarBoton(word_values)
F=button[0]
actualizar_listado(window.FindElement('datosj')) ## habria que multiplicar el valor de cada letra o palabra
print("ESTE ES EL PUNTAJE DEL JUGADOR: -------------" + str(puntaje_jugador))
## modifiquenlo para que muestres los puntos que se van acumulando por casillas
##
l=0
if type(button) is tuple:
if l ==-1:
sg.Popup('movimiento incorrecto')
if (opc2==1)and wait2:
PC.inteligencia(controlAt,window,boardConfig,images,listadoPc,clasificar,images_keys, conf,fichasIA)
actualizar_layout_bolsa()
print('IA FINAL')
controlAt=[8,7,0,0]
"""control del fin del tiempo de juego."""
final=time.time()
if final-inicio>120:
break
try:
if (current_time // 100) % 60 == 10:
print('=============================================10 SEGUNDOS====================================')
print('=============================================10 SEGUNDOS====================================')
print('=============================================10 SEGUNDOS====================================')
print('=============================================10 SEGUNDOS====================================')
except:
sg.Popup('Por favor aprete el boton comenzar',background_color='#00796B')
sg.Popup('FIN Juego')
print(bolsa.check_bolsa_vacia())
break
wait=True
window.FindElement('PASAR').update(disabled=True)
window.FindElement('GUARDAR').update(disabled=True)
window.FindElement('FINALIZAR TURNO').update(disabled=True)
#window.FindElement('PASAR TURNO').update(disabled=True)
window.FindElement('COMENZAR').update(disabled=False)
window['COMENZAR'].update( button_color=('white','green'))
while(button!='COMENZAR'):
button , value = window.Read()
if button=='COMENZAR':
initial_atril=[]
images_keys= list(images.keys()) ### seria la lista de palabras
print(images_keys)
images_keys.remove('BLANK')
random.shuffle(images_keys,random.random)
initial_atril=[]
initial_atril2=[]
PC.atrilPalabrasValidas(images_keys,initial_atril2, conf)
initial_atril=initial_atril2[:]
for i in range(7):
#window[i].update(initial_atril[i])
piece_image = images[initial_atril[i]]
img=piece_image['imagen']
window[i].update(image_filename=img,image_size=(50, 50), button_color=('',''))
##### blanquear tablero
#actulizarTablero(opc)
BorrarTablerGeneral()#cant=4
T1=True
T2=True
T3=True
palabra=['']
listado=[]
listadoPc=[]
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
initial_atril2=[]
cantPasadas=0
actualizar_listado(window.FindElement('datosj'))
actualizar_listado(window.FindElement('datosm'))
controlAt=[7,7,0,0]
#window['COMENZAR'].update( button_color=('white','green'))
bolsa = Bolsa(conf.getConfiguracionLetras())
##Una vez que el juego termino, se guardan los puntajes
puntaje_final_jugador = Puntaje()
puntaje_final_jugador.agregar_nuevo_puntaje(nombre,puntaje_jugador,configuracion.getConfiguracionesSeleccionadas()['dificultad'])
if __name__ == "__main__":
main_game(1)
| 37.467517 | 409 | 0.605319 | import PySimpleGUI as sg
import random
from itertools import combinations
import time
import clasificarPalabra
import IA
import os.path
import config_tablero
from Bolsa import Bolsa
from Configuracion import Configuracion
from puntajes import Puntaje
base_path=os.path.dirname(os.path.abspath(__file__))
def main_game(num_tablero, configuracion):
conf = configuracion
bolsa = Bolsa(conf.getConfiguracionLetras())
PC=IA
clasificar=clasificarPalabra
blank = {'letra':'', 'imagen': os.path.join(base_path,'images/fondo.png')}
a={'letra':'A','imagen': os.path.join(base_path,'images/a.png')}
b={'letra':'B','imagen': os.path.join(base_path,'images/b.png')}
c={'letra':'C','imagen': os.path.join(base_path,'images/c.png')}
d={'letra':'D','imagen': os.path.join(base_path,'images/d.png')}
e={'letra':'E','imagen': os.path.join(base_path,'images/e.png')}
f={'letra':'F','imagen': os.path.join(base_path,'images/f.png')}
g={'letra':'G','imagen': os.path.join(base_path,'images/g.png')}
h={'letra':'H','imagen': os.path.join(base_path,'images/h.png')}
i={'letra':'I','imagen': os.path.join(base_path,'images/i.png')}
j={'letra':'J','imagen': os.path.join(base_path,'images/j.png')}
k={'letra':'K','imagen': os.path.join(base_path,'images/k.png')}
l={'letra':'L','imagen': os.path.join(base_path,'images/l.png')}
m={'letra':'M','imagen': os.path.join(base_path,'images/m.png')}
n={'letra':'N','imagen': os.path.join(base_path,'images/n.png')}
o={'letra':'O','imagen': os.path.join(base_path,'images/o.png')}
p={'letra':'P','imagen': os.path.join(base_path,'images/p.png')}
q={'letra':'Q','imagen': os.path.join(base_path,'images/q.png')}
r={'letra':'R','imagen': os.path.join(base_path,'images/r.png')}
s={'letra':'S','imagen': os.path.join(base_path,'images/s.png')}
t={'letra':'T','imagen': os.path.join(base_path,'images/t.png')}
u={'letra':'U','imagen': os.path.join(base_path,'images/u.png')}
v={'letra':'V','imagen': os.path.join(base_path,'images/v.png')}
w={'letra':'W','imagen': os.path.join(base_path,'images/w.png')}
x={'letra':'X','imagen': os.path.join(base_path,'images/x.png')}
y={'letra':'Y','imagen': os.path.join(base_path,'images/y.png')}
z={'letra':'Z','imagen': os.path.join(base_path,'images/z.png')}
images_PuntosTablero2={'centro':os.path.join(base_path,'images/centro.png'), 'fondo':os.path.join(base_path,'images/fond2.png'), 'green' :os.path.join(base_path,'images/LX2.png') ,'red':os.path.join(base_path,'images/PX3.png'),'orange':os.path.join(base_path,'images/PX-2.png'),'blue':os.path.join(base_path,'images/LX3.png')}
images_PuntosTablero3={'centro':os.path.join(base_path,'images/corona1.png'),'fondo':os.path.join(base_path,'images/fond3.png'),'red':os.path.join(base_path,'images/PX3ESC.png'),'orange':os.path.join(base_path,'images/PX2ESC.png'),'blue':os.path.join(base_path,'images/LX-3Cr.png'),'green':os.path.join(base_path,'images/LX-2Cr.png')}
images_PuntosTablero1={'centro':os.path.join(base_path,'images/corona.png'),'fondo':os.path.join(base_path,'images/fondo.png'),'red':os.path.join(base_path,'images/PX3.png'),'orange':os.path.join(base_path,'images/PX2.png'),'blue':os.path.join(base_path,'images/LX3.png'),'green':os.path.join(base_path,'images/LX2.png')}
images_PuntosTablero={}
fichasIA=[]
color_button=('white','white')
images = {'BLANK':blank,'A': a, 'B': b, 'C': c, 'D': d, 'E': e, 'F': f, 'G': g, 'H': h, 'I': i, 'J': j, 'K': k, 'L': l, 'M': m, 'N': n, 'O': o, 'P': p, 'Q': q, 'R': r, 'S': s, 'T': t, 'U': u, 'V': v, 'W': w, 'X': x, 'Y': y, 'Z': z}
images_keys= bolsa 2, conf)
initial_atril=initial_atril2[:]
update(bolsa.cant_letras(ficha))
def get_name():
layout = [[sg.Text('Bienvenido a ScrabbleAR. Por favor introduce tu nombre:',background_color='#00796B'),],
[sg.InputText(key='-IN-')],
[sg.Submit(), sg.Cancel()]]
window = sg.Window('Window Title', layout)
event, values = window.read()
window.close()
text_input = values['-IN-']
return text_input
class Tablero():
def render_square(self, image ,key , texto= '',color_button=('white','white')):
return sg.RButton(texto,image_filename=image,image_size=(50, 50), pad=(2,2),key=key,button_color=color_button)
class Tablero(Tablero):
def Tab(self,images):
tamaño=(50,50)
tablero1=[]
for i in range(15):
row=[]
for j in range(15):
piece_image=images_PuntosTablero['fondo']
valor=boardConfig[i][j].get_valor()
color=boardConfig[i][j].get_color()
if color == 'green':
piece_image=images_PuntosTablero['green']
row.append(self.render_square(piece_image,key =(i,j),texto='', color_button=('white','green')))
elif color == 'red':
piece_image=images_PuntosTablero['red']
row.append(self.render_square(piece_image,key =(i,j),texto='', color_button=('white','red')))
elif color == 'blue':
piece_image=images_PuntosTablero['blue']
row.append(self.render_square(piece_image,key =(i,j),texto='', color_button=('white','blue')))
elif color == 'violet':
piece_image=images_PuntosTablero['centro']
row.append(self.render_square(piece_image,key =(i,j),texto='', color_button=('white','Dark violet')))
elif color == 'orange':
piece_image=images_PuntosTablero['orange']
row.append(self.render_square(piece_image,key =(i,j),texto='', color_button=('white','orange')))
else:
color_button=('white','white')
row.append(self.render_square(piece_image,key =(i,j),texto=''))
tablero1.append(row)
return (tablero1,tamaño)
class atril1():
def __init__(self,T=True):
self._T= T
def crearAtril(self):
def render1(image, key, texto='',color_button=('white','white')):
return sg.RButton(texto,image_filename=image,image_size=(50, 50), pad=(2,2),key=key,button_color=color_button)
atril=[]
if self._T:
for i in range(7):
row=[]
piece_image = images[initial_atril[i]]
row.append(render1(piece_image['imagen'],key =(i),texto='', color_button=('white','white')))
atril.append(row)
else:
img=os.path.join(base_path,'images/interrogacion.png')
for i in range(7):
row=[]
row.append(render1(img,key =(i),texto='', color_button=('white','white')))
atril.append(row)
return atril
def modificarBoton(valores):
if boardConfig[button[0]][button[1]].get_estado() == False:
img=''
window[i].update(image_filename=img,image_size=(50, 50), button_color=('',''))
valores.append(boardConfig[button[0]][button[1]].get_valor())
piece_image = images[initial_atril[i]]
img=piece_image['imagen']
window[button].update(image_filename=img, image_size= tamaño_img ,button_color=('white','grey'))
listadoPosicionLetrasTablero.append(button)
p2=palabra[0]
p2=p2+letra
palabra[0]=p2
initial_atril[i]='' tril.append(i)
boardConfig[button[0]][button[1]].set_estado(True)
print('los valores de las letras son: ', valores)
def devolverLetras():
p=palabra[0]
print(p)
cont=0
for i in listadoPosicionLetrasAtril:
piece_image = images[p[cont]]
img=piece_image['imagen']
window[i].update(image_filename=img,image_size=(50, 50), button_color=('',''))
initial_atril[i]=p[cont]
img=images_PuntosTablero['fondo']
boardConfig[listadoPosicionLetrasTablero[cont][0]][listadoPosicionLetrasTablero[cont][1]].set_estado(False)
color=boardConfig[listadoPosicionLetrasTablero[cont][0]][listadoPosicionLetrasTablero[cont][1]].get_color()
if color == 'violet':
piece_image=images_PuntosTablero['centro']
window[listadoPosicionLetrasTablero[cont]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','Dark violet'))
elif color == 'green':
piece_image=images_PuntosTablero['green']
window[listadoPosicionLetrasTablero[cont]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','green'))
elif color == 'red':
piece_image=images_PuntosTablero['red']
window[listadoPosicionLetrasTablero[cont]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','red'))
elif color == 'blue':
piece_image=images_PuntosTablero['blue']
window[listadoPosicionLetrasTablero[cont]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','blue'))
elif color == 'orange':
piece_image=images_PuntosTablero['orange']
window[listadoPosicionLetrasTablero[cont]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','orange'))
else:
window[listadoPosicionLetrasTablero[cont]].update(image_filename=img, image_size= tamaño_img ,button_color=('white','white'))
cont=cont+1
print(initial_atril)
def actualizarAtrilJugador():
initial_atril2=[]
PC.atrilPalabrasValidas(images_keys,initial_atril2, conf)
for i in range(0,7):
if initial_atril[i]=='':
initial_atril[i]=initial_atril2[i]
piece_image = images[initial_atril[i]]
img=piece_image['imagen']
window[i].update(image_filename=img,image_size=(50, 50), button_color=('',''))
print(initial_atril)
def PasarTurno(initial_atril):
if len(listadoPosicionLetrasTablero)>0:
for i in range(0,len(listadoPosicionLetrasTablero)):
img=images_PuntosTablero['fondo']
boardConfig[listadoPosicionLetrasTablero[i][0]][listadoPosicionLetrasTablero[i][1]].set_estado(False)
color=boardConfig[listadoPosicionLetrasTablero[i][0]][listadoPosicionLetrasTablero[i][1]].get_color()
if color == 'violet':
piece_image=images_PuntosTablero['centro']
window[listadoPosicionLetrasTablero[i]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','Dark violet'))
elif color == 'green':
piece_image=images_PuntosTablero['green']
window[listadoPosicionLetrasTablero[i]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','green'))
elif color == 'red':
piece_image=images_PuntosTablero['red']
window[listadoPosicionLetrasTablero[i]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','red'))
elif color == 'blue':
piece_image=images_PuntosTablero['blue']
window[listadoPosicionLetrasTablero[i]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','blue'))
elif color == 'orange':
piece_image=images_PuntosTablero['orange']
window[listadoPosicionLetrasTablero[i]].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','orange'))
else:
window[listadoPosicionLetrasTablero[i]].update(image_filename=img, image_size= tamaño_img ,button_color=('white','white'))
initial_atril2=[]
PC.atrilPalabrasValidas(images_keys,initial_atril2, conf)
initial_atril=[]
initial_atril=initial_atril2[:]
print(initial_atril,'Final')
for i in range(7):
piece_image = images[initial_atril[i]]
img=piece_image['imagen']
window[i].update(image_filename=img,image_size=(50, 50), button_color=('',''))
return initial_atril
def BorrarTablerGeneral():
def BorrarTablero(color):
piece_image=images_PuntosTablero['fondo']
if color == 'green':
piece_image=images_PuntosTablero['green']
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','green'))
elif color == 'red':
piece_image=images_PuntosTablero['red']
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','red'))
elif color == 'blue':
piece_image=images_PuntosTablero['blue']
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','blue'))
elif color == 'violet':
piece_image=images_PuntosTablero['centro']
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','Dark violet'))
elif color == 'orange':
piece_image=images_PuntosTablero['orange']
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','orange'))
else:
window[(i,j)].update(image_filename=piece_image, image_size= tamaño_img ,button_color=('white','white'))
for i in range(15):
for j in range(15):
window[(i,j)].update('')
boardConfig[i][j].set_estado(False)
color=boardConfig[i][j].get_color()
BorrarTablero(color)
def actualizar_listado(listbox):
listbox.Update(listado) .Config1()
obj = Tablero()
opc=1
elif num_tablero == 2:
images_PuntosTablero=images_PuntosTablero2
boardConfig=config_tablero.Config2()
obj = Tablero()
elif num_tablero ==3:
images_PuntosTablero=images_PuntosTablero3
boardConfig=config_tablero.Config3()
obj = Tablero()
elementos=obj.Tab(images) bolsa.get_layout(),key="BOLSA")]]
columna_1 = [ [sg.Text('PUNTOS JUGADOR', background_color='#00796B')],[sg.Listbox(values =[], key='datosj', font='Courier 18',size=(20,10))],[sg.Text('TOTAL PUNTOS', background_color='#00796B'), sg.Text(background_color='#00796B', size=(5,1), key='puntaje')],[sg.Text('00:00:00', background_color=('#01a9b4'),key='reloj')]]
columna_3 = [ [sg.Text('Total Puntos: '), sg.Text(size=(12,1), key='puntaje')]]
board_tab=[[sg.Button('FINALIZAR TURNO', size=(10,0), button_color=('#FFFFFF', '#004A79'), disabled=True)],[sg.Column(columna_1), sg.Column(atr1),sg.Column(tablero),sg.Column(atr2),sg.Column(columna_2)],[sg.Button('COMENZAR',button_color=('white','green')),sg.Button('PASAR',disabled=True),sg.Button('GUARDAR',disabled=True),sg.Button('FINALIZAR PARTIDA', size=(10,0), button_color=('#FFFFFF', '#F74343'))]]
window = sg.Window('ScrabbleAr',default_button_element_size=(12,1), auto_size_buttons=False).Layout(board_tab)
cantPasadas=0
controlAt=[7,7,0,0]
palabra=['']
cant=2
T1=True
T2= True
T3= True
T4= True
F=0
C=0
puntosCasilla=[]
putosL=0
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
listadoPc=[]
listado=[]
wait=True
wait2=True
window.Finalize()
inicio=time.time()
iniciar=True
puntaje_jugador = 0
while ((True and iniciar)and (not bolsa.check_bolsa_vacia())):
while True:
if wait:
button , value = window.Read()
if button in (None , 'FINALIZAR PARTIDA'):
exit()
if button=='COMENZAR' and wait:
io=time.time()
current_time = 0
paused = False
start_time = int(round(time.time() * 100))
window.FindElement('PASAR').update(disabled=False)
window.FindElement('GUARDAR').update(disabled=False)
window.FindElement('FINALIZAR TURNO').update(disabled=False)
window.FindElement('COMENZAR').update(disabled=True)
window['COMENZAR'].update( button_color=('white','red'))
wait=False
opc2=random.randint(0,1)
if opc2==1:
print('empieza el jugador')
if not(wait):
if (opc2==0)and wait2:
PC.inteligencia(controlAt,window,boardConfig,images,listadoPc,clasificar,images_keys,conf,fichasIA)
actualizar_layout_bolsa()
print('IA INICIAL')
wait2=False
urrent_time = int(round(time.time() * 100)) - start_time
window['reloj'].update('{:02d}:{:02d}.{:02d}'.format((current_time // 100) // 60,
(current_time // 100) % 60,
current_time % 100),background_color=('red'))
if conf.getConfiguracionesSeleccionadas()['tiempo'] == 'minimo':
if (current_time // 100) // 60 == 5:
print('=============================================5 MINUTOS====================================')
print('=============================================5 MINUTOS====================================')
print('=============================================5 MINUTOS====================================')
print('=============================================5 MINUTOS====================================')
sg.Popup('SE ACABO EL TIEMPO!!! PUNTAJE GUARDADO')
_final_jugador.agregar_nuevo_puntaje(nombre,puntaje_jugador,configuracion.getConfiguracionesSeleccionadas()['dificultad'])
window.close()
if conf.getConfiguracionesSeleccionadas()['tiempo'] == 'medio':
if (current_time // 100) // 60 == 15:
print('=============================================15 MINUTOS====================================')
print('=============================================15 MINUTOS====================================')
print('=============================================15 MINUTOS====================================')
print('=============================================15 MINUTOS====================================')
sg.Popup('SE ACABO EL TIEMPO!!! PUNTAJE GUARDADO')
_final_jugador.agregar_nuevo_puntaje(nombre,puntaje_jugador,configuracion.getConfiguracionesSeleccionadas()['dificultad'])
window.close()
if conf.getConfiguracionesSeleccionadas()['tiempo'] == 'maximo':
if (current_time // 100) // 60 == 30:
print('=============================================30 MINUTOS====================================')
print('=============================================30 MINUTOS====================================')
print('=============================================30 MINUTOS====================================')
print('=============================================30 MINUTOS====================================')
sg.Popup('SE ACABO EL TIEMPO!!! PUNTAJE GUARDADO')
_final_jugador.agregar_nuevo_puntaje(nombre,puntaje_jugador,configuracion.getConfiguracionesSeleccionadas()['dificultad'])
window.close()
puntosP=0
puntosL=0
l=-1
button , value = window.Read(timeout=10)
if button == 'FINALIZAR TURNO':
p = ""
p = p.join(palabra)
j
if palabra == '':
sg.Popup('todavia no formo una palabra')
elif len(palabra[0])>1:
if (clasificar.comprobarPalabraEnBaseAlNivel(palabra[0], conf)):
sg.Popup('PALABRA FORMADA : ' ,palabra)
print(clasificar.comprobarPalabraEnBaseAlNivel(palabra[0], conf))
T2= True
T1=True
T3= True
F=0
C=0
T4=True
if (clasificar.comprobarPalabraEnBaseAlNivel(palabra[0], conf)):
palabra[0]=''
actualizarAtrilJugador()
wait2=True
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
lues)) + " Puntos")
actualizar_listado(window.FindElement('datosj'))
puntaje_jugador = puntaje_jugador + bolsa.calcular_puntos(p,word_values)
print(puntaje_jugador)
window['puntaje'].update(puntaje_jugador)
lizar_layout_bolsa()
del word_values[:]
break
sg.Popup('PALABRA INVALIDA')
devolverLetras()
T2=True
T3=True
T1=True
T4=True
palabra[0]=''
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
del word_values[:]
elif len(palabra[0])<2:
sg.Popup('la palabra es menor de 2')
if button in (None , 'FINALIZAR PARTIDA'):
exit()
if button =='PASAR':
cantPasadas=cantPasadas+1
controlAt=[7,7,0,0]
if cantPasadas<4:
initial_atril=PasarTurno(initial_atril)
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
palabra=['']
T1=True
T2=True
T4=True
listado=[]
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
PC.inteligencia(controlAt,window,boardConfig,images,listadoPc,clasificar,images_keys,conf,fichasIA)
actualizar_layout_bolsa()
else:
sg.Popup('se supero la cantidad de pasadas')
if type(button) is int:
print(button)
if initial_atril[button] !='':
i=button
letra= initial_atril[button]
on , value = window.Read()
if type(button) is tuple:
if not(boardConfig[7][7].get_estado()):
print('posicion central no ocupada')
if not(boardConfig[7][7].get_estado()):
print('posicion central no ocupada')
if (button[0]==7 and button[1]==7)and T3 :
print(button)
modificarBoton(word_values)
T3=False
F=button[0]
C=button[1]
cant=0
if not(T3):
if(button[0]==F)and T1:
if C<button[1]and(button[1]==C+1):
T2=False
modificarBoton(word_values)
C=button[1]
if(button[1]==C)and T2:
if F<button[0]and(button[0]==F+1):
print(button)
T1=False
modificarBoton(word_values)
F=button[0]
else:
ton(word_values)
F=button[0]
C=button[1]
T4=False
else:
if(button[0]==F)and T1 :
if C<button[1]and(button[1]==C+1):
T2=False
modificarBoton(word_values)
C=button[1]
if(button[1]==C)and T2:
if F<button[0]and(button[0]==F+1):
T1=False
modificarBoton(word_values)
F=button[0]
actualizar_listado(window.FindElement('datosj')) ---" + str(puntaje_jugador))
if type(button) is tuple:
if l ==-1:
sg.Popup('movimiento incorrecto')
if (opc2==1)and wait2:
PC.inteligencia(controlAt,window,boardConfig,images,listadoPc,clasificar,images_keys, conf,fichasIA)
actualizar_layout_bolsa()
print('IA FINAL')
controlAt=[8,7,0,0]
final=time.time()
if final-inicio>120:
break
try:
if (current_time // 100) % 60 == 10:
print('=============================================10 SEGUNDOS====================================')
print('=============================================10 SEGUNDOS====================================')
print('=============================================10 SEGUNDOS====================================')
print('=============================================10 SEGUNDOS====================================')
except:
sg.Popup('Por favor aprete el boton comenzar',background_color='#00796B')
sg.Popup('FIN Juego')
print(bolsa.check_bolsa_vacia())
break
wait=True
window.FindElement('PASAR').update(disabled=True)
window.FindElement('GUARDAR').update(disabled=True)
window.FindElement('FINALIZAR TURNO').update(disabled=True)
window.FindElement('COMENZAR').update(disabled=False)
window['COMENZAR'].update( button_color=('white','green'))
while(button!='COMENZAR'):
button , value = window.Read()
if button=='COMENZAR':
initial_atril=[]
images_keys= list(images.keys()) random.shuffle(images_keys,random.random)
initial_atril=[]
initial_atril2=[]
PC.atrilPalabrasValidas(images_keys,initial_atril2, conf)
initial_atril=initial_atril2[:]
for i in range(7):
piece_image = images[initial_atril[i]]
img=piece_image['imagen']
window[i].update(image_filename=img,image_size=(50, 50), button_color=('',''))
]
listado=[]
listadoPc=[]
listadoPosicionLetrasAtril=[]
listadoPosicionLetrasTablero=[]
initial_atril2=[]
cantPasadas=0
actualizar_listado(window.FindElement('datosj'))
actualizar_listado(window.FindElement('datosm'))
controlAt=[7,7,0,0]
bolsa = Bolsa(conf.getConfiguracionLetras())
dor.agregar_nuevo_puntaje(nombre,puntaje_jugador,configuracion.getConfiguracionesSeleccionadas()['dificultad'])
if __name__ == "__main__":
main_game(1)
| true | true |
1c3fbdd86124ddfe35fa159c15df6eb261761d5d | 1,153 | py | Python | exercicios/PythonExercicios/ex059.py | Roberto-Sartore/Python | 98f91f13cf78d761893c4a1f3264ed999244d32b | [
"MIT"
] | null | null | null | exercicios/PythonExercicios/ex059.py | Roberto-Sartore/Python | 98f91f13cf78d761893c4a1f3264ed999244d32b | [
"MIT"
] | null | null | null | exercicios/PythonExercicios/ex059.py | Roberto-Sartore/Python | 98f91f13cf78d761893c4a1f3264ed999244d32b | [
"MIT"
] | null | null | null | from time import sleep
n1 = int(input('Primeiro número:'))
n2 = int(input('Segundo número'))
opcao = 0
while opcao != 5:
print(''' [ 1 ] Somar
[ 2 ] Multiplicar
[ 3 ] Maior
[ 4 ] Novos números
[ 5 ] Sair do programa''')
opcao = int(input('\033[33m Qual é a sua opção? \033[m'))
if opcao == 1:
soma = n1 + n2
print('\033[34m A soma entre {} e {} é {} \033[m'.format(n1, n2, soma))
elif opcao == 2:
produto = n1 * n2
print('\033[34m O produto de {} X {} é {} \033[m'.format(n1, n2, produto))
elif opcao == 3:
if n1 > n2:
maior = n1
else:
maior = n2
print('\033[34m Entre {} e {} o maior valor é {} \033[m'.format(n1, n2, maior))
elif opcao == 4:
print('\033[34m Informe os números novamente:\033[m')
n1 = int(input('Primeiro valor:'))
n2 = int(input('Segundo valor:'))
elif opcao == 5:
print('\033[32m Finalizando...\033[m')
else:
print('\033[31m Opção inválida. Tente novamente. \033[m')
print('=-=' * 12)
sleep(2)
print('\033[33m Fim do programa! Volte sempre! \033[m')
| 29.564103 | 87 | 0.529055 | from time import sleep
n1 = int(input('Primeiro número:'))
n2 = int(input('Segundo número'))
opcao = 0
while opcao != 5:
print(''' [ 1 ] Somar
[ 2 ] Multiplicar
[ 3 ] Maior
[ 4 ] Novos números
[ 5 ] Sair do programa''')
opcao = int(input('\033[33m Qual é a sua opção? \033[m'))
if opcao == 1:
soma = n1 + n2
print('\033[34m A soma entre {} e {} é {} \033[m'.format(n1, n2, soma))
elif opcao == 2:
produto = n1 * n2
print('\033[34m O produto de {} X {} é {} \033[m'.format(n1, n2, produto))
elif opcao == 3:
if n1 > n2:
maior = n1
else:
maior = n2
print('\033[34m Entre {} e {} o maior valor é {} \033[m'.format(n1, n2, maior))
elif opcao == 4:
print('\033[34m Informe os números novamente:\033[m')
n1 = int(input('Primeiro valor:'))
n2 = int(input('Segundo valor:'))
elif opcao == 5:
print('\033[32m Finalizando...\033[m')
else:
print('\033[31m Opção inválida. Tente novamente. \033[m')
print('=-=' * 12)
sleep(2)
print('\033[33m Fim do programa! Volte sempre! \033[m')
| true | true |
1c3fbf17afd7a87d138502f9050c796fa3c76392 | 7,032 | py | Python | Va-Project/Modules/gomoku_game/Gomoku.py | AdamKatborgpy/Virtuel-assistent | df226c0a0bdeb345840ddc41ea1e91fd77380d6b | [
"MIT"
] | null | null | null | Va-Project/Modules/gomoku_game/Gomoku.py | AdamKatborgpy/Virtuel-assistent | df226c0a0bdeb345840ddc41ea1e91fd77380d6b | [
"MIT"
] | null | null | null | Va-Project/Modules/gomoku_game/Gomoku.py | AdamKatborgpy/Virtuel-assistent | df226c0a0bdeb345840ddc41ea1e91fd77380d6b | [
"MIT"
] | null | null | null | import pygame
from pygame.locals import *
# Define some colors
BLACK = (0, 0, 0)
WHITE = (245, 245, 245)
RED = (133, 42, 44)
YELLOW = (208, 176, 144)
GREEN = (26, 81, 79)
PLAYER = False
# Define grid globals
WIDTH = 20
MARGIN = 1
PADDING = 20
DOT = 4
BOARD = (WIDTH + MARGIN) * 14 + MARGIN
GAME_WIDTH = BOARD + PADDING * 2
GAME_HIGHT = GAME_WIDTH + 100
class Gomoku:
def __init__(self):
self.grid = [[0 for x in range(15)] for y in range(15)]
pygame.init()
pygame.font.init()
self._display_surf = pygame.display.set_mode((GAME_WIDTH,GAME_HIGHT), pygame.HWSURFACE | pygame.DOUBLEBUF)
pygame.display.set_caption('Gomoku')
self._running = True
self._playing = False
self._win = False
self.lastPosition = [-1,-1]
def on_event(self, event):
if event.type == pygame.QUIT:
self._running = False
if event.type == pygame.MOUSEBUTTONUP:
#does not update postion in python3.6, and I don't know why
pos = pygame.mouse.get_pos()
global PLAYER
if self.mouse_in_botton(pos):
if not self._playing:
self.start()
if PLAYER:
PLAYER = not PLAYER
else:
self.surrender()
PLAYER = not PLAYER
elif self._playing:
r = (pos[0] - PADDING + WIDTH // 2) // (WIDTH + MARGIN)
c = (pos[1] - PADDING + WIDTH // 2) // (WIDTH + MARGIN)
if 0 <= r < 15 and 0 <= c < 15:
if self.grid[r][c] == 0:
self.lastPosition = [r,c]
self.grid[r][c] = 1 if PLAYER else 2
# check win
if self.check_win([r,c],PLAYER):
self._win = True
self._playing = False
else:
PLAYER = not PLAYER
def on_render(self):
self.render_gomoku_piece()
self.render_last_position()
self.render_game_info()
self.render_button()
pygame.display.update()
def on_cleanup(self):
pygame.quit()
def on_execute(self):
while( self._running ):
self.gomoku_board_init()
for event in pygame.event.get():
self.on_event(event)
self.on_render()
self.on_cleanup()
def start(self):
self._playing = True
self.grid = [[0 for x in range(15)] for y in range(15)]
self.lastPosition = [-1,-1]
self._win = False
def surrender(self):
self._playing = False
self._win = True
def gomoku_board_init(self):
self._display_surf.fill(YELLOW)
# Draw background rect for game area
pygame.draw.rect(self._display_surf, BLACK,
[PADDING,
PADDING,
BOARD,
BOARD])
# Draw the grid
for row in range(14):
for column in range(14):
pygame.draw.rect(self._display_surf, YELLOW,
[(MARGIN + WIDTH) * column + MARGIN + PADDING,
(MARGIN + WIDTH) * row + MARGIN + PADDING,
WIDTH,
WIDTH])
# Five dots
points = [(3,3),(11,3),(3,11),(11,11),(7,7)]
for point in points:
pygame.draw.rect(self._display_surf, BLACK,
(PADDING + point[0] * (MARGIN + WIDTH) - DOT // 2,
PADDING + point[1] * (MARGIN + WIDTH) - DOT // 2,
DOT,
DOT),0)
def mouse_in_botton(self,pos):
if GAME_WIDTH // 2 - 50 <= pos[0] <= GAME_WIDTH // 2 + 50 and GAME_HIGHT - 50 <= pos[1] <= GAME_HIGHT - 20:
return True
return False
def render_button(self):
color = GREEN if not self._playing else RED
info = "Start" if not self._playing else "Surrender"
pygame.draw.rect(self._display_surf, color,
(GAME_WIDTH // 2 - 50, GAME_HIGHT - 50, 100, 30))
info_font = pygame.font.SysFont('Helvetica', 18)
text = info_font.render(info, True, WHITE)
textRect = text.get_rect()
textRect.centerx = GAME_WIDTH // 2
textRect.centery = GAME_HIGHT - 35
self._display_surf.blit(text, textRect)
def render_game_info(self):
#current player color
color = BLACK if not PLAYER else WHITE
center = (GAME_WIDTH // 2 - 60, BOARD + 60)
radius = 12
pygame.draw.circle(self._display_surf, color, center, radius, 0)
info = "You Win" if self._win else "Your Turn"
info_font = pygame.font.SysFont('Helvetica', 24)
text = info_font.render(info, True, BLACK)
textRect = text.get_rect()
textRect.centerx = self._display_surf.get_rect().centerx + 20
textRect.centery = center[1]
self._display_surf.blit(text, textRect)
def render_gomoku_piece(self):
for r in range(15):
for c in range(15):
center = ((MARGIN + WIDTH) * r + MARGIN + PADDING,
(MARGIN + WIDTH) * c + MARGIN + PADDING)
if self.grid[r][c] > 0:
color = BLACK if self.grid[r][c] == 2 else WHITE
pygame.draw.circle(self._display_surf, color,
center,
WIDTH // 2 - MARGIN,0)
def render_last_position(self):
if self.lastPosition[0] > 0 and self.lastPosition[1] > 0:
pygame.draw.rect(self._display_surf,RED,
((MARGIN + WIDTH) * self.lastPosition[0] + (MARGIN + WIDTH) // 2,
(MARGIN + WIDTH) * self.lastPosition[1] + (MARGIN + WIDTH) // 2,
(MARGIN + WIDTH),
(MARGIN + WIDTH)),1)
def check_win(self,position,player):
target = 1 if player else 2
if self.grid[position[0]][position[1]] != target:
return False
directions = [([0,1] , [0,-1]) , ([1,0] , [-1,0]) , ([-1,1] , [1,-1]) , ([1,1] , [-1,-1])]
for direction in directions:
continue_chess = 0
for i in range(2):
p = position[:]
while 0 <= p[0] < 15 and 0 <= p[1] < 15:
if self.grid[p[0]][p[1]] == target:
continue_chess += 1
else:
break
p[0] += direction[i][0]
p[1] += direction[i][1]
if continue_chess >= 6:
return True
return False
if __name__ == "__main__" :
gomoku = Gomoku()
gomoku.on_execute() | 32.555556 | 115 | 0.486775 | import pygame
from pygame.locals import *
BLACK = (0, 0, 0)
WHITE = (245, 245, 245)
RED = (133, 42, 44)
YELLOW = (208, 176, 144)
GREEN = (26, 81, 79)
PLAYER = False
WIDTH = 20
MARGIN = 1
PADDING = 20
DOT = 4
BOARD = (WIDTH + MARGIN) * 14 + MARGIN
GAME_WIDTH = BOARD + PADDING * 2
GAME_HIGHT = GAME_WIDTH + 100
class Gomoku:
def __init__(self):
self.grid = [[0 for x in range(15)] for y in range(15)]
pygame.init()
pygame.font.init()
self._display_surf = pygame.display.set_mode((GAME_WIDTH,GAME_HIGHT), pygame.HWSURFACE | pygame.DOUBLEBUF)
pygame.display.set_caption('Gomoku')
self._running = True
self._playing = False
self._win = False
self.lastPosition = [-1,-1]
def on_event(self, event):
if event.type == pygame.QUIT:
self._running = False
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
global PLAYER
if self.mouse_in_botton(pos):
if not self._playing:
self.start()
if PLAYER:
PLAYER = not PLAYER
else:
self.surrender()
PLAYER = not PLAYER
elif self._playing:
r = (pos[0] - PADDING + WIDTH // 2) // (WIDTH + MARGIN)
c = (pos[1] - PADDING + WIDTH // 2) // (WIDTH + MARGIN)
if 0 <= r < 15 and 0 <= c < 15:
if self.grid[r][c] == 0:
self.lastPosition = [r,c]
self.grid[r][c] = 1 if PLAYER else 2
# check win
if self.check_win([r,c],PLAYER):
self._win = True
self._playing = False
else:
PLAYER = not PLAYER
def on_render(self):
self.render_gomoku_piece()
self.render_last_position()
self.render_game_info()
self.render_button()
pygame.display.update()
def on_cleanup(self):
pygame.quit()
def on_execute(self):
while( self._running ):
self.gomoku_board_init()
for event in pygame.event.get():
self.on_event(event)
self.on_render()
self.on_cleanup()
def start(self):
self._playing = True
self.grid = [[0 for x in range(15)] for y in range(15)]
self.lastPosition = [-1,-1]
self._win = False
def surrender(self):
self._playing = False
self._win = True
def gomoku_board_init(self):
self._display_surf.fill(YELLOW)
# Draw background rect for game area
pygame.draw.rect(self._display_surf, BLACK,
[PADDING,
PADDING,
BOARD,
BOARD])
# Draw the grid
for row in range(14):
for column in range(14):
pygame.draw.rect(self._display_surf, YELLOW,
[(MARGIN + WIDTH) * column + MARGIN + PADDING,
(MARGIN + WIDTH) * row + MARGIN + PADDING,
WIDTH,
WIDTH])
# Five dots
points = [(3,3),(11,3),(3,11),(11,11),(7,7)]
for point in points:
pygame.draw.rect(self._display_surf, BLACK,
(PADDING + point[0] * (MARGIN + WIDTH) - DOT // 2,
PADDING + point[1] * (MARGIN + WIDTH) - DOT // 2,
DOT,
DOT),0)
def mouse_in_botton(self,pos):
if GAME_WIDTH // 2 - 50 <= pos[0] <= GAME_WIDTH // 2 + 50 and GAME_HIGHT - 50 <= pos[1] <= GAME_HIGHT - 20:
return True
return False
def render_button(self):
color = GREEN if not self._playing else RED
info = "Start" if not self._playing else "Surrender"
pygame.draw.rect(self._display_surf, color,
(GAME_WIDTH // 2 - 50, GAME_HIGHT - 50, 100, 30))
info_font = pygame.font.SysFont('Helvetica', 18)
text = info_font.render(info, True, WHITE)
textRect = text.get_rect()
textRect.centerx = GAME_WIDTH // 2
textRect.centery = GAME_HIGHT - 35
self._display_surf.blit(text, textRect)
def render_game_info(self):
#current player color
color = BLACK if not PLAYER else WHITE
center = (GAME_WIDTH // 2 - 60, BOARD + 60)
radius = 12
pygame.draw.circle(self._display_surf, color, center, radius, 0)
info = "You Win" if self._win else "Your Turn"
info_font = pygame.font.SysFont('Helvetica', 24)
text = info_font.render(info, True, BLACK)
textRect = text.get_rect()
textRect.centerx = self._display_surf.get_rect().centerx + 20
textRect.centery = center[1]
self._display_surf.blit(text, textRect)
def render_gomoku_piece(self):
for r in range(15):
for c in range(15):
center = ((MARGIN + WIDTH) * r + MARGIN + PADDING,
(MARGIN + WIDTH) * c + MARGIN + PADDING)
if self.grid[r][c] > 0:
color = BLACK if self.grid[r][c] == 2 else WHITE
pygame.draw.circle(self._display_surf, color,
center,
WIDTH // 2 - MARGIN,0)
def render_last_position(self):
if self.lastPosition[0] > 0 and self.lastPosition[1] > 0:
pygame.draw.rect(self._display_surf,RED,
((MARGIN + WIDTH) * self.lastPosition[0] + (MARGIN + WIDTH) // 2,
(MARGIN + WIDTH) * self.lastPosition[1] + (MARGIN + WIDTH) // 2,
(MARGIN + WIDTH),
(MARGIN + WIDTH)),1)
def check_win(self,position,player):
target = 1 if player else 2
if self.grid[position[0]][position[1]] != target:
return False
directions = [([0,1] , [0,-1]) , ([1,0] , [-1,0]) , ([-1,1] , [1,-1]) , ([1,1] , [-1,-1])]
for direction in directions:
continue_chess = 0
for i in range(2):
p = position[:]
while 0 <= p[0] < 15 and 0 <= p[1] < 15:
if self.grid[p[0]][p[1]] == target:
continue_chess += 1
else:
break
p[0] += direction[i][0]
p[1] += direction[i][1]
if continue_chess >= 6:
return True
return False
if __name__ == "__main__" :
gomoku = Gomoku()
gomoku.on_execute() | true | true |
1c3fbf6ee31f65152d01042d7740ecb05064ff89 | 1,062 | py | Python | turtlebot3_dqn/nodes/tf_broadcaster.py | 2529342549/turtlebot3_m_learning | 19fc961de8a993eafcd421186ad1c38473d04818 | [
"Apache-2.0"
] | 1 | 2022-02-21T02:02:11.000Z | 2022-02-21T02:02:11.000Z | turtlebot3_dqn/nodes/tf_broadcaster.py | 2529342549/turtlebot3_machine_learning | bdb8cc0fa0110269cd3573d3f78011c3e0201e09 | [
"Apache-2.0"
] | null | null | null | turtlebot3_dqn/nodes/tf_broadcaster.py | 2529342549/turtlebot3_machine_learning | bdb8cc0fa0110269cd3573d3f78011c3e0201e09 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
#coding=utf-8
import rospy
from geometry_msgs.msg import Twist, Pose
from nav_msgs.msg import Odometry
import tf
def pose_callback(msg,robotname):
br = tf.TransformBroadcaster() #将坐标变换广播出去
#向/tf发布消息 tb3_0距离原点的坐标x ,y ,平移
br.sendTransform((msg.pose.pose.position.x, msg.pose.pose.position.y, 0),
(msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w), #旋转 quaternion_from_euler:欧拉角变四元数
rospy.Time.now(), #打上时间戳
'/%s/odom' % robotname, #发布 tb_name 到 "map" 的平移和翻转
"map")
if __name__ == '__main__':
rospy.init_node('item')
robotname = rospy.get_param('~robot') #取参数服务器robot的值
rospy.Subscriber('/%s/odom' % robotname, #要接收的topic名 /turtle1/pose或者/turtle2/pose
Odometry, #接收的数据类型
pose_callback, #回调函数
robotname) #回调函数参数
rospy.spin() #保持节点运行,直到节点关闭
| 37.928571 | 173 | 0.594162 |
import rospy
from geometry_msgs.msg import Twist, Pose
from nav_msgs.msg import Odometry
import tf
def pose_callback(msg,robotname):
br = tf.TransformBroadcaster()
br.sendTransform((msg.pose.pose.position.x, msg.pose.pose.position.y, 0),
(msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w),
rospy.Time.now(),
'/%s/odom' % robotname,
"map")
if __name__ == '__main__':
rospy.init_node('item')
robotname = rospy.get_param('~robot')
rospy.Subscriber('/%s/odom' % robotname,
Odometry,
pose_callback,
robotname)
rospy.spin()
| true | true |
1c3fc02ecf4ffdcde6d9493188d850afab605017 | 792 | py | Python | solutions/Interview-04-er-wei-shu-zu-zhong-de-cha-zhao-lcof/04.py | leetcode-notebook/wonz | 9ffd2ce9b5f3a544ee958f5a0673215afd176c2b | [
"MIT"
] | 12 | 2020-04-21T01:09:14.000Z | 2022-01-13T08:42:03.000Z | solutions/Interview-04-er-wei-shu-zu-zhong-de-cha-zhao-lcof/04.py | leetcode-notebook/wonz | 9ffd2ce9b5f3a544ee958f5a0673215afd176c2b | [
"MIT"
] | null | null | null | solutions/Interview-04-er-wei-shu-zu-zhong-de-cha-zhao-lcof/04.py | leetcode-notebook/wonz | 9ffd2ce9b5f3a544ee958f5a0673215afd176c2b | [
"MIT"
] | 4 | 2020-03-31T03:06:16.000Z | 2021-07-06T07:27:44.000Z | from typing import List
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
# solution one: 暴力
# 特判
if matrix == []:
return False
n, m = len(matrix), len(matrix[0])
for i in range(n):
for j in range(m):
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
break
return False
# solution two: 左下角标志数法
i, j = len(matrix) - 1, 0
while i >= 0 and j < len(matrix[0]):
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
i -= 1
else:
j += 1
return False
| 27.310345 | 80 | 0.433081 | from typing import List
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if matrix == []:
return False
n, m = len(matrix), len(matrix[0])
for i in range(n):
for j in range(m):
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
break
return False
i, j = len(matrix) - 1, 0
while i >= 0 and j < len(matrix[0]):
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
i -= 1
else:
j += 1
return False
| true | true |
1c3fc10050896dd77684b430b69808c0479ca325 | 234 | py | Python | Capstone Two/setup.py | shalin4788/Springboard-Do-not-refer- | e7627e6f4b09456e08c6f10baeb66b0a22422b7a | [
"MIT"
] | 2 | 2020-10-23T06:24:18.000Z | 2020-10-23T06:24:25.000Z | Capstone Two/setup.py | shalin4788/Springboard-Do-not-refer- | e7627e6f4b09456e08c6f10baeb66b0a22422b7a | [
"MIT"
] | 5 | 2021-06-08T22:56:21.000Z | 2022-01-13T03:35:07.000Z | Capstone Two/setup.py | shalin4788/Springboard | e7627e6f4b09456e08c6f10baeb66b0a22422b7a | [
"MIT"
] | null | null | null | from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Quora insincere data classification',
author='Shalin Gosalia',
license='MIT',
)
| 21.272727 | 55 | 0.653846 | from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Quora insincere data classification',
author='Shalin Gosalia',
license='MIT',
)
| true | true |
1c3fc2ea92b55d79bb3978373317cc25b7fa52ed | 636 | py | Python | sdeux/utils/alparser.py | ngost/alpes_laser_s2_custom | c2ef808998485e147d32b951bfd8350a4d32be2d | [
"MIT"
] | null | null | null | sdeux/utils/alparser.py | ngost/alpes_laser_s2_custom | c2ef808998485e147d32b951bfd8350a4d32be2d | [
"MIT"
] | null | null | null | sdeux/utils/alparser.py | ngost/alpes_laser_s2_custom | c2ef808998485e147d32b951bfd8350a4d32be2d | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on September 01, 2015
Copyright Alpes Lasers SA, Neuchatel, Switzerland, 2015
@author: chiesa
"""
import argparse
import logging
logger = logging.getLogger(__name__)
_version = 'undefined'
try:
from sdeux import pkg, version
_version = '{} {}'.format(pkg, version)
except Exception as e:
logger.debug(e, exc_info=1)
baseparser = argparse.ArgumentParser(add_help=False)
baseparser.add_argument("--show-version", help="Show the project version",
action="version", version="%s %s" % (pkg, version))
alparser = argparse.ArgumentParser(parents=[baseparser])
| 20.516129 | 75 | 0.690252 |
import argparse
import logging
logger = logging.getLogger(__name__)
_version = 'undefined'
try:
from sdeux import pkg, version
_version = '{} {}'.format(pkg, version)
except Exception as e:
logger.debug(e, exc_info=1)
baseparser = argparse.ArgumentParser(add_help=False)
baseparser.add_argument("--show-version", help="Show the project version",
action="version", version="%s %s" % (pkg, version))
alparser = argparse.ArgumentParser(parents=[baseparser])
| true | true |
1c3fc3cbd94a9a36a1c0614624ab4f2519ffad6c | 5,048 | py | Python | tempo/seldon/k8s.py | majolo/tempo | 516b7df0beaf36d69366e8e759ce00a362225278 | [
"Apache-2.0"
] | null | null | null | tempo/seldon/k8s.py | majolo/tempo | 516b7df0beaf36d69366e8e759ce00a362225278 | [
"Apache-2.0"
] | null | null | null | tempo/seldon/k8s.py | majolo/tempo | 516b7df0beaf36d69366e8e759ce00a362225278 | [
"Apache-2.0"
] | null | null | null | import json
import time
from typing import Optional, Sequence
import yaml
from kubernetes import client
from kubernetes.client.rest import ApiException
from tempo.k8s.constants import TempoK8sLabel, TempoK8sModelSpecAnnotation
from tempo.k8s.utils import create_k8s_client
from tempo.seldon.endpoint import Endpoint
from tempo.seldon.specs import KubernetesSpec
from tempo.serve.base import DeployedModel, ModelSpec, Runtime
from tempo.serve.metadata import RuntimeOptions
from tempo.serve.stub import deserialize
from tempo.utils import logger
class SeldonCoreOptions(RuntimeOptions):
runtime: str = "tempo.seldon.SeldonKubernetesRuntime"
class SeldonKubernetesRuntime(Runtime):
def __init__(self, runtime_options: Optional[RuntimeOptions] = None):
if runtime_options is None:
runtime_options = RuntimeOptions()
runtime_options.runtime = "tempo.seldon.SeldonKubernetesRuntime"
super().__init__(runtime_options)
def get_endpoint_spec(self, model_spec: ModelSpec) -> str:
create_k8s_client()
endpoint = Endpoint()
return endpoint.get_url(model_spec)
def undeploy_spec(self, model_spec: ModelSpec):
create_k8s_client()
api_instance = client.CustomObjectsApi()
api_instance.delete_namespaced_custom_object(
"machinelearning.seldon.io",
"v1",
model_spec.runtime_options.k8s_options.namespace,
"seldondeployments",
model_spec.model_details.name,
body=client.V1DeleteOptions(propagation_policy="Foreground"),
)
def deploy_spec(self, model_spec: ModelSpec):
create_k8s_client()
k8s_specer = KubernetesSpec(model_spec)
k8s_spec = k8s_specer.spec
logger.debug(k8s_spec)
api_instance = client.CustomObjectsApi()
try:
existing = api_instance.get_namespaced_custom_object(
"machinelearning.seldon.io",
"v1",
model_spec.runtime_options.k8s_options.namespace,
"seldondeployments",
model_spec.model_details.name,
)
k8s_spec["metadata"]["resourceVersion"] = existing["metadata"]["resourceVersion"]
api_instance.replace_namespaced_custom_object(
"machinelearning.seldon.io",
"v1",
model_spec.runtime_options.k8s_options.namespace,
"seldondeployments",
model_spec.model_details.name,
k8s_spec,
)
except ApiException as e:
if e.status == 404:
api_instance.create_namespaced_custom_object(
"machinelearning.seldon.io",
"v1",
model_spec.runtime_options.k8s_options.namespace,
"seldondeployments",
k8s_spec,
)
else:
raise e
def wait_ready_spec(self, model_spec: ModelSpec, timeout_secs=None) -> bool:
create_k8s_client()
ready = False
t0 = time.time()
while not ready:
api_instance = client.CustomObjectsApi()
existing = api_instance.get_namespaced_custom_object(
"machinelearning.seldon.io",
"v1",
model_spec.runtime_options.k8s_options.namespace,
"seldondeployments",
model_spec.model_details.name,
)
if "status" in existing and "state" in existing["status"]:
ready = existing["status"]["state"] == "Available"
if timeout_secs is not None:
t1 = time.time()
if t1 - t0 > timeout_secs:
return ready
return ready
def to_k8s_yaml_spec(self, model_spec: ModelSpec) -> str:
k8s_spec = KubernetesSpec(model_spec)
return yaml.safe_dump(k8s_spec.spec)
def list_models(self, namespace: Optional[str] = None) -> Sequence[DeployedModel]:
create_k8s_client()
api_instance = client.CustomObjectsApi()
if namespace is None and self.runtime_options is not None:
namespace = self.runtime_options.k8s_options.namespace
if namespace is None:
return []
try:
models = []
response = api_instance.list_namespaced_custom_object(
group="machinelearning.seldon.io",
version="v1",
namespace=namespace,
plural="seldondeployments",
label_selector=TempoK8sLabel + "=true",
)
for model in response["items"]:
metadata = model["metadata"]["annotations"][TempoK8sModelSpecAnnotation]
remote_model = deserialize(json.loads(metadata))
models.append(remote_model)
return models
except ApiException as e:
if e.status == 404:
return []
else:
raise e
| 36.57971 | 93 | 0.612916 | import json
import time
from typing import Optional, Sequence
import yaml
from kubernetes import client
from kubernetes.client.rest import ApiException
from tempo.k8s.constants import TempoK8sLabel, TempoK8sModelSpecAnnotation
from tempo.k8s.utils import create_k8s_client
from tempo.seldon.endpoint import Endpoint
from tempo.seldon.specs import KubernetesSpec
from tempo.serve.base import DeployedModel, ModelSpec, Runtime
from tempo.serve.metadata import RuntimeOptions
from tempo.serve.stub import deserialize
from tempo.utils import logger
class SeldonCoreOptions(RuntimeOptions):
runtime: str = "tempo.seldon.SeldonKubernetesRuntime"
class SeldonKubernetesRuntime(Runtime):
def __init__(self, runtime_options: Optional[RuntimeOptions] = None):
if runtime_options is None:
runtime_options = RuntimeOptions()
runtime_options.runtime = "tempo.seldon.SeldonKubernetesRuntime"
super().__init__(runtime_options)
def get_endpoint_spec(self, model_spec: ModelSpec) -> str:
create_k8s_client()
endpoint = Endpoint()
return endpoint.get_url(model_spec)
def undeploy_spec(self, model_spec: ModelSpec):
create_k8s_client()
api_instance = client.CustomObjectsApi()
api_instance.delete_namespaced_custom_object(
"machinelearning.seldon.io",
"v1",
model_spec.runtime_options.k8s_options.namespace,
"seldondeployments",
model_spec.model_details.name,
body=client.V1DeleteOptions(propagation_policy="Foreground"),
)
def deploy_spec(self, model_spec: ModelSpec):
create_k8s_client()
k8s_specer = KubernetesSpec(model_spec)
k8s_spec = k8s_specer.spec
logger.debug(k8s_spec)
api_instance = client.CustomObjectsApi()
try:
existing = api_instance.get_namespaced_custom_object(
"machinelearning.seldon.io",
"v1",
model_spec.runtime_options.k8s_options.namespace,
"seldondeployments",
model_spec.model_details.name,
)
k8s_spec["metadata"]["resourceVersion"] = existing["metadata"]["resourceVersion"]
api_instance.replace_namespaced_custom_object(
"machinelearning.seldon.io",
"v1",
model_spec.runtime_options.k8s_options.namespace,
"seldondeployments",
model_spec.model_details.name,
k8s_spec,
)
except ApiException as e:
if e.status == 404:
api_instance.create_namespaced_custom_object(
"machinelearning.seldon.io",
"v1",
model_spec.runtime_options.k8s_options.namespace,
"seldondeployments",
k8s_spec,
)
else:
raise e
def wait_ready_spec(self, model_spec: ModelSpec, timeout_secs=None) -> bool:
create_k8s_client()
ready = False
t0 = time.time()
while not ready:
api_instance = client.CustomObjectsApi()
existing = api_instance.get_namespaced_custom_object(
"machinelearning.seldon.io",
"v1",
model_spec.runtime_options.k8s_options.namespace,
"seldondeployments",
model_spec.model_details.name,
)
if "status" in existing and "state" in existing["status"]:
ready = existing["status"]["state"] == "Available"
if timeout_secs is not None:
t1 = time.time()
if t1 - t0 > timeout_secs:
return ready
return ready
def to_k8s_yaml_spec(self, model_spec: ModelSpec) -> str:
k8s_spec = KubernetesSpec(model_spec)
return yaml.safe_dump(k8s_spec.spec)
def list_models(self, namespace: Optional[str] = None) -> Sequence[DeployedModel]:
create_k8s_client()
api_instance = client.CustomObjectsApi()
if namespace is None and self.runtime_options is not None:
namespace = self.runtime_options.k8s_options.namespace
if namespace is None:
return []
try:
models = []
response = api_instance.list_namespaced_custom_object(
group="machinelearning.seldon.io",
version="v1",
namespace=namespace,
plural="seldondeployments",
label_selector=TempoK8sLabel + "=true",
)
for model in response["items"]:
metadata = model["metadata"]["annotations"][TempoK8sModelSpecAnnotation]
remote_model = deserialize(json.loads(metadata))
models.append(remote_model)
return models
except ApiException as e:
if e.status == 404:
return []
else:
raise e
| true | true |
1c3fc41e856187a3e2fe1ff0df604b7b87395070 | 1,702 | py | Python | aliyun-python-sdk-domain/aliyunsdkdomain/request/v20180129/SetDefaultRegistrantProfileRequest.py | yndu13/aliyun-openapi-python-sdk | 12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5 | [
"Apache-2.0"
] | 1,001 | 2015-07-24T01:32:41.000Z | 2022-03-25T01:28:18.000Z | aliyun-python-sdk-domain/aliyunsdkdomain/request/v20180129/SetDefaultRegistrantProfileRequest.py | yndu13/aliyun-openapi-python-sdk | 12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5 | [
"Apache-2.0"
] | 363 | 2015-10-20T03:15:00.000Z | 2022-03-08T12:26:19.000Z | aliyun-python-sdk-domain/aliyunsdkdomain/request/v20180129/SetDefaultRegistrantProfileRequest.py | yndu13/aliyun-openapi-python-sdk | 12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5 | [
"Apache-2.0"
] | 682 | 2015-09-22T07:19:02.000Z | 2022-03-22T09:51:46.000Z | # 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 aliyunsdkcore.request import RpcRequest
from aliyunsdkdomain.endpoint import endpoint_data
class SetDefaultRegistrantProfileRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Domain', '2018-01-29', 'SetDefaultRegistrantProfile')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_RegistrantProfileId(self):
return self.get_query_params().get('RegistrantProfileId')
def set_RegistrantProfileId(self,RegistrantProfileId):
self.add_query_param('RegistrantProfileId',RegistrantProfileId)
def get_UserClientIp(self):
return self.get_query_params().get('UserClientIp')
def set_UserClientIp(self,UserClientIp):
self.add_query_param('UserClientIp',UserClientIp) | 38.681818 | 83 | 0.780846 |
from aliyunsdkcore.request import RpcRequest
from aliyunsdkdomain.endpoint import endpoint_data
class SetDefaultRegistrantProfileRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Domain', '2018-01-29', 'SetDefaultRegistrantProfile')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_RegistrantProfileId(self):
return self.get_query_params().get('RegistrantProfileId')
def set_RegistrantProfileId(self,RegistrantProfileId):
self.add_query_param('RegistrantProfileId',RegistrantProfileId)
def get_UserClientIp(self):
return self.get_query_params().get('UserClientIp')
def set_UserClientIp(self,UserClientIp):
self.add_query_param('UserClientIp',UserClientIp) | true | true |
1c3fc5d94d81003b54cea11a1d4e28a8b570d730 | 3,142 | py | Python | src/midi_board/controls/encoder_button.py | lkt23/midi_board | 543fd5d6abf915990a6d3bc2df061066006427f4 | [
"MIT"
] | null | null | null | src/midi_board/controls/encoder_button.py | lkt23/midi_board | 543fd5d6abf915990a6d3bc2df061066006427f4 | [
"MIT"
] | null | null | null | src/midi_board/controls/encoder_button.py | lkt23/midi_board | 543fd5d6abf915990a6d3bc2df061066006427f4 | [
"MIT"
] | null | null | null | """Encoder Controls for a MIDI controller."""
from midi_board.adapters.adapter import Adapter
from midi_board.controls.button import Button
from midi_board.controls.encoder import Encoder
from midi_board import midi_utility
class EncoderButton(Encoder, Button, Adapter):
"""An Encoder with Button control."""
DEFAULT_NAME = 'encoder'
DEFAULT_DESCRIPTION = 'An encoder with a button.'
def __init__(self, identifier, name=DEFAULT_NAME, description=DEFAULT_DESCRIPTION, **kwargs):
"""Construct EncoderButton."""
Button.__init__(self, identifier, name=name, description=description, **kwargs)
Encoder.__init__(self, identifier, name=name, description=description, **kwargs)
Adapter.__init__(self, name=name, **kwargs)
self._dial = None
self._min = None
self._max = None
self._val_set = None
self._control_param_name = None
self._pop_up_dialog = None
self._validator = None
def update_qt_dial(self, control):
self._dial.setValue(self._raw_value)
self._val_set.setText(str(self.value))
self._min.setText(str(self.min_value))
self._max.setText(str(self.max_value))
if self._dial.signalsBlocked():
self._dial.blockSignals(False)
def move_dial(self, control):
if Encoder.RAW_MIN_VALUE <= self.raw_value <= Encoder.RAW_MAX_VALUE:
message = [0xB0, self.identifier, self.raw_value] # CONTROL_CHANGE = 0xB0. To remove rtmidi import.
midi_utility.send_msg(message)
def on_dial_changed_value_cb(self, val):
self.on_dial_changed_value(val)
def on_dial_changed_value(self, value):
self.raw_value = value
self._val_set.setText(str(self.value))
def on_val_set_return_pressed_cb(self):
self.on_val_set_return_pressed()
def on_val_set_return_pressed(self):
self.value = float(self._val_set.text())
self._slider.setValue(self.raw_value)
def on_range_edited_cb(self):
self.on_range_edited()
def on_range_edited(self):
self._pop_up_dialog.curr_min = self.min_value
self._pop_up_dialog.curr_max = self.max_value
dialog_code = self._pop_up_dialog.exec_()
if dialog_code == 1: # Accepted
if self._pop_up_dialog.new_min is None or self._pop_up_dialog.new_max is None \
or self._pop_up_dialog.new_min >= self._pop_up_dialog.new_max:
self._pop_up_dialog.popup_err_msg.setText("Invalid range!")
self._pop_up_dialog.popup_err_msg.setStyleSheet("color : red")
self.on_range_edited()
return
self._pop_up_dialog.popup_err_msg.setText("")
self.min_value = self._pop_up_dialog.new_min
self.max_value = self._pop_up_dialog.new_max
self._validator.setRange(self.min_value, self.max_value, 20)
self._val_set.setValidator(self._validator)
self._pop_up_dialog.close()
if dialog_code == 0: # Rejected
self._pop_up_dialog.close()
self._dial.blockSignals(True)
| 37.404762 | 112 | 0.674093 |
from midi_board.adapters.adapter import Adapter
from midi_board.controls.button import Button
from midi_board.controls.encoder import Encoder
from midi_board import midi_utility
class EncoderButton(Encoder, Button, Adapter):
DEFAULT_NAME = 'encoder'
DEFAULT_DESCRIPTION = 'An encoder with a button.'
def __init__(self, identifier, name=DEFAULT_NAME, description=DEFAULT_DESCRIPTION, **kwargs):
Button.__init__(self, identifier, name=name, description=description, **kwargs)
Encoder.__init__(self, identifier, name=name, description=description, **kwargs)
Adapter.__init__(self, name=name, **kwargs)
self._dial = None
self._min = None
self._max = None
self._val_set = None
self._control_param_name = None
self._pop_up_dialog = None
self._validator = None
def update_qt_dial(self, control):
self._dial.setValue(self._raw_value)
self._val_set.setText(str(self.value))
self._min.setText(str(self.min_value))
self._max.setText(str(self.max_value))
if self._dial.signalsBlocked():
self._dial.blockSignals(False)
def move_dial(self, control):
if Encoder.RAW_MIN_VALUE <= self.raw_value <= Encoder.RAW_MAX_VALUE:
message = [0xB0, self.identifier, self.raw_value]
midi_utility.send_msg(message)
def on_dial_changed_value_cb(self, val):
self.on_dial_changed_value(val)
def on_dial_changed_value(self, value):
self.raw_value = value
self._val_set.setText(str(self.value))
def on_val_set_return_pressed_cb(self):
self.on_val_set_return_pressed()
def on_val_set_return_pressed(self):
self.value = float(self._val_set.text())
self._slider.setValue(self.raw_value)
def on_range_edited_cb(self):
self.on_range_edited()
def on_range_edited(self):
self._pop_up_dialog.curr_min = self.min_value
self._pop_up_dialog.curr_max = self.max_value
dialog_code = self._pop_up_dialog.exec_()
if dialog_code == 1:
if self._pop_up_dialog.new_min is None or self._pop_up_dialog.new_max is None \
or self._pop_up_dialog.new_min >= self._pop_up_dialog.new_max:
self._pop_up_dialog.popup_err_msg.setText("Invalid range!")
self._pop_up_dialog.popup_err_msg.setStyleSheet("color : red")
self.on_range_edited()
return
self._pop_up_dialog.popup_err_msg.setText("")
self.min_value = self._pop_up_dialog.new_min
self.max_value = self._pop_up_dialog.new_max
self._validator.setRange(self.min_value, self.max_value, 20)
self._val_set.setValidator(self._validator)
self._pop_up_dialog.close()
if dialog_code == 0:
self._pop_up_dialog.close()
self._dial.blockSignals(True)
| true | true |
1c3fc6593cca9bc77e3e6c6e5426fc6faf71bb6d | 9,802 | py | Python | networking_cisco/tests/unit/ml2/drivers/cisco/nexus/test_cisco_nexus_restapi_events_vxlan.py | Tehsmash/networking-cisco | fdbd79a832fe090f3c4c7bd7a4f0ec0c349d4d16 | [
"Apache-2.0"
] | 1 | 2019-01-19T09:12:49.000Z | 2019-01-19T09:12:49.000Z | networking_cisco/tests/unit/ml2/drivers/cisco/nexus/test_cisco_nexus_restapi_events_vxlan.py | Tehsmash/networking-cisco | fdbd79a832fe090f3c4c7bd7a4f0ec0c349d4d16 | [
"Apache-2.0"
] | null | null | null | networking_cisco/tests/unit/ml2/drivers/cisco/nexus/test_cisco_nexus_restapi_events_vxlan.py | Tehsmash/networking-cisco | fdbd79a832fe090f3c4c7bd7a4f0ec0c349d4d16 | [
"Apache-2.0"
] | null | null | null | #Copyright (c) 2017 Cisco Systems, Inc.
# All Rights Reserved.
#
# 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.
"""
VXLAN Test Class using RESTAPI Driver to test Cisco Nexus platforms.
These Classes are based on the original ssh VXLAN event driver
so same tests occur with same configuration. What's different
between the tests is the resulting driver output which is what
the tests in this class presents to its parent class.
You will notice in this file there are test methods which
are skipped by using 'pass'. This is because these tests
apply to ssh only OR because rerunning the test would be
redundant.
"""
from oslo_config import cfg
from networking_cisco.plugins.ml2.drivers.cisco.nexus import (
nexus_restapi_snippets as snipp)
from networking_cisco.tests.unit.ml2.drivers.cisco.nexus import (
test_cisco_nexus_base as base)
from networking_cisco.tests.unit.ml2.drivers.cisco.nexus import (
test_cisco_nexus_events_vxlan)
class TestCiscoNexusRestVxlanResults(base.TestCiscoNexusBaseResults):
"""Unit tests driver results for Cisco ML2 Nexus."""
test_results = {
# The following contains desired Nexus output for
# some basic vxlan config.
'add_port_driver_result': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_VNI_UPDATE % (
'70000', '70000', '70000',
base.MCAST_GROUP)),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST]
],
'delete_port_driver_result': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_1,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
[(snipp.PATH_VLAN % '267'),
base.NEXUS_IP_ADDRESS_1,
'',
base.DELETE]
],
'add_port2_driver_result': [
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/20]'),
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST]
],
'delete_port2_driver_result': [
[(snipp.PATH_IF % 'phys-[eth1/20]'),
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
],
'add_port_driver_result3': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_6,
(snipp.BODY_VNI_UPDATE % (
'70000', '70000', '70000',
base.MCAST_GROUP)),
base.POST],
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_VNI_UPDATE % (
'70000', '70000', '70000',
base.MCAST_GROUP)),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_6,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_6,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/2]'),
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/3]'),
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST]
],
'delete_port_driver_result3': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_6,
'',
base.DELETE],
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_7,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_6,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
[(snipp.PATH_VLAN % '267'),
base.NEXUS_IP_ADDRESS_6,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/2]'),
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
[(snipp.PATH_VLAN % '267'),
base.NEXUS_IP_ADDRESS_7,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/3]'),
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
],
'add_port_driver_result2': [
[(snipp.PATH_VNI_UPDATE % ('1', '70001')),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_VNI_UPDATE % (
'70001', '70001', '70001',
base.MCAST_GROUP)),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_VXLAN_ADD % (265, 70001)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/20]'),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+265')),
base.POST]
],
'delete_port_driver_result2': [
[(snipp.PATH_VNI_UPDATE % ('1', '70001')),
base.NEXUS_IP_ADDRESS_8,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/20]'),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-265')),
base.POST],
[(snipp.PATH_VLAN % '265'),
base.NEXUS_IP_ADDRESS_8,
'',
base.DELETE]
],
'add_port_driver_result4': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_VNI_UPDATE % (
'70000', '70000', '70000',
base.MCAST_GROUP)),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST]
],
'delete_port_driver_result4': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_8,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
[(snipp.PATH_VLAN % '267'),
base.NEXUS_IP_ADDRESS_8,
'',
base.DELETE]
],
}
class TestCiscoNexusRestVxlanDevice(
test_cisco_nexus_events_vxlan.TestCiscoNexusVxlanDevice):
"""Unit tests for Cisco ML2 VXLAN Nexus device driver."""
def setUp(self):
"""Sets up mock ncclient, and switch and credentials dictionaries."""
cfg.CONF.set_override('switch_heartbeat_time', 0, 'ml2_cisco')
# Call Grandfather's setUp(); otherwise parent will set driver to
# 'ncclient' instead of 'restapi'.
super(test_cisco_nexus_events_vxlan.TestCiscoNexusVxlanDevice,
self).setUp()
self.mock_ncclient.reset_mock()
self.addCleanup(self._clear_nve_db)
self.results = TestCiscoNexusRestVxlanResults()
def test_enable_vxlan_feature_failure(self):
pass
def test_disable_vxlan_feature_failure(self):
pass
def test_create_nve_member_failure(self):
pass
def test_delete_nve_member_failure(self):
pass
def test_nexus_vxlan_one_network_two_hosts(self):
(super(TestCiscoNexusRestVxlanDevice, self).
test_nexus_vxlan_one_network_two_hosts())
def test_nexus_missing_vxlan_fields(self):
pass
def test_nexus_vxlan_bind_port(self):
pass
def test_nexus_vxlan_bind_port_no_physnet(self):
pass
def test_nexus_vxlan_bind_port_no_dynamic_segment(self):
pass
def test_nexus_vxlan_one_network(self):
(super(TestCiscoNexusRestVxlanDevice, self).
test_nexus_vxlan_one_network())
def test_nexus_vxlan_two_network(self):
(super(TestCiscoNexusRestVxlanDevice, self).
test_nexus_vxlan_two_network())
| 33.568493 | 77 | 0.55254 |
from oslo_config import cfg
from networking_cisco.plugins.ml2.drivers.cisco.nexus import (
nexus_restapi_snippets as snipp)
from networking_cisco.tests.unit.ml2.drivers.cisco.nexus import (
test_cisco_nexus_base as base)
from networking_cisco.tests.unit.ml2.drivers.cisco.nexus import (
test_cisco_nexus_events_vxlan)
class TestCiscoNexusRestVxlanResults(base.TestCiscoNexusBaseResults):
test_results = {
'add_port_driver_result': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_VNI_UPDATE % (
'70000', '70000', '70000',
base.MCAST_GROUP)),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST]
],
'delete_port_driver_result': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_1,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
[(snipp.PATH_VLAN % '267'),
base.NEXUS_IP_ADDRESS_1,
'',
base.DELETE]
],
'add_port2_driver_result': [
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/20]'),
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST]
],
'delete_port2_driver_result': [
[(snipp.PATH_IF % 'phys-[eth1/20]'),
base.NEXUS_IP_ADDRESS_1,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
],
'add_port_driver_result3': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_6,
(snipp.BODY_VNI_UPDATE % (
'70000', '70000', '70000',
base.MCAST_GROUP)),
base.POST],
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_VNI_UPDATE % (
'70000', '70000', '70000',
base.MCAST_GROUP)),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_6,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_6,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/2]'),
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/3]'),
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST]
],
'delete_port_driver_result3': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_6,
'',
base.DELETE],
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_7,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_6,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
[(snipp.PATH_VLAN % '267'),
base.NEXUS_IP_ADDRESS_6,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/2]'),
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
[(snipp.PATH_VLAN % '267'),
base.NEXUS_IP_ADDRESS_7,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/3]'),
base.NEXUS_IP_ADDRESS_7,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
],
'add_port_driver_result2': [
[(snipp.PATH_VNI_UPDATE % ('1', '70001')),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_VNI_UPDATE % (
'70001', '70001', '70001',
base.MCAST_GROUP)),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_VXLAN_ADD % (265, 70001)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/20]'),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+265')),
base.POST]
],
'delete_port_driver_result2': [
[(snipp.PATH_VNI_UPDATE % ('1', '70001')),
base.NEXUS_IP_ADDRESS_8,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/20]'),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-265')),
base.POST],
[(snipp.PATH_VLAN % '265'),
base.NEXUS_IP_ADDRESS_8,
'',
base.DELETE]
],
'add_port_driver_result4': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_VNI_UPDATE % (
'70000', '70000', '70000',
base.MCAST_GROUP)),
base.POST],
[snipp.PATH_ALL,
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_VXLAN_ADD % (267, 70000)),
base.POST],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '+267')),
base.POST]
],
'delete_port_driver_result4': [
[(snipp.PATH_VNI_UPDATE % ('1', '70000')),
base.NEXUS_IP_ADDRESS_8,
'',
base.DELETE],
[(snipp.PATH_IF % 'phys-[eth1/10]'),
base.NEXUS_IP_ADDRESS_8,
(snipp.BODY_TRUNKVLAN % ('l1PhysIf', '', '-267')),
base.POST],
[(snipp.PATH_VLAN % '267'),
base.NEXUS_IP_ADDRESS_8,
'',
base.DELETE]
],
}
class TestCiscoNexusRestVxlanDevice(
test_cisco_nexus_events_vxlan.TestCiscoNexusVxlanDevice):
def setUp(self):
cfg.CONF.set_override('switch_heartbeat_time', 0, 'ml2_cisco')
# 'ncclient' instead of 'restapi'.
super(test_cisco_nexus_events_vxlan.TestCiscoNexusVxlanDevice,
self).setUp()
self.mock_ncclient.reset_mock()
self.addCleanup(self._clear_nve_db)
self.results = TestCiscoNexusRestVxlanResults()
def test_enable_vxlan_feature_failure(self):
pass
def test_disable_vxlan_feature_failure(self):
pass
def test_create_nve_member_failure(self):
pass
def test_delete_nve_member_failure(self):
pass
def test_nexus_vxlan_one_network_two_hosts(self):
(super(TestCiscoNexusRestVxlanDevice, self).
test_nexus_vxlan_one_network_two_hosts())
def test_nexus_missing_vxlan_fields(self):
pass
def test_nexus_vxlan_bind_port(self):
pass
def test_nexus_vxlan_bind_port_no_physnet(self):
pass
def test_nexus_vxlan_bind_port_no_dynamic_segment(self):
pass
def test_nexus_vxlan_one_network(self):
(super(TestCiscoNexusRestVxlanDevice, self).
test_nexus_vxlan_one_network())
def test_nexus_vxlan_two_network(self):
(super(TestCiscoNexusRestVxlanDevice, self).
test_nexus_vxlan_two_network())
| true | true |
1c3fca1f69d79f498cd13753a85b2fc3f0428449 | 1,309 | py | Python | app/core/tests/test_admin.py | idy-3/recipe-rest-api | 4ed1db6bda54232c3f0506ece5606fe00fb2eb7b | [
"MIT"
] | null | null | null | app/core/tests/test_admin.py | idy-3/recipe-rest-api | 4ed1db6bda54232c3f0506ece5606fe00fb2eb7b | [
"MIT"
] | null | null | null | app/core/tests/test_admin.py | idy-3/recipe-rest-api | 4ed1db6bda54232c3f0506ece5606fe00fb2eb7b | [
"MIT"
] | null | null | null | from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email='admin@idudoh.com',
password='password123'
)
self.client.force_login(self.admin_user)
self.user = get_user_model().objects.create_user(
email='test@idudoh.com',
password='password123',
name='Test Name',
)
def test_users_listed(self):
"""Test that users are listed onuser page"""
url = reverse('admin:core_user_changelist')
res = self.client.get(url)
self.assertContains(res, self.user.name)
self.assertContains(res, self.user.email)
def test_user_change_page(self):
"""Test that the user edit page works"""
url = reverse('admin:core_user_change', args=[self.user.id])
res = self.client.get(url)
self.assertEqual(res.status_code, 200)
def test_create_user_page(self):
"""Test that the create user page works"""
url = reverse('admin:core_user_add')
res = self.client.get(url)
self.assertEqual(res.status_code, 200)
| 31.166667 | 68 | 0.638655 | from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email='admin@idudoh.com',
password='password123'
)
self.client.force_login(self.admin_user)
self.user = get_user_model().objects.create_user(
email='test@idudoh.com',
password='password123',
name='Test Name',
)
def test_users_listed(self):
url = reverse('admin:core_user_changelist')
res = self.client.get(url)
self.assertContains(res, self.user.name)
self.assertContains(res, self.user.email)
def test_user_change_page(self):
url = reverse('admin:core_user_change', args=[self.user.id])
res = self.client.get(url)
self.assertEqual(res.status_code, 200)
def test_create_user_page(self):
url = reverse('admin:core_user_add')
res = self.client.get(url)
self.assertEqual(res.status_code, 200)
| true | true |
1c3fcac8dd4a1ba0496ef013bd4eb468a0075125 | 701 | py | Python | benchmark/fluid/models/__init__.py | limeng357/Paddle | dbd25805c88c48998eb9dc0f4b2ca1fd46326482 | [
"ECL-2.0",
"Apache-2.0"
] | 9 | 2017-12-04T02:58:01.000Z | 2020-12-03T14:46:30.000Z | benchmark/fluid/models/__init__.py | limeng357/Paddle | dbd25805c88c48998eb9dc0f4b2ca1fd46326482 | [
"ECL-2.0",
"Apache-2.0"
] | 7 | 2017-12-05T20:29:08.000Z | 2018-10-15T08:57:40.000Z | benchmark/fluid/models/__init__.py | limeng357/Paddle | dbd25805c88c48998eb9dc0f4b2ca1fd46326482 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2018-03-19T22:38:46.000Z | 2019-11-01T22:28:27.000Z | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# 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.
__all__ = [
"machine_translation", "resnet", "vgg", "mnist", "stacked_dynamic_lstm"
]
| 38.944444 | 75 | 0.750357 |
__all__ = [
"machine_translation", "resnet", "vgg", "mnist", "stacked_dynamic_lstm"
]
| true | true |
1c3fcae299c5564f70363317bc35a332a100318c | 9,126 | py | Python | hgvs/intervalmapper.py | andreas-invitae/hgvs | 5291f1a4fb1991c6da2d004b0e5ad6bf70bbeb64 | [
"Apache-2.0"
] | 177 | 2017-03-12T12:49:52.000Z | 2022-03-19T10:55:08.000Z | hgvs/intervalmapper.py | andreas-invitae/hgvs | 5291f1a4fb1991c6da2d004b0e5ad6bf70bbeb64 | [
"Apache-2.0"
] | 244 | 2017-03-10T22:53:09.000Z | 2022-02-03T09:25:18.000Z | hgvs/intervalmapper.py | andreas-invitae/hgvs | 5291f1a4fb1991c6da2d004b0e5ad6bf70bbeb64 | [
"Apache-2.0"
] | 77 | 2017-03-12T08:51:34.000Z | 2022-02-09T21:56:12.000Z | # -*- coding: utf-8 -*-
"""
Mapping intervals between pairs of congruent segments
The IntervalMapper class is at the heart of mapping between aligned sequences. An instance
of :class:`uta.tools.intervalmapper.IntervalMapper` is constructed with an ordered list of
:class:`uta.tools.intervalmapper.IntervalPair` instances, each of which consists of two
:class:`uta.tools.intervalmapper.Interval` instances. The IntervalMapper class is unaware
of strand/orientation; that issue is handled by the
:class:`uta.tools.transcriptmapper.TranscriptMapper` class.
NOTE: Mapping at the boundaries around indels requires a choice. If seq B
has an insertion relative to seq A, then mapping coordinate at the
boundaries can either be minimal or maximal for both the start and
end. Consider this alignment::
0 15 20 35 50
|==========|====|==========|==========|
| | __/ __/| |
| |/ / | |
|==========|==========|====|==========|
0 15 30 35 50
15M 5D 15M 5I 15M
segment 1: [ 0,15] ~ [ 0,15]
segment 2: [15,20] ~ [15,15]
segment 3: [20,35] ~ [15,30]
segment 4: [35,35] ~ [30,35]
segment 5: [35,50] ~ [35,50]
and these intervals around reference position 35::
interval 1: 34,36 -> 29,36 (no ambiguity)
interval 2: 35,35 -> 30,35 (reasonable)
interval 3: 34,35 -> 29,30 (minimal) or 29,35 (maximal)
interval 4: 35,36 -> 35,36 (minimal) or 30,36 (maximal)
So, for interval 3, end_i=35 matches segment 3 and segment 4. Analagously
for interval 4, start_i=35 matches segment 4 and segment 5.
Currently, this code matches an interval <start_i,end_i> using the maximal
start_i and minimal end_i.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import re
from hgvs.exceptions import HGVSInvalidIntervalError
from six.moves import range
_logger = logging.getLogger(__name__)
_logger.warning("This module is deprecated and will be removed in a future release")
# N.B. This Interval is internal to intervalmapper.py. It is *NOT* the
# same as the Interval defined in location.py.
class Interval(object):
"""Represents a segment of a sequence in interbase
coordinates (0-based, right-open).
"""
__slots__ = ("start_i", "end_i")
def __init__(self, start_i, end_i):
if not (start_i <= end_i):
raise HGVSInvalidIntervalError("start_i must be less than or equal to end_i")
self.start_i = start_i
self.end_i = end_i
@property
def len(self):
return self.end_i - self.start_i
def __repr__(self):
return "{self.__class__.__name__}(start_i={self.start_i},end_i={self.end_i})".format(
self=self)
class IntervalPair(object):
"""Represents a match, insertion, or deletion segment of an
alignment. If a match, the lengths must be equal; if an insertion or
deletion, the length of the ref or tgt must be zero respectively."""
__slots__ = ("ref", "tgt")
def __init__(self, ref, tgt):
if not ((ref.len == tgt.len) or (ref.len == 0 and tgt.len != 0) or
(ref.len != 0 and tgt.len == 0)):
raise HGVSInvalidIntervalError(
"IntervalPair doesn't represent a match, insertion, or deletion")
self.ref = ref
self.tgt = tgt
def __repr__(self):
return "{self.__class__.__name__}(ref={self.ref},tgt={self.tgt})".format(self=self)
class IntervalMapper(object):
"""Provides mapping between sequence coordinates according to an
ordered set of IntervalPairs."""
__slots__ = ("interval_pairs", "ref_intervals", "tgt_intervals", "ref_len", "tgt_len")
def __init__(self, interval_pairs):
"""
:param interval_pairs: an ordered list of IntervalPair instances
:type interval_pairs: list (of IntervalPair instances).
:returns: an IntervalMapper instance
"""
def _validate_intervals(ivs):
for i in range(1, len(ivs)):
# check for adjacency/non-overlap
# This constraint, combined with the start_i <= end_i constraint
# of Intervals, guarantees that intervals are ordered
assert ivs[i - 1].end_i == ivs[i].start_i, "intervals must be adjacent"
self.interval_pairs = interval_pairs
self.ref_intervals = [ip.ref for ip in self.interval_pairs]
self.tgt_intervals = [ip.tgt for ip in self.interval_pairs]
_validate_intervals(self.ref_intervals)
_validate_intervals(self.tgt_intervals)
self.ref_len = sum([iv.len for iv in self.ref_intervals])
self.tgt_len = sum([iv.len for iv in self.tgt_intervals])
@staticmethod
def from_cigar(cigar):
"""
:param cigar: a Compact Idiosyncratic Gapped Alignment Report string
:type cigar: str.
:returns: an IntervalMapper instance from the CIGAR string
"""
return IntervalMapper(cigar_to_intervalpairs(cigar))
def map_ref_to_tgt(self, start_i, end_i, max_extent=False):
return self._map(self.ref_intervals, self.tgt_intervals, start_i, end_i, max_extent)
def map_tgt_to_ref(self, start_i, end_i, max_extent=False):
return self._map(self.tgt_intervals, self.ref_intervals, start_i, end_i, max_extent)
@staticmethod
def _map(from_ivs, to_ivs, from_start_i, from_end_i, max_extent):
def iv_map(from_ivs, to_ivs, from_start_i, from_end_i, max_extent):
"""returns the <start,end> intervals indexes in which from_start_i and from_end_i occur"""
# first look for 0-width interval that matches
seil = [
i for i, iv in enumerate(from_ivs)
if iv.start_i == from_start_i and iv.end_i == from_end_i
]
if len(seil) > 0:
si = ei = seil[0]
else:
sil = [i for i, iv in enumerate(from_ivs) if iv.start_i <= from_start_i <= iv.end_i]
eil = [i for i, iv in enumerate(from_ivs) if iv.start_i <= from_end_i <= iv.end_i]
if len(sil) == 0 or len(eil) == 0:
raise HGVSInvalidIntervalError(
"start or end or both are beyond the bounds of transcript record")
si, ei = (sil[0], eil[-1]) if max_extent else (sil[-1], eil[0])
return si, ei
def clip_to_iv(iv, pos):
return max(iv.start_i, min(iv.end_i, pos))
assert from_start_i <= from_end_i, "expected from_start_i <= from_end_i"
try:
si, ei = iv_map(from_ivs, to_ivs, from_start_i, from_end_i, max_extent)
except ValueError:
raise HGVSInvalidIntervalError("start_i,end_i interval out of bounds")
to_start_i = clip_to_iv(to_ivs[si],
to_ivs[si].start_i + (from_start_i - from_ivs[si].start_i))
to_end_i = clip_to_iv(to_ivs[ei], to_ivs[ei].end_i - (from_ivs[ei].end_i - from_end_i))
return to_start_i, to_end_i
class CIGARElement(object):
"""represents elements of a CIGAR string and provides methods for
determining the number of ref and tgt bases consumed by the
operation"""
__slots__ = ("len", "op")
def __init__(self, len, op):
self.len = len
self.op = op
@property
def ref_len(self):
"""returns number of nt/aa consumed in reference sequence for this edit"""
return self.len if self.op in "=INX" else 0
@property
def tgt_len(self):
"""returns number of nt/aa consumed in target sequence for this edit"""
return self.len if self.op in "=DX" else 0
def cigar_to_intervalpairs(cigar):
"""For a given CIGAR string, return a list of (Interval,Interval)
pairs. The length of the returned list will be equal to the
number of CIGAR operations
"""
cigar_elem_re = re.compile(r"(?P<len>\d+)(?P<op>[=DIMNX])")
ces = [
CIGARElement(op=md["op"], len=int(md["len"]))
for md in [m.groupdict() for m in cigar_elem_re.finditer(cigar)]
]
ips = [None] * len(ces)
ref_pos = tgt_pos = 0
for i, ce in enumerate(ces):
ips[i] = IntervalPair(
Interval(ref_pos, ref_pos + ce.ref_len), Interval(tgt_pos, tgt_pos + ce.tgt_len))
ref_pos += ce.ref_len
tgt_pos += ce.tgt_len
return ips
# <LICENSE>
# Copyright 2018 HGVS Contributors (https://github.com/biocommons/hgvs)
#
# 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.
# </LICENSE>
| 39.336207 | 102 | 0.641026 |
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import re
from hgvs.exceptions import HGVSInvalidIntervalError
from six.moves import range
_logger = logging.getLogger(__name__)
_logger.warning("This module is deprecated and will be removed in a future release")
class Interval(object):
__slots__ = ("start_i", "end_i")
def __init__(self, start_i, end_i):
if not (start_i <= end_i):
raise HGVSInvalidIntervalError("start_i must be less than or equal to end_i")
self.start_i = start_i
self.end_i = end_i
@property
def len(self):
return self.end_i - self.start_i
def __repr__(self):
return "{self.__class__.__name__}(start_i={self.start_i},end_i={self.end_i})".format(
self=self)
class IntervalPair(object):
__slots__ = ("ref", "tgt")
def __init__(self, ref, tgt):
if not ((ref.len == tgt.len) or (ref.len == 0 and tgt.len != 0) or
(ref.len != 0 and tgt.len == 0)):
raise HGVSInvalidIntervalError(
"IntervalPair doesn't represent a match, insertion, or deletion")
self.ref = ref
self.tgt = tgt
def __repr__(self):
return "{self.__class__.__name__}(ref={self.ref},tgt={self.tgt})".format(self=self)
class IntervalMapper(object):
__slots__ = ("interval_pairs", "ref_intervals", "tgt_intervals", "ref_len", "tgt_len")
def __init__(self, interval_pairs):
def _validate_intervals(ivs):
for i in range(1, len(ivs)):
# check for adjacency/non-overlap
# This constraint, combined with the start_i <= end_i constraint
# of Intervals, guarantees that intervals are ordered
assert ivs[i - 1].end_i == ivs[i].start_i, "intervals must be adjacent"
self.interval_pairs = interval_pairs
self.ref_intervals = [ip.ref for ip in self.interval_pairs]
self.tgt_intervals = [ip.tgt for ip in self.interval_pairs]
_validate_intervals(self.ref_intervals)
_validate_intervals(self.tgt_intervals)
self.ref_len = sum([iv.len for iv in self.ref_intervals])
self.tgt_len = sum([iv.len for iv in self.tgt_intervals])
@staticmethod
def from_cigar(cigar):
return IntervalMapper(cigar_to_intervalpairs(cigar))
def map_ref_to_tgt(self, start_i, end_i, max_extent=False):
return self._map(self.ref_intervals, self.tgt_intervals, start_i, end_i, max_extent)
def map_tgt_to_ref(self, start_i, end_i, max_extent=False):
return self._map(self.tgt_intervals, self.ref_intervals, start_i, end_i, max_extent)
@staticmethod
def _map(from_ivs, to_ivs, from_start_i, from_end_i, max_extent):
def iv_map(from_ivs, to_ivs, from_start_i, from_end_i, max_extent):
# first look for 0-width interval that matches
seil = [
i for i, iv in enumerate(from_ivs)
if iv.start_i == from_start_i and iv.end_i == from_end_i
]
if len(seil) > 0:
si = ei = seil[0]
else:
sil = [i for i, iv in enumerate(from_ivs) if iv.start_i <= from_start_i <= iv.end_i]
eil = [i for i, iv in enumerate(from_ivs) if iv.start_i <= from_end_i <= iv.end_i]
if len(sil) == 0 or len(eil) == 0:
raise HGVSInvalidIntervalError(
"start or end or both are beyond the bounds of transcript record")
si, ei = (sil[0], eil[-1]) if max_extent else (sil[-1], eil[0])
return si, ei
def clip_to_iv(iv, pos):
return max(iv.start_i, min(iv.end_i, pos))
assert from_start_i <= from_end_i, "expected from_start_i <= from_end_i"
try:
si, ei = iv_map(from_ivs, to_ivs, from_start_i, from_end_i, max_extent)
except ValueError:
raise HGVSInvalidIntervalError("start_i,end_i interval out of bounds")
to_start_i = clip_to_iv(to_ivs[si],
to_ivs[si].start_i + (from_start_i - from_ivs[si].start_i))
to_end_i = clip_to_iv(to_ivs[ei], to_ivs[ei].end_i - (from_ivs[ei].end_i - from_end_i))
return to_start_i, to_end_i
class CIGARElement(object):
__slots__ = ("len", "op")
def __init__(self, len, op):
self.len = len
self.op = op
@property
def ref_len(self):
return self.len if self.op in "=INX" else 0
@property
def tgt_len(self):
return self.len if self.op in "=DX" else 0
def cigar_to_intervalpairs(cigar):
cigar_elem_re = re.compile(r"(?P<len>\d+)(?P<op>[=DIMNX])")
ces = [
CIGARElement(op=md["op"], len=int(md["len"]))
for md in [m.groupdict() for m in cigar_elem_re.finditer(cigar)]
]
ips = [None] * len(ces)
ref_pos = tgt_pos = 0
for i, ce in enumerate(ces):
ips[i] = IntervalPair(
Interval(ref_pos, ref_pos + ce.ref_len), Interval(tgt_pos, tgt_pos + ce.tgt_len))
ref_pos += ce.ref_len
tgt_pos += ce.tgt_len
return ips
# <LICENSE>
# Copyright 2018 HGVS Contributors (https://github.com/biocommons/hgvs)
#
# 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.
# </LICENSE>
| true | true |
1c3fcb5770492394a9cb08febb1f7816ab936f00 | 2,564 | py | Python | src/gausskernel/dbmind/tools/anomaly_detection/detector/algorithm/fb_prophet.py | Yanci0/openGauss-server | b2ff10be1367c77f2fda396d6c12ffa3c25874c7 | [
"MulanPSL-1.0"
] | 360 | 2020-06-30T14:47:34.000Z | 2022-03-31T15:21:53.000Z | src/gausskernel/dbmind/tools/anomaly_detection/detector/algorithm/fb_prophet.py | Yanci0/openGauss-server | b2ff10be1367c77f2fda396d6c12ffa3c25874c7 | [
"MulanPSL-1.0"
] | 4 | 2020-06-30T15:09:16.000Z | 2020-07-14T06:20:03.000Z | src/gausskernel/dbmind/tools/anomaly_detection/detector/algorithm/fb_prophet.py | futurewei-cloud/chogori-opengauss | f43410e1643c887819e718d9baceb9e853ad9574 | [
"MulanPSL-1.0"
] | 133 | 2020-06-30T14:47:36.000Z | 2022-03-25T15:29:00.000Z | """
Copyright (c) 2020 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
import pickle
import time
import pandas as pd
from fbprophet import Prophet
from .model import AlgModel
class FbProphet(AlgModel):
"""
This class inherits from the AlgModel class.
It is based on the Facebook prophet algorithm and uses to forecast time-series.
"""
def __init__(self):
AlgModel.__init__(self)
self.model = None
self.train_length = 0
def fit(self, timeseries):
"""
:param timeseries: list, it should include timestamp and value like
[[111111111, 2222222222, ...], [4.0, 5.0, ...]].
:return: NA
"""
timeseries = pd.DataFrame(timeseries, columns=['ds', 'y'])
timeseries['ds'] = timeseries['ds'].map(
lambda x: time.strftime(AlgModel.DATE_FORMAT, time.localtime(x)))
self.train_length = len(timeseries)
self.model = Prophet(yearly_seasonality=True,
weekly_seasonality=True,
daily_seasonality=True)
self.model.fit(timeseries)
def forecast(self, period, freq):
"""
:param freq: int, time interval.
:param period: string, like '100S','1D', reprensent forecast period.
:return: list, forecast result which include date and value.
"""
if freq.endswith('M'):
freq = freq.replace('M', 'T')
future = self.model.make_future_dataframe(freq=freq,
periods=period,
include_history=False)
forecast_result = self.model.predict(future)[['ds', 'yhat']]
forecast_result['ds'] = forecast_result['ds'].map(lambda x: x.strftime(AlgModel.DATE_FORMAT))
return forecast_result.values[:, 0], forecast_result.values[:, 1]
def save(self, model_path):
with open(model_path, mode='wb') as f:
pickle.dump(self.model, f)
def load(self, model_path):
with open(model_path, mode='rb') as f:
self.model = pickle.load(f)
| 35.123288 | 101 | 0.618175 | import pickle
import time
import pandas as pd
from fbprophet import Prophet
from .model import AlgModel
class FbProphet(AlgModel):
def __init__(self):
AlgModel.__init__(self)
self.model = None
self.train_length = 0
def fit(self, timeseries):
timeseries = pd.DataFrame(timeseries, columns=['ds', 'y'])
timeseries['ds'] = timeseries['ds'].map(
lambda x: time.strftime(AlgModel.DATE_FORMAT, time.localtime(x)))
self.train_length = len(timeseries)
self.model = Prophet(yearly_seasonality=True,
weekly_seasonality=True,
daily_seasonality=True)
self.model.fit(timeseries)
def forecast(self, period, freq):
if freq.endswith('M'):
freq = freq.replace('M', 'T')
future = self.model.make_future_dataframe(freq=freq,
periods=period,
include_history=False)
forecast_result = self.model.predict(future)[['ds', 'yhat']]
forecast_result['ds'] = forecast_result['ds'].map(lambda x: x.strftime(AlgModel.DATE_FORMAT))
return forecast_result.values[:, 0], forecast_result.values[:, 1]
def save(self, model_path):
with open(model_path, mode='wb') as f:
pickle.dump(self.model, f)
def load(self, model_path):
with open(model_path, mode='rb') as f:
self.model = pickle.load(f)
| true | true |
1c3fcc29c72899455097c9c023a835636dff2790 | 5,578 | py | Python | Flask/loginRadius-flask-auth/models.py | FuzzySid/engineering-blog-samples | 7521cb1ea6d4300a91142c9e30f09fbcebcf8a1e | [
"MIT"
] | null | null | null | Flask/loginRadius-flask-auth/models.py | FuzzySid/engineering-blog-samples | 7521cb1ea6d4300a91142c9e30f09fbcebcf8a1e | [
"MIT"
] | null | null | null | Flask/loginRadius-flask-auth/models.py | FuzzySid/engineering-blog-samples | 7521cb1ea6d4300a91142c9e30f09fbcebcf8a1e | [
"MIT"
] | null | null | null | """Application Models"""
import bson, os
from dotenv import load_dotenv
from pymongo import MongoClient
from werkzeug.security import generate_password_hash, check_password_hash
load_dotenv()
DATABASE_URL=os.environ.get('DATABASE_URL') or 'mongodb://localhost:27017/myDatabase'
print(DATABASE_URL)
client = MongoClient(DATABASE_URL)
db = client.myDatabase
class Books:
"""Books Model"""
def __init__(self):
return
def create(self, title="", description="", image_url="", category="", user_id=""):
"""Create a new book"""
book = self.get_by_user_id_and_title(user_id, title)
if book:
return
new_book = db.books.insert_one(
{
"title": title,
"description": description,
"image_url": image_url,
"category": category,
"user_id": user_id
}
)
return self.get_by_id(new_book.inserted_id)
def get_all(self):
"""Get all books"""
books = db.books.find()
return [{**book, "_id": str(book["_id"])} for book in books]
def get_by_id(self, book_id):
"""Get a book by id"""
book = db.books.find_one({"_id": bson.ObjectId(book_id)})
if not book:
return
book["_id"] = str(book["_id"])
return book
def get_by_user_id(self, user_id):
"""Get all books created by a user"""
books = db.books.find({"user_id": user_id})
return [{**book, "_id": str(book["_id"])} for book in books]
def get_by_category(self, category):
"""Get all books by category"""
books = db.books.find({"category": category})
return [book for book in books]
def get_by_user_id_and_category(self, user_id, category):
"""Get all books by category for a particular user"""
books = db.books.find({"user_id": user_id, "category": category})
return [{**book, "_id": str(book["_id"])} for book in books]
def get_by_user_id_and_title(self, user_id, title):
"""Get a book given its title and author"""
book = db.books.find_one({"user_id": user_id, "title": title})
if not book:
return
book["_id"] = str(book["_id"])
return book
def update(self, book_id, title="", description="", image_url="", category="", user_id=""):
"""Update a book"""
data={}
if title: data["title"]=title
if description: data["description"]=description
if image_url: data["image_url"]=image_url
if category: data["category"]=category
book = db.books.update_one(
{"_id": bson.ObjectId(book_id)},
{
"$set": data
}
)
book = self.get_by_id(book_id)
return book
def delete(self, book_id):
"""Delete a book"""
book = db.books.delete_one({"_id": bson.ObjectId(book_id)})
return book
def delete_by_user_id(self, user_id):
"""Delete all books created by a user"""
book = db.books.delete_many({"user_id": bson.ObjectId(user_id)})
return book
class User:
"""User Model"""
def __init__(self):
return
def create(self, name="", email="", password=""):
"""Create a new user"""
user = self.get_by_email(email)
if user:
return
new_user = db.users.insert_one(
{
"name": name,
"email": email,
"password": self.encrypt_password(password),
"active": True
}
)
return self.get_by_id(new_user.inserted_id)
def get_all(self):
"""Get all users"""
users = db.users.find({"active": True})
return [{**user, "_id": str(user["_id"])} for user in users]
def get_by_id(self, user_id):
"""Get a user by id"""
user = db.users.find_one({"_id": bson.ObjectId(user_id), "active": True})
if not user:
return
user["_id"] = str(user["_id"])
user.pop("password")
return user
def get_by_email(self, email):
"""Get a user by email"""
user = db.users.find_one({"email": email, "active": True})
if not user:
return
user["_id"] = str(user["_id"])
return user
def update(self, user_id, name=""):
"""Update a user"""
data = {}
if name:
data["name"] = name
user = db.users.update_one(
{"_id": bson.ObjectId(user_id)},
{
"$set": data
}
)
user = self.get_by_id(user_id)
return user
def delete(self, user_id):
"""Delete a user"""
Books().delete_by_user_id(user_id)
user = db.users.delete_one({"_id": bson.ObjectId(user_id)})
user = self.get_by_id(user_id)
return user
def disable_account(self, user_id):
"""Disable a user account"""
user = db.users.update_one(
{"_id": bson.ObjectId(user_id)},
{"$set": {"active": False}}
)
user = self.get_by_id(user_id)
return user
def encrypt_password(self, password):
"""Encrypt password"""
return generate_password_hash(password)
def login(self, email, password):
"""Login a user"""
user = self.get_by_email(email)
if not user or not check_password_hash(user["password"], password):
return
user.pop("password")
return user
| 30.648352 | 95 | 0.551811 | import bson, os
from dotenv import load_dotenv
from pymongo import MongoClient
from werkzeug.security import generate_password_hash, check_password_hash
load_dotenv()
DATABASE_URL=os.environ.get('DATABASE_URL') or 'mongodb://localhost:27017/myDatabase'
print(DATABASE_URL)
client = MongoClient(DATABASE_URL)
db = client.myDatabase
class Books:
def __init__(self):
return
def create(self, title="", description="", image_url="", category="", user_id=""):
book = self.get_by_user_id_and_title(user_id, title)
if book:
return
new_book = db.books.insert_one(
{
"title": title,
"description": description,
"image_url": image_url,
"category": category,
"user_id": user_id
}
)
return self.get_by_id(new_book.inserted_id)
def get_all(self):
books = db.books.find()
return [{**book, "_id": str(book["_id"])} for book in books]
def get_by_id(self, book_id):
book = db.books.find_one({"_id": bson.ObjectId(book_id)})
if not book:
return
book["_id"] = str(book["_id"])
return book
def get_by_user_id(self, user_id):
books = db.books.find({"user_id": user_id})
return [{**book, "_id": str(book["_id"])} for book in books]
def get_by_category(self, category):
books = db.books.find({"category": category})
return [book for book in books]
def get_by_user_id_and_category(self, user_id, category):
books = db.books.find({"user_id": user_id, "category": category})
return [{**book, "_id": str(book["_id"])} for book in books]
def get_by_user_id_and_title(self, user_id, title):
book = db.books.find_one({"user_id": user_id, "title": title})
if not book:
return
book["_id"] = str(book["_id"])
return book
def update(self, book_id, title="", description="", image_url="", category="", user_id=""):
data={}
if title: data["title"]=title
if description: data["description"]=description
if image_url: data["image_url"]=image_url
if category: data["category"]=category
book = db.books.update_one(
{"_id": bson.ObjectId(book_id)},
{
"$set": data
}
)
book = self.get_by_id(book_id)
return book
def delete(self, book_id):
book = db.books.delete_one({"_id": bson.ObjectId(book_id)})
return book
def delete_by_user_id(self, user_id):
book = db.books.delete_many({"user_id": bson.ObjectId(user_id)})
return book
class User:
def __init__(self):
return
def create(self, name="", email="", password=""):
user = self.get_by_email(email)
if user:
return
new_user = db.users.insert_one(
{
"name": name,
"email": email,
"password": self.encrypt_password(password),
"active": True
}
)
return self.get_by_id(new_user.inserted_id)
def get_all(self):
users = db.users.find({"active": True})
return [{**user, "_id": str(user["_id"])} for user in users]
def get_by_id(self, user_id):
user = db.users.find_one({"_id": bson.ObjectId(user_id), "active": True})
if not user:
return
user["_id"] = str(user["_id"])
user.pop("password")
return user
def get_by_email(self, email):
user = db.users.find_one({"email": email, "active": True})
if not user:
return
user["_id"] = str(user["_id"])
return user
def update(self, user_id, name=""):
data = {}
if name:
data["name"] = name
user = db.users.update_one(
{"_id": bson.ObjectId(user_id)},
{
"$set": data
}
)
user = self.get_by_id(user_id)
return user
def delete(self, user_id):
Books().delete_by_user_id(user_id)
user = db.users.delete_one({"_id": bson.ObjectId(user_id)})
user = self.get_by_id(user_id)
return user
def disable_account(self, user_id):
user = db.users.update_one(
{"_id": bson.ObjectId(user_id)},
{"$set": {"active": False}}
)
user = self.get_by_id(user_id)
return user
def encrypt_password(self, password):
return generate_password_hash(password)
def login(self, email, password):
user = self.get_by_email(email)
if not user or not check_password_hash(user["password"], password):
return
user.pop("password")
return user
| true | true |
1c3fd02c8d60b07aa813e5e6f9443d79434be0ec | 29,654 | py | Python | python/neuroglancer/tool/screenshot.py | janelia-cosem/neuroglancer | add6885da32498a1cfd1075a4c19aae8ffb5a6f2 | [
"Apache-2.0"
] | 755 | 2016-06-06T13:56:32.000Z | 2022-03-31T14:48:19.000Z | python/neuroglancer/tool/screenshot.py | janelia-cosem/neuroglancer | add6885da32498a1cfd1075a4c19aae8ffb5a6f2 | [
"Apache-2.0"
] | 331 | 2016-06-07T22:06:43.000Z | 2022-03-24T21:48:51.000Z | python/neuroglancer/tool/screenshot.py | janelia-cosem/neuroglancer | add6885da32498a1cfd1075a4c19aae8ffb5a6f2 | [
"Apache-2.0"
] | 240 | 2016-06-07T00:56:43.000Z | 2022-03-31T21:10:50.000Z | #!/usr/bin/env python
# @license
# Copyright 2020 Google Inc.
# 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.
"""Tool for creating screenshots with Neuroglancer.
The Neuroglancer state may be specified either by a URL or by a path to a JSON
state file.
Rendering requires a web browser. By default, a headless chromedriver is
started in the background. It is also possible to use non-headless chromedriver
or a manually-opened browser.
There are several methods by which the screenshot image may be rendered:
1. The state can be rendered directly as a single frame by Neuroglancer. This
is the simplest and fastest method and works for most states.
2. If the output image size exceeds what Neuroglancer/the browser can support
(usually about 4096x4096), tiled rendering can be used. In this case,
Neuroglancer will render the image as multiple tiles which are assembled
automatically into a single image. This is enabled automatically if the
requested image size exceeds the specified tile dimensions. All normal
functionality is supported, except for the "show_slices" option whereby
cross-section panels are also shown in the 3-d view. Manually-specified
cross sections via the "cross_sections" property are supported, however.
3. If a very large number of 3-d objects are to be rendered, it may be
impossible for Neuroglancer to render them all simultaneously due to memory
limits. The `--segment-shard-size` option may be specified to enable a
special rendering mode in which subsets of the objects are rendered
independently and then combined together into a single image. Depth
information is used to combine the images together. Currently, transparent
rendering of objects is not supported, though. As the final image is
produced incrementally, the state is saved in a `.npz` file, which allows
resuming if the screenshot process is interrupted. To avoid resuming if you
change options, delete the `.npz` file.
Tips:
- The Neuroglancer UI controls are not shown, and in the case of multi-panel
layouts, there is no border between panels. In most cases it is desirable to
capture a single-panel layout.
- The layer side panel and statistics panel, if open, will be closed for the
screenshot.
- The specified image dimensions will be used, rather than the dimensions of
your browser window. This, in combination with the removal of the normal
Neuroglancer UI controls, means that the field of view may differ somewhat.
- The axis lines and volume bounding boxes will be shown if they are enabled in
the Neuroglancer state. If you don't want them in the screenshot, you should
disable them in the Neuroglancer state. You may also use the
`--hide-axis-lines` and `--hide-default-annotations` options. In most cases
it is desirable to hide the axis lines and default annotations.
- The scale bars will be shown if they are enabled in the Neuroglancer state.
If you specify a large image size, you may want to increase the size of the
scale bar, using the `--scale-bar-scale` option.
"""
import argparse
import collections
import contextlib
import copy
import datetime
import itertools
import numbers
import os
import threading
import time
from typing import NamedTuple, Tuple, Callable, Iterator, List, Optional
import PIL
import numpy as np
import neuroglancer
import neuroglancer.cli
import neuroglancer.webdriver
def _get_total_segments(state):
num_segments = 0
for layer in state.layers:
if not isinstance(layer.layer, neuroglancer.SegmentationLayer):
continue
num_segments += len(layer.segments)
return num_segments
def _should_shard_segments(state, segment_shard_size):
return _get_total_segments(state) > segment_shard_size
def _calculate_num_shards(state, segment_shard_size):
total_segments = _get_total_segments(state)
return -(-total_segments // segment_shard_size)
def _get_sharded_states(state, segment_shard_size, reverse_bits):
if reverse_bits:
sort_key = lambda x: int('{:064b}'.format(x)[::-1], 2)
else:
sort_key = None
num_shards = _calculate_num_shards(state, segment_shard_size)
for shard_i in range(num_shards):
new_state = copy.deepcopy(state)
cum_retained = 0
cum_skipped = segment_shard_size * shard_i
for i, layer in enumerate(new_state.layers):
if not isinstance(layer.layer, neuroglancer.SegmentationLayer):
continue
segments = sorted(layer.segments, key=sort_key)
num_to_skip = min(cum_skipped, len(segments))
segments = segments[num_to_skip:]
cum_skipped += num_to_skip
num_to_retain = min(segment_shard_size - cum_retained, len(segments))
cum_retained += num_to_retain
layer.segments = set(segments[:num_to_retain])
yield new_state
class TileGenerator:
def __init__(self, shape, tile_shape):
self.tile_shape = tuple(tile_shape)
self.shape = tuple(shape)
self.tile_grid_shape = tuple(-(-self.shape[i] // self.tile_shape[i]) for i in range(2))
self.tile_shape = tuple(-(-self.shape[i] // self.tile_grid_shape[i]) for i in range(2))
self.num_tiles = self.tile_grid_shape[0] * self.tile_grid_shape[1]
def get_tile_states(self, state):
for tile_y in range(self.tile_grid_shape[1]):
for tile_x in range(self.tile_grid_shape[0]):
x_offset = tile_x * self.tile_shape[0]
y_offset = tile_y * self.tile_shape[1]
tile_width = min(self.tile_shape[0], self.shape[0] - x_offset)
tile_height = min(self.tile_shape[1], self.shape[1] - y_offset)
new_state = copy.deepcopy(state)
new_state.partial_viewport = [
x_offset / self.shape[0], y_offset / self.shape[1], tile_width / self.shape[0],
tile_height / self.shape[1]
]
params = {
'tile_x': tile_x,
'tile_y': tile_y,
'x_offset': x_offset,
'y_offset': y_offset,
'tile_width': tile_width,
'tile_height': tile_height,
}
yield params, new_state
class ShardedTileGenerator(TileGenerator):
def __init__(self, state, segment_shard_size, reverse_bits, **kwargs):
super(ShardedTileGenerator, self).__init__(**kwargs)
self.state = state
self.reverse_bits = reverse_bits
self.total_segments = _get_total_segments(self.state)
self.segment_shard_size = segment_shard_size
self.num_shards = _calculate_num_shards(self.state, self.segment_shard_size)
self.num_tiles *= self.num_shards
def get_states(self):
for shard_i, state in enumerate(
_get_sharded_states(self.state,
self.segment_shard_size,
reverse_bits=self.reverse_bits)):
for params, state in self.get_tile_states(state):
params['segment_shard'] = shard_i
yield params, state
class CaptureScreenshotRequest(NamedTuple):
state: neuroglancer.ViewerState
description: str
config_callback: Callable[[neuroglancer.viewer_config_state.ConfigState], None]
response_callback: neuroglancer.viewer_config_state.ScreenshotReply
include_depth: bool = False
def buffered_iterator(base_iter, lock, buffer_size):
while True:
with lock:
buffered_items = list(itertools.islice(base_iter, buffer_size))
if not buffered_items: break
for item in buffered_items:
yield item
def capture_screenshots(viewer: neuroglancer.Viewer,
request_iter: Iterator[CaptureScreenshotRequest],
refresh_browser_callback: Callable[[], None],
refresh_browser_timeout: int,
num_to_prefetch: int = 1) -> None:
prefetch_buffer = list(itertools.islice(request_iter, num_to_prefetch + 1))
while prefetch_buffer:
with viewer.config_state.txn() as s:
s.show_ui_controls = False
s.show_panel_borders = False
del s.prefetch[:]
for i, request in enumerate(prefetch_buffer[1:]):
s.prefetch.append(
neuroglancer.PrefetchState(state=request.state, priority=num_to_prefetch - i))
request = prefetch_buffer[0]
request.config_callback(s)
viewer.set_state(request.state)
print('%s [%s] Requesting screenshot' % (
datetime.datetime.now().strftime('%Y-%m-%dT%H:%M%S.%f'),
request.description,
))
last_statistics_time = time.time()
def statistics_callback(statistics):
nonlocal last_statistics_time
last_statistics_time = time.time()
total = statistics.total
print(
'%s [%s] Screenshot in progress: %6d/%6d chunks loaded (%10d bytes), %3d downloading'
% (
datetime.datetime.now().strftime('%Y-%m-%dT%H:%M%S.%f'),
request.description,
total.visible_chunks_gpu_memory,
total.visible_chunks_total,
total.visible_gpu_memory,
total.visible_chunks_downloading,
))
event = threading.Event()
screenshot = None
def result_callback(s):
nonlocal screenshot
screenshot = s.screenshot
event.set()
viewer.async_screenshot(
result_callback,
include_depth=request.include_depth,
statistics_callback=statistics_callback,
)
def get_timeout():
return max(0, last_statistics_time + refresh_browser_timeout - time.time())
while True:
if event.wait(get_timeout()):
break
if get_timeout() > 0:
continue
last_statistics_time = time.time()
refresh_browser_callback()
request.response_callback(screenshot)
del prefetch_buffer[0]
next_request = next(request_iter, None)
if next_request is not None:
prefetch_buffer.append(next_request)
def capture_screenshots_in_parallel(viewers: List[Tuple[neuroglancer.Viewer, Callable[[], None]]],
request_iter: Iterator[CaptureScreenshotRequest],
refresh_browser_timeout: numbers.Number, num_to_prefetch: int,
total_requests: Optional[int] = None,
buffer_size: Optional[int] = None):
if buffer_size is None:
if total_requests is None:
copy_of_requests = list(request_iter)
total_requests = len(copy_of_requests)
request_iter = iter(copy_of_requests)
buffer_size = max(1, total_requests // (len(viewers) * 4))
request_iter = iter(request_iter)
threads = []
buffer_lock = threading.Lock()
for viewer, refresh_browser_callback in viewers:
def capture_func(viewer, refresh_browser_callback):
viewer_request_iter = buffered_iterator(base_iter=request_iter,
lock=buffer_lock,
buffer_size=buffer_size)
capture_screenshots(
viewer=viewer,
request_iter=viewer_request_iter,
num_to_prefetch=num_to_prefetch,
refresh_browser_timeout=refresh_browser_timeout,
refresh_browser_callback=refresh_browser_callback,
)
t = threading.Thread(target=capture_func, args=(viewer, refresh_browser_callback))
t.start()
threads.append(t)
for t in threads:
t.join()
class MultiCapturer:
def __init__(self,
shape,
include_depth,
output,
config_callback,
num_to_prefetch,
checkpoint_interval=60):
self.include_depth = include_depth
self.checkpoint_interval = checkpoint_interval
self.config_callback = config_callback
self.num_to_prefetch = num_to_prefetch
self.output = output
self._processed = set()
self.state_file = output + '.npz'
self.temp_state_file = self.state_file + '.tmp'
self.image_array = np.zeros((shape[1], shape[0], 4), dtype=np.uint8)
if self.include_depth:
self.depth_array = np.zeros((shape[1], shape[0]), dtype=np.float32)
self._load_state()
self._add_image_lock = threading.Lock()
self._last_save_time = time.time()
self._save_state_in_progress = threading.Event()
self._save_state_in_progress.set()
self._num_states_processed = 0
self._start_time = time.time()
def _load_state(self):
if not os.path.exists(self.state_file):
return
with np.load(self.state_file, allow_pickle=True) as f:
if self.include_depth:
self.depth_array = f['depth']
self.image_array = f['image']
self._processed = set(f['processed'].ravel()[0])
def _save_state(self, save_image=False):
with self._add_image_lock:
processed = set(self._processed)
with open(self.temp_state_file, 'wb') as f:
save_arrays = {
'image': self.image_array,
'processed': processed,
}
if self.include_depth:
save_arrays['depth'] = self.depth_array
np.savez_compressed(f, **save_arrays)
os.replace(self.temp_state_file, self.state_file)
if save_image:
self._save_image()
def _save_state_async(self, save_image=False):
print('Starting checkpointing')
def func():
try:
self._save_state()
print('Done checkpointing')
finally:
self._save_state_in_progress.set()
threading.Thread(target=func, daemon=True).start()
def _save_image(self):
im = PIL.Image.fromarray(self.image_array)
im.save(self.output)
def _add_image(self, params, screenshot):
with self._add_image_lock:
tile_image = screenshot.image_pixels
tile_selector = np.s_[params['y_offset']:params['y_offset'] + params['tile_height'],
params['x_offset']:params['x_offset'] + params['tile_width']]
if self.include_depth:
tile_depth = screenshot.depth_array
depth_array_part = self.depth_array[tile_selector]
mask = np.logical_and(np.logical_or(tile_depth != 0, depth_array_part == 0),
tile_depth >= depth_array_part)
depth_array_part[mask] = tile_depth[mask]
else:
mask = Ellipsis
self.image_array[tile_selector][mask] = tile_image[mask]
self._processed.add(self._get_description(params))
self._num_states_processed += 1
elapsed = time.time() - self._start_time
print('%4d tiles rendered in %5d seconds: %.1f seconds/tile' %
(self._num_states_processed, elapsed, elapsed / self._num_states_processed))
def _maybe_save_state(self):
if not self._save_state_in_progress.is_set(): return
with self._add_image_lock:
if self._last_save_time + self.checkpoint_interval < time.time():
self._last_save_time = time.time()
self._save_state_in_progress.clear()
self._save_state_async(save_image=False)
def _get_description(self, params):
segment_shard = params.get('segment_shard')
if segment_shard is not None:
prefix = 'segment_shard=%d ' % (segment_shard, )
else:
prefix = ''
return '%stile_x=%d tile_y=%d' % (prefix, params['tile_x'], params['tile_y'])
def _make_capture_request(self, params, state):
description = self._get_description(params)
if description in self._processed: return None
def config_callback(s):
s.viewer_size = (params['tile_width'], params['tile_height'])
self.config_callback(s)
def response_callback(screenshot):
self._add_image(params, screenshot)
self._maybe_save_state()
return CaptureScreenshotRequest(state=state,
description=self._get_description(params),
config_callback=config_callback,
response_callback=response_callback,
include_depth=self.include_depth)
def _get_capture_screenshot_request_iter(self, state_iter):
for params, state in state_iter:
request = self._make_capture_request(params, state)
if request is not None: yield request
def capture(self, viewers, state_iter, refresh_browser_timeout: int, save_depth: bool, total_requests: int):
capture_screenshots_in_parallel(
viewers=viewers,
request_iter=self._get_capture_screenshot_request_iter(state_iter),
refresh_browser_timeout=refresh_browser_timeout,
num_to_prefetch=self.num_to_prefetch,
total_requests=total_requests)
if not self._save_state_in_progress.is_set():
print('Waiting for previous save state to complete')
self._save_state_in_progress.wait()
if save_depth:
self._save_state()
else:
self._save_image()
if os.path.exists(self.state_file):
os.remove(self.state_file)
def capture_image(viewers, args, state):
def config_callback(s):
s.scale_bar_options.scale_factor = args.scale_bar_scale
segment_shard_size = args.segment_shard_size
tile_parameters = dict(
shape=(args.width, args.height),
tile_shape=(args.tile_width, args.tile_height),
)
if segment_shard_size is not None and _should_shard_segments(state, segment_shard_size):
gen = ShardedTileGenerator(state=state,
segment_shard_size=segment_shard_size,
reverse_bits=args.sort_segments_by_reversed_bits,
**tile_parameters)
num_states = gen.num_tiles
state_iter = gen.get_states()
include_depth = True
else:
gen = TileGenerator(**tile_parameters)
num_states = gen.num_tiles
state_iter = gen.get_tile_states(state)
include_depth = False
capturer = MultiCapturer(
shape=tile_parameters['shape'],
include_depth=include_depth,
output=args.output,
config_callback=config_callback,
num_to_prefetch=args.prefetch,
checkpoint_interval=args.checkpoint_interval,
)
num_output_shards = args.num_output_shards
tiles_per_output_shard = args.tiles_per_output_shard
output_shard = args.output_shard
if (output_shard is None) != (num_output_shards is None and tiles_per_output_shard is None):
raise ValueError(
'--output-shard must be specified in combination with --num-output-shards or --tiles-per-output-shard'
)
if output_shard is not None:
if num_output_shards is not None:
if num_output_shards < 1:
raise ValueError('Invalid --num-output-shards: %d' % (num_output_shards, ))
states_per_shard = -(-num_states // num_output_shards)
else:
if tiles_per_output_shard < 1:
raise ValueError('Invalid --tiles-per-output-shard: %d' %
(tiles_per_output_shard, ))
num_output_shards = -(-num_states // tiles_per_output_shard)
states_per_shard = tiles_per_output_shard
if output_shard < 0 or output_shard >= num_output_shards:
raise ValueError('Invalid --output-shard: %d' % (output_shard, ))
print('Total states: %d, Number of output shards: %d' % (num_states, num_output_shards))
state_iter = itertools.islice(state_iter, states_per_shard * output_shard,
states_per_shard * (output_shard + 1))
else:
states_per_shard = num_states
capturer.capture(
viewers=viewers,
state_iter=state_iter,
refresh_browser_timeout=args.refresh_browser_timeout,
save_depth=output_shard is not None,
total_requests=states_per_shard,
)
def define_state_modification_args(ap: argparse.ArgumentParser):
ap.add_argument('--hide-axis-lines',
dest='show_axis_lines',
action='store_false',
help='Override showAxisLines setting in state.')
ap.add_argument('--hide-default-annotations',
action='store_false',
dest='show_default_annotations',
help='Override showDefaultAnnotations setting in state.')
ap.add_argument('--projection-scale-multiplier',
type=float,
help='Multiply projection view scale by specified factor.')
ap.add_argument('--system-memory-limit',
type=int,
default=3 * 1024 * 1024 * 1024,
help='System memory limit')
ap.add_argument('--gpu-memory-limit',
type=int,
default=3 * 1024 * 1024 * 1024,
help='GPU memory limit')
ap.add_argument('--concurrent-downloads', type=int, default=32, help='Concurrent downloads')
ap.add_argument('--layout', type=str, help='Override layout setting in state.')
ap.add_argument('--cross-section-background-color',
type=str,
help='Background color for cross sections.')
ap.add_argument('--scale-bar-scale', type=float, help='Scale factor for scale bar', default=1)
def apply_state_modifications(state: neuroglancer.ViewerState, args: argparse.Namespace):
state.selected_layer.visible = False
state.statistics.visible = False
if args.layout is not None:
state.layout = args.layout
if args.show_axis_lines is not None:
state.show_axis_lines = args.show_axis_lines
if args.show_default_annotations is not None:
state.show_default_annotations = args.show_default_annotations
if args.projection_scale_multiplier is not None:
state.projection_scale *= args.projection_scale_multiplier
if args.cross_section_background_color is not None:
state.cross_section_background_color = args.cross_section_background_color
state.gpu_memory_limit = args.gpu_memory_limit
state.system_memory_limit = args.system_memory_limit
state.concurrent_downloads = args.concurrent_downloads
def define_viewer_args(ap: argparse.ArgumentParser):
ap.add_argument('--browser', choices=['chrome', 'firefox'], default='chrome')
ap.add_argument('--no-webdriver',
action='store_true',
help='Do not open browser automatically via webdriver.')
ap.add_argument('--no-headless',
dest='headless',
action='store_false',
help='Use non-headless webdriver.')
ap.add_argument('--docker-chromedriver',
action='store_true',
help='Run Chromedriver with options suitable for running inside docker')
ap.add_argument('--debug-chromedriver',
action='store_true',
help='Enable debug logging in Chromedriver')
ap.add_argument('--jobs',
'-j',
type=int,
default=1,
help='Number of browsers to use concurrently. '
'This may improve performance at the cost of greater memory usage. '
'On a 64GiB 16 hyperthread machine, --jobs=6 works well.')
def define_size_args(ap: argparse.ArgumentParser):
ap.add_argument('--width', type=int, default=3840, help='Width in pixels of image.')
ap.add_argument('--height', type=int, default=2160, help='Height in pixels of image.')
def define_tile_args(ap: argparse.ArgumentParser):
ap.add_argument(
'--tile-width',
type=int,
default=4096,
help=
'Width in pixels of single tile. If total width is larger, the screenshot will be captured as multiple tiles.'
)
ap.add_argument(
'--tile-height',
type=int,
default=4096,
help=
'Height in pixels of single tile. If total height is larger, the screenshot will be captured as multiple tiles.'
)
ap.add_argument('--segment-shard-size',
type=int,
help='Maximum number of segments to render simultaneously. '
'If the number of selected segments exceeds this number, '
'multiple passes will be used (transparency not supported).')
ap.add_argument(
'--sort-segments-by-reversed-bits',
action='store_true',
help=
'When --segment-shard-size is also specified, normally segment ids are ordered numerically before being partitioned into shards. If segment ids are spatially correlated, then this can lead to slower and more memory-intensive rendering. If --sort-segments-by-reversed-bits is specified, segment ids are instead ordered by their bit reversed values, which may avoid the spatial correlation.'
)
def define_capture_args(ap: argparse.ArgumentParser):
ap.add_argument('--prefetch', type=int, default=1, help='Number of states to prefetch.')
ap.add_argument(
'--refresh-browser-timeout',
type=int,
default=60,
help=
'Number of seconds without receiving statistics while capturing a screenshot before browser is considered unresponsive.'
)
@contextlib.contextmanager
def get_viewers(args: argparse.Namespace):
if args.no_webdriver:
viewers = [neuroglancer.Viewer() for _ in range(args.jobs)]
print('Open the following URLs to begin rendering')
for viewer in viewers:
print(viewer)
def refresh_browser_callback():
print('Browser unresponsive, consider reloading')
yield [(viewer, refresh_browser_callback) for viewer in viewers]
else:
def _make_webdriver():
webdriver = neuroglancer.webdriver.Webdriver(
headless=args.headless,
docker=args.docker_chromedriver,
debug=args.debug_chromedriver,
browser=args.browser,
)
def refresh_browser_callback():
print('Browser unresponsive, reloading')
webdriver.reload_browser()
return webdriver, refresh_browser_callback
webdrivers = [_make_webdriver() for _ in range(args.jobs)]
try:
yield [(webdriver.viewer, refresh_browser_callback)
for webdriver, refresh_browser_callback in webdrivers]
finally:
for webdriver, _ in webdrivers:
try:
webdriver.__exit__()
except:
pass
def run(args: argparse.Namespace):
neuroglancer.cli.handle_server_arguments(args)
state = args.state
apply_state_modifications(state, args)
with get_viewers(args) as viewers:
capture_image(viewers, args, state)
def main(args=None):
ap = argparse.ArgumentParser()
neuroglancer.cli.add_server_arguments(ap)
neuroglancer.cli.add_state_arguments(ap, required=True)
ap.add_argument('output', help='Output path of screenshot file in PNG format.')
ap.add_argument('--output-shard', type=int, help='Output shard to write.')
output_shard_group = ap.add_mutually_exclusive_group(required=False)
output_shard_group.add_argument('--num-output-shards',
type=int,
help='Number of output shards.')
output_shard_group.add_argument('--tiles-per-output-shard',
type=int,
help='Number of tiles per output shard.')
ap.add_argument('--checkpoint-interval',
type=float,
default=60,
help='Interval in seconds at which to save checkpoints.')
define_state_modification_args(ap)
define_viewer_args(ap)
define_size_args(ap)
define_tile_args(ap)
define_capture_args(ap)
run(ap.parse_args(args))
if __name__ == '__main__':
main()
| 41.707454 | 399 | 0.634956 |
import argparse
import collections
import contextlib
import copy
import datetime
import itertools
import numbers
import os
import threading
import time
from typing import NamedTuple, Tuple, Callable, Iterator, List, Optional
import PIL
import numpy as np
import neuroglancer
import neuroglancer.cli
import neuroglancer.webdriver
def _get_total_segments(state):
num_segments = 0
for layer in state.layers:
if not isinstance(layer.layer, neuroglancer.SegmentationLayer):
continue
num_segments += len(layer.segments)
return num_segments
def _should_shard_segments(state, segment_shard_size):
return _get_total_segments(state) > segment_shard_size
def _calculate_num_shards(state, segment_shard_size):
total_segments = _get_total_segments(state)
return -(-total_segments // segment_shard_size)
def _get_sharded_states(state, segment_shard_size, reverse_bits):
if reverse_bits:
sort_key = lambda x: int('{:064b}'.format(x)[::-1], 2)
else:
sort_key = None
num_shards = _calculate_num_shards(state, segment_shard_size)
for shard_i in range(num_shards):
new_state = copy.deepcopy(state)
cum_retained = 0
cum_skipped = segment_shard_size * shard_i
for i, layer in enumerate(new_state.layers):
if not isinstance(layer.layer, neuroglancer.SegmentationLayer):
continue
segments = sorted(layer.segments, key=sort_key)
num_to_skip = min(cum_skipped, len(segments))
segments = segments[num_to_skip:]
cum_skipped += num_to_skip
num_to_retain = min(segment_shard_size - cum_retained, len(segments))
cum_retained += num_to_retain
layer.segments = set(segments[:num_to_retain])
yield new_state
class TileGenerator:
def __init__(self, shape, tile_shape):
self.tile_shape = tuple(tile_shape)
self.shape = tuple(shape)
self.tile_grid_shape = tuple(-(-self.shape[i] // self.tile_shape[i]) for i in range(2))
self.tile_shape = tuple(-(-self.shape[i] // self.tile_grid_shape[i]) for i in range(2))
self.num_tiles = self.tile_grid_shape[0] * self.tile_grid_shape[1]
def get_tile_states(self, state):
for tile_y in range(self.tile_grid_shape[1]):
for tile_x in range(self.tile_grid_shape[0]):
x_offset = tile_x * self.tile_shape[0]
y_offset = tile_y * self.tile_shape[1]
tile_width = min(self.tile_shape[0], self.shape[0] - x_offset)
tile_height = min(self.tile_shape[1], self.shape[1] - y_offset)
new_state = copy.deepcopy(state)
new_state.partial_viewport = [
x_offset / self.shape[0], y_offset / self.shape[1], tile_width / self.shape[0],
tile_height / self.shape[1]
]
params = {
'tile_x': tile_x,
'tile_y': tile_y,
'x_offset': x_offset,
'y_offset': y_offset,
'tile_width': tile_width,
'tile_height': tile_height,
}
yield params, new_state
class ShardedTileGenerator(TileGenerator):
def __init__(self, state, segment_shard_size, reverse_bits, **kwargs):
super(ShardedTileGenerator, self).__init__(**kwargs)
self.state = state
self.reverse_bits = reverse_bits
self.total_segments = _get_total_segments(self.state)
self.segment_shard_size = segment_shard_size
self.num_shards = _calculate_num_shards(self.state, self.segment_shard_size)
self.num_tiles *= self.num_shards
def get_states(self):
for shard_i, state in enumerate(
_get_sharded_states(self.state,
self.segment_shard_size,
reverse_bits=self.reverse_bits)):
for params, state in self.get_tile_states(state):
params['segment_shard'] = shard_i
yield params, state
class CaptureScreenshotRequest(NamedTuple):
state: neuroglancer.ViewerState
description: str
config_callback: Callable[[neuroglancer.viewer_config_state.ConfigState], None]
response_callback: neuroglancer.viewer_config_state.ScreenshotReply
include_depth: bool = False
def buffered_iterator(base_iter, lock, buffer_size):
while True:
with lock:
buffered_items = list(itertools.islice(base_iter, buffer_size))
if not buffered_items: break
for item in buffered_items:
yield item
def capture_screenshots(viewer: neuroglancer.Viewer,
request_iter: Iterator[CaptureScreenshotRequest],
refresh_browser_callback: Callable[[], None],
refresh_browser_timeout: int,
num_to_prefetch: int = 1) -> None:
prefetch_buffer = list(itertools.islice(request_iter, num_to_prefetch + 1))
while prefetch_buffer:
with viewer.config_state.txn() as s:
s.show_ui_controls = False
s.show_panel_borders = False
del s.prefetch[:]
for i, request in enumerate(prefetch_buffer[1:]):
s.prefetch.append(
neuroglancer.PrefetchState(state=request.state, priority=num_to_prefetch - i))
request = prefetch_buffer[0]
request.config_callback(s)
viewer.set_state(request.state)
print('%s [%s] Requesting screenshot' % (
datetime.datetime.now().strftime('%Y-%m-%dT%H:%M%S.%f'),
request.description,
))
last_statistics_time = time.time()
def statistics_callback(statistics):
nonlocal last_statistics_time
last_statistics_time = time.time()
total = statistics.total
print(
'%s [%s] Screenshot in progress: %6d/%6d chunks loaded (%10d bytes), %3d downloading'
% (
datetime.datetime.now().strftime('%Y-%m-%dT%H:%M%S.%f'),
request.description,
total.visible_chunks_gpu_memory,
total.visible_chunks_total,
total.visible_gpu_memory,
total.visible_chunks_downloading,
))
event = threading.Event()
screenshot = None
def result_callback(s):
nonlocal screenshot
screenshot = s.screenshot
event.set()
viewer.async_screenshot(
result_callback,
include_depth=request.include_depth,
statistics_callback=statistics_callback,
)
def get_timeout():
return max(0, last_statistics_time + refresh_browser_timeout - time.time())
while True:
if event.wait(get_timeout()):
break
if get_timeout() > 0:
continue
last_statistics_time = time.time()
refresh_browser_callback()
request.response_callback(screenshot)
del prefetch_buffer[0]
next_request = next(request_iter, None)
if next_request is not None:
prefetch_buffer.append(next_request)
def capture_screenshots_in_parallel(viewers: List[Tuple[neuroglancer.Viewer, Callable[[], None]]],
request_iter: Iterator[CaptureScreenshotRequest],
refresh_browser_timeout: numbers.Number, num_to_prefetch: int,
total_requests: Optional[int] = None,
buffer_size: Optional[int] = None):
if buffer_size is None:
if total_requests is None:
copy_of_requests = list(request_iter)
total_requests = len(copy_of_requests)
request_iter = iter(copy_of_requests)
buffer_size = max(1, total_requests // (len(viewers) * 4))
request_iter = iter(request_iter)
threads = []
buffer_lock = threading.Lock()
for viewer, refresh_browser_callback in viewers:
def capture_func(viewer, refresh_browser_callback):
viewer_request_iter = buffered_iterator(base_iter=request_iter,
lock=buffer_lock,
buffer_size=buffer_size)
capture_screenshots(
viewer=viewer,
request_iter=viewer_request_iter,
num_to_prefetch=num_to_prefetch,
refresh_browser_timeout=refresh_browser_timeout,
refresh_browser_callback=refresh_browser_callback,
)
t = threading.Thread(target=capture_func, args=(viewer, refresh_browser_callback))
t.start()
threads.append(t)
for t in threads:
t.join()
class MultiCapturer:
def __init__(self,
shape,
include_depth,
output,
config_callback,
num_to_prefetch,
checkpoint_interval=60):
self.include_depth = include_depth
self.checkpoint_interval = checkpoint_interval
self.config_callback = config_callback
self.num_to_prefetch = num_to_prefetch
self.output = output
self._processed = set()
self.state_file = output + '.npz'
self.temp_state_file = self.state_file + '.tmp'
self.image_array = np.zeros((shape[1], shape[0], 4), dtype=np.uint8)
if self.include_depth:
self.depth_array = np.zeros((shape[1], shape[0]), dtype=np.float32)
self._load_state()
self._add_image_lock = threading.Lock()
self._last_save_time = time.time()
self._save_state_in_progress = threading.Event()
self._save_state_in_progress.set()
self._num_states_processed = 0
self._start_time = time.time()
def _load_state(self):
if not os.path.exists(self.state_file):
return
with np.load(self.state_file, allow_pickle=True) as f:
if self.include_depth:
self.depth_array = f['depth']
self.image_array = f['image']
self._processed = set(f['processed'].ravel()[0])
def _save_state(self, save_image=False):
with self._add_image_lock:
processed = set(self._processed)
with open(self.temp_state_file, 'wb') as f:
save_arrays = {
'image': self.image_array,
'processed': processed,
}
if self.include_depth:
save_arrays['depth'] = self.depth_array
np.savez_compressed(f, **save_arrays)
os.replace(self.temp_state_file, self.state_file)
if save_image:
self._save_image()
def _save_state_async(self, save_image=False):
print('Starting checkpointing')
def func():
try:
self._save_state()
print('Done checkpointing')
finally:
self._save_state_in_progress.set()
threading.Thread(target=func, daemon=True).start()
def _save_image(self):
im = PIL.Image.fromarray(self.image_array)
im.save(self.output)
def _add_image(self, params, screenshot):
with self._add_image_lock:
tile_image = screenshot.image_pixels
tile_selector = np.s_[params['y_offset']:params['y_offset'] + params['tile_height'],
params['x_offset']:params['x_offset'] + params['tile_width']]
if self.include_depth:
tile_depth = screenshot.depth_array
depth_array_part = self.depth_array[tile_selector]
mask = np.logical_and(np.logical_or(tile_depth != 0, depth_array_part == 0),
tile_depth >= depth_array_part)
depth_array_part[mask] = tile_depth[mask]
else:
mask = Ellipsis
self.image_array[tile_selector][mask] = tile_image[mask]
self._processed.add(self._get_description(params))
self._num_states_processed += 1
elapsed = time.time() - self._start_time
print('%4d tiles rendered in %5d seconds: %.1f seconds/tile' %
(self._num_states_processed, elapsed, elapsed / self._num_states_processed))
def _maybe_save_state(self):
if not self._save_state_in_progress.is_set(): return
with self._add_image_lock:
if self._last_save_time + self.checkpoint_interval < time.time():
self._last_save_time = time.time()
self._save_state_in_progress.clear()
self._save_state_async(save_image=False)
def _get_description(self, params):
segment_shard = params.get('segment_shard')
if segment_shard is not None:
prefix = 'segment_shard=%d ' % (segment_shard, )
else:
prefix = ''
return '%stile_x=%d tile_y=%d' % (prefix, params['tile_x'], params['tile_y'])
def _make_capture_request(self, params, state):
description = self._get_description(params)
if description in self._processed: return None
def config_callback(s):
s.viewer_size = (params['tile_width'], params['tile_height'])
self.config_callback(s)
def response_callback(screenshot):
self._add_image(params, screenshot)
self._maybe_save_state()
return CaptureScreenshotRequest(state=state,
description=self._get_description(params),
config_callback=config_callback,
response_callback=response_callback,
include_depth=self.include_depth)
def _get_capture_screenshot_request_iter(self, state_iter):
for params, state in state_iter:
request = self._make_capture_request(params, state)
if request is not None: yield request
def capture(self, viewers, state_iter, refresh_browser_timeout: int, save_depth: bool, total_requests: int):
capture_screenshots_in_parallel(
viewers=viewers,
request_iter=self._get_capture_screenshot_request_iter(state_iter),
refresh_browser_timeout=refresh_browser_timeout,
num_to_prefetch=self.num_to_prefetch,
total_requests=total_requests)
if not self._save_state_in_progress.is_set():
print('Waiting for previous save state to complete')
self._save_state_in_progress.wait()
if save_depth:
self._save_state()
else:
self._save_image()
if os.path.exists(self.state_file):
os.remove(self.state_file)
def capture_image(viewers, args, state):
def config_callback(s):
s.scale_bar_options.scale_factor = args.scale_bar_scale
segment_shard_size = args.segment_shard_size
tile_parameters = dict(
shape=(args.width, args.height),
tile_shape=(args.tile_width, args.tile_height),
)
if segment_shard_size is not None and _should_shard_segments(state, segment_shard_size):
gen = ShardedTileGenerator(state=state,
segment_shard_size=segment_shard_size,
reverse_bits=args.sort_segments_by_reversed_bits,
**tile_parameters)
num_states = gen.num_tiles
state_iter = gen.get_states()
include_depth = True
else:
gen = TileGenerator(**tile_parameters)
num_states = gen.num_tiles
state_iter = gen.get_tile_states(state)
include_depth = False
capturer = MultiCapturer(
shape=tile_parameters['shape'],
include_depth=include_depth,
output=args.output,
config_callback=config_callback,
num_to_prefetch=args.prefetch,
checkpoint_interval=args.checkpoint_interval,
)
num_output_shards = args.num_output_shards
tiles_per_output_shard = args.tiles_per_output_shard
output_shard = args.output_shard
if (output_shard is None) != (num_output_shards is None and tiles_per_output_shard is None):
raise ValueError(
'--output-shard must be specified in combination with --num-output-shards or --tiles-per-output-shard'
)
if output_shard is not None:
if num_output_shards is not None:
if num_output_shards < 1:
raise ValueError('Invalid --num-output-shards: %d' % (num_output_shards, ))
states_per_shard = -(-num_states // num_output_shards)
else:
if tiles_per_output_shard < 1:
raise ValueError('Invalid --tiles-per-output-shard: %d' %
(tiles_per_output_shard, ))
num_output_shards = -(-num_states // tiles_per_output_shard)
states_per_shard = tiles_per_output_shard
if output_shard < 0 or output_shard >= num_output_shards:
raise ValueError('Invalid --output-shard: %d' % (output_shard, ))
print('Total states: %d, Number of output shards: %d' % (num_states, num_output_shards))
state_iter = itertools.islice(state_iter, states_per_shard * output_shard,
states_per_shard * (output_shard + 1))
else:
states_per_shard = num_states
capturer.capture(
viewers=viewers,
state_iter=state_iter,
refresh_browser_timeout=args.refresh_browser_timeout,
save_depth=output_shard is not None,
total_requests=states_per_shard,
)
def define_state_modification_args(ap: argparse.ArgumentParser):
ap.add_argument('--hide-axis-lines',
dest='show_axis_lines',
action='store_false',
help='Override showAxisLines setting in state.')
ap.add_argument('--hide-default-annotations',
action='store_false',
dest='show_default_annotations',
help='Override showDefaultAnnotations setting in state.')
ap.add_argument('--projection-scale-multiplier',
type=float,
help='Multiply projection view scale by specified factor.')
ap.add_argument('--system-memory-limit',
type=int,
default=3 * 1024 * 1024 * 1024,
help='System memory limit')
ap.add_argument('--gpu-memory-limit',
type=int,
default=3 * 1024 * 1024 * 1024,
help='GPU memory limit')
ap.add_argument('--concurrent-downloads', type=int, default=32, help='Concurrent downloads')
ap.add_argument('--layout', type=str, help='Override layout setting in state.')
ap.add_argument('--cross-section-background-color',
type=str,
help='Background color for cross sections.')
ap.add_argument('--scale-bar-scale', type=float, help='Scale factor for scale bar', default=1)
def apply_state_modifications(state: neuroglancer.ViewerState, args: argparse.Namespace):
state.selected_layer.visible = False
state.statistics.visible = False
if args.layout is not None:
state.layout = args.layout
if args.show_axis_lines is not None:
state.show_axis_lines = args.show_axis_lines
if args.show_default_annotations is not None:
state.show_default_annotations = args.show_default_annotations
if args.projection_scale_multiplier is not None:
state.projection_scale *= args.projection_scale_multiplier
if args.cross_section_background_color is not None:
state.cross_section_background_color = args.cross_section_background_color
state.gpu_memory_limit = args.gpu_memory_limit
state.system_memory_limit = args.system_memory_limit
state.concurrent_downloads = args.concurrent_downloads
def define_viewer_args(ap: argparse.ArgumentParser):
ap.add_argument('--browser', choices=['chrome', 'firefox'], default='chrome')
ap.add_argument('--no-webdriver',
action='store_true',
help='Do not open browser automatically via webdriver.')
ap.add_argument('--no-headless',
dest='headless',
action='store_false',
help='Use non-headless webdriver.')
ap.add_argument('--docker-chromedriver',
action='store_true',
help='Run Chromedriver with options suitable for running inside docker')
ap.add_argument('--debug-chromedriver',
action='store_true',
help='Enable debug logging in Chromedriver')
ap.add_argument('--jobs',
'-j',
type=int,
default=1,
help='Number of browsers to use concurrently. '
'This may improve performance at the cost of greater memory usage. '
'On a 64GiB 16 hyperthread machine, --jobs=6 works well.')
def define_size_args(ap: argparse.ArgumentParser):
ap.add_argument('--width', type=int, default=3840, help='Width in pixels of image.')
ap.add_argument('--height', type=int, default=2160, help='Height in pixels of image.')
def define_tile_args(ap: argparse.ArgumentParser):
ap.add_argument(
'--tile-width',
type=int,
default=4096,
help=
'Width in pixels of single tile. If total width is larger, the screenshot will be captured as multiple tiles.'
)
ap.add_argument(
'--tile-height',
type=int,
default=4096,
help=
'Height in pixels of single tile. If total height is larger, the screenshot will be captured as multiple tiles.'
)
ap.add_argument('--segment-shard-size',
type=int,
help='Maximum number of segments to render simultaneously. '
'If the number of selected segments exceeds this number, '
'multiple passes will be used (transparency not supported).')
ap.add_argument(
'--sort-segments-by-reversed-bits',
action='store_true',
help=
'When --segment-shard-size is also specified, normally segment ids are ordered numerically before being partitioned into shards. If segment ids are spatially correlated, then this can lead to slower and more memory-intensive rendering. If --sort-segments-by-reversed-bits is specified, segment ids are instead ordered by their bit reversed values, which may avoid the spatial correlation.'
)
def define_capture_args(ap: argparse.ArgumentParser):
ap.add_argument('--prefetch', type=int, default=1, help='Number of states to prefetch.')
ap.add_argument(
'--refresh-browser-timeout',
type=int,
default=60,
help=
'Number of seconds without receiving statistics while capturing a screenshot before browser is considered unresponsive.'
)
@contextlib.contextmanager
def get_viewers(args: argparse.Namespace):
if args.no_webdriver:
viewers = [neuroglancer.Viewer() for _ in range(args.jobs)]
print('Open the following URLs to begin rendering')
for viewer in viewers:
print(viewer)
def refresh_browser_callback():
print('Browser unresponsive, consider reloading')
yield [(viewer, refresh_browser_callback) for viewer in viewers]
else:
def _make_webdriver():
webdriver = neuroglancer.webdriver.Webdriver(
headless=args.headless,
docker=args.docker_chromedriver,
debug=args.debug_chromedriver,
browser=args.browser,
)
def refresh_browser_callback():
print('Browser unresponsive, reloading')
webdriver.reload_browser()
return webdriver, refresh_browser_callback
webdrivers = [_make_webdriver() for _ in range(args.jobs)]
try:
yield [(webdriver.viewer, refresh_browser_callback)
for webdriver, refresh_browser_callback in webdrivers]
finally:
for webdriver, _ in webdrivers:
try:
webdriver.__exit__()
except:
pass
def run(args: argparse.Namespace):
neuroglancer.cli.handle_server_arguments(args)
state = args.state
apply_state_modifications(state, args)
with get_viewers(args) as viewers:
capture_image(viewers, args, state)
def main(args=None):
ap = argparse.ArgumentParser()
neuroglancer.cli.add_server_arguments(ap)
neuroglancer.cli.add_state_arguments(ap, required=True)
ap.add_argument('output', help='Output path of screenshot file in PNG format.')
ap.add_argument('--output-shard', type=int, help='Output shard to write.')
output_shard_group = ap.add_mutually_exclusive_group(required=False)
output_shard_group.add_argument('--num-output-shards',
type=int,
help='Number of output shards.')
output_shard_group.add_argument('--tiles-per-output-shard',
type=int,
help='Number of tiles per output shard.')
ap.add_argument('--checkpoint-interval',
type=float,
default=60,
help='Interval in seconds at which to save checkpoints.')
define_state_modification_args(ap)
define_viewer_args(ap)
define_size_args(ap)
define_tile_args(ap)
define_capture_args(ap)
run(ap.parse_args(args))
if __name__ == '__main__':
main()
| true | true |
1c3fd089676e66f279943ebbb8aa269ae5ba3497 | 1,343 | py | Python | demo/dcgan_v3_generate.py | hircumg/keras-text-to-image | 365cf61075b04e9a98f69d471f0efd8b7e0adb6f | [
"MIT"
] | null | null | null | demo/dcgan_v3_generate.py | hircumg/keras-text-to-image | 365cf61075b04e9a98f69d471f0efd8b7e0adb6f | [
"MIT"
] | null | null | null | demo/dcgan_v3_generate.py | hircumg/keras-text-to-image | 365cf61075b04e9a98f69d471f0efd8b7e0adb6f | [
"MIT"
] | null | null | null | import os
import sys
import numpy as np
from random import shuffle
def main():
seed = 42
np.random.seed(seed)
current_dir = os.path.dirname(__file__)
sys.path.append(os.path.join(current_dir, '..'))
current_dir = current_dir if current_dir is not '' else '.'
img_dir_path = current_dir + '/data/paintings/img'
txt_dir_path = current_dir + '/data/paintings/txt'
model_dir_path = current_dir + '/models'
img_width = 32
img_height = 32
from keras_text_to_image.library.dcgan_v3 import DCGanV3
from keras_text_to_image.library.utility.image_utils import img_from_normalized_img
from keras_text_to_image.library.utility.img_cap_loader import load_normalized_img_and_its_text
image_label_pairs = load_normalized_img_and_its_text(img_dir_path, txt_dir_path, img_width=img_width, img_height=img_height)
shuffle(image_label_pairs)
gan = DCGanV3()
gan.load_model(model_dir_path)
text = ["Impressionism, French",
"Baroque,Spanish",
"Symbolism,French"]
print("=======LOADED=================")
for i in range(len(text)):
generated_image = gan.generate_image_from_text(text[i])
generated_image.save(current_dir + '/data/outputs/' + DCGanV3.model_name + '-generated-' + str(i) + '.png')
if __name__ == '__main__':
main()
| 29.844444 | 128 | 0.699181 | import os
import sys
import numpy as np
from random import shuffle
def main():
seed = 42
np.random.seed(seed)
current_dir = os.path.dirname(__file__)
sys.path.append(os.path.join(current_dir, '..'))
current_dir = current_dir if current_dir is not '' else '.'
img_dir_path = current_dir + '/data/paintings/img'
txt_dir_path = current_dir + '/data/paintings/txt'
model_dir_path = current_dir + '/models'
img_width = 32
img_height = 32
from keras_text_to_image.library.dcgan_v3 import DCGanV3
from keras_text_to_image.library.utility.image_utils import img_from_normalized_img
from keras_text_to_image.library.utility.img_cap_loader import load_normalized_img_and_its_text
image_label_pairs = load_normalized_img_and_its_text(img_dir_path, txt_dir_path, img_width=img_width, img_height=img_height)
shuffle(image_label_pairs)
gan = DCGanV3()
gan.load_model(model_dir_path)
text = ["Impressionism, French",
"Baroque,Spanish",
"Symbolism,French"]
print("=======LOADED=================")
for i in range(len(text)):
generated_image = gan.generate_image_from_text(text[i])
generated_image.save(current_dir + '/data/outputs/' + DCGanV3.model_name + '-generated-' + str(i) + '.png')
if __name__ == '__main__':
main()
| true | true |
1c3fd17fd284852ba7aeedaa87ca07e74fdd23e5 | 32,578 | py | Python | python/paddle/fluid/tests/unittests/test_optimizer.py | frankwhzhang/Paddle | 131b1dc3240e53ea295cc49323bb2a7e7dcc717f | [
"Apache-2.0"
] | 1 | 2020-11-03T04:57:40.000Z | 2020-11-03T04:57:40.000Z | python/paddle/fluid/tests/unittests/test_optimizer.py | frankwhzhang/Paddle | 131b1dc3240e53ea295cc49323bb2a7e7dcc717f | [
"Apache-2.0"
] | null | null | null | python/paddle/fluid/tests/unittests/test_optimizer.py | frankwhzhang/Paddle | 131b1dc3240e53ea295cc49323bb2a7e7dcc717f | [
"Apache-2.0"
] | 4 | 2019-09-30T02:15:34.000Z | 2019-09-30T02:41:30.000Z | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# 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 print_function
import unittest
import paddle.fluid.framework as framework
import paddle.fluid.optimizer as optimizer
import paddle.compat as cpt
from paddle.fluid.backward import append_backward
class TestOptimizer(unittest.TestCase):
def test_sgd_optimizer(self):
def check_sgd_optimizer(optimizer_attr):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr=optimizer_attr)
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
sgd_optimizer = optimizer.SGDOptimizer(learning_rate=0.01)
opts, _ = sgd_optimizer.minimize(mean_out, init_program)
return opts
opts = check_sgd_optimizer({'learning_rate': 1.1})
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "sgd"])
opts = check_sgd_optimizer({'learning_rate': 1.0})
self.assertEqual(len(opts), 1)
self.assertEqual([op.type for op in opts], ["sgd"])
class TestOptimizerBackwardApplygrad(unittest.TestCase):
def test_sgd_optimizer(self):
def check_sgd_optimizer(optimizer_attr):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr=optimizer_attr)
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
sgd_optimizer = optimizer.SGDOptimizer(learning_rate=0.01)
with framework.program_guard(program, init_program):
p_g = sgd_optimizer.backward(mean_out)
opts = sgd_optimizer.apply_gradients(p_g)
return opts
opts = check_sgd_optimizer({'learning_rate': 1.1})
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "sgd"])
opts = check_sgd_optimizer({'learning_rate': 1.0})
self.assertEqual(len(opts), 1)
self.assertEqual([op.type for op in opts], ["sgd"])
class TestMomentumOptimizer(unittest.TestCase):
class MockMomentum(optimizer.MomentumOptimizer):
def get_accumulators(self):
return self._accumulators
def get_velocity_str(self):
return self._velocity_acc_str
def test_vanilla_momentum_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
learning_rate = 0.01
momentum_optimizer = self.MockMomentum(
learning_rate=learning_rate, momentum=0.2)
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(momentum_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = momentum_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 2)
sgd_op = opts[-1]
self.assertEqual([op.type for op in opts], ["scale", "momentum"])
self.assertFalse(sgd_op.attr('use_nesterov'))
# Check accumulators
accumulators = momentum_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 1)
self.assertTrue(momentum_optimizer.get_velocity_str() in accumulators)
velocity_acc = accumulators[momentum_optimizer.get_velocity_str()]
self.assertEqual(len(velocity_acc), 1)
self.assertTrue(mul_x.name in velocity_acc)
# Check init_program
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 2)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
self.assertEqual(init_ops[1].type, "fill_constant")
self.assertAlmostEqual(init_ops[1].attr('value'), 0.0)
def test_nesterov_momentum_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
momentum_optimizer = self.MockMomentum(
learning_rate=learning_rate, momentum=0.2, use_nesterov=True)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(momentum_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = momentum_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 2)
sgd_op = opts[-1]
self.assertEqual([op.type for op in opts], ["scale", "momentum"])
self.assertTrue(sgd_op.attr('use_nesterov'))
# Check accumulators
accumulators = momentum_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 1)
self.assertTrue(momentum_optimizer.get_velocity_str() in accumulators)
velocity_acc = accumulators[momentum_optimizer.get_velocity_str()]
self.assertEqual(len(velocity_acc), 1)
self.assertTrue(mul_x.name in velocity_acc)
# Check init_program
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 2)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
self.assertEqual(init_ops[1].type, "fill_constant")
self.assertAlmostEqual(init_ops[1].attr('value'), 0.0)
class TestAdagradOptimizer(unittest.TestCase):
class MockAdagrad(optimizer.AdagradOptimizer):
def get_accumulators(self):
return self._accumulators
def get_moment_str(self):
return self._moment_acc_str
def test_adagrad_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
adagrad_optimizer = self.MockAdagrad(
learning_rate=learning_rate, epsilon=1.0e-6)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(adagrad_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = adagrad_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "adagrad"])
# Check accumulators
accumulators = adagrad_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 1)
self.assertTrue(adagrad_optimizer.get_moment_str() in accumulators)
moment_acc = accumulators[adagrad_optimizer.get_moment_str()]
self.assertEqual(len(moment_acc), 1)
self.assertTrue(mul_x.name in moment_acc)
# Check init_program
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 3)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
self.assertEqual(init_ops[1].type, "fill_constant")
self.assertAlmostEqual(init_ops[1].attr('value'), 0.0)
class TestAdamOptimizer(unittest.TestCase):
class MockAdam(optimizer.AdamOptimizer):
def get_accumulators(self):
return self._accumulators
def get_moment1_str(self):
return self._moment1_acc_str
def get_moment2_str(self):
return self._moment2_acc_str
def test_adam_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
adam_optimizer = self.MockAdam(
learning_rate=learning_rate, beta1=0.9, beta2=0.999)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(adam_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = adam_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 4)
self.assertEqual([op.type for op in opts],
["scale", "adam", "scale", "scale"])
# Check accumulators
accumulators = adam_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 4)
self.assertTrue(adam_optimizer.get_moment1_str() in accumulators)
self.assertTrue(adam_optimizer.get_moment2_str() in accumulators)
moment1_acc = accumulators[adam_optimizer.get_moment1_str()]
moment2_acc = accumulators[adam_optimizer.get_moment2_str()]
self.assertEqual(len(moment1_acc), 1)
self.assertEqual(len(moment2_acc), 1)
self.assertTrue(mul_x.name in moment1_acc)
self.assertTrue(mul_x.name in moment2_acc)
# Check init_program
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 5)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
class TestAdamaxOptimizer(unittest.TestCase):
class MockAdamax(optimizer.AdamaxOptimizer):
def get_accumulators(self):
return self._accumulators
def get_moment_str(self):
return self._moment_acc_str
def get_inf_norm_str(self):
return self._inf_norm_acc_str
def test_adamax_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
adamax_optimizer = self.MockAdamax(
learning_rate=learning_rate, beta1=0.9, beta2=0.999)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(adamax_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = adamax_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 3)
self.assertEqual([op.type for op in opts], ["scale", "adamax", "scale"])
# Check accumulators
accumulators = adamax_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 3)
self.assertTrue(adamax_optimizer.get_moment_str() in accumulators)
self.assertTrue(adamax_optimizer.get_inf_norm_str() in accumulators)
moment_acc = accumulators[adamax_optimizer.get_moment_str()]
inf_norm_acc = accumulators[adamax_optimizer.get_inf_norm_str()]
self.assertEqual(len(moment_acc), 1)
self.assertEqual(len(inf_norm_acc), 1)
self.assertTrue(mul_x.name in moment_acc)
self.assertTrue(mul_x.name in inf_norm_acc)
# Check init_program
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 4)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
class TestDpsgdOptimizer(unittest.TestCase):
def test_dpsgd_optimizer(self):
def check_dpsgd_optimizer(optimizer_attr):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr=optimizer_attr)
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
dpsgd_optimizer = optimizer.DpsgdOptimizer(
learning_rate=0.01, clip=100.0, batch_size=16.0, sigma=0.0)
opts, _ = dpsgd_optimizer.minimize(mean_out, init_program)
return opts
opts = check_dpsgd_optimizer({
'learning_rate': 1.1,
'clip': 100.0,
'batch_size': 16.0,
'sigma': 4.0
})
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "dpsgd"])
class TestDecayedAdagradOptimizer(unittest.TestCase):
class MockDecayedAdagrad(optimizer.DecayedAdagradOptimizer):
def get_accumulators(self):
return self._accumulators
def get_moment_str(self):
return self._moment_acc_str
def test_decayed_adagrad_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
decayed_adagrad_optimizer = self.MockDecayedAdagrad(
learning_rate=learning_rate, decay=0.95, epsilon=1.0e-6)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(decayed_adagrad_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = decayed_adagrad_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "decayed_adagrad"])
# Check accumulators
accumulators = decayed_adagrad_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 1)
self.assertTrue(
decayed_adagrad_optimizer.get_moment_str() in accumulators)
moment_acc = accumulators[decayed_adagrad_optimizer.get_moment_str()]
self.assertEqual(len(moment_acc), 1)
self.assertTrue(mul_x.name in moment_acc)
# Check init_program
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 2)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
self.assertEqual(init_ops[1].type, "fill_constant")
self.assertAlmostEqual(init_ops[1].attr('value'), 0.0)
class TestFtrlOptimizer(unittest.TestCase):
class MockFtrl(optimizer.FtrlOptimizer):
def get_accumulators(self):
return self._accumulators
def get_squared_str(self):
return self._squared_acc_str
def get_linear_str(self):
return self._linear_acc_str
def test_ftrl_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
ftrl_optimizer = self.MockFtrl(
learning_rate=learning_rate, l1=0.0, l2=0.0, lr_power=-0.5)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(ftrl_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = ftrl_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "ftrl"])
# Check accumulators
accumulators = ftrl_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 2)
self.assertTrue(ftrl_optimizer.get_squared_str() in accumulators)
self.assertTrue(ftrl_optimizer.get_linear_str() in accumulators)
squared_acc = accumulators[ftrl_optimizer.get_squared_str()]
linear_acc = accumulators[ftrl_optimizer.get_linear_str()]
self.assertEqual(len(squared_acc), 1)
self.assertEqual(len(linear_acc), 1)
self.assertTrue(mul_x.name in squared_acc)
self.assertTrue(mul_x.name in linear_acc)
# Check init_program
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 3)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
class TestLookaheadOptimizer(unittest.TestCase):
def test_lookahead_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
init_block = init_program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
init_mul_x = init_block.create_parameter(
dtype="float32", shape=[5, 10], lod_level=0, name="mul.x")
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
sgd = optimizer.SGD(learning_rate=0.01)
lookahead = optimizer.LookaheadOptimizer(sgd, alpha=0.5, k=5)
with framework.program_guard(program, init_program):
opts, _ = lookahead.minimize(mean_out)
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "sgd"])
class TestRecomputeOptimizer(unittest.TestCase):
def net(self):
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32", shape=[5, 10], lod_level=0, name="mul.x")
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
b1 = block.create_parameter(
dtype="float32", shape=[5, 8], lod_level=0, name="b1")
b1_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="b1_out")
b2 = block.create_parameter(
dtype="float32", shape=[5, 8], lod_level=0, name="b2")
b2_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="b2_out")
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
block.append_op(
type="elementwise_add",
inputs={"X": mul_out,
"Y": b1},
outputs={"Out": b1_out})
block.append_op(
type="elementwise_add",
inputs={"X": b1_out,
"Y": b2},
outputs={"Out": b2_out})
block.append_op(
type="mean", inputs={"X": b2_out}, outputs={"Out": mean_out})
return mul_out, b1_out, b2_out, mean_out
def test_no_checkpoint(self):
mul_out, b1_out, b2_out, mean_out = self.net()
self.assertEqual(len(mean_out.block.ops), 4)
self.assertEqual([op.type for op in mean_out.block.ops],
["mul", "elementwise_add", "elementwise_add", "mean"])
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([])
opts, params_grads = recompute_optimizer.minimize(mean_out)
self.assertEqual(len(mean_out.block.ops), 12)
self.assertEqual([op.type for op in mean_out.block.ops], [
"mul", "elementwise_add", "elementwise_add", "mean",
"fill_constant", "mean_grad", "elementwise_add_grad",
"elementwise_add_grad", "mul_grad", "sgd", "sgd", "sgd"
])
def test_one_checkpoint(self):
mul_out, b1_out, b2_out, mean_out = self.net()
self.assertEqual(len(mean_out.block.ops), 4)
self.assertEqual([op.type for op in mean_out.block.ops],
["mul", "elementwise_add", "elementwise_add", "mean"])
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([b1_out])
opts, params_grads = recompute_optimizer.minimize(mean_out)
self.assertEqual(len(mean_out.block.ops), 13)
self.assertEqual([op.type for op in mean_out.block.ops], [
"mul", "elementwise_add", "elementwise_add", "mean",
"fill_constant", "mean_grad", "elementwise_add_grad", "mul",
"elementwise_add_grad", "mul_grad", "sgd", "sgd", "sgd"
])
def test_multi_checkpoint(self):
mul_out, b1_out, b2_out, mean_out = self.net()
self.assertEqual(len(mean_out.block.ops), 4)
self.assertEqual([op.type for op in mean_out.block.ops],
["mul", "elementwise_add", "elementwise_add", "mean"])
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([mul_out, b2_out])
opts, params_grads = recompute_optimizer.minimize(mean_out)
self.assertEqual(len(mean_out.block.ops), 13)
self.assertEqual([op.type for op in mean_out.block.ops], [
"mul", "elementwise_add", "elementwise_add", "mean",
"fill_constant", "mean_grad", "elementwise_add",
"elementwise_add_grad", "elementwise_add_grad", "mul_grad", "sgd",
"sgd", "sgd"
])
def test_adjacent_checkpoint(self):
mul_out, b1_out, b2_out, mean_out = self.net()
self.assertEqual(len(mean_out.block.ops), 4)
self.assertEqual([op.type for op in mean_out.block.ops],
["mul", "elementwise_add", "elementwise_add", "mean"])
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([mul_out, b1_out])
opts, params_grads = recompute_optimizer.minimize(mean_out)
self.assertEqual(len(mean_out.block.ops), 12)
self.assertEqual([op.type for op in mean_out.block.ops], [
"mul", "elementwise_add", "elementwise_add", "mean",
"fill_constant", "mean_grad", "elementwise_add_grad",
"elementwise_add_grad", "mul_grad", "sgd", "sgd", "sgd"
])
def test_apply_gradients(self):
mul_out, b1_out, b2_out, mean_out = self.net()
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([b1_out])
# apply backward
params_grads = recompute_optimizer.backward(
mean_out,
startup_program=None,
parameter_list=None,
no_grad_set=None,
checkpoints=[b1_out])
# apply gradient
program = mean_out.block.program
with framework.program_guard(program, None):
optimize_ops = recompute_optimizer.apply_gradients(params_grads)
self.assertEqual(len(mean_out.block.ops), 13)
self.assertEqual([op.type for op in mean_out.block.ops], [
"mul", "elementwise_add", "elementwise_add", "mean",
"fill_constant", "mean_grad", "elementwise_add_grad", "mul",
"elementwise_add_grad", "mul_grad", "sgd", "sgd", "sgd"
])
def test_load(self):
mul_out, b1_out, b2_out, mean_out = self.net()
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([b1_out])
try:
stat_dict = {}
recompute_optimizer.load(stat_dict)
except NotImplementedError as e:
self.assertEqual(
"load function is not supported by Recompute Optimizer for now",
cpt.get_exception_message(e))
if __name__ == '__main__':
unittest.main()
| 42.474576 | 80 | 0.610228 |
from __future__ import print_function
import unittest
import paddle.fluid.framework as framework
import paddle.fluid.optimizer as optimizer
import paddle.compat as cpt
from paddle.fluid.backward import append_backward
class TestOptimizer(unittest.TestCase):
def test_sgd_optimizer(self):
def check_sgd_optimizer(optimizer_attr):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr=optimizer_attr)
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
sgd_optimizer = optimizer.SGDOptimizer(learning_rate=0.01)
opts, _ = sgd_optimizer.minimize(mean_out, init_program)
return opts
opts = check_sgd_optimizer({'learning_rate': 1.1})
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "sgd"])
opts = check_sgd_optimizer({'learning_rate': 1.0})
self.assertEqual(len(opts), 1)
self.assertEqual([op.type for op in opts], ["sgd"])
class TestOptimizerBackwardApplygrad(unittest.TestCase):
def test_sgd_optimizer(self):
def check_sgd_optimizer(optimizer_attr):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr=optimizer_attr)
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
sgd_optimizer = optimizer.SGDOptimizer(learning_rate=0.01)
with framework.program_guard(program, init_program):
p_g = sgd_optimizer.backward(mean_out)
opts = sgd_optimizer.apply_gradients(p_g)
return opts
opts = check_sgd_optimizer({'learning_rate': 1.1})
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "sgd"])
opts = check_sgd_optimizer({'learning_rate': 1.0})
self.assertEqual(len(opts), 1)
self.assertEqual([op.type for op in opts], ["sgd"])
class TestMomentumOptimizer(unittest.TestCase):
class MockMomentum(optimizer.MomentumOptimizer):
def get_accumulators(self):
return self._accumulators
def get_velocity_str(self):
return self._velocity_acc_str
def test_vanilla_momentum_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
learning_rate = 0.01
momentum_optimizer = self.MockMomentum(
learning_rate=learning_rate, momentum=0.2)
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(momentum_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = momentum_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 2)
sgd_op = opts[-1]
self.assertEqual([op.type for op in opts], ["scale", "momentum"])
self.assertFalse(sgd_op.attr('use_nesterov'))
accumulators = momentum_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 1)
self.assertTrue(momentum_optimizer.get_velocity_str() in accumulators)
velocity_acc = accumulators[momentum_optimizer.get_velocity_str()]
self.assertEqual(len(velocity_acc), 1)
self.assertTrue(mul_x.name in velocity_acc)
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 2)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
self.assertEqual(init_ops[1].type, "fill_constant")
self.assertAlmostEqual(init_ops[1].attr('value'), 0.0)
def test_nesterov_momentum_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
momentum_optimizer = self.MockMomentum(
learning_rate=learning_rate, momentum=0.2, use_nesterov=True)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(momentum_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = momentum_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 2)
sgd_op = opts[-1]
self.assertEqual([op.type for op in opts], ["scale", "momentum"])
self.assertTrue(sgd_op.attr('use_nesterov'))
accumulators = momentum_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 1)
self.assertTrue(momentum_optimizer.get_velocity_str() in accumulators)
velocity_acc = accumulators[momentum_optimizer.get_velocity_str()]
self.assertEqual(len(velocity_acc), 1)
self.assertTrue(mul_x.name in velocity_acc)
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 2)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
self.assertEqual(init_ops[1].type, "fill_constant")
self.assertAlmostEqual(init_ops[1].attr('value'), 0.0)
class TestAdagradOptimizer(unittest.TestCase):
class MockAdagrad(optimizer.AdagradOptimizer):
def get_accumulators(self):
return self._accumulators
def get_moment_str(self):
return self._moment_acc_str
def test_adagrad_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
adagrad_optimizer = self.MockAdagrad(
learning_rate=learning_rate, epsilon=1.0e-6)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(adagrad_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = adagrad_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "adagrad"])
accumulators = adagrad_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 1)
self.assertTrue(adagrad_optimizer.get_moment_str() in accumulators)
moment_acc = accumulators[adagrad_optimizer.get_moment_str()]
self.assertEqual(len(moment_acc), 1)
self.assertTrue(mul_x.name in moment_acc)
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 3)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
self.assertEqual(init_ops[1].type, "fill_constant")
self.assertAlmostEqual(init_ops[1].attr('value'), 0.0)
class TestAdamOptimizer(unittest.TestCase):
class MockAdam(optimizer.AdamOptimizer):
def get_accumulators(self):
return self._accumulators
def get_moment1_str(self):
return self._moment1_acc_str
def get_moment2_str(self):
return self._moment2_acc_str
def test_adam_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
adam_optimizer = self.MockAdam(
learning_rate=learning_rate, beta1=0.9, beta2=0.999)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(adam_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = adam_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 4)
self.assertEqual([op.type for op in opts],
["scale", "adam", "scale", "scale"])
accumulators = adam_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 4)
self.assertTrue(adam_optimizer.get_moment1_str() in accumulators)
self.assertTrue(adam_optimizer.get_moment2_str() in accumulators)
moment1_acc = accumulators[adam_optimizer.get_moment1_str()]
moment2_acc = accumulators[adam_optimizer.get_moment2_str()]
self.assertEqual(len(moment1_acc), 1)
self.assertEqual(len(moment2_acc), 1)
self.assertTrue(mul_x.name in moment1_acc)
self.assertTrue(mul_x.name in moment2_acc)
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 5)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
class TestAdamaxOptimizer(unittest.TestCase):
class MockAdamax(optimizer.AdamaxOptimizer):
def get_accumulators(self):
return self._accumulators
def get_moment_str(self):
return self._moment_acc_str
def get_inf_norm_str(self):
return self._inf_norm_acc_str
def test_adamax_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
adamax_optimizer = self.MockAdamax(
learning_rate=learning_rate, beta1=0.9, beta2=0.999)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(adamax_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = adamax_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 3)
self.assertEqual([op.type for op in opts], ["scale", "adamax", "scale"])
accumulators = adamax_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 3)
self.assertTrue(adamax_optimizer.get_moment_str() in accumulators)
self.assertTrue(adamax_optimizer.get_inf_norm_str() in accumulators)
moment_acc = accumulators[adamax_optimizer.get_moment_str()]
inf_norm_acc = accumulators[adamax_optimizer.get_inf_norm_str()]
self.assertEqual(len(moment_acc), 1)
self.assertEqual(len(inf_norm_acc), 1)
self.assertTrue(mul_x.name in moment_acc)
self.assertTrue(mul_x.name in inf_norm_acc)
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 4)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
class TestDpsgdOptimizer(unittest.TestCase):
def test_dpsgd_optimizer(self):
def check_dpsgd_optimizer(optimizer_attr):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr=optimizer_attr)
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
dpsgd_optimizer = optimizer.DpsgdOptimizer(
learning_rate=0.01, clip=100.0, batch_size=16.0, sigma=0.0)
opts, _ = dpsgd_optimizer.minimize(mean_out, init_program)
return opts
opts = check_dpsgd_optimizer({
'learning_rate': 1.1,
'clip': 100.0,
'batch_size': 16.0,
'sigma': 4.0
})
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "dpsgd"])
class TestDecayedAdagradOptimizer(unittest.TestCase):
class MockDecayedAdagrad(optimizer.DecayedAdagradOptimizer):
def get_accumulators(self):
return self._accumulators
def get_moment_str(self):
return self._moment_acc_str
def test_decayed_adagrad_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
decayed_adagrad_optimizer = self.MockDecayedAdagrad(
learning_rate=learning_rate, decay=0.95, epsilon=1.0e-6)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(decayed_adagrad_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = decayed_adagrad_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "decayed_adagrad"])
accumulators = decayed_adagrad_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 1)
self.assertTrue(
decayed_adagrad_optimizer.get_moment_str() in accumulators)
moment_acc = accumulators[decayed_adagrad_optimizer.get_moment_str()]
self.assertEqual(len(moment_acc), 1)
self.assertTrue(mul_x.name in moment_acc)
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 2)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
self.assertEqual(init_ops[1].type, "fill_constant")
self.assertAlmostEqual(init_ops[1].attr('value'), 0.0)
class TestFtrlOptimizer(unittest.TestCase):
class MockFtrl(optimizer.FtrlOptimizer):
def get_accumulators(self):
return self._accumulators
def get_squared_str(self):
return self._squared_acc_str
def get_linear_str(self):
return self._linear_acc_str
def test_ftrl_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
learning_rate = 0.01
ftrl_optimizer = self.MockFtrl(
learning_rate=learning_rate, l1=0.0, l2=0.0, lr_power=-0.5)
params_grads = append_backward(mean_out)
self.assertEqual(len(params_grads), 1)
self.assertEqual(len(ftrl_optimizer.get_accumulators()), 0)
with framework.program_guard(program, init_program):
opts = ftrl_optimizer.apply_gradients(params_grads)
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "ftrl"])
accumulators = ftrl_optimizer.get_accumulators()
self.assertEqual(len(accumulators), 2)
self.assertTrue(ftrl_optimizer.get_squared_str() in accumulators)
self.assertTrue(ftrl_optimizer.get_linear_str() in accumulators)
squared_acc = accumulators[ftrl_optimizer.get_squared_str()]
linear_acc = accumulators[ftrl_optimizer.get_linear_str()]
self.assertEqual(len(squared_acc), 1)
self.assertEqual(len(linear_acc), 1)
self.assertTrue(mul_x.name in squared_acc)
self.assertTrue(mul_x.name in linear_acc)
init_ops = init_program.global_block().ops
self.assertEqual(len(init_ops), 3)
self.assertEqual(init_ops[0].type, "fill_constant")
self.assertAlmostEqual(init_ops[0].attr('value'), learning_rate)
class TestLookaheadOptimizer(unittest.TestCase):
def test_lookahead_optimizer(self):
init_program = framework.Program()
program = framework.Program()
block = program.global_block()
init_block = init_program.global_block()
mul_x = block.create_parameter(
dtype="float32",
shape=[5, 10],
lod_level=0,
name="mul.x",
optimize_attr={'learning_rate': 1.1})
init_mul_x = init_block.create_parameter(
dtype="float32", shape=[5, 10], lod_level=0, name="mul.x")
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
block.append_op(
type="mean", inputs={"X": mul_out}, outputs={"Out": mean_out})
sgd = optimizer.SGD(learning_rate=0.01)
lookahead = optimizer.LookaheadOptimizer(sgd, alpha=0.5, k=5)
with framework.program_guard(program, init_program):
opts, _ = lookahead.minimize(mean_out)
self.assertEqual(len(opts), 2)
self.assertEqual([op.type for op in opts], ["scale", "sgd"])
class TestRecomputeOptimizer(unittest.TestCase):
def net(self):
program = framework.Program()
block = program.global_block()
mul_x = block.create_parameter(
dtype="float32", shape=[5, 10], lod_level=0, name="mul.x")
mul_y = block.create_var(
dtype="float32", shape=[10, 8], lod_level=0, name="mul.y")
mul_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="mul.out")
b1 = block.create_parameter(
dtype="float32", shape=[5, 8], lod_level=0, name="b1")
b1_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="b1_out")
b2 = block.create_parameter(
dtype="float32", shape=[5, 8], lod_level=0, name="b2")
b2_out = block.create_var(
dtype="float32", shape=[5, 8], lod_level=0, name="b2_out")
mean_out = block.create_var(
dtype="float32", shape=[1], lod_level=0, name="mean.out")
block.append_op(
type="mul",
inputs={"X": mul_x,
"Y": mul_y},
outputs={"Out": mul_out},
attrs={"x_num_col_dims": 1})
block.append_op(
type="elementwise_add",
inputs={"X": mul_out,
"Y": b1},
outputs={"Out": b1_out})
block.append_op(
type="elementwise_add",
inputs={"X": b1_out,
"Y": b2},
outputs={"Out": b2_out})
block.append_op(
type="mean", inputs={"X": b2_out}, outputs={"Out": mean_out})
return mul_out, b1_out, b2_out, mean_out
def test_no_checkpoint(self):
mul_out, b1_out, b2_out, mean_out = self.net()
self.assertEqual(len(mean_out.block.ops), 4)
self.assertEqual([op.type for op in mean_out.block.ops],
["mul", "elementwise_add", "elementwise_add", "mean"])
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([])
opts, params_grads = recompute_optimizer.minimize(mean_out)
self.assertEqual(len(mean_out.block.ops), 12)
self.assertEqual([op.type for op in mean_out.block.ops], [
"mul", "elementwise_add", "elementwise_add", "mean",
"fill_constant", "mean_grad", "elementwise_add_grad",
"elementwise_add_grad", "mul_grad", "sgd", "sgd", "sgd"
])
def test_one_checkpoint(self):
mul_out, b1_out, b2_out, mean_out = self.net()
self.assertEqual(len(mean_out.block.ops), 4)
self.assertEqual([op.type for op in mean_out.block.ops],
["mul", "elementwise_add", "elementwise_add", "mean"])
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([b1_out])
opts, params_grads = recompute_optimizer.minimize(mean_out)
self.assertEqual(len(mean_out.block.ops), 13)
self.assertEqual([op.type for op in mean_out.block.ops], [
"mul", "elementwise_add", "elementwise_add", "mean",
"fill_constant", "mean_grad", "elementwise_add_grad", "mul",
"elementwise_add_grad", "mul_grad", "sgd", "sgd", "sgd"
])
def test_multi_checkpoint(self):
mul_out, b1_out, b2_out, mean_out = self.net()
self.assertEqual(len(mean_out.block.ops), 4)
self.assertEqual([op.type for op in mean_out.block.ops],
["mul", "elementwise_add", "elementwise_add", "mean"])
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([mul_out, b2_out])
opts, params_grads = recompute_optimizer.minimize(mean_out)
self.assertEqual(len(mean_out.block.ops), 13)
self.assertEqual([op.type for op in mean_out.block.ops], [
"mul", "elementwise_add", "elementwise_add", "mean",
"fill_constant", "mean_grad", "elementwise_add",
"elementwise_add_grad", "elementwise_add_grad", "mul_grad", "sgd",
"sgd", "sgd"
])
def test_adjacent_checkpoint(self):
mul_out, b1_out, b2_out, mean_out = self.net()
self.assertEqual(len(mean_out.block.ops), 4)
self.assertEqual([op.type for op in mean_out.block.ops],
["mul", "elementwise_add", "elementwise_add", "mean"])
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([mul_out, b1_out])
opts, params_grads = recompute_optimizer.minimize(mean_out)
self.assertEqual(len(mean_out.block.ops), 12)
self.assertEqual([op.type for op in mean_out.block.ops], [
"mul", "elementwise_add", "elementwise_add", "mean",
"fill_constant", "mean_grad", "elementwise_add_grad",
"elementwise_add_grad", "mul_grad", "sgd", "sgd", "sgd"
])
def test_apply_gradients(self):
mul_out, b1_out, b2_out, mean_out = self.net()
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([b1_out])
params_grads = recompute_optimizer.backward(
mean_out,
startup_program=None,
parameter_list=None,
no_grad_set=None,
checkpoints=[b1_out])
program = mean_out.block.program
with framework.program_guard(program, None):
optimize_ops = recompute_optimizer.apply_gradients(params_grads)
self.assertEqual(len(mean_out.block.ops), 13)
self.assertEqual([op.type for op in mean_out.block.ops], [
"mul", "elementwise_add", "elementwise_add", "mean",
"fill_constant", "mean_grad", "elementwise_add_grad", "mul",
"elementwise_add_grad", "mul_grad", "sgd", "sgd", "sgd"
])
def test_load(self):
mul_out, b1_out, b2_out, mean_out = self.net()
sgd_optimizer = optimizer.SGD(learning_rate=1.0)
recompute_optimizer = optimizer.RecomputeOptimizer(sgd_optimizer)
recompute_optimizer._set_checkpoints([b1_out])
try:
stat_dict = {}
recompute_optimizer.load(stat_dict)
except NotImplementedError as e:
self.assertEqual(
"load function is not supported by Recompute Optimizer for now",
cpt.get_exception_message(e))
if __name__ == '__main__':
unittest.main()
| true | true |
1c3fd18d95dde9b8c931da1988561fbe274ebc18 | 14,247 | py | Python | tests/function/test_simple.py | klmitch/micropath | 3de7f3d3da59dea802b502ebc71ec5e139e25e1f | [
"Apache-2.0"
] | 1 | 2018-06-07T22:17:14.000Z | 2018-06-07T22:17:14.000Z | tests/function/test_simple.py | klmitch/micropath | 3de7f3d3da59dea802b502ebc71ec5e139e25e1f | [
"Apache-2.0"
] | null | null | null | tests/function/test_simple.py | klmitch/micropath | 3de7f3d3da59dea802b502ebc71ec5e139e25e1f | [
"Apache-2.0"
] | null | null | null | # Copyright (C) 2018 by Kevin L. Mitchell <klmitch@mit.edu>
#
# 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 micropath
from tests.function import utils
class BookController(micropath.Controller):
@micropath.route('get')
def index(self, request, sub_id=None):
return 'book::index(sub_id=%s)' % utils.safestr(sub_id)
@micropath.route('post')
def create(self, request, sub_id=None):
return 'book::create(sub_id=%s)' % utils.safestr(sub_id)
book_id = micropath.bind()
@book_id.route('get')
def get(self, request, book_id, sub_id=None):
return 'book::get(book_id=%s, sub_id=%s)' % (
utils.safestr(book_id), utils.safestr(sub_id),
)
@book_id.route('put')
def update(self, request, book_id, sub_id=None):
return 'book::update(book_id=%s, sub_id=%s)' % (
utils.safestr(book_id), utils.safestr(sub_id),
)
@book_id.route('delete')
def delete(self, request, book_id, sub_id=None):
return 'book::delete(book_id=%s, sub_id=%s)' % (
utils.safestr(book_id), utils.safestr(sub_id),
)
class SubscriberController(micropath.Controller):
@micropath.route('get')
def index(self, request):
return 'sub::index()'
@micropath.route('post')
def create(self, request):
return 'sub::create()'
sub_id = micropath.bind()
@sub_id.route('get')
def get(self, request, sub_id):
return 'sub::get(sub_id=%s)' % utils.safestr(sub_id)
@sub_id.route('put')
def update(self, request, sub_id):
return 'sub::update(sub_id=%s)' % utils.safestr(sub_id)
@sub_id.route('delete')
def delete(self, request, sub_id):
return 'sub::delete(sub_id=%s)' % utils.safestr(sub_id)
books = sub_id.path().mount(BookController)
class TestSimple(object):
def test_subscriber_index(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/',
method='GET',
)
assert status == '200 OK'
assert body == b'sub::index()'
def test_subscriber_index_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.index)
assert result == 'http://example.com/'
def test_subscriber_index_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.index)
assert result == 'http://example.com/api/'
def test_subscriber_create(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/',
method='POST',
)
assert status == '200 OK'
assert body == b'sub::create()'
def test_subscriber_create_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.create)
assert result == 'http://example.com/'
def test_subscriber_create_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.create)
assert result == 'http://example.com/api/'
def test_subscriber_options(self):
controller = SubscriberController()
status, headers, body = utils.invoke(
controller, '/',
method='OPTIONS',
)
assert status == '204 No Content'
assert 'allow' in headers
assert headers['allow'] == 'GET,HEAD,OPTIONS,POST'
assert body == b''
def test_subscriber_other(self):
controller = SubscriberController()
status, _headers, _body = utils.invoke(
controller, '/',
method='OTHER',
)
assert status == '501 Not Implemented'
def test_subscriber_subid_get(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234',
method='GET',
)
assert status == '200 OK'
assert body == b'sub::get(sub_id=1234)'
def test_subscriber_get_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.get, sub_id='1234')
assert result == 'http://example.com/1234'
def test_subscriber_get_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.get, sub_id='1234')
assert result == 'http://example.com/api/1234'
def test_subscriber_subid_update(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234',
method='PUT',
)
assert status == '200 OK'
assert body == b'sub::update(sub_id=1234)'
def test_subscriber_update_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.update, sub_id='1234')
assert result == 'http://example.com/1234'
def test_subscriber_update_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.update, sub_id='1234')
assert result == 'http://example.com/api/1234'
def test_subscriber_subid_delete(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234',
method='DELETE',
)
assert status == '200 OK'
assert body == b'sub::delete(sub_id=1234)'
def test_subscriber_delete_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.delete, sub_id='1234')
assert result == 'http://example.com/1234'
def test_subscriber_delete_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.delete, sub_id='1234')
assert result == 'http://example.com/api/1234'
def test_subscriber_subid_options(self):
controller = SubscriberController()
status, headers, body = utils.invoke(
controller, '/1234',
method='OPTIONS',
)
assert status == '204 No Content'
assert 'allow' in headers
assert headers['allow'] == 'DELETE,GET,HEAD,OPTIONS,PUT'
assert body == b''
def test_subscriber_subid_other(self):
controller = SubscriberController()
status, _headers, _body = utils.invoke(
controller, '/1234',
method='OTHER',
)
assert status == '501 Not Implemented'
def test_subscriber_not_found(self):
controller = SubscriberController()
status, _headers, _body = utils.invoke(
controller, '/1234/not_found',
method='GET',
)
assert status == '404 Not Found'
def test_book_index(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234/books',
method='GET',
)
assert status == '200 OK'
assert body == b'book::index(sub_id=1234)'
def test_book_index_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.books.index, sub_id='1234')
assert result == 'http://example.com/1234/books'
def test_book_index_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.books.index, sub_id='1234')
assert result == 'http://example.com/api/1234/books'
def test_book_create(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234/books',
method='POST',
)
assert status == '200 OK'
assert body == b'book::create(sub_id=1234)'
def test_book_create_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.books.create, sub_id='1234')
assert result == 'http://example.com/1234/books'
def test_book_create_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.books.create, sub_id='1234')
assert result == 'http://example.com/api/1234/books'
def test_book_options(self):
controller = SubscriberController()
status, headers, body = utils.invoke(
controller, '/1234/books',
method='OPTIONS',
)
assert status == '204 No Content'
assert 'allow' in headers
assert headers['allow'] == 'GET,HEAD,OPTIONS,POST'
assert body == b''
def test_book_other(self):
controller = SubscriberController()
status, _headers, _body = utils.invoke(
controller, '/1234/books',
method='OTHER',
)
assert status == '501 Not Implemented'
def test_book_bookid_get(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234/books/5678',
method='GET',
)
assert status == '200 OK'
assert body == b'book::get(book_id=5678, sub_id=1234)'
def test_book_bookid_get_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(
controller.books.get,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/1234/books/5678'
def test_book_bookid_get_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(
controller.books.get,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/api/1234/books/5678'
def test_book_bookid_update(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234/books/5678',
method='PUT',
)
assert status == '200 OK'
assert body == b'book::update(book_id=5678, sub_id=1234)'
def test_book_bookid_update_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(
controller.books.update,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/1234/books/5678'
def test_book_bookid_update_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(
controller.books.update,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/api/1234/books/5678'
def test_book_bookid_delete(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234/books/5678',
method='DELETE',
)
assert status == '200 OK'
assert body == b'book::delete(book_id=5678, sub_id=1234)'
def test_book_bookid_delete_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(
controller.books.delete,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/1234/books/5678'
def test_book_bookid_delete_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(
controller.books.delete,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/api/1234/books/5678'
def test_book_bookid_options(self):
controller = SubscriberController()
status, headers, body = utils.invoke(
controller, '/1234/books/5678',
method='OPTIONS',
)
assert status == '204 No Content'
assert 'allow' in headers
assert headers['allow'] == 'DELETE,GET,HEAD,OPTIONS,PUT'
assert body == b''
def test_book_bookid_other(self):
controller = SubscriberController()
status, _headers, _body = utils.invoke(
controller, '/1234/books/5678',
method='OTHER',
)
assert status == '501 Not Implemented'
| 30.184322 | 77 | 0.610865 |
import micropath
from tests.function import utils
class BookController(micropath.Controller):
@micropath.route('get')
def index(self, request, sub_id=None):
return 'book::index(sub_id=%s)' % utils.safestr(sub_id)
@micropath.route('post')
def create(self, request, sub_id=None):
return 'book::create(sub_id=%s)' % utils.safestr(sub_id)
book_id = micropath.bind()
@book_id.route('get')
def get(self, request, book_id, sub_id=None):
return 'book::get(book_id=%s, sub_id=%s)' % (
utils.safestr(book_id), utils.safestr(sub_id),
)
@book_id.route('put')
def update(self, request, book_id, sub_id=None):
return 'book::update(book_id=%s, sub_id=%s)' % (
utils.safestr(book_id), utils.safestr(sub_id),
)
@book_id.route('delete')
def delete(self, request, book_id, sub_id=None):
return 'book::delete(book_id=%s, sub_id=%s)' % (
utils.safestr(book_id), utils.safestr(sub_id),
)
class SubscriberController(micropath.Controller):
@micropath.route('get')
def index(self, request):
return 'sub::index()'
@micropath.route('post')
def create(self, request):
return 'sub::create()'
sub_id = micropath.bind()
@sub_id.route('get')
def get(self, request, sub_id):
return 'sub::get(sub_id=%s)' % utils.safestr(sub_id)
@sub_id.route('put')
def update(self, request, sub_id):
return 'sub::update(sub_id=%s)' % utils.safestr(sub_id)
@sub_id.route('delete')
def delete(self, request, sub_id):
return 'sub::delete(sub_id=%s)' % utils.safestr(sub_id)
books = sub_id.path().mount(BookController)
class TestSimple(object):
def test_subscriber_index(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/',
method='GET',
)
assert status == '200 OK'
assert body == b'sub::index()'
def test_subscriber_index_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.index)
assert result == 'http://example.com/'
def test_subscriber_index_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.index)
assert result == 'http://example.com/api/'
def test_subscriber_create(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/',
method='POST',
)
assert status == '200 OK'
assert body == b'sub::create()'
def test_subscriber_create_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.create)
assert result == 'http://example.com/'
def test_subscriber_create_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.create)
assert result == 'http://example.com/api/'
def test_subscriber_options(self):
controller = SubscriberController()
status, headers, body = utils.invoke(
controller, '/',
method='OPTIONS',
)
assert status == '204 No Content'
assert 'allow' in headers
assert headers['allow'] == 'GET,HEAD,OPTIONS,POST'
assert body == b''
def test_subscriber_other(self):
controller = SubscriberController()
status, _headers, _body = utils.invoke(
controller, '/',
method='OTHER',
)
assert status == '501 Not Implemented'
def test_subscriber_subid_get(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234',
method='GET',
)
assert status == '200 OK'
assert body == b'sub::get(sub_id=1234)'
def test_subscriber_get_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.get, sub_id='1234')
assert result == 'http://example.com/1234'
def test_subscriber_get_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.get, sub_id='1234')
assert result == 'http://example.com/api/1234'
def test_subscriber_subid_update(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234',
method='PUT',
)
assert status == '200 OK'
assert body == b'sub::update(sub_id=1234)'
def test_subscriber_update_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.update, sub_id='1234')
assert result == 'http://example.com/1234'
def test_subscriber_update_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.update, sub_id='1234')
assert result == 'http://example.com/api/1234'
def test_subscriber_subid_delete(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234',
method='DELETE',
)
assert status == '200 OK'
assert body == b'sub::delete(sub_id=1234)'
def test_subscriber_delete_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.delete, sub_id='1234')
assert result == 'http://example.com/1234'
def test_subscriber_delete_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.delete, sub_id='1234')
assert result == 'http://example.com/api/1234'
def test_subscriber_subid_options(self):
controller = SubscriberController()
status, headers, body = utils.invoke(
controller, '/1234',
method='OPTIONS',
)
assert status == '204 No Content'
assert 'allow' in headers
assert headers['allow'] == 'DELETE,GET,HEAD,OPTIONS,PUT'
assert body == b''
def test_subscriber_subid_other(self):
controller = SubscriberController()
status, _headers, _body = utils.invoke(
controller, '/1234',
method='OTHER',
)
assert status == '501 Not Implemented'
def test_subscriber_not_found(self):
controller = SubscriberController()
status, _headers, _body = utils.invoke(
controller, '/1234/not_found',
method='GET',
)
assert status == '404 Not Found'
def test_book_index(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234/books',
method='GET',
)
assert status == '200 OK'
assert body == b'book::index(sub_id=1234)'
def test_book_index_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.books.index, sub_id='1234')
assert result == 'http://example.com/1234/books'
def test_book_index_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.books.index, sub_id='1234')
assert result == 'http://example.com/api/1234/books'
def test_book_create(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234/books',
method='POST',
)
assert status == '200 OK'
assert body == b'book::create(sub_id=1234)'
def test_book_create_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(controller.books.create, sub_id='1234')
assert result == 'http://example.com/1234/books'
def test_book_create_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(controller.books.create, sub_id='1234')
assert result == 'http://example.com/api/1234/books'
def test_book_options(self):
controller = SubscriberController()
status, headers, body = utils.invoke(
controller, '/1234/books',
method='OPTIONS',
)
assert status == '204 No Content'
assert 'allow' in headers
assert headers['allow'] == 'GET,HEAD,OPTIONS,POST'
assert body == b''
def test_book_other(self):
controller = SubscriberController()
status, _headers, _body = utils.invoke(
controller, '/1234/books',
method='OTHER',
)
assert status == '501 Not Implemented'
def test_book_bookid_get(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234/books/5678',
method='GET',
)
assert status == '200 OK'
assert body == b'book::get(book_id=5678, sub_id=1234)'
def test_book_bookid_get_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(
controller.books.get,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/1234/books/5678'
def test_book_bookid_get_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(
controller.books.get,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/api/1234/books/5678'
def test_book_bookid_update(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234/books/5678',
method='PUT',
)
assert status == '200 OK'
assert body == b'book::update(book_id=5678, sub_id=1234)'
def test_book_bookid_update_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(
controller.books.update,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/1234/books/5678'
def test_book_bookid_update_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(
controller.books.update,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/api/1234/books/5678'
def test_book_bookid_delete(self):
controller = SubscriberController()
status, _headers, body = utils.invoke(
controller, '/1234/books/5678',
method='DELETE',
)
assert status == '200 OK'
assert body == b'book::delete(book_id=5678, sub_id=1234)'
def test_book_bookid_delete_url_for(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com')
result = req.url_for(
controller.books.delete,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/1234/books/5678'
def test_book_bookid_delete_url_for_scriptname(self):
controller = SubscriberController()
req = micropath.Request.blank('/', base_url='http://example.com/api')
result = req.url_for(
controller.books.delete,
sub_id='1234',
book_id='5678',
)
assert result == 'http://example.com/api/1234/books/5678'
def test_book_bookid_options(self):
controller = SubscriberController()
status, headers, body = utils.invoke(
controller, '/1234/books/5678',
method='OPTIONS',
)
assert status == '204 No Content'
assert 'allow' in headers
assert headers['allow'] == 'DELETE,GET,HEAD,OPTIONS,PUT'
assert body == b''
def test_book_bookid_other(self):
controller = SubscriberController()
status, _headers, _body = utils.invoke(
controller, '/1234/books/5678',
method='OTHER',
)
assert status == '501 Not Implemented'
| true | true |
1c3fd1a1d43154bc61a1a422c1177bc1c1c2e413 | 424 | py | Python | library_member/__manifest__.py | jhonaelramos/Odoo-14-Development-Essentials | 52d1317c67b629233f5e246105d452018ae01700 | [
"MIT"
] | 8 | 2020-06-29T15:23:01.000Z | 2021-11-08T13:10:50.000Z | library_member/__manifest__.py | jhonaelramos/Odoo-14-Development-Essentials | 52d1317c67b629233f5e246105d452018ae01700 | [
"MIT"
] | null | null | null | library_member/__manifest__.py | jhonaelramos/Odoo-14-Development-Essentials | 52d1317c67b629233f5e246105d452018ae01700 | [
"MIT"
] | 11 | 2020-08-31T13:39:00.000Z | 2021-11-06T13:05:07.000Z | {
"name": "Library Members",
"description": "Manage members borrowing books.",
"author": "Daniel Reis",
"depends": ["library_app", "mail"],
"application": False,
"data": [
"security/library_security.xml",
"security/ir.model.access.csv",
"views/book_view.xml",
"views/member_view.xml",
"views/library_menu.xml",
"views/book_list_template.xml",
],
}
| 26.5 | 53 | 0.582547 | {
"name": "Library Members",
"description": "Manage members borrowing books.",
"author": "Daniel Reis",
"depends": ["library_app", "mail"],
"application": False,
"data": [
"security/library_security.xml",
"security/ir.model.access.csv",
"views/book_view.xml",
"views/member_view.xml",
"views/library_menu.xml",
"views/book_list_template.xml",
],
}
| true | true |
1c3fd2c55334fd038f3412b030377b167a93d36d | 1,037 | py | Python | Django/DjangoT3.2_LTS/06 Pagination dan queryset pada ListView/blog/views.py | Akhadafi/WEB-Framework | 4547a682ac1f007aa6f97512baf76b92ef1c9b9a | [
"MIT"
] | null | null | null | Django/DjangoT3.2_LTS/06 Pagination dan queryset pada ListView/blog/views.py | Akhadafi/WEB-Framework | 4547a682ac1f007aa6f97512baf76b92ef1c9b9a | [
"MIT"
] | null | null | null | Django/DjangoT3.2_LTS/06 Pagination dan queryset pada ListView/blog/views.py | Akhadafi/WEB-Framework | 4547a682ac1f007aa6f97512baf76b92ef1c9b9a | [
"MIT"
] | null | null | null | from django.shortcuts import render
from django.views.generic import ListView
from .models import Artikel
# Create your views here.
class ArtikelListView(ListView):
model = Artikel
# urut berdasarkan
ordering = ["judul"]
# membagi halaman
paginate_by = 2
extra_context = {
"judul": "Blog List",
}
def get_queryset(self):
if self.kwargs["penulis"] != "all":
self.queryset = self.model.objects.filter(
penulis__iexact=self.kwargs["penulis"]
)
self.kwargs.update(
{
"punulis": self.kwargs["penulis"],
}
)
return super().get_queryset()
def get_context_data(self, *args, **kwargs):
self.kwargs.update(self.extra_context)
kwargs = self.kwargs
print(kwargs)
return super().get_context_data(*args, **kwargs)
def index(request):
context = {
"judul": "Blog",
}
return render(request, "blog/index.html", context)
| 24.690476 | 56 | 0.577628 | from django.shortcuts import render
from django.views.generic import ListView
from .models import Artikel
class ArtikelListView(ListView):
model = Artikel
ordering = ["judul"]
paginate_by = 2
extra_context = {
"judul": "Blog List",
}
def get_queryset(self):
if self.kwargs["penulis"] != "all":
self.queryset = self.model.objects.filter(
penulis__iexact=self.kwargs["penulis"]
)
self.kwargs.update(
{
"punulis": self.kwargs["penulis"],
}
)
return super().get_queryset()
def get_context_data(self, *args, **kwargs):
self.kwargs.update(self.extra_context)
kwargs = self.kwargs
print(kwargs)
return super().get_context_data(*args, **kwargs)
def index(request):
context = {
"judul": "Blog",
}
return render(request, "blog/index.html", context)
| true | true |
1c3fd34730bf6106bb035873310bd6717278ea53 | 3,724 | py | Python | server/migrations/versions/5e634fc119ae_.py | TheKnarf/proost-app | 7b7b9a20d6a9ca51424421e62765c7c26e4c4b78 | [
"Apache-2.0"
] | 6 | 2019-11-20T17:25:09.000Z | 2019-12-06T11:07:21.000Z | server/migrations/versions/5e634fc119ae_.py | TheKnarf/proost-app | 7b7b9a20d6a9ca51424421e62765c7c26e4c4b78 | [
"Apache-2.0"
] | 6 | 2019-12-10T18:26:51.000Z | 2021-10-06T07:40:51.000Z | server/migrations/versions/5e634fc119ae_.py | itso-io/aika | 86f333edcd3ad2d3125cbbd6c9f37764c8e05848 | [
"Unlicense"
] | 1 | 2019-12-06T11:08:57.000Z | 2019-12-06T11:08:57.000Z | """empty message
Revision ID: 5e634fc119ae
Revises: 3368ac633bb4
Create Date: 2019-10-09 21:52:05.255230
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '5e634fc119ae'
down_revision = '3368ac633bb4'
branch_labels = None
depends_on = None
def upgrade(engine_name):
globals()["upgrade_%s" % engine_name]()
def downgrade(engine_name):
globals()["downgrade_%s" % engine_name]()
def upgrade_():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('user', sa.Column('time_created', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True))
op.add_column('user', sa.Column('time_updated', sa.DateTime(timezone=True), nullable=True))
op.add_column('user_databases', sa.Column('time_created', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True))
op.add_column('user_databases', sa.Column('time_updated', sa.DateTime(timezone=True), nullable=True))
# ### end Alembic commands ###
def downgrade_():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('user_databases', 'time_updated')
op.drop_column('user_databases', 'time_created')
op.drop_column('user', 'time_updated')
op.drop_column('user', 'time_created')
# ### end Alembic commands ###
def upgrade_user_db():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('event_attendees')
op.drop_table('events')
# ### end Alembic commands ###
def downgrade_user_db():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('events',
sa.Column('id', mysql.VARCHAR(length=100), nullable=False),
sa.Column('calendar_id', mysql.VARCHAR(length=150), nullable=True),
sa.Column('created_at', mysql.TIMESTAMP(), nullable=True),
sa.Column('organizer_email', mysql.VARCHAR(length=200), nullable=True),
sa.Column('is_recurring', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True),
sa.Column('title', mysql.VARCHAR(length=500), nullable=True),
sa.Column('location', mysql.VARCHAR(length=500), nullable=True),
sa.Column('start_time', mysql.TIMESTAMP(), nullable=True),
sa.Column('end_time', mysql.TIMESTAMP(), nullable=True),
sa.Column('description', mysql.VARCHAR(length=5000), nullable=True),
sa.CheckConstraint('(`is_recurring` in (0,1))', name='events_chk_1'),
sa.PrimaryKeyConstraint('id'),
mysql_default_charset='utf8',
mysql_engine='InnoDB'
)
op.create_table('event_attendees',
sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
sa.Column('event_id', mysql.VARCHAR(length=100), nullable=True),
sa.Column('email', mysql.VARCHAR(length=200), nullable=True),
sa.Column('working_hours_start_time', mysql.TIME(), nullable=True),
sa.Column('working_hours_end_time', mysql.TIME(), nullable=True),
sa.Column('display_name', mysql.VARCHAR(length=200), nullable=True),
sa.Column('response_status', mysql.VARCHAR(length=20), nullable=True),
sa.Column('is_organizer', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True),
sa.Column('is_optional', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True),
sa.CheckConstraint('(`is_optional` in (0,1))', name='event_attendees_chk_2'),
sa.CheckConstraint('(`is_organizer` in (0,1))', name='event_attendees_chk_1'),
sa.ForeignKeyConstraint(['event_id'], ['events.id'], name='event_attendees_ibfk_1'),
sa.PrimaryKeyConstraint('id'),
mysql_default_charset='utf8',
mysql_engine='InnoDB'
)
# ### end Alembic commands ###
| 40.478261 | 138 | 0.707304 | from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
revision = '5e634fc119ae'
down_revision = '3368ac633bb4'
branch_labels = None
depends_on = None
def upgrade(engine_name):
globals()["upgrade_%s" % engine_name]()
def downgrade(engine_name):
globals()["downgrade_%s" % engine_name]()
def upgrade_():
, sa.DateTime(timezone=True), nullable=True))
op.add_column('user_databases', sa.Column('time_created', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True))
op.add_column('user_databases', sa.Column('time_updated', sa.DateTime(timezone=True), nullable=True))
h=500), nullable=True),
sa.Column('location', mysql.VARCHAR(length=500), nullable=True),
sa.Column('start_time', mysql.TIMESTAMP(), nullable=True),
sa.Column('end_time', mysql.TIMESTAMP(), nullable=True),
sa.Column('description', mysql.VARCHAR(length=5000), nullable=True),
sa.CheckConstraint('(`is_recurring` in (0,1))', name='events_chk_1'),
sa.PrimaryKeyConstraint('id'),
mysql_default_charset='utf8',
mysql_engine='InnoDB'
)
op.create_table('event_attendees',
sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
sa.Column('event_id', mysql.VARCHAR(length=100), nullable=True),
sa.Column('email', mysql.VARCHAR(length=200), nullable=True),
sa.Column('working_hours_start_time', mysql.TIME(), nullable=True),
sa.Column('working_hours_end_time', mysql.TIME(), nullable=True),
sa.Column('display_name', mysql.VARCHAR(length=200), nullable=True),
sa.Column('response_status', mysql.VARCHAR(length=20), nullable=True),
sa.Column('is_organizer', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True),
sa.Column('is_optional', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True),
sa.CheckConstraint('(`is_optional` in (0,1))', name='event_attendees_chk_2'),
sa.CheckConstraint('(`is_organizer` in (0,1))', name='event_attendees_chk_1'),
sa.ForeignKeyConstraint(['event_id'], ['events.id'], name='event_attendees_ibfk_1'),
sa.PrimaryKeyConstraint('id'),
mysql_default_charset='utf8',
mysql_engine='InnoDB'
)
| true | true |
1c3fd38688bd2384d0ceb47363edfc9a526b2e63 | 2,883 | py | Python | classy/migrations/0018_auto_20180306_1051.py | Krocodial/DSC | 91063b06b536e732e655ce7f1ad0b7c2caa61e0d | [
"Apache-2.0"
] | null | null | null | classy/migrations/0018_auto_20180306_1051.py | Krocodial/DSC | 91063b06b536e732e655ce7f1ad0b7c2caa61e0d | [
"Apache-2.0"
] | null | null | null | classy/migrations/0018_auto_20180306_1051.py | Krocodial/DSC | 91063b06b536e732e655ce7f1ad0b7c2caa61e0d | [
"Apache-2.0"
] | null | null | null | # Generated by Django 2.0.1 on 2018-03-06 18:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('classy', '0017_classification_review_classy_id'),
]
operations = [
migrations.AlterField(
model_name='classification',
name='column_name',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification',
name='created_by',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification',
name='datasource_description',
field=models.CharField(default='', max_length=200),
preserve_default=False,
),
migrations.AlterField(
model_name='classification',
name='schema',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification',
name='state',
field=models.CharField(choices=[('Active', 0), ('Inactive', 1), ('Pending Review', 2)], default='Active', max_length=15),
),
migrations.AlterField(
model_name='classification',
name='table_name',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_logs',
name='user_id',
field=models.CharField(default='', max_length=100),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_review',
name='column_name',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_review',
name='datasource_description',
field=models.CharField(default='', max_length=100),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_review',
name='schema',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_review',
name='table_name',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_review',
name='user',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
]
| 33.917647 | 133 | 0.57232 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('classy', '0017_classification_review_classy_id'),
]
operations = [
migrations.AlterField(
model_name='classification',
name='column_name',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification',
name='created_by',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification',
name='datasource_description',
field=models.CharField(default='', max_length=200),
preserve_default=False,
),
migrations.AlterField(
model_name='classification',
name='schema',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification',
name='state',
field=models.CharField(choices=[('Active', 0), ('Inactive', 1), ('Pending Review', 2)], default='Active', max_length=15),
),
migrations.AlterField(
model_name='classification',
name='table_name',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_logs',
name='user_id',
field=models.CharField(default='', max_length=100),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_review',
name='column_name',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_review',
name='datasource_description',
field=models.CharField(default='', max_length=100),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_review',
name='schema',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_review',
name='table_name',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='classification_review',
name='user',
field=models.CharField(default='', max_length=50),
preserve_default=False,
),
]
| true | true |
1c3fd3b3cd4e5e6f759361f63f2b7ee6e61e7c88 | 13,290 | py | Python | simpletransformers/experimental/classification/classification_utils.py | kinoute/simpletransformers | c14d01c8011cbdbf51996f07fc2fbe3d3c433f46 | [
"Apache-2.0"
] | 4 | 2020-03-06T00:03:22.000Z | 2021-01-21T14:07:25.000Z | simpletransformers/experimental/classification/classification_utils.py | kinoute/simpletransformers | c14d01c8011cbdbf51996f07fc2fbe3d3c433f46 | [
"Apache-2.0"
] | 4 | 2019-12-24T10:55:32.000Z | 2020-03-27T02:19:07.000Z | simpletransformers/experimental/classification/classification_utils.py | kinoute/simpletransformers | c14d01c8011cbdbf51996f07fc2fbe3d3c433f46 | [
"Apache-2.0"
] | 1 | 2021-01-21T14:36:55.000Z | 2021-01-21T14:36:55.000Z | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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.
""" BERT classification fine-tuning: utilities to work with GLUE tasks """
from __future__ import absolute_import, division, print_function
import os
import sys
import csv
import logging
from io import open
from multiprocessing import Pool, cpu_count
from tqdm.auto import tqdm
from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import matthews_corrcoef, f1_score
logger = logging.getLogger(__name__)
csv.field_size_limit(2147483647)
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None):
"""
Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
Only must be specified for sequence pair tasks.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.label = label
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, input_ids, input_mask, segment_ids, label_id):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id
def convert_example_to_feature(
example_row,
pad_token=0,
sequence_a_segment_id=0,
sequence_b_segment_id=1,
cls_token_segment_id=1,
pad_token_segment_id=0,
mask_padding_with_zero=True,
sep_token_extra=False
):
example, max_seq_length, tokenizer, output_mode, cls_token_at_end, cls_token, sep_token, cls_token_segment_id, pad_on_left, pad_token_segment_id, sep_token_extra, multi_label = example_row
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
# Modifies `tokens_a` and `tokens_b` in place so that the total
# length is less than the specified length.
# Account for [CLS], [SEP], [SEP] with "- 3". " -4" for RoBERTa.
special_tokens_count = 4 if sep_token_extra else 3
_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - special_tokens_count)
else:
# Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
special_tokens_count = 3 if sep_token_extra else 2
if len(tokens_a) > max_seq_length - special_tokens_count:
tokens_a = tokens_a[:(max_seq_length - special_tokens_count)]
# The convention in BERT is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
tokens = tokens_a + [sep_token]
segment_ids = [sequence_a_segment_id] * len(tokens)
if tokens_b:
tokens += tokens_b + [sep_token]
segment_ids += [sequence_b_segment_id] * (len(tokens_b) + 1)
if cls_token_at_end:
tokens = tokens + [cls_token]
segment_ids = segment_ids + [cls_token_segment_id]
else:
tokens = [cls_token] + tokens
segment_ids = [cls_token_segment_id] + segment_ids
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
# Zero-pad up to the sequence length.
padding_length = max_seq_length - len(input_ids)
if pad_on_left:
input_ids = ([pad_token] * padding_length) + input_ids
input_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
segment_ids = ([pad_token_segment_id] * padding_length) + segment_ids
else:
input_ids = input_ids + ([pad_token] * padding_length)
input_mask = input_mask + ([0 if mask_padding_with_zero else 1] * padding_length)
segment_ids = segment_ids + ([pad_token_segment_id] * padding_length)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
# if output_mode == "classification":
# label_id = label_map[example.label]
# elif output_mode == "regression":
# label_id = float(example.label)
# else:
# raise KeyError(output_mode)
return InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=example.label
)
def convert_example_to_feature_sliding_window(
example_row,
pad_token=0,
sequence_a_segment_id=0,
sequence_b_segment_id=1,
cls_token_segment_id=1,
pad_token_segment_id=0,
mask_padding_with_zero=True,
sep_token_extra=False,
):
example, max_seq_length, tokenizer, output_mode, cls_token_at_end, cls_token, sep_token, cls_token_segment_id, pad_on_left, pad_token_segment_id, sep_token_extra, multi_label, stride = example_row
if stride < 1:
stride = int(max_seq_length * stride)
bucket_size = max_seq_length - (3 if sep_token_extra else 2)
token_sets = []
tokens_a = tokenizer.tokenize(example.text_a)
special_tokens_count = 3 if sep_token_extra else 2
if len(tokens_a) > bucket_size:
token_sets = [tokens_a[i:i + bucket_size] for i in range(0, len(tokens_a), stride)]
else:
token_sets.append(tokens_a)
if example.text_b:
raise ValueError("Sequence pair tasks not implemented for sliding window tokenization.")
# The convention in BERT is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
input_features = []
for tokens_a in token_sets:
tokens = tokens_a + [sep_token]
segment_ids = [sequence_a_segment_id] * len(tokens)
if cls_token_at_end:
tokens = tokens + [cls_token]
segment_ids = segment_ids + [cls_token_segment_id]
else:
tokens = [cls_token] + tokens
segment_ids = [cls_token_segment_id] + segment_ids
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
# Zero-pad up to the sequence length.
padding_length = max_seq_length - len(input_ids)
if pad_on_left:
input_ids = ([pad_token] * padding_length) + input_ids
input_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
segment_ids = ([pad_token_segment_id] * padding_length) + segment_ids
else:
input_ids = input_ids + ([pad_token] * padding_length)
input_mask = input_mask + ([0 if mask_padding_with_zero else 1] * padding_length)
segment_ids = segment_ids + ([pad_token_segment_id] * padding_length)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
# if output_mode == "classification":
# label_id = label_map[example.label]
# elif output_mode == "regression":
# label_id = float(example.label)
# else:
# raise KeyError(output_mode)
input_features.append(
InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=example.label
)
)
return input_features
def convert_examples_to_features(
examples,
max_seq_length,
tokenizer,
output_mode,
cls_token_at_end=False,
sep_token_extra=False,
pad_on_left=False,
cls_token="[CLS]",
sep_token="[SEP]",
pad_token=0,
sequence_a_segment_id=0,
sequence_b_segment_id=1,
cls_token_segment_id=1,
pad_token_segment_id=0,
mask_padding_with_zero=True,
process_count=cpu_count() - 2,
multi_label=False,
silent=False,
use_multiprocessing=True,
sliding_window=False,
stride=False
):
""" Loads a data file into a list of `InputBatch`s
`cls_token_at_end` define the location of the CLS token:
- False (Default, BERT/XLM pattern): [CLS] + A + [SEP] + B + [SEP]
- True (XLNet/GPT pattern): A + [SEP] + B + [SEP] + [CLS]
`cls_token_segment_id` define the segment id associated to the CLS token (0 for BERT, 2 for XLNet)
"""
if sliding_window:
if not stride:
stride = 0.9
examples = [(example, max_seq_length, tokenizer, output_mode, cls_token_at_end, cls_token, sep_token, cls_token_segment_id, pad_on_left, pad_token_segment_id, sep_token_extra, multi_label, stride) for example in examples]
if use_multiprocessing:
with Pool(process_count) as p:
features = list(tqdm(p.imap(convert_example_to_feature_sliding_window, examples, chunksize=500), total=len(examples), disable=silent))
else:
features = [convert_example_to_feature_sliding_window(example) for example in tqdm(examples, disable=silent)]
else:
examples = [(example, max_seq_length, tokenizer, output_mode, cls_token_at_end, cls_token, sep_token, cls_token_segment_id, pad_on_left, pad_token_segment_id, sep_token_extra, multi_label) for example in examples]
if use_multiprocessing:
with Pool(process_count) as p:
features = list(tqdm(p.imap(convert_example_to_feature, examples, chunksize=500), total=len(examples), disable=silent))
else:
features = [convert_example_to_feature(example) for example in tqdm(examples, disable=silent)]
return features
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
| 40.03012 | 229 | 0.666441 |
from __future__ import absolute_import, division, print_function
import os
import sys
import csv
import logging
from io import open
from multiprocessing import Pool, cpu_count
from tqdm.auto import tqdm
from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import matthews_corrcoef, f1_score
logger = logging.getLogger(__name__)
csv.field_size_limit(2147483647)
class InputExample(object):
def __init__(self, guid, text_a, text_b=None, label=None):
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.label = label
class InputFeatures(object):
def __init__(self, input_ids, input_mask, segment_ids, label_id):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id
def convert_example_to_feature(
example_row,
pad_token=0,
sequence_a_segment_id=0,
sequence_b_segment_id=1,
cls_token_segment_id=1,
pad_token_segment_id=0,
mask_padding_with_zero=True,
sep_token_extra=False
):
example, max_seq_length, tokenizer, output_mode, cls_token_at_end, cls_token, sep_token, cls_token_segment_id, pad_on_left, pad_token_segment_id, sep_token_extra, multi_label = example_row
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
special_tokens_count = 4 if sep_token_extra else 3
_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - special_tokens_count)
else:
special_tokens_count = 3 if sep_token_extra else 2
if len(tokens_a) > max_seq_length - special_tokens_count:
tokens_a = tokens_a[:(max_seq_length - special_tokens_count)]
* len(tokens)
if tokens_b:
tokens += tokens_b + [sep_token]
segment_ids += [sequence_b_segment_id] * (len(tokens_b) + 1)
if cls_token_at_end:
tokens = tokens + [cls_token]
segment_ids = segment_ids + [cls_token_segment_id]
else:
tokens = [cls_token] + tokens
segment_ids = [cls_token_segment_id] + segment_ids
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
padding_length = max_seq_length - len(input_ids)
if pad_on_left:
input_ids = ([pad_token] * padding_length) + input_ids
input_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
segment_ids = ([pad_token_segment_id] * padding_length) + segment_ids
else:
input_ids = input_ids + ([pad_token] * padding_length)
input_mask = input_mask + ([0 if mask_padding_with_zero else 1] * padding_length)
segment_ids = segment_ids + ([pad_token_segment_id] * padding_length)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
return InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=example.label
)
def convert_example_to_feature_sliding_window(
example_row,
pad_token=0,
sequence_a_segment_id=0,
sequence_b_segment_id=1,
cls_token_segment_id=1,
pad_token_segment_id=0,
mask_padding_with_zero=True,
sep_token_extra=False,
):
example, max_seq_length, tokenizer, output_mode, cls_token_at_end, cls_token, sep_token, cls_token_segment_id, pad_on_left, pad_token_segment_id, sep_token_extra, multi_label, stride = example_row
if stride < 1:
stride = int(max_seq_length * stride)
bucket_size = max_seq_length - (3 if sep_token_extra else 2)
token_sets = []
tokens_a = tokenizer.tokenize(example.text_a)
special_tokens_count = 3 if sep_token_extra else 2
if len(tokens_a) > bucket_size:
token_sets = [tokens_a[i:i + bucket_size] for i in range(0, len(tokens_a), stride)]
else:
token_sets.append(tokens_a)
if example.text_b:
raise ValueError("Sequence pair tasks not implemented for sliding window tokenization.")
ns_a + [sep_token]
segment_ids = [sequence_a_segment_id] * len(tokens)
if cls_token_at_end:
tokens = tokens + [cls_token]
segment_ids = segment_ids + [cls_token_segment_id]
else:
tokens = [cls_token] + tokens
segment_ids = [cls_token_segment_id] + segment_ids
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
padding_length = max_seq_length - len(input_ids)
if pad_on_left:
input_ids = ([pad_token] * padding_length) + input_ids
input_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
segment_ids = ([pad_token_segment_id] * padding_length) + segment_ids
else:
input_ids = input_ids + ([pad_token] * padding_length)
input_mask = input_mask + ([0 if mask_padding_with_zero else 1] * padding_length)
segment_ids = segment_ids + ([pad_token_segment_id] * padding_length)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
input_features.append(
InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=example.label
)
)
return input_features
def convert_examples_to_features(
examples,
max_seq_length,
tokenizer,
output_mode,
cls_token_at_end=False,
sep_token_extra=False,
pad_on_left=False,
cls_token="[CLS]",
sep_token="[SEP]",
pad_token=0,
sequence_a_segment_id=0,
sequence_b_segment_id=1,
cls_token_segment_id=1,
pad_token_segment_id=0,
mask_padding_with_zero=True,
process_count=cpu_count() - 2,
multi_label=False,
silent=False,
use_multiprocessing=True,
sliding_window=False,
stride=False
):
if sliding_window:
if not stride:
stride = 0.9
examples = [(example, max_seq_length, tokenizer, output_mode, cls_token_at_end, cls_token, sep_token, cls_token_segment_id, pad_on_left, pad_token_segment_id, sep_token_extra, multi_label, stride) for example in examples]
if use_multiprocessing:
with Pool(process_count) as p:
features = list(tqdm(p.imap(convert_example_to_feature_sliding_window, examples, chunksize=500), total=len(examples), disable=silent))
else:
features = [convert_example_to_feature_sliding_window(example) for example in tqdm(examples, disable=silent)]
else:
examples = [(example, max_seq_length, tokenizer, output_mode, cls_token_at_end, cls_token, sep_token, cls_token_segment_id, pad_on_left, pad_token_segment_id, sep_token_extra, multi_label) for example in examples]
if use_multiprocessing:
with Pool(process_count) as p:
features = list(tqdm(p.imap(convert_example_to_feature, examples, chunksize=500), total=len(examples), disable=silent))
else:
features = [convert_example_to_feature(example) for example in tqdm(examples, disable=silent)]
return features
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
| true | true |
1c3fd450d13f394c1939457f17417a0da2f33a35 | 12,127 | py | Python | z.mine/test/ExpTestTrainedModel.py | hunsooni/sumo-rl | 92fb5716c22bf71e6fcf976c5e65c9e47f44a2fc | [
"MIT"
] | null | null | null | z.mine/test/ExpTestTrainedModel.py | hunsooni/sumo-rl | 92fb5716c22bf71e6fcf976c5e65c9e47f44a2fc | [
"MIT"
] | null | null | null | z.mine/test/ExpTestTrainedModel.py | hunsooni/sumo-rl | 92fb5716c22bf71e6fcf976c5e65c9e47f44a2fc | [
"MIT"
] | null | null | null |
# from https://github.com/ray-project/ray/blob/master/rllib/examples/custom_keras_model.py
import argparse
import os
import ray
from ray import tune
from ray.rllib.agents.dqn.distributional_q_tf_model import DistributionalQTFModel
from ray.rllib.models import ModelCatalog
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
# from ray.rllib.models.tf.visionnet import VisionNetwork as MyVisionNetwork
from ray.rllib.policy.policy import LEARNER_STATS_KEY
from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID
# from ray.rllib.utils.framework import try_import_tf
#
# tf1, tf, tfv = try_import_tf()
import tensorflow as tf
from ray.tune.registry import register_env
from MyEnvConfig import DEFAULT_CONFIG_SINGLE, DEFAULT_CONFIG_MULTI
from internal.MyTrafficSimulationEnvironment import TrafficSimulationEnvironment
import ray.rllib.agents.ppo as ppo
import ray.rllib.agents.a3c as a3c
from ray.tune.logger import pretty_print
class MyKerasModel(TFModelV2):
"""Custom model for policy gradient algorithms."""
def __init__(self, obs_space, action_space, num_outputs, model_config,
name):
super(MyKerasModel, self).__init__(obs_space, action_space,
num_outputs, model_config, name)
self.inputs = tf.keras.layers.Input(shape=obs_space.shape, name="observations")
layer_1 = tf.keras.layers.Dense(
128,
name="my_layer1",
activation=tf.nn.relu,
kernel_initializer=normc_initializer(1.0))(self.inputs)
layer_out = tf.keras.layers.Dense(
num_outputs,
name="my_out",
activation=None,
kernel_initializer=normc_initializer(0.01))(layer_1)
value_out = tf.keras.layers.Dense(
1,
name="value_out",
activation=None,
kernel_initializer=normc_initializer(0.01))(layer_1)
self.base_model = tf.keras.Model(self.inputs, [layer_out, value_out])
def forward(self, input_dict, state, seq_lens):
model_out, self._value_out = self.base_model(input_dict["obs"])
# sess = tf.Session()
# value=sess.run(model_out)
# print("11111 model_out={}".format(pretty_print(value)))
return model_out, state
def value_function(self):
return tf.reshape(self._value_out, [-1])
def metrics(self):
return {"foo": tf.constant(42.0)}
class MyKerasQModel(DistributionalQTFModel):
"""Custom model for DQN."""
def __init__(self, obs_space, action_space, num_outputs, model_config,
name, **kw):
super(MyKerasQModel, self).__init__(
obs_space, action_space, num_outputs, model_config, name, **kw)
# Define the core model layers which will be used by the other
# output heads of DistributionalQModel
self.inputs = tf.keras.layers.Input(shape=obs_space.shape, name="observations")
layer_1 = tf.keras.layers.Dense(
128,
name="my_layer1",
activation=tf.nn.relu,
kernel_initializer=normc_initializer(1.0))(self.inputs)
layer_out = tf.keras.layers.Dense(
num_outputs,
name="my_out",
activation=tf.nn.relu,
kernel_initializer=normc_initializer(1.0))(layer_1)
self.base_model = tf.keras.Model(self.inputs, layer_out)
# Implement the core forward method.
def forward(self, input_dict, state, seq_lens):
model_out = self.base_model(input_dict["obs"])
return model_out, state
def metrics(self):
return {"foo": tf.constant(42.0)}
def getCfgTrainer(trainer_type):
import ray.rllib.agents.ddpg as ddpg
if trainer_type=="ppo":
return ppo.DEFAULT_CONFIG, ppo.PPOTrainer
elif trainer_type=="a3c":
return a3c.DEFAULT_CONFIG, a3c.A3CTrainer
elif trainer_type=="ddpg":
return ddpg.DEFAULT_CONFIG, ddpg.DDPGTrainer
## 중간에 죽는다....
##
## Simulation ended at time : 899.0
## Reason: TraCI requested termination
def withTrainer_Fail_1(args, env_config, trainer_type="ppo", epoch=1):
ray.init()
register_env("sumo_env", lambda _: TrafficSimulationEnvironment(env_config))
ModelCatalog.register_custom_model("keras_model", MyKerasModel)
ModelCatalog.register_custom_model("keras_q_model", MyKerasQModel)
env_config["gui"]=True
env = TrafficSimulationEnvironment(env_config)
DEFAULT_CONFIG, TRAINER_CLASS = getCfgTrainer(trainer_type)
config = DEFAULT_CONFIG
config["num_gpus"] = 0
config["num_workers"] = 1
config["framework"]="tf" # tf, tf2, tfe, torch
model_config = config["model"]
model_config["custom_model"] = "keras_q_model" if args.run == "DQN" else "keras_model"
config["model"] = model_config
config["explore"] = False
# exploration_cfg = config["exploration_config"]
# agent = TRAINER_CLASS(config=config)
# # ValueError: None is an invalid env specification.
# # You can specify a custom env as either a class (e.g., YourEnvCls) or a registered env id (e.g., "your_env").
agent = TRAINER_CLASS(env="sumo_env", config=config)
checkpoint_path = "/home/developer/ray_results/PPO_sumo_env_2021-07-21_14-29-25zezlzgib/checkpoint_000001/checkpoint-1"
if 0:
agent.load_checkpoint(checkpoint_path=checkpoint_path)
else:
agent.restore(checkpoint_path=checkpoint_path)
episode_reward = 0
done = False
obs = env.reset()
while not done:
print("#####obs=\n{}".format(pretty_print(obs)))
action = agent.compute_actions(obs)
print("##### action={}".format(pretty_print(action)))
obs, reward, done, info = env.step(action)
# episode_reward += reward
# unsupported operand type(s) for +=: 'int' and 'dict'
episode_reward += sum(reward.values())
ray.shutdown()
def withTrainerFail_2(args, env_config, trainer_type="ppo", epoch=1):
ray.init()
register_env("sumo_env", lambda _: TrafficSimulationEnvironment(env_config))
ModelCatalog.register_custom_model("keras_model", MyKerasModel)
ModelCatalog.register_custom_model("keras_q_model", MyKerasQModel)
# env_config["gui"]=True
# env = TrafficSimulationEnvironment(env_config)
DEFAULT_CONFIG, TRAINER_CLASS = getCfgTrainer(trainer_type)
config = DEFAULT_CONFIG
config["num_gpus"] = 0
config["num_workers"] = 0
config["framework"]="tf" # tf, tf2, tfe, torch
model_config = config["model"]
model_config["custom_model"] = "keras_q_model" if args.run == "DQN" else "keras_model"
config["model"] = model_config
config["explore"] = False
# exploration_cfg = config["exploration_config"]
# agent = TRAINER_CLASS(config=config)
# # ValueError: None is an invalid env specification.
# # You can specify a custom env as either a class (e.g., YourEnvCls) or a registered env id (e.g., "your_env").
agent = TRAINER_CLASS(env="sumo_env", config=config)
#checkpoint_path = "/home/developer/ray_results/PPO_sumo_env_2021-07-21_14-29-25zezlzgib/checkpoint_000001/checkpoint-1"
checkpoint_path = "/home/developer/ray_results/PPO_sumo_env_2021-07-21_16-53-23vgsl8di4/checkpoint_000009/checkpoint-9"
if 0:
agent.load_checkpoint(checkpoint_path=checkpoint_path)
else:
agent.restore(checkpoint_path=checkpoint_path)
env = agent.env_creator(env_config) ##
episode_reward = 0
done = False
obs = env.reset()
while not done:
print("#####obs=\n{}".format(pretty_print(obs)))
action = agent.compute_actions(obs)
print("##### action={}".format(pretty_print(action)))
obs, reward, done, info = env.step(action)
# episode_reward += reward
# unsupported operand type(s) for +=: 'int' and 'dict'
episode_reward += sum(reward.values())
ray.shutdown()
def withTrainer(args, env_config, trainer_type="ppo", epoch=1):
ray.init()
#env_config["gui"] = True
register_env("sumo_env", lambda _: TrafficSimulationEnvironment(env_config))
ModelCatalog.register_custom_model("keras_model", MyKerasModel)
ModelCatalog.register_custom_model("keras_q_model", MyKerasQModel)
# env_config["gui"]=True
# env = TrafficSimulationEnvironment(env_config)
DEFAULT_CONFIG, TRAINER_CLASS = getCfgTrainer(trainer_type)
config = DEFAULT_CONFIG
config["num_gpus"] = 0
config["num_workers"] = 0
config["framework"] = "tf" # tf, tf2, tfe, torch
model_config = config["model"]
model_config["custom_model"] = "keras_q_model" if args.run == "DQN" else "keras_model"
config["model"] = model_config
config["explore"] = False
# exploration_cfg = config["exploration_config"]
# agent = TRAINER_CLASS(config=config)
# # ValueError: None is an invalid env specification.
# # You can specify a custom env as either a class (e.g., YourEnvCls) or a registered env id (e.g., "your_env").
agent = TRAINER_CLASS(env="sumo_env", config=config)
# checkpoint_path = "/home/developer/ray_results/PPO_sumo_env_2021-07-21_14-29-25zezlzgib/checkpoint_000001/checkpoint-1"
checkpoint_path = "/home/developer/ray_results/PPO_sumo_env_2021-07-21_16-53-23vgsl8di4/checkpoint_000009/checkpoint-9"
if 0:
agent.load_checkpoint(checkpoint_path=checkpoint_path)
else:
agent.restore(checkpoint_path=checkpoint_path)
result = agent.evaluate()
print(result)
#
# env = agent.env_creator(env_config) ##
#
# episode_reward = 0
# done = False
# obs = env.reset()
# while not done:
# print("#####obs=\n{}".format(pretty_print(obs)))
#
# action = agent.compute_actions(obs)
# print("##### action={}".format(pretty_print(action)))
#
# obs, reward, done, info = env.step(action)
#
# # episode_reward += reward
# # unsupported operand type(s) for +=: 'int' and 'dict'
# episode_reward += sum(reward.values())
print("before ray.shutdown()")
ray.shutdown()
print("after ray.shutdown()")
def withTune(args, env_config, trainer_type="ppo"):
# https://discuss.ray.io/t/restore-agent-and-continue-training-with-tune-run/2791
ray.init()
register_env("sumo_env", lambda _: TrafficSimulationEnvironment(env_config))
ModelCatalog.register_custom_model("keras_model", MyKerasModel)
ModelCatalog.register_custom_model("keras_q_model", MyKerasQModel)
DEFAULT_CONFIG, TRAINER_CLASS = getCfgTrainer(trainer_type)
config = DEFAULT_CONFIG
config["num_gpus"] = 0
config["num_workers"] = 0
config["framework"] = "tf" # tf, tf2, tfe, torch
model_config = config["model"]
model_config["custom_model"] = "keras_q_model" if args.run == "DQN" else "keras_model"
config["model"] = model_config
config["explore"] = False
config["env"] = "sumo_env"
checkpoint_path = "/home/developer/ray_results/PPO_sumo_env_2021-07-21_16-53-23vgsl8di4/checkpoint_000009/checkpoint-9"
tune.run(TRAINER_CLASS, name="restoredExp", restore=checkpoint_path, config=config)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--run",
type=str,
# default="DQN",
default="PPO",
help="The RLlib-registered algorithm to use.")
parser.add_argument("--stop", type=int, default=200)
parser.add_argument("--use-vision-network", action="store_true")
parser.add_argument("--num-cpus", type=int, default=0)
args = parser.parse_args()
# ray.init(num_cpus=args.num_cpus or None)
if os.environ.get("UNIQ_OPT_HOME") is None:
os.environ["UNIQ_OPT_HOME"] = os.getcwd()
env_config = DEFAULT_CONFIG_SINGLE
env_config["gui"] = False
env_config["action_type"] = "phase_split"
env_config["out_csv_name"] = "outputs/rllib_single"
withTrainer(args, env_config, trainer_type="ppo") # not work
# withTune(args, env_config, trainer_type="ppo") # not tested yet
| 35.049133 | 125 | 0.681372 |
import argparse
import os
import ray
from ray import tune
from ray.rllib.agents.dqn.distributional_q_tf_model import DistributionalQTFModel
from ray.rllib.models import ModelCatalog
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.policy.policy import LEARNER_STATS_KEY
from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID
import tensorflow as tf
from ray.tune.registry import register_env
from MyEnvConfig import DEFAULT_CONFIG_SINGLE, DEFAULT_CONFIG_MULTI
from internal.MyTrafficSimulationEnvironment import TrafficSimulationEnvironment
import ray.rllib.agents.ppo as ppo
import ray.rllib.agents.a3c as a3c
from ray.tune.logger import pretty_print
class MyKerasModel(TFModelV2):
def __init__(self, obs_space, action_space, num_outputs, model_config,
name):
super(MyKerasModel, self).__init__(obs_space, action_space,
num_outputs, model_config, name)
self.inputs = tf.keras.layers.Input(shape=obs_space.shape, name="observations")
layer_1 = tf.keras.layers.Dense(
128,
name="my_layer1",
activation=tf.nn.relu,
kernel_initializer=normc_initializer(1.0))(self.inputs)
layer_out = tf.keras.layers.Dense(
num_outputs,
name="my_out",
activation=None,
kernel_initializer=normc_initializer(0.01))(layer_1)
value_out = tf.keras.layers.Dense(
1,
name="value_out",
activation=None,
kernel_initializer=normc_initializer(0.01))(layer_1)
self.base_model = tf.keras.Model(self.inputs, [layer_out, value_out])
def forward(self, input_dict, state, seq_lens):
model_out, self._value_out = self.base_model(input_dict["obs"])
return model_out, state
def value_function(self):
return tf.reshape(self._value_out, [-1])
def metrics(self):
return {"foo": tf.constant(42.0)}
class MyKerasQModel(DistributionalQTFModel):
def __init__(self, obs_space, action_space, num_outputs, model_config,
name, **kw):
super(MyKerasQModel, self).__init__(
obs_space, action_space, num_outputs, model_config, name, **kw)
self.inputs = tf.keras.layers.Input(shape=obs_space.shape, name="observations")
layer_1 = tf.keras.layers.Dense(
128,
name="my_layer1",
activation=tf.nn.relu,
kernel_initializer=normc_initializer(1.0))(self.inputs)
layer_out = tf.keras.layers.Dense(
num_outputs,
name="my_out",
activation=tf.nn.relu,
kernel_initializer=normc_initializer(1.0))(layer_1)
self.base_model = tf.keras.Model(self.inputs, layer_out)
def forward(self, input_dict, state, seq_lens):
model_out = self.base_model(input_dict["obs"])
return model_out, state
def metrics(self):
return {"foo": tf.constant(42.0)}
def getCfgTrainer(trainer_type):
import ray.rllib.agents.ddpg as ddpg
if trainer_type=="ppo":
return ppo.DEFAULT_CONFIG, ppo.PPOTrainer
elif trainer_type=="a3c":
return a3c.DEFAULT_CONFIG, a3c.A3CTrainer
elif trainer_type=="ddpg":
return ddpg.DEFAULT_CONFIG, ddpg.DDPGTrainer
nit()
register_env("sumo_env", lambda _: TrafficSimulationEnvironment(env_config))
ModelCatalog.register_custom_model("keras_model", MyKerasModel)
ModelCatalog.register_custom_model("keras_q_model", MyKerasQModel)
env_config["gui"]=True
env = TrafficSimulationEnvironment(env_config)
DEFAULT_CONFIG, TRAINER_CLASS = getCfgTrainer(trainer_type)
config = DEFAULT_CONFIG
config["num_gpus"] = 0
config["num_workers"] = 1
config["framework"]="tf"
model_config = config["model"]
model_config["custom_model"] = "keras_q_model" if args.run == "DQN" else "keras_model"
config["model"] = model_config
config["explore"] = False
kpoint_000001/checkpoint-1"
if 0:
agent.load_checkpoint(checkpoint_path=checkpoint_path)
else:
agent.restore(checkpoint_path=checkpoint_path)
episode_reward = 0
done = False
obs = env.reset()
while not done:
print("#####obs=\n{}".format(pretty_print(obs)))
action = agent.compute_actions(obs)
print("##### action={}".format(pretty_print(action)))
obs, reward, done, info = env.step(action)
episode_reward += sum(reward.values())
ray.shutdown()
def withTrainerFail_2(args, env_config, trainer_type="ppo", epoch=1):
ray.init()
register_env("sumo_env", lambda _: TrafficSimulationEnvironment(env_config))
ModelCatalog.register_custom_model("keras_model", MyKerasModel)
ModelCatalog.register_custom_model("keras_q_model", MyKerasQModel)
DEFAULT_CONFIG, TRAINER_CLASS = getCfgTrainer(trainer_type)
config = DEFAULT_CONFIG
config["num_gpus"] = 0
config["num_workers"] = 0
config["framework"]="tf"
model_config = config["model"]
model_config["custom_model"] = "keras_q_model" if args.run == "DQN" else "keras_model"
config["model"] = model_config
config["explore"] = False
/checkpoint_000009/checkpoint-9"
if 0:
agent.load_checkpoint(checkpoint_path=checkpoint_path)
else:
agent.restore(checkpoint_path=checkpoint_path)
env = agent.env_creator(env_config)
episode_reward = 0
done = False
obs = env.reset()
while not done:
print("#####obs=\n{}".format(pretty_print(obs)))
action = agent.compute_actions(obs)
print("##### action={}".format(pretty_print(action)))
obs, reward, done, info = env.step(action)
episode_reward += sum(reward.values())
ray.shutdown()
def withTrainer(args, env_config, trainer_type="ppo", epoch=1):
ray.init()
register_env("sumo_env", lambda _: TrafficSimulationEnvironment(env_config))
ModelCatalog.register_custom_model("keras_model", MyKerasModel)
ModelCatalog.register_custom_model("keras_q_model", MyKerasQModel)
DEFAULT_CONFIG, TRAINER_CLASS = getCfgTrainer(trainer_type)
config = DEFAULT_CONFIG
config["num_gpus"] = 0
config["num_workers"] = 0
config["framework"] = "tf"
model_config = config["model"]
model_config["custom_model"] = "keras_q_model" if args.run == "DQN" else "keras_model"
config["model"] = model_config
config["explore"] = False
/checkpoint_000009/checkpoint-9"
if 0:
agent.load_checkpoint(checkpoint_path=checkpoint_path)
else:
agent.restore(checkpoint_path=checkpoint_path)
result = agent.evaluate()
print(result)
er ray.shutdown()")
def withTune(args, env_config, trainer_type="ppo"):
ray.init()
register_env("sumo_env", lambda _: TrafficSimulationEnvironment(env_config))
ModelCatalog.register_custom_model("keras_model", MyKerasModel)
ModelCatalog.register_custom_model("keras_q_model", MyKerasQModel)
DEFAULT_CONFIG, TRAINER_CLASS = getCfgTrainer(trainer_type)
config = DEFAULT_CONFIG
config["num_gpus"] = 0
config["num_workers"] = 0
config["framework"] = "tf"
model_config = config["model"]
model_config["custom_model"] = "keras_q_model" if args.run == "DQN" else "keras_model"
config["model"] = model_config
config["explore"] = False
config["env"] = "sumo_env"
checkpoint_path = "/home/developer/ray_results/PPO_sumo_env_2021-07-21_16-53-23vgsl8di4/checkpoint_000009/checkpoint-9"
tune.run(TRAINER_CLASS, name="restoredExp", restore=checkpoint_path, config=config)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--run",
type=str,
default="PPO",
help="The RLlib-registered algorithm to use.")
parser.add_argument("--stop", type=int, default=200)
parser.add_argument("--use-vision-network", action="store_true")
parser.add_argument("--num-cpus", type=int, default=0)
args = parser.parse_args()
if os.environ.get("UNIQ_OPT_HOME") is None:
os.environ["UNIQ_OPT_HOME"] = os.getcwd()
env_config = DEFAULT_CONFIG_SINGLE
env_config["gui"] = False
env_config["action_type"] = "phase_split"
env_config["out_csv_name"] = "outputs/rllib_single"
withTrainer(args, env_config, trainer_type="ppo")
| true | true |
1c3fd582b6c3eb660989a7e8560f197c75a80c2b | 396 | py | Python | app/article/migrations/0018_auto_20200601_1120.py | nabechin/article | 63bbaaaa9c194cc259456c46d8c3ccd0f8ee10c1 | [
"MIT"
] | null | null | null | app/article/migrations/0018_auto_20200601_1120.py | nabechin/article | 63bbaaaa9c194cc259456c46d8c3ccd0f8ee10c1 | [
"MIT"
] | 9 | 2020-07-09T15:29:48.000Z | 2020-07-29T13:05:30.000Z | app/article/migrations/0018_auto_20200601_1120.py | nabechin/article | 63bbaaaa9c194cc259456c46d8c3ccd0f8ee10c1 | [
"MIT"
] | null | null | null | # Generated by Django 2.2.12 on 2020-06-01 11:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('article', '0017_comment_user'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='content',
field=models.TextField(blank=True, max_length=500),
),
]
| 20.842105 | 63 | 0.60101 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('article', '0017_comment_user'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='content',
field=models.TextField(blank=True, max_length=500),
),
]
| true | true |
1c3fd5d5fc441b45465cee3727a99a6456d08b0b | 5,309 | py | Python | horovod/runner/common/util/hosts.py | zarzen/horovod | d3c93d7b97c6158f003dad9aa377fe2bbf194e38 | [
"Apache-2.0"
] | 7,676 | 2019-02-12T02:57:22.000Z | 2022-03-31T21:05:40.000Z | horovod/runner/common/util/hosts.py | zarzen/horovod | d3c93d7b97c6158f003dad9aa377fe2bbf194e38 | [
"Apache-2.0"
] | 2,431 | 2019-02-12T01:34:21.000Z | 2022-03-31T21:43:38.000Z | horovod/runner/common/util/hosts.py | zarzen/horovod | d3c93d7b97c6158f003dad9aa377fe2bbf194e38 | [
"Apache-2.0"
] | 1,557 | 2019-02-12T07:52:15.000Z | 2022-03-31T21:05:43.000Z | # Copyright 2019 Uber Technologies, Inc. All Rights Reserved.
#
# 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 collections
import re
from dataclasses import dataclass
class HostInfo:
def __init__(self, hostname, slots):
self.hostname = hostname
self.slots = slots
@staticmethod
def from_string(host_string):
hostname, slots = host_string.strip().split(':')
return HostInfo(hostname, int(slots))
@dataclass
class SlotInfo:
hostname: str
rank: int
local_rank: int
cross_rank: int
size: int
local_size: int
cross_size: int
def to_response_string(self):
return ','.join(str(v) for v in [self.rank, self.size,
self.local_rank, self.local_size,
self.cross_rank, self.cross_size])
INVALID_SLOT_INFO = SlotInfo(hostname='',
rank=-1, local_rank=-1, cross_rank=-1,
size=-1, local_size=-1, cross_size=-1)
def parse_host_files(filename):
"""
Transform the hostfile into a format of
<IP address> or <host name>:<Number of GPUs>
:param filename: Should be in <IP address> or <host name> slots=<number of GPUs>
:return: Comma separated string of <IP address> or <host name>:<Number of GPUs>
"""
hosts = []
with open(filename, 'r') as f:
for line in f.readlines():
line = line.rstrip()
hostname = line.split()[0]
slots = line.split('=')[1]
hosts.append('{name}:{slots}'.format(name=hostname, slots=slots))
return ','.join(hosts)
def parse_hosts_and_slots(hosts):
host_names = []
host_to_slots = {}
host_list = hosts.split(',')
pattern = re.compile(r'^[\w.-]+:[0-9]+$')
for host in host_list:
if not pattern.match(host.strip()):
raise ValueError('Invalid host input, please make sure it has '
'format as : worker-0:2,worker-1:2.')
hostname, slots = host.strip().split(':')
host_names.append(hostname)
host_to_slots[hostname] = int(slots)
return host_names, host_to_slots
def parse_hosts(hosts_string):
"""Parse a string of comma-separated hostname:slots mappings into a list of HostItem objects.
:param hosts_string: list of addresses and number of processes on each host.
For example:
- 'worker-0:2,worker-1:2'
- '10.11.11.11:4,10.11.11.12:4'
:return: a list of HostInfo objects describing host to slot mappings
:rtype: list[HostInfo]
"""
return [HostInfo.from_string(host_string) for host_string in hosts_string.split(',')]
def get_host_assignments(hosts, min_np, max_np=None):
"""Assign hosts with process capacities (slots) to ranks in the Horovod process.
This function will try to allocate as many as possible processes on the same host to leverage
local network.
:param hosts: list of HostInfo objects describing host and slot capacity
:type hosts: list[HostInfo]
:param min_np: minimum number of processes to be allocated
:type min_np: int
:param max_np: (optional) maximum number of processes to be allocated
:type max_np: int
:return: a list of the allocation of process on hosts in a `SlotInfo` object.
:rtype: list[SlotInfo]
"""
host_ranks = []
cross_ranks = collections.defaultdict(dict)
rank = 0
for host_info in hosts:
ranks = []
for local_rank in range(host_info.slots):
if rank == max_np:
break
ranks.append(rank)
rank += 1
cross_ranks_at_local = cross_ranks[local_rank]
cross_ranks_at_local[host_info.hostname] = len(cross_ranks_at_local)
host_ranks.append((host_info, ranks))
world_size = rank
if world_size < min_np:
raise ValueError('Requested more processes ({}) than there are available slots ({})'
.format(min_np, world_size))
alloc_list = []
for host_info, ranks in host_ranks:
local_size = len(ranks)
for local_rank, rank in enumerate(ranks):
cross_ranks_at_local = cross_ranks[local_rank]
cross_rank = cross_ranks_at_local[host_info.hostname]
cross_size = len(cross_ranks_at_local)
alloc_list.append(
SlotInfo(
hostname=host_info.hostname,
rank=rank,
local_rank=local_rank,
cross_rank=cross_rank,
size=world_size,
local_size=local_size,
cross_size=cross_size))
return alloc_list
| 34.032051 | 97 | 0.618761 |
import collections
import re
from dataclasses import dataclass
class HostInfo:
def __init__(self, hostname, slots):
self.hostname = hostname
self.slots = slots
@staticmethod
def from_string(host_string):
hostname, slots = host_string.strip().split(':')
return HostInfo(hostname, int(slots))
@dataclass
class SlotInfo:
hostname: str
rank: int
local_rank: int
cross_rank: int
size: int
local_size: int
cross_size: int
def to_response_string(self):
return ','.join(str(v) for v in [self.rank, self.size,
self.local_rank, self.local_size,
self.cross_rank, self.cross_size])
INVALID_SLOT_INFO = SlotInfo(hostname='',
rank=-1, local_rank=-1, cross_rank=-1,
size=-1, local_size=-1, cross_size=-1)
def parse_host_files(filename):
hosts = []
with open(filename, 'r') as f:
for line in f.readlines():
line = line.rstrip()
hostname = line.split()[0]
slots = line.split('=')[1]
hosts.append('{name}:{slots}'.format(name=hostname, slots=slots))
return ','.join(hosts)
def parse_hosts_and_slots(hosts):
host_names = []
host_to_slots = {}
host_list = hosts.split(',')
pattern = re.compile(r'^[\w.-]+:[0-9]+$')
for host in host_list:
if not pattern.match(host.strip()):
raise ValueError('Invalid host input, please make sure it has '
'format as : worker-0:2,worker-1:2.')
hostname, slots = host.strip().split(':')
host_names.append(hostname)
host_to_slots[hostname] = int(slots)
return host_names, host_to_slots
def parse_hosts(hosts_string):
return [HostInfo.from_string(host_string) for host_string in hosts_string.split(',')]
def get_host_assignments(hosts, min_np, max_np=None):
host_ranks = []
cross_ranks = collections.defaultdict(dict)
rank = 0
for host_info in hosts:
ranks = []
for local_rank in range(host_info.slots):
if rank == max_np:
break
ranks.append(rank)
rank += 1
cross_ranks_at_local = cross_ranks[local_rank]
cross_ranks_at_local[host_info.hostname] = len(cross_ranks_at_local)
host_ranks.append((host_info, ranks))
world_size = rank
if world_size < min_np:
raise ValueError('Requested more processes ({}) than there are available slots ({})'
.format(min_np, world_size))
alloc_list = []
for host_info, ranks in host_ranks:
local_size = len(ranks)
for local_rank, rank in enumerate(ranks):
cross_ranks_at_local = cross_ranks[local_rank]
cross_rank = cross_ranks_at_local[host_info.hostname]
cross_size = len(cross_ranks_at_local)
alloc_list.append(
SlotInfo(
hostname=host_info.hostname,
rank=rank,
local_rank=local_rank,
cross_rank=cross_rank,
size=world_size,
local_size=local_size,
cross_size=cross_size))
return alloc_list
| true | true |
1c3fd60d60e1b548ab64d419546139d32861b974 | 1,150 | py | Python | libs/ExtractLocation.py | douglask3/UKESM_albedo_tile_optimization | 6f9d39c6fae7d671bf5e455a871ea48cda512aab | [
"BSD-3-Clause"
] | 1 | 2019-10-09T11:57:31.000Z | 2019-10-09T11:57:31.000Z | libs/ExtractLocation.py | douglask3/UKESM-ConFire | 344b07b9f5c230dd3925a05b96a54d127e3dd39c | [
"BSD-3-Clause"
] | null | null | null | libs/ExtractLocation.py | douglask3/UKESM-ConFire | 344b07b9f5c230dd3925a05b96a54d127e3dd39c | [
"BSD-3-Clause"
] | null | null | null | import iris
from pdb import set_trace as browser
class ExtractLocation(object):
def __init__(self, cubes, west= None, east = None, south = None, north = None):
self.lon = self.coordRange2List([west, east])
self.lat = self.coordRange2List([south, north])
def lonRange(cell): return self.lon[0] <= cell <= self.lon[1]
def latRange(cell): return self.lat[0] <= cell <= self.lat[1]
if self.lon is not None:
try:
cubes = cubes.extract(iris.Constraint(longitude = lonRange))
except:
cubes = [cube.extract(iris.Constraint(longitude = lonRange)) for cube in cubes]
if self.lat is not None:
try:
cubes = cubes.extract(iris.Constraint(latitude = latRange))
except:
cubes = [cube.extract(iris.Constraint(latitude = latRange)) for cube in cubes]
self.cubes = cubes
def coordRange2List(self, c):
if c is not None:
if not isinstance(c, list) or len(c) == 1: c = [c, c]
if c[0] is None: return None
return c
| 38.333333 | 95 | 0.564348 | import iris
from pdb import set_trace as browser
class ExtractLocation(object):
def __init__(self, cubes, west= None, east = None, south = None, north = None):
self.lon = self.coordRange2List([west, east])
self.lat = self.coordRange2List([south, north])
def lonRange(cell): return self.lon[0] <= cell <= self.lon[1]
def latRange(cell): return self.lat[0] <= cell <= self.lat[1]
if self.lon is not None:
try:
cubes = cubes.extract(iris.Constraint(longitude = lonRange))
except:
cubes = [cube.extract(iris.Constraint(longitude = lonRange)) for cube in cubes]
if self.lat is not None:
try:
cubes = cubes.extract(iris.Constraint(latitude = latRange))
except:
cubes = [cube.extract(iris.Constraint(latitude = latRange)) for cube in cubes]
self.cubes = cubes
def coordRange2List(self, c):
if c is not None:
if not isinstance(c, list) or len(c) == 1: c = [c, c]
if c[0] is None: return None
return c
| true | true |
1c3fd64e6099747c37dee97de029d91872fabe84 | 155 | py | Python | produtos/apps.py | SolutionUp/SolutionUP-System | 4f341df1a51a43b350e626d47abd207a55edb94d | [
"MIT"
] | 4 | 2021-08-30T01:45:46.000Z | 2022-01-08T18:05:10.000Z | produtos/apps.py | DiskFar/DiskFar-System | dfd687e55cbca03118656d14761eb5de6c5a58a9 | [
"MIT"
] | 6 | 2021-08-29T03:26:48.000Z | 2021-09-24T00:13:11.000Z | produtos/apps.py | DiskFar/DiskFar-System | dfd687e55cbca03118656d14761eb5de6c5a58a9 | [
"MIT"
] | 1 | 2021-08-16T21:21:34.000Z | 2021-08-16T21:21:34.000Z | from django.apps import AppConfig
class EstoqueProdutosConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'produtos'
| 22.142857 | 56 | 0.774194 | from django.apps import AppConfig
class EstoqueProdutosConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'produtos'
| true | true |
1c3fd67199919cae4449110ec7ddd4039586f363 | 5,139 | py | Python | stock_alerter/tests/test_rule.py | aamco-software/product-dev | 02931667ff1a8a97a0f2debdff1618820eb0e0b5 | [
"MIT"
] | 1 | 2020-11-08T22:26:01.000Z | 2020-11-08T22:26:01.000Z | stock_alerter/tests/test_rule.py | aamco-software/product-dev | 02931667ff1a8a97a0f2debdff1618820eb0e0b5 | [
"MIT"
] | null | null | null | stock_alerter/tests/test_rule.py | aamco-software/product-dev | 02931667ff1a8a97a0f2debdff1618820eb0e0b5 | [
"MIT"
] | 4 | 2016-05-26T13:30:59.000Z | 2021-01-18T19:33:55.000Z | import unittest
from datetime import datetime
from ..stock import Stock
from ..rule import PriceRule, TrendRule, AndRule
class PriceRuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
goog = Stock("GOOG")
goog.update(datetime(2014, 2, 10), 11)
cls.exchange = {"GOOG": goog}
def test_a_PriceRule_matches_when_it_meets_the_condition(self):
rule = PriceRule("GOOG", lambda stock: stock.price > 10)
self.assertTrue(rule.matches(self.exchange))
def test_a_PriceRule_is_False_if_the_condition_is_not_met(self):
rule = PriceRule("GOOG", lambda stock: stock.price < 10)
self.assertFalse(rule.matches(self.exchange))
def test_a_PriceRule_is_False_if_the_stock_is_not_in_the_exchange(self):
rule = PriceRule("MSFT", lambda stock: stock.price > 10)
self.assertFalse(rule.matches(self.exchange))
def test_a_PriceRule_is_False_if_the_stock_hasnt_got_an_update_yet(self):
self.exchange["AAPL"] = Stock("AAPL")
rule = PriceRule("AAPL", lambda stock: stock.price > 10)
self.assertFalse(rule.matches(self.exchange))
def test_a_PriceRule_only_depends_on_its_stock(self):
rule = PriceRule("MSFT", lambda stock: stock.price > 10)
self.assertEqual(set(["MSFT"]), rule.depends_on())
class TrendRuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
goog = Stock("GOOG")
goog.update(datetime(2014, 2, 10), 8)
goog.update(datetime(2014, 2, 11), 10)
goog.update(datetime(2014, 2, 12), 12)
msft = Stock("MSFT")
msft.update(datetime(2014, 2, 10), 10)
msft.update(datetime(2014, 2, 11), 10)
msft.update(datetime(2014, 2, 12), 12)
cls.exchange = {"GOOG": goog, "MSFT": msft}
def test_a_TrendRule_matches_if_the_stock_increased_last_3_updates(self):
rule = TrendRule("GOOG")
self.assertTrue(rule.matches(self.exchange))
def test_a_TrendRule_is_False_if_stock_doesnt_increasing_trend(self):
rule = TrendRule("MSFT")
self.assertFalse(rule.matches(self.exchange))
def test_a_TrendRule_is_False_if_stock_is_not_in_the_exchange(self):
rule = TrendRule("APPL")
self.assertFalse(rule.matches(self.exchange))
def test_a_TrendRule_is_False_if_the_stock_hasnt_got_an_update_yet(self):
self.exchange["AAPL"] = Stock("AAPL")
rule = PriceRule("AAPL", lambda price: price > 10)
self.assertFalse(rule.matches(self.exchange))
def test_a_TrendRule_only_depends_on_its_stock(self):
rule = TrendRule("AAPL")
self.assertEqual(set(["AAPL"]), rule.depends_on())
class AndRuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
goog = Stock("GOOG")
goog.update(datetime(2014, 2, 10), 8)
goog.update(datetime(2014, 2, 11), 10)
goog.update(datetime(2014, 2, 12), 12)
msft = Stock("MSFT")
msft.update(datetime(2014, 2, 10), 10)
msft.update(datetime(2014, 2, 11), 10)
msft.update(datetime(2014, 2, 12), 12)
redhat = Stock("RHT")
redhat.update(datetime(2014, 2, 10), 7)
cls.exchange = {"GOOG": goog, "MSFT": msft, "RHT": redhat}
def test_an_AndRule_matches_if_all_component_rules_are_true(self):
rule = AndRule(PriceRule("GOOG", lambda stock: stock.price > 8),
PriceRule("MSFT", lambda stock: stock.price > 10))
self.assertTrue(rule.matches(self.exchange))
def test_an_AndRule_is_False_if_any_component_is_false(self):
rule = AndRule(PriceRule("GOOG", lambda stock: stock.price > 15),
PriceRule("MSFT", lambda stock: stock.price > 10))
self.assertFalse(rule.matches(self.exchange))
def test_an_AndRule_should_support_any_number_of_subrules(self):
rule = AndRule(PriceRule("RHT", lambda stock: stock.price < 10),
PriceRule("GOOG", lambda stock: stock.price > 8),
PriceRule("MSFT", lambda stock: stock.price > 10))
self.assertTrue(rule.matches(self.exchange))
def test_an_empty_AndRule_is_true(self):
rule = AndRule()
self.assertTrue(rule.matches(self.exchange))
def test_an_AndRule_can_be_nested(self):
rule = AndRule(PriceRule("RHT", lambda stock: stock.price < 10),
AndRule(PriceRule("GOOG", lambda stock: stock.price > 8),
PriceRule("MSFT", lambda stock: stock.price > 10)))
self.assertTrue(rule.matches(self.exchange))
def test_an_AndRule_depends_on_what_the_component_rules_depend_on(self):
rule = AndRule(PriceRule("AAPL", lambda stock: stock.price < 10),
PriceRule("GOOG", lambda stock: stock.price > 8))
self.assertEqual(set(["AAPL", "GOOG"]), rule.depends_on())
def test_depends_on_should_not_have_duplicates(self):
rule = AndRule(PriceRule("AAPL", lambda stock: stock.price < 10),
PriceRule("AAPL", lambda stock: stock.price > 5))
self.assertEqual(set(["AAPL"]), rule.depends_on())
| 42.122951 | 82 | 0.657132 | import unittest
from datetime import datetime
from ..stock import Stock
from ..rule import PriceRule, TrendRule, AndRule
class PriceRuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
goog = Stock("GOOG")
goog.update(datetime(2014, 2, 10), 11)
cls.exchange = {"GOOG": goog}
def test_a_PriceRule_matches_when_it_meets_the_condition(self):
rule = PriceRule("GOOG", lambda stock: stock.price > 10)
self.assertTrue(rule.matches(self.exchange))
def test_a_PriceRule_is_False_if_the_condition_is_not_met(self):
rule = PriceRule("GOOG", lambda stock: stock.price < 10)
self.assertFalse(rule.matches(self.exchange))
def test_a_PriceRule_is_False_if_the_stock_is_not_in_the_exchange(self):
rule = PriceRule("MSFT", lambda stock: stock.price > 10)
self.assertFalse(rule.matches(self.exchange))
def test_a_PriceRule_is_False_if_the_stock_hasnt_got_an_update_yet(self):
self.exchange["AAPL"] = Stock("AAPL")
rule = PriceRule("AAPL", lambda stock: stock.price > 10)
self.assertFalse(rule.matches(self.exchange))
def test_a_PriceRule_only_depends_on_its_stock(self):
rule = PriceRule("MSFT", lambda stock: stock.price > 10)
self.assertEqual(set(["MSFT"]), rule.depends_on())
class TrendRuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
goog = Stock("GOOG")
goog.update(datetime(2014, 2, 10), 8)
goog.update(datetime(2014, 2, 11), 10)
goog.update(datetime(2014, 2, 12), 12)
msft = Stock("MSFT")
msft.update(datetime(2014, 2, 10), 10)
msft.update(datetime(2014, 2, 11), 10)
msft.update(datetime(2014, 2, 12), 12)
cls.exchange = {"GOOG": goog, "MSFT": msft}
def test_a_TrendRule_matches_if_the_stock_increased_last_3_updates(self):
rule = TrendRule("GOOG")
self.assertTrue(rule.matches(self.exchange))
def test_a_TrendRule_is_False_if_stock_doesnt_increasing_trend(self):
rule = TrendRule("MSFT")
self.assertFalse(rule.matches(self.exchange))
def test_a_TrendRule_is_False_if_stock_is_not_in_the_exchange(self):
rule = TrendRule("APPL")
self.assertFalse(rule.matches(self.exchange))
def test_a_TrendRule_is_False_if_the_stock_hasnt_got_an_update_yet(self):
self.exchange["AAPL"] = Stock("AAPL")
rule = PriceRule("AAPL", lambda price: price > 10)
self.assertFalse(rule.matches(self.exchange))
def test_a_TrendRule_only_depends_on_its_stock(self):
rule = TrendRule("AAPL")
self.assertEqual(set(["AAPL"]), rule.depends_on())
class AndRuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
goog = Stock("GOOG")
goog.update(datetime(2014, 2, 10), 8)
goog.update(datetime(2014, 2, 11), 10)
goog.update(datetime(2014, 2, 12), 12)
msft = Stock("MSFT")
msft.update(datetime(2014, 2, 10), 10)
msft.update(datetime(2014, 2, 11), 10)
msft.update(datetime(2014, 2, 12), 12)
redhat = Stock("RHT")
redhat.update(datetime(2014, 2, 10), 7)
cls.exchange = {"GOOG": goog, "MSFT": msft, "RHT": redhat}
def test_an_AndRule_matches_if_all_component_rules_are_true(self):
rule = AndRule(PriceRule("GOOG", lambda stock: stock.price > 8),
PriceRule("MSFT", lambda stock: stock.price > 10))
self.assertTrue(rule.matches(self.exchange))
def test_an_AndRule_is_False_if_any_component_is_false(self):
rule = AndRule(PriceRule("GOOG", lambda stock: stock.price > 15),
PriceRule("MSFT", lambda stock: stock.price > 10))
self.assertFalse(rule.matches(self.exchange))
def test_an_AndRule_should_support_any_number_of_subrules(self):
rule = AndRule(PriceRule("RHT", lambda stock: stock.price < 10),
PriceRule("GOOG", lambda stock: stock.price > 8),
PriceRule("MSFT", lambda stock: stock.price > 10))
self.assertTrue(rule.matches(self.exchange))
def test_an_empty_AndRule_is_true(self):
rule = AndRule()
self.assertTrue(rule.matches(self.exchange))
def test_an_AndRule_can_be_nested(self):
rule = AndRule(PriceRule("RHT", lambda stock: stock.price < 10),
AndRule(PriceRule("GOOG", lambda stock: stock.price > 8),
PriceRule("MSFT", lambda stock: stock.price > 10)))
self.assertTrue(rule.matches(self.exchange))
def test_an_AndRule_depends_on_what_the_component_rules_depend_on(self):
rule = AndRule(PriceRule("AAPL", lambda stock: stock.price < 10),
PriceRule("GOOG", lambda stock: stock.price > 8))
self.assertEqual(set(["AAPL", "GOOG"]), rule.depends_on())
def test_depends_on_should_not_have_duplicates(self):
rule = AndRule(PriceRule("AAPL", lambda stock: stock.price < 10),
PriceRule("AAPL", lambda stock: stock.price > 5))
self.assertEqual(set(["AAPL"]), rule.depends_on())
| true | true |
1c3fd7009ea90c16a51ea4de59f4f5a27f39e9bd | 1,719 | py | Python | pol/curd/user.py | MoguCloud/server | f33e5cb3556a4fc99592c28b7ea4893708d9dbbd | [
"BSD-3-Clause"
] | null | null | null | pol/curd/user.py | MoguCloud/server | f33e5cb3556a4fc99592c28b7ea4893708d9dbbd | [
"BSD-3-Clause"
] | null | null | null | pol/curd/user.py | MoguCloud/server | f33e5cb3556a4fc99592c28b7ea4893708d9dbbd | [
"BSD-3-Clause"
] | null | null | null | from typing import Optional
from datetime import datetime, timedelta
from loguru import logger
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from pol import sa
from pol.db.tables import ChiiMember, ChiiOauthAccessToken
from pol.permission import Role, UserGroup
from pol.curd.exceptions import NotFoundError
class User(Role, BaseModel):
id: int
username: str
nickname: str
group_id: UserGroup
registration_date: datetime
sign: str
avatar: str
# lastvisit: int
# lastactivity: int
# lastpost: int
# dateformat: str
# timeformat: int
# timeoffset: str
# newpm: int
# new_notify: int
def allow_nsfw(self) -> bool:
allow_date = self.registration_date + timedelta(days=60)
return datetime.utcnow().astimezone() > allow_date
async def get_by_valid_token(db: AsyncSession, access_token: str) -> User:
access: Optional[ChiiOauthAccessToken] = await db.scalar(
sa.get(
ChiiOauthAccessToken,
ChiiOauthAccessToken.access_token == access_token,
ChiiOauthAccessToken.expires > datetime.now(),
)
)
if not access:
raise NotFoundError()
member: ChiiMember = await db.get(ChiiMember, int(access.user_id))
if not member:
# 有access token又没有对应的user不太可能发生,如果发生的话打个 log 当作验证失败
logger.error("can't find user {} for access token", access.user_id)
raise NotFoundError()
return User(
id=member.uid,
group_id=member.groupid,
username=member.username,
nickname=member.nickname,
registration_date=member.regdate,
sign=member.sign,
avatar=member.avatar,
)
| 26.446154 | 75 | 0.680628 | from typing import Optional
from datetime import datetime, timedelta
from loguru import logger
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from pol import sa
from pol.db.tables import ChiiMember, ChiiOauthAccessToken
from pol.permission import Role, UserGroup
from pol.curd.exceptions import NotFoundError
class User(Role, BaseModel):
id: int
username: str
nickname: str
group_id: UserGroup
registration_date: datetime
sign: str
avatar: str
def allow_nsfw(self) -> bool:
allow_date = self.registration_date + timedelta(days=60)
return datetime.utcnow().astimezone() > allow_date
async def get_by_valid_token(db: AsyncSession, access_token: str) -> User:
access: Optional[ChiiOauthAccessToken] = await db.scalar(
sa.get(
ChiiOauthAccessToken,
ChiiOauthAccessToken.access_token == access_token,
ChiiOauthAccessToken.expires > datetime.now(),
)
)
if not access:
raise NotFoundError()
member: ChiiMember = await db.get(ChiiMember, int(access.user_id))
if not member:
logger.error("can't find user {} for access token", access.user_id)
raise NotFoundError()
return User(
id=member.uid,
group_id=member.groupid,
username=member.username,
nickname=member.nickname,
registration_date=member.regdate,
sign=member.sign,
avatar=member.avatar,
)
| true | true |
1c3fd7a17e7dc122fce64c4ea4fa0d975dd40cc5 | 1,874 | py | Python | tests/contract_tests/KT1NYqJMeLbUKuNaRrXyePrCZ4Uth2HU3173/test_nyqjme_addToken.py | konchunas/pytezos | 65576d18bdf1956fae8ea21241b6c43a38921b83 | [
"MIT"
] | 98 | 2019-02-07T16:33:38.000Z | 2022-03-31T15:53:41.000Z | tests/contract_tests/KT1NYqJMeLbUKuNaRrXyePrCZ4Uth2HU3173/test_nyqjme_addToken.py | konchunas/pytezos | 65576d18bdf1956fae8ea21241b6c43a38921b83 | [
"MIT"
] | 152 | 2019-05-20T16:38:56.000Z | 2022-03-30T14:24:38.000Z | tests/contract_tests/KT1NYqJMeLbUKuNaRrXyePrCZ4Uth2HU3173/test_nyqjme_addToken.py | konchunas/pytezos | 65576d18bdf1956fae8ea21241b6c43a38921b83 | [
"MIT"
] | 34 | 2019-07-25T12:03:51.000Z | 2021-11-11T22:23:38.000Z | from unittest import TestCase
from os.path import dirname, join
import json
from pytezos.michelson.program import MichelsonProgram
from pytezos.michelson.types.big_map import big_map_diff_to_lazy_diff
from pytezos.michelson.forge import forge_micheline, unforge_micheline
folder = 'dexter_usdtz_xtz'
entrypoint = 'removeLiquidity'
class MainnetOperationTestCaseNYQJME(TestCase):
@classmethod
def setUpClass(cls):
with open(join(dirname(__file__), f'', '__script__.json')) as f:
script = json.loads(f.read())
cls.program = MichelsonProgram.match(script['code'])
with open(join(dirname(__file__), f'', f'addToken.json')) as f:
operation = json.loads(f.read())
cls.entrypoint = f'addToken'
cls.operation = operation
# cls.maxDiff = None
def test_parameters_nyqjme(self):
original_params = self.program.parameter.from_parameters(self.operation['parameters'])
py_obj = original_params.to_python_object()
# pprint(py_obj)
readable_params = self.program.parameter.from_parameters(original_params.to_parameters(mode='readable'))
self.assertEqual(py_obj, readable_params.to_python_object())
self.program.parameter.from_python_object(py_obj)
def test_lazy_storage_nyqjme(self):
storage = self.program.storage.from_micheline_value(self.operation['storage'])
lazy_diff = big_map_diff_to_lazy_diff(self.operation['big_map_diff'])
extended_storage = storage.merge_lazy_diff(lazy_diff)
py_obj = extended_storage.to_python_object(try_unpack=True, lazy_diff=True)
# pprint(py_obj)
def test_parameters_forging(self):
expected = self.operation['parameters'].get('value', {'prim': 'Unit'})
actual = unforge_micheline(forge_micheline(expected))
self.assertEqual(expected, actual)
| 39.041667 | 112 | 0.721985 | from unittest import TestCase
from os.path import dirname, join
import json
from pytezos.michelson.program import MichelsonProgram
from pytezos.michelson.types.big_map import big_map_diff_to_lazy_diff
from pytezos.michelson.forge import forge_micheline, unforge_micheline
folder = 'dexter_usdtz_xtz'
entrypoint = 'removeLiquidity'
class MainnetOperationTestCaseNYQJME(TestCase):
@classmethod
def setUpClass(cls):
with open(join(dirname(__file__), f'', '__script__.json')) as f:
script = json.loads(f.read())
cls.program = MichelsonProgram.match(script['code'])
with open(join(dirname(__file__), f'', f'addToken.json')) as f:
operation = json.loads(f.read())
cls.entrypoint = f'addToken'
cls.operation = operation
def test_parameters_nyqjme(self):
original_params = self.program.parameter.from_parameters(self.operation['parameters'])
py_obj = original_params.to_python_object()
readable_params = self.program.parameter.from_parameters(original_params.to_parameters(mode='readable'))
self.assertEqual(py_obj, readable_params.to_python_object())
self.program.parameter.from_python_object(py_obj)
def test_lazy_storage_nyqjme(self):
storage = self.program.storage.from_micheline_value(self.operation['storage'])
lazy_diff = big_map_diff_to_lazy_diff(self.operation['big_map_diff'])
extended_storage = storage.merge_lazy_diff(lazy_diff)
py_obj = extended_storage.to_python_object(try_unpack=True, lazy_diff=True)
def test_parameters_forging(self):
expected = self.operation['parameters'].get('value', {'prim': 'Unit'})
actual = unforge_micheline(forge_micheline(expected))
self.assertEqual(expected, actual)
| true | true |
1c3fd85d598b3d6c44fb247eae813bcf20a7a88e | 742 | py | Python | docs/code_snippets/map_reduce/limitations/single_mapping_node/invalid.py | raztud/dagger | 7b394138c139e3b4fdf228e3d34359f1ae6bdd7a | [
"Apache-2.0"
] | 9 | 2021-09-06T14:22:38.000Z | 2022-02-08T07:48:39.000Z | docs/code_snippets/map_reduce/limitations/single_mapping_node/invalid.py | raztud/dagger | 7b394138c139e3b4fdf228e3d34359f1ae6bdd7a | [
"Apache-2.0"
] | 36 | 2021-09-04T06:20:19.000Z | 2021-12-26T17:54:59.000Z | docs/code_snippets/map_reduce/limitations/single_mapping_node/invalid.py | raztud/dagger | 7b394138c139e3b4fdf228e3d34359f1ae6bdd7a | [
"Apache-2.0"
] | 4 | 2021-09-06T08:07:19.000Z | 2021-10-18T19:13:18.000Z | from typing import List
from dagger import dsl
Partition = str
@dsl.task()
def get_partitions() -> List[Partition]:
return ["first", "second", "...", "last"]
@dsl.task()
def do_something_with(partition: Partition) -> Partition:
return f"{partition}*"
@dsl.task()
def do_something_else_with(partition: Partition) -> Partition:
return f"{partition}$"
@dsl.task()
def aggregate(partial_results: List[Partition]):
return ", ".join(partial_results)
@dsl.DAG()
def dag():
partitions = get_partitions()
partial_results = []
for partition in partitions:
p1 = do_something_with(partition)
p2 = do_something_else_with(p1)
partial_results.append(p2)
return aggregate(partial_results)
| 19.526316 | 62 | 0.684636 | from typing import List
from dagger import dsl
Partition = str
@dsl.task()
def get_partitions() -> List[Partition]:
return ["first", "second", "...", "last"]
@dsl.task()
def do_something_with(partition: Partition) -> Partition:
return f"{partition}*"
@dsl.task()
def do_something_else_with(partition: Partition) -> Partition:
return f"{partition}$"
@dsl.task()
def aggregate(partial_results: List[Partition]):
return ", ".join(partial_results)
@dsl.DAG()
def dag():
partitions = get_partitions()
partial_results = []
for partition in partitions:
p1 = do_something_with(partition)
p2 = do_something_else_with(p1)
partial_results.append(p2)
return aggregate(partial_results)
| true | true |
1c3fd85dad49a2866b00e6e6336ab5dd4353b86e | 13,938 | py | Python | src/sage/rings/padics/padic_base_generic.py | sensen1/sage | d6c5cd9be78cc448ee4c54bac93385b1244a234c | [
"BSL-1.0"
] | 1 | 2021-03-15T21:45:56.000Z | 2021-03-15T21:45:56.000Z | src/sage/rings/padics/padic_base_generic.py | sensen1/sage | d6c5cd9be78cc448ee4c54bac93385b1244a234c | [
"BSL-1.0"
] | null | null | null | src/sage/rings/padics/padic_base_generic.py | sensen1/sage | d6c5cd9be78cc448ee4c54bac93385b1244a234c | [
"BSL-1.0"
] | null | null | null | r"""
`p`-Adic Base Generic
A superclass for implementations of `\ZZ_p` and `\QQ_p`.
AUTHORS:
- David Roe
"""
#*****************************************************************************
# Copyright (C) 2007-2013 David Roe <roed.math@gmail.com>
# William Stein <wstein@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# http://www.gnu.org/licenses/
#*****************************************************************************
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from .padic_generic import pAdicGeneric
from .misc import precprint
from sage.rings.padics.pow_computer import PowComputer
from sage.rings.padics.padic_capped_relative_element import pAdicCoercion_ZZ_CR, pAdicCoercion_QQ_CR, pAdicConvert_QQ_CR
from sage.rings.padics.padic_capped_absolute_element import pAdicCoercion_ZZ_CA, pAdicConvert_QQ_CA
from sage.rings.padics.padic_fixed_mod_element import pAdicCoercion_ZZ_FM, pAdicConvert_QQ_FM
from sage.rings.padics.padic_floating_point_element import pAdicCoercion_ZZ_FP, pAdicCoercion_QQ_FP, pAdicConvert_QQ_FP
class pAdicBaseGeneric(pAdicGeneric):
_implementation = 'GMP'
def __init__(self, p, prec, print_mode, names, element_class):
"""
Initialization
TESTS::
sage: R = Zp(5) #indirect doctest
"""
self.prime_pow = PowComputer(p, max(min(prec - 1, 30), 1), prec, self.is_field(), self._prec_type())
pAdicGeneric.__init__(self, self, p, prec, print_mode, names, element_class)
if self.is_field():
if self.is_capped_relative():
coerce_list = [pAdicCoercion_ZZ_CR(self), pAdicCoercion_QQ_CR(self)]
convert_list = []
elif self.is_floating_point():
coerce_list = [pAdicCoercion_ZZ_FP(self), pAdicCoercion_QQ_FP(self)]
convert_list = []
elif self.is_lattice_prec():
coerce_list = [QQ]
convert_list = []
else:
raise RuntimeError
elif self.is_capped_relative():
coerce_list = [pAdicCoercion_ZZ_CR(self)]
convert_list = [pAdicConvert_QQ_CR(self)]
elif self.is_capped_absolute():
coerce_list = [pAdicCoercion_ZZ_CA(self)]
convert_list = [pAdicConvert_QQ_CA(self)]
elif self.is_fixed_mod():
coerce_list = [pAdicCoercion_ZZ_FM(self)]
convert_list = [pAdicConvert_QQ_FM(self)]
elif self.is_floating_point():
coerce_list = [pAdicCoercion_ZZ_FP(self)]
convert_list = [pAdicConvert_QQ_FP(self)]
elif self.is_lattice_prec():
coerce_list = [ZZ]
convert_list = [QQ]
else:
raise RuntimeError
self.Element = element_class
self._populate_coercion_lists_(coerce_list=coerce_list, convert_list=convert_list)
def _repr_(self, do_latex=False):
r"""
Returns a print representation of this p-adic ring or field.
EXAMPLES::
sage: K = Zp(17); K #indirect doctest
17-adic Ring with capped relative precision 20
sage: latex(K)
\Bold{Z}_{17}
sage: K = ZpCA(17); K #indirect doctest
17-adic Ring with capped absolute precision 20
sage: latex(K)
\Bold{Z}_{17}
sage: K = ZpFP(17); K #indirect doctest
17-adic Ring with floating precision 20
sage: latex(K)
\Bold{Z}_{17}
sage: K = ZpFM(7); K
7-adic Ring of fixed modulus 7^20
sage: latex(K) #indirect doctest
\Bold{Z}_{7}
sage: K = ZpLF(2); K # indirect doctest
doctest:...: FutureWarning: This class/method/function is marked as experimental. It, its functionality or its interface might change without a formal deprecation.
See http://trac.sagemath.org/23505 for details.
2-adic Ring with lattice-float precision
sage: latex(K)
\Bold{Z}_{2}
sage: K = Qp(17); K #indirect doctest
17-adic Field with capped relative precision 20
sage: latex(K)
\Bold{Q}_{17}
sage: K = QpFP(17); K #indirect doctest
17-adic Field with floating precision 20
sage: latex(K)
\Bold{Q}_{17}
sage: K = QpLC(2); K # indirect doctest
2-adic Field with lattice-cap precision
sage: latex(K)
\Bold{Q}_{2}
"""
if do_latex:
if self.is_field():
s = r"\Bold{Q}_{%s}" % self.prime()
else:
s = r"\Bold{Z}_{%s}" % self.prime()
if hasattr(self, '_label') and self._label:
s = r"\verb'%s' (\simeq %s)"%(self._label, s)
else:
s = "Field " if self.is_field() else "Ring "
s = "%s-adic "%self.prime() + s + precprint(self._prec_type(), self.precision_cap(), self.prime())
if hasattr(self, '_label') and self._label:
s+= " (label: %s)"%self._label
return s
def exact_field(self):
"""
Returns the rational field.
For compatibility with extensions of p-adics.
EXAMPLES::
sage: Zp(5).exact_field()
Rational Field
"""
from sage.rings.rational_field import QQ
return QQ
def exact_ring(self):
"""
Returns the integer ring.
EXAMPLES::
sage: Zp(5).exact_ring()
Integer Ring
"""
from sage.rings.integer_ring import ZZ
return ZZ
def is_isomorphic(self, ring):
r"""
Returns whether ``self`` and ``ring`` are isomorphic, i.e. whether ``ring`` is an implementation of `\ZZ_p` for the same prime as ``self``.
INPUT:
- ``self`` -- a `p`-adic ring
- ``ring`` -- a ring
OUTPUT:
- ``boolean`` -- whether ``ring`` is an implementation of \ZZ_p` for the same prime as ``self``.
EXAMPLES::
sage: R = Zp(5, 15, print_mode='digits'); S = Zp(5, 44, print_max_terms=4); R.is_isomorphic(S)
True
"""
return isinstance(ring, pAdicBaseGeneric) and self.prime() == ring.prime() and self.is_field() == ring.is_field()
def gen(self, n=0):
"""
Returns the ``nth`` generator of this extension. For base
rings/fields, we consider the generator to be the prime.
EXAMPLES::
sage: R = Zp(5); R.gen()
5 + O(5^21)
"""
if n != 0:
raise IndexError("only one generator")
return self(self.prime())
def modulus(self, exact=False):
r"""
Returns the polynomial defining this extension.
For compatibility with extension fields; we define the modulus to be x-1.
INPUT:
- ``exact`` -- boolean (default ``False``), whether to return a polynomial with integer entries.
EXAMPLES::
sage: Zp(5).modulus(exact=True)
x
"""
return self.defining_polynomial(exact=exact)
def absolute_discriminant(self):
"""
Returns the absolute discriminant of this `p`-adic ring
EXAMPLES::
sage: Zp(5).absolute_discriminant()
1
"""
return 1
def discriminant(self, K=None):
"""
Returns the discriminant of this `p`-adic ring over ``K``
INPUT:
- ``self`` -- a `p`-adic ring
- ``K`` -- a sub-ring of ``self`` or ``None`` (default: ``None``)
OUTPUT:
- integer -- the discriminant of this ring over ``K`` (or the
absolute discriminant if ``K`` is ``None``)
EXAMPLES::
sage: Zp(5).discriminant()
1
"""
if (K is None or K is self):
return 1
else:
raise ValueError("Ground Ring must be a subring of self")
def is_abelian(self):
"""
Returns whether the Galois group is abelian, i.e. ``True``.
#should this be automorphism group?
EXAMPLES::
sage: R = Zp(3, 10,'fixed-mod'); R.is_abelian()
True
"""
return True
def is_normal(self):
"""
Returns whether or not this is a normal extension, i.e. ``True``.
EXAMPLES::
sage: R = Zp(3, 10,'fixed-mod'); R.is_normal()
True
"""
return True
def uniformizer(self):
"""
Returns a uniformizer for this ring.
EXAMPLES::
sage: R = Zp(3,5,'fixed-mod', 'series')
sage: R.uniformizer()
3
"""
return self(self.prime_pow._prime())
def uniformizer_pow(self, n):
"""
Returns the ``nth`` power of the uniformizer of ``self`` (as
an element of ``self``).
EXAMPLES::
sage: R = Zp(5)
sage: R.uniformizer_pow(5)
5^5 + O(5^25)
sage: R.uniformizer_pow(infinity)
0
"""
return self(self.prime_pow(n))
def _uniformizer_print(self):
"""
Returns how the uniformizer is supposed to print.
EXAMPLES::
sage: R = Zp(5, names='pi'); R._uniformizer_print()
'pi'
"""
return self.variable_name()
def has_pth_root(self):
r"""
Returns whether or not `\ZZ_p` has a primitive `p^{th}`
root of unity.
EXAMPLES::
sage: Zp(2).has_pth_root()
True
sage: Zp(17).has_pth_root()
False
"""
return (self.prime() == 2)
def has_root_of_unity(self, n):
r"""
Returns whether or not `\ZZ_p` has a primitive `n^{th}`
root of unity.
INPUT:
- ``self`` -- a `p`-adic ring
- ``n`` -- an integer
OUTPUT:
- ``boolean`` -- whether ``self`` has primitive `n^{th}` root
of unity
EXAMPLES::
sage: R=Zp(37)
sage: R.has_root_of_unity(12)
True
sage: R.has_root_of_unity(11)
False
"""
if (self.prime() == 2):
return n.divides(2)
else:
return n.divides(self.prime() - 1)
def zeta(self, n=None):
r"""
Returns a generator of the group of roots of unity.
INPUT:
- ``self`` -- a `p`-adic ring
- ``n`` -- an integer or ``None`` (default: ``None``)
OUTPUT:
- ``element`` -- a generator of the `n^{th}` roots of unity,
or a generator of the full group of roots of unity if ``n``
is ``None``
EXAMPLES::
sage: R = Zp(37,5)
sage: R.zeta(12)
8 + 24*37 + 37^2 + 29*37^3 + 23*37^4 + O(37^5)
"""
if (self.prime() == 2):
if (n is None) or (n == 2):
return self(-1)
if n == 1:
return self(1)
else:
raise ValueError("No, %sth root of unity in self"%n)
else:
from sage.rings.finite_rings.finite_field_constructor import GF
return self.teichmuller(GF(self.prime()).zeta(n).lift())
def zeta_order(self):
"""
Returns the order of the group of roots of unity.
EXAMPLES::
sage: R = Zp(37); R.zeta_order()
36
sage: Zp(2).zeta_order()
2
"""
if (self.prime() == 2):
return 2
else:
return self.prime() - 1
def plot(self, max_points=2500, **args):
r"""
Create a visualization of this `p`-adic ring as a fractal
similar to a generalization of the Sierpi\'nski
triangle.
The resulting image attempts to capture the
algebraic and topological characteristics of `\ZZ_p`.
INPUT:
- ``max_points`` -- the maximum number or points to plot,
which controls the depth of recursion (default 2500)
- ``**args`` -- color, size, etc. that are passed to the
underlying point graphics objects
REFERENCES:
- Cuoco, A. ''Visualizing the `p`-adic Integers'', The
American Mathematical Monthly, Vol. 98, No. 4 (Apr., 1991),
pp. 355-364
EXAMPLES::
sage: Zp(3).plot()
Graphics object consisting of 1 graphics primitive
sage: Zp(5).plot(max_points=625)
Graphics object consisting of 1 graphics primitive
sage: Zp(23).plot(rgbcolor=(1,0,0))
Graphics object consisting of 1 graphics primitive
"""
if 'pointsize' not in args:
args['pointsize'] = 1
from sage.misc.mrange import cartesian_product_iterator
from sage.rings.real_double import RDF
from sage.plot.all import points
p = self.prime()
phi = 2*RDF.pi()/p
V = RDF**2
vs = [V([(phi*t).sin(), (phi*t).cos()]) for t in range(p)]
all = []
depth = max(RDF(max_points).log(p).floor(), 1)
scale = min(RDF(1.5/p), 1/RDF(3))
pts = [vs]*depth
if depth == 1 and 23 < p < max_points:
extras = int(max_points/p)
if p/extras > 5:
pts = [vs]*depth + [vs[::extras]]
for digits in cartesian_product_iterator(pts):
p = sum([v * scale**n for n, v in enumerate(digits)])
all.append(tuple(p))
g = points(all, **args)
# Set default plotting options
g.axes(False)
g.set_aspect_ratio(1)
return g
| 30.565789 | 175 | 0.536088 |
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from .padic_generic import pAdicGeneric
from .misc import precprint
from sage.rings.padics.pow_computer import PowComputer
from sage.rings.padics.padic_capped_relative_element import pAdicCoercion_ZZ_CR, pAdicCoercion_QQ_CR, pAdicConvert_QQ_CR
from sage.rings.padics.padic_capped_absolute_element import pAdicCoercion_ZZ_CA, pAdicConvert_QQ_CA
from sage.rings.padics.padic_fixed_mod_element import pAdicCoercion_ZZ_FM, pAdicConvert_QQ_FM
from sage.rings.padics.padic_floating_point_element import pAdicCoercion_ZZ_FP, pAdicCoercion_QQ_FP, pAdicConvert_QQ_FP
class pAdicBaseGeneric(pAdicGeneric):
_implementation = 'GMP'
def __init__(self, p, prec, print_mode, names, element_class):
self.prime_pow = PowComputer(p, max(min(prec - 1, 30), 1), prec, self.is_field(), self._prec_type())
pAdicGeneric.__init__(self, self, p, prec, print_mode, names, element_class)
if self.is_field():
if self.is_capped_relative():
coerce_list = [pAdicCoercion_ZZ_CR(self), pAdicCoercion_QQ_CR(self)]
convert_list = []
elif self.is_floating_point():
coerce_list = [pAdicCoercion_ZZ_FP(self), pAdicCoercion_QQ_FP(self)]
convert_list = []
elif self.is_lattice_prec():
coerce_list = [QQ]
convert_list = []
else:
raise RuntimeError
elif self.is_capped_relative():
coerce_list = [pAdicCoercion_ZZ_CR(self)]
convert_list = [pAdicConvert_QQ_CR(self)]
elif self.is_capped_absolute():
coerce_list = [pAdicCoercion_ZZ_CA(self)]
convert_list = [pAdicConvert_QQ_CA(self)]
elif self.is_fixed_mod():
coerce_list = [pAdicCoercion_ZZ_FM(self)]
convert_list = [pAdicConvert_QQ_FM(self)]
elif self.is_floating_point():
coerce_list = [pAdicCoercion_ZZ_FP(self)]
convert_list = [pAdicConvert_QQ_FP(self)]
elif self.is_lattice_prec():
coerce_list = [ZZ]
convert_list = [QQ]
else:
raise RuntimeError
self.Element = element_class
self._populate_coercion_lists_(coerce_list=coerce_list, convert_list=convert_list)
def _repr_(self, do_latex=False):
if do_latex:
if self.is_field():
s = r"\Bold{Q}_{%s}" % self.prime()
else:
s = r"\Bold{Z}_{%s}" % self.prime()
if hasattr(self, '_label') and self._label:
s = r"\verb'%s' (\simeq %s)"%(self._label, s)
else:
s = "Field " if self.is_field() else "Ring "
s = "%s-adic "%self.prime() + s + precprint(self._prec_type(), self.precision_cap(), self.prime())
if hasattr(self, '_label') and self._label:
s+= " (label: %s)"%self._label
return s
def exact_field(self):
from sage.rings.rational_field import QQ
return QQ
def exact_ring(self):
from sage.rings.integer_ring import ZZ
return ZZ
def is_isomorphic(self, ring):
return isinstance(ring, pAdicBaseGeneric) and self.prime() == ring.prime() and self.is_field() == ring.is_field()
def gen(self, n=0):
if n != 0:
raise IndexError("only one generator")
return self(self.prime())
def modulus(self, exact=False):
return self.defining_polynomial(exact=exact)
def absolute_discriminant(self):
return 1
def discriminant(self, K=None):
if (K is None or K is self):
return 1
else:
raise ValueError("Ground Ring must be a subring of self")
def is_abelian(self):
return True
def is_normal(self):
return True
def uniformizer(self):
return self(self.prime_pow._prime())
def uniformizer_pow(self, n):
return self(self.prime_pow(n))
def _uniformizer_print(self):
return self.variable_name()
def has_pth_root(self):
return (self.prime() == 2)
def has_root_of_unity(self, n):
if (self.prime() == 2):
return n.divides(2)
else:
return n.divides(self.prime() - 1)
def zeta(self, n=None):
if (self.prime() == 2):
if (n is None) or (n == 2):
return self(-1)
if n == 1:
return self(1)
else:
raise ValueError("No, %sth root of unity in self"%n)
else:
from sage.rings.finite_rings.finite_field_constructor import GF
return self.teichmuller(GF(self.prime()).zeta(n).lift())
def zeta_order(self):
if (self.prime() == 2):
return 2
else:
return self.prime() - 1
def plot(self, max_points=2500, **args):
if 'pointsize' not in args:
args['pointsize'] = 1
from sage.misc.mrange import cartesian_product_iterator
from sage.rings.real_double import RDF
from sage.plot.all import points
p = self.prime()
phi = 2*RDF.pi()/p
V = RDF**2
vs = [V([(phi*t).sin(), (phi*t).cos()]) for t in range(p)]
all = []
depth = max(RDF(max_points).log(p).floor(), 1)
scale = min(RDF(1.5/p), 1/RDF(3))
pts = [vs]*depth
if depth == 1 and 23 < p < max_points:
extras = int(max_points/p)
if p/extras > 5:
pts = [vs]*depth + [vs[::extras]]
for digits in cartesian_product_iterator(pts):
p = sum([v * scale**n for n, v in enumerate(digits)])
all.append(tuple(p))
g = points(all, **args)
g.axes(False)
g.set_aspect_ratio(1)
return g
| true | true |
1c3fd8926309431eb4f88378356064832fc6f8c6 | 149 | py | Python | febio_python/test/test_feb.py | Nobregaigor/febio-python | 6895b4e2f8959444a66b6f77a000ce193c3357a7 | [
"MIT"
] | null | null | null | febio_python/test/test_feb.py | Nobregaigor/febio-python | 6895b4e2f8959444a66b6f77a000ce193c3357a7 | [
"MIT"
] | null | null | null | febio_python/test/test_feb.py | Nobregaigor/febio-python | 6895b4e2f8959444a66b6f77a000ce193c3357a7 | [
"MIT"
] | null | null | null | import unittest
from febio_python import feb
class test_feb(unittest.TestCase):
def test_load_feb(self):
feb.FEBio_feb("./sample.feb")
| 18.625 | 37 | 0.731544 | import unittest
from febio_python import feb
class test_feb(unittest.TestCase):
def test_load_feb(self):
feb.FEBio_feb("./sample.feb")
| true | true |
1c3fd9c8cb6f1720691d88a108b04aa9c9562f9a | 2,706 | py | Python | testjinja/testjinja/settings.py | csiubru/py | 769d7f5f4278e1c3b3719203e372992859268347 | [
"MIT"
] | null | null | null | testjinja/testjinja/settings.py | csiubru/py | 769d7f5f4278e1c3b3719203e372992859268347 | [
"MIT"
] | null | null | null | testjinja/testjinja/settings.py | csiubru/py | 769d7f5f4278e1c3b3719203e372992859268347 | [
"MIT"
] | null | null | null | """
Django settings for testjinja project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'l1h47cgs#9s4%2ki1e=+%sc1-hw$p2wf-w+l$#1hhytms&7#@0'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'testjin',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'testjinja.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2'
,
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'testjinja.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
| 25.528302 | 71 | 0.695492 |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'l1h47cgs#9s4%2ki1e=+%sc1-hw$p2wf-w+l$#1hhytms&7#@0'
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'testjin',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'testjinja.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2'
,
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'testjinja.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
| true | true |
1c3fdad50a1ce722cf607472598169e7f53cbe31 | 4,140 | py | Python | setup.py | cwoebker/paxo | 7d0dbc8e7ef5a1cb7f9fb14d765ada0134fd4a12 | [
"BSD-3-Clause"
] | 1 | 2018-09-16T13:04:53.000Z | 2018-09-16T13:04:53.000Z | setup.py | cwoebker/paxo | 7d0dbc8e7ef5a1cb7f9fb14d765ada0134fd4a12 | [
"BSD-3-Clause"
] | null | null | null | setup.py | cwoebker/paxo | 7d0dbc8e7ef5a1cb7f9fb14d765ada0134fd4a12 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
# Note: also necessary for building the code:
# $ pip install wheel
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
import paxo
# Package meta-data.
NAME = paxo.__title__
DESCRIPTION = 'paxo: python ♡ terminal'
URL = 'https://github.com/cwoebker/paxo'
EMAIL = 'me@cwoebker.com'
AUTHOR = paxo.__author__
REQUIRES_PYTHON = '>=3.6.0'
VERSION = paxo.__version__
LICENSE = paxo.__license__
# What packages are required for this module to be executed?
REQUIRED = [
'clint',
]
# What packages are optional?
EXTRAS = {
# 'fancy feature': ['django'],
}
# The rest you shouldn't have to touch too much :)
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!
here = os.path.abspath(os.path.dirname(__file__))
# Import the README and use it as the long-description.
# Note: this will only work if 'README.md' is present in your MANIFEST.in file!
try:
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = '\n' + f.read()
except FileNotFoundError:
long_description = DESCRIPTION
# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
with open(os.path.join(here, NAME, '__version__.py')) as f:
exec (f.read(), about)
else:
about['__version__'] = VERSION
class UploadCommand(Command):
"""Support setup.py upload."""
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPI via Twine…')
os.system('twine upload dist/*')
self.status('Pushing git tags…')
os.system('git tag v{0}'.format(about['__version__']))
os.system('git push --tags')
sys.exit()
# Where the magic happens:
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
long_description_content_type='text/markdown',
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(exclude=('tests',)),
# If your package is a single module, use this instead of 'packages':
# py_modules=['mypackage'],
# entry_points={
# 'console_scripts': ['mycli=mymodule:cli'],
# },
install_requires=REQUIRED,
extras_require=EXTRAS,
include_package_data=True,
license=LICENSE,
classifiers=[
# Trove classifiers
# Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'License :: OSI Approved :: BSD License',
'Environment :: Console',
'Natural Language :: English',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Topic :: Software Development',
'Topic :: Terminals',
'Topic :: Utilities',
'Topic :: Text Processing',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy'
],
# $ setup.py publish support.
cmdclass={
'upload': UploadCommand,
},
) | 28.551724 | 86 | 0.638164 |
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
import paxo
NAME = paxo.__title__
DESCRIPTION = 'paxo: python ♡ terminal'
URL = 'https://github.com/cwoebker/paxo'
EMAIL = 'me@cwoebker.com'
AUTHOR = paxo.__author__
REQUIRES_PYTHON = '>=3.6.0'
VERSION = paxo.__version__
LICENSE = paxo.__license__
REQUIRED = [
'clint',
]
EXTRAS = {
}
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!
here = os.path.abspath(os.path.dirname(__file__))
# Import the README and use it as the long-description.
# Note: this will only work if 'README.md' is present in your MANIFEST.in file!
try:
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = '\n' + f.read()
except FileNotFoundError:
long_description = DESCRIPTION
# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
with open(os.path.join(here, NAME, '__version__.py')) as f:
exec (f.read(), about)
else:
about['__version__'] = VERSION
class UploadCommand(Command):
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPI via Twine…')
os.system('twine upload dist/*')
self.status('Pushing git tags…')
os.system('git tag v{0}'.format(about['__version__']))
os.system('git push --tags')
sys.exit()
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
long_description_content_type='text/markdown',
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(exclude=('tests',)),
install_requires=REQUIRED,
extras_require=EXTRAS,
include_package_data=True,
license=LICENSE,
classifiers=[
'License :: OSI Approved :: BSD License',
'Environment :: Console',
'Natural Language :: English',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Topic :: Software Development',
'Topic :: Terminals',
'Topic :: Utilities',
'Topic :: Text Processing',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy'
],
cmdclass={
'upload': UploadCommand,
},
) | true | true |
1c3fdb16e203e45980d65e859f19336bbd347cea | 3,983 | py | Python | trainweak.py | HKUST-KnowComp/MLMET | ae1188a929a5ca6a8e087bb091853b328ea2c7e7 | [
"MIT"
] | 10 | 2021-05-21T16:16:05.000Z | 2022-02-23T11:22:52.000Z | trainweak.py | HKUST-KnowComp/MLMET | ae1188a929a5ca6a8e087bb091853b328ea2c7e7 | [
"MIT"
] | 4 | 2021-07-03T05:20:01.000Z | 2021-08-08T16:48:44.000Z | trainweak.py | HKUST-KnowComp/MLMET | ae1188a929a5ca6a8e087bb091853b328ea2c7e7 | [
"MIT"
] | 3 | 2021-08-20T08:26:45.000Z | 2022-03-13T14:10:16.000Z | import datetime
import torch
import os
import logging
from utils import utils
from exp import bertufexp
import config
def __setup_logging(to_file):
log_file = os.path.join(config.DATA_DIR, 'ultrafine/log/{}-{}-{}-{}.log'.format(os.path.splitext(
os.path.basename(__file__))[0], args.idx, str_today, config.MACHINE_NAME)) if to_file else None
utils.init_universal_logging(log_file, mode='a', to_stdout=True)
logging.info('logging to {}'.format(log_file))
def __train1():
print('train 1')
__setup_logging(True)
el_train_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/total_train/el_train.json')
el_extra_label_file = os.path.join(config.DATA_DIR, 'ultrafine/bert_labels/el_train_ama_ms_10types.json')
open_train_files = [os.path.join(
config.DATA_DIR, 'ultrafine/uf_data/total_train/open_train_{:02d}.json'.format(i)) for i in range(21)]
open_extra_label_files = [os.path.join(
config.DATA_DIR,
'ultrafine/bert_labels/open_train_{:02d}_ama_ms_10types.json'.format(i)) for i in range(21)]
pronoun_mention_file = os.path.join(config.DATA_DIR, 'ultrafine/gigaword_eng_5_texts_pronoun_s005.txt')
pronoun_type_file = os.path.join(
config.DATA_DIR, 'ultrafine/bert_labels/gigaword5_pronoun_s005_ama_ms_10types.json')
dev_data_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/crowd/dev.json')
type_vocab_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/ontology/types.txt')
load_model_file = None
save_model_file = os.path.join(config.DATA_DIR, 'ultrafine/output/models/uf_bert_weak_ama_ms')
# save_model_file = None
tc = bertufexp.TrainConfig(device, bert_model='bert-base-cased', batch_size=32, max_n_ex_types=10,
eval_interval=1000, lr=1e-5, w_decay=0.01, n_steps=1502000, save_interval=100000,
weighted_loss=True, weight_for_origin_label=5.0, ex_tids=True)
# bertufexp.train_bert_uf(tc, type_vocab_file, train_data_file, dev_data_file, save_model_file)
bertufexp.train_wuf(
tc, type_vocab_file, el_train_file, el_extra_label_file, open_train_files,
open_extra_label_files, pronoun_mention_file, pronoun_type_file, dev_data_file,
None, save_model_file)
def __train():
print('train 0')
__setup_logging(True)
el_train_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/total_train/el_train.json')
el_extra_label_file = None
open_train_files = [os.path.join(
config.DATA_DIR, 'ultrafine/uf_data/total_train/open_train_{:02d}.json'.format(i)) for i in range(21)]
open_extra_label_files = None
dev_data_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/crowd/dev.json')
pronoun_mention_file = None
pronoun_type_file = None
type_vocab_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/ontology/types.txt')
load_model_file = None
save_model_file = os.path.join(config.DATA_DIR, 'ultrafine/output/models/uf_bert_weak')
# save_model_file = None
tc = bertufexp.TrainConfig(
device, bert_model='bert-base-cased', batch_size=32, eval_interval=1000, lr=1e-5, w_decay=0.01,
n_iter=400, n_steps=1002000, save_interval=100000)
# bertufexp.train_bert_uf(tc, type_vocab_file, train_data_file, dev_data_file, save_model_file)
bertufexp.train_wuf(
tc, type_vocab_file, el_train_file, el_extra_label_file, open_train_files,
open_extra_label_files, pronoun_mention_file, pronoun_type_file, dev_data_file,
None, save_model_file)
if __name__ == '__main__':
str_today = datetime.date.today().strftime('%y-%m-%d')
args = utils.parse_idx_device_args()
cuda_device_str = 'cuda' if len(args.d) == 0 else 'cuda:{}'.format(args.d[0])
device = torch.device(cuda_device_str) if torch.cuda.device_count() > 0 else torch.device('cpu')
device_ids = args.d
if args.idx == 0:
__train()
elif args.idx == 1:
__train1()
| 47.416667 | 112 | 0.72709 | import datetime
import torch
import os
import logging
from utils import utils
from exp import bertufexp
import config
def __setup_logging(to_file):
log_file = os.path.join(config.DATA_DIR, 'ultrafine/log/{}-{}-{}-{}.log'.format(os.path.splitext(
os.path.basename(__file__))[0], args.idx, str_today, config.MACHINE_NAME)) if to_file else None
utils.init_universal_logging(log_file, mode='a', to_stdout=True)
logging.info('logging to {}'.format(log_file))
def __train1():
print('train 1')
__setup_logging(True)
el_train_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/total_train/el_train.json')
el_extra_label_file = os.path.join(config.DATA_DIR, 'ultrafine/bert_labels/el_train_ama_ms_10types.json')
open_train_files = [os.path.join(
config.DATA_DIR, 'ultrafine/uf_data/total_train/open_train_{:02d}.json'.format(i)) for i in range(21)]
open_extra_label_files = [os.path.join(
config.DATA_DIR,
'ultrafine/bert_labels/open_train_{:02d}_ama_ms_10types.json'.format(i)) for i in range(21)]
pronoun_mention_file = os.path.join(config.DATA_DIR, 'ultrafine/gigaword_eng_5_texts_pronoun_s005.txt')
pronoun_type_file = os.path.join(
config.DATA_DIR, 'ultrafine/bert_labels/gigaword5_pronoun_s005_ama_ms_10types.json')
dev_data_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/crowd/dev.json')
type_vocab_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/ontology/types.txt')
load_model_file = None
save_model_file = os.path.join(config.DATA_DIR, 'ultrafine/output/models/uf_bert_weak_ama_ms')
tc = bertufexp.TrainConfig(device, bert_model='bert-base-cased', batch_size=32, max_n_ex_types=10,
eval_interval=1000, lr=1e-5, w_decay=0.01, n_steps=1502000, save_interval=100000,
weighted_loss=True, weight_for_origin_label=5.0, ex_tids=True)
bertufexp.train_wuf(
tc, type_vocab_file, el_train_file, el_extra_label_file, open_train_files,
open_extra_label_files, pronoun_mention_file, pronoun_type_file, dev_data_file,
None, save_model_file)
def __train():
print('train 0')
__setup_logging(True)
el_train_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/total_train/el_train.json')
el_extra_label_file = None
open_train_files = [os.path.join(
config.DATA_DIR, 'ultrafine/uf_data/total_train/open_train_{:02d}.json'.format(i)) for i in range(21)]
open_extra_label_files = None
dev_data_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/crowd/dev.json')
pronoun_mention_file = None
pronoun_type_file = None
type_vocab_file = os.path.join(config.DATA_DIR, 'ultrafine/uf_data/ontology/types.txt')
load_model_file = None
save_model_file = os.path.join(config.DATA_DIR, 'ultrafine/output/models/uf_bert_weak')
tc = bertufexp.TrainConfig(
device, bert_model='bert-base-cased', batch_size=32, eval_interval=1000, lr=1e-5, w_decay=0.01,
n_iter=400, n_steps=1002000, save_interval=100000)
bertufexp.train_wuf(
tc, type_vocab_file, el_train_file, el_extra_label_file, open_train_files,
open_extra_label_files, pronoun_mention_file, pronoun_type_file, dev_data_file,
None, save_model_file)
if __name__ == '__main__':
str_today = datetime.date.today().strftime('%y-%m-%d')
args = utils.parse_idx_device_args()
cuda_device_str = 'cuda' if len(args.d) == 0 else 'cuda:{}'.format(args.d[0])
device = torch.device(cuda_device_str) if torch.cuda.device_count() > 0 else torch.device('cpu')
device_ids = args.d
if args.idx == 0:
__train()
elif args.idx == 1:
__train1()
| true | true |
1c3fdb75e6069de112bca35146a844c47b3af97c | 8,504 | py | Python | ADBShell.py | AlvISsReimu/ArknightsAutoHelper | 7112b73c01fe381b20314342ba0dfa2f7e01805d | [
"MIT"
] | 2 | 2021-07-14T04:03:57.000Z | 2022-03-17T03:23:19.000Z | ADBShell.py | AlvISsReimu/ArknightsAutoHelper | 7112b73c01fe381b20314342ba0dfa2f7e01805d | [
"MIT"
] | null | null | null | ADBShell.py | AlvISsReimu/ArknightsAutoHelper | 7112b73c01fe381b20314342ba0dfa2f7e01805d | [
"MIT"
] | null | null | null | import os
from config import ADB_ROOT, ADB_HOST, SCREEN_SHOOT_SAVE_PATH, ShellColor
from PIL import Image
from time import sleep
from random import randint
# from numpy import average, dot, linalg
class ADBShell(object):
def __init__(self, adb_host=ADB_HOST):
self.SCREEN_SHOOT_SAVE_PATH = os.path.abspath(SCREEN_SHOOT_SAVE_PATH) + "\\"
# os.chdir(ADB_ROOT)
self.ADB_ROOT = ADB_ROOT
self.ADB_HOST = adb_host
self.__buffer = ""
self.shell_color = ShellColor()
self.__adb_tools = ""
self.__adb_command = ""
self.DEVICE_NAME = self.__adb_device_name_detector()
self.__command = "\"" + self.ADB_ROOT + "\\adb.exe\" -s " + self.DEVICE_NAME + " {tools} {command} "
# 命令格式 "D:\Program Files\Nox\bin\adb.exe" -s 127.0.0.1:62001 shell am start ...
# Linux 和 Mac 机器我不太清楚咋整. 不过好像大家目前还没这个需求
# self.__adb_connect()
def __adb_device_name_detector(self):
self.__command = "\"" + self.ADB_ROOT + "\\adb.exe\" {tools} {command}"
self.__adb_tools = "devices"
content = self.run_cmd(DEBUG_LEVEL=1).strip().split("\n")
content.pop(0)
if content.__len__() == 1:
device_name = content[0].split("\t")[0]
else:
self.shell_color.helper_text("[!] 检测到多台设备,根据 ADB_HOST 参数将自动选择设备")
device_name = ""
for c in range(content.__len__()):
print("[*] " + c.__str__() + "\t" + content[c])
if self.ADB_HOST == content[c].split("\t")[0]:
device_name = self.ADB_HOST
if device_name == "":
print("自动选择设备失败,请根据上述内容自行输入数字并选择")
input_valid_flag = False
num = "0"
while not input_valid_flag:
num = input(">")
if num.isnumeric() and int(num) <= content.__len__():
input_valid_flag = True
else:
print("输入不合法,请重新输入")
device_name = content[int(num)].split("\t")[0]
self.shell_color.helper_text("[+] 确认设备名称\t" + device_name)
return device_name
def __adb_connect(self):
self.__adb_tools = "connect"
self.__adb_command = self.DEVICE_NAME
self.run_cmd(DEBUG_LEVEL=1)
if "device" in self.__buffer or "already connected to {}".format(self.DEVICE_NAME) in self.__buffer:
self.shell_color.warning_text("[+] Connect to DEVICE {} Success".format(self.DEVICE_NAME))
else:
self.shell_color.failure_text("[-] Connect to DEVICE {} Failed".format(self.DEVICE_NAME))
def run_cmd(self, DEBUG_LEVEL=2):
"""
:param DEBUG_LEVEL:
0 : cannot get any info
1 : use get_buffer() to get info
2 : print command and can use get_buffer() to get info
3 : print command and print the return content
:return:
"""
if DEBUG_LEVEL == 3:
print(self.shell_color.H_OK_BLUE +
self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command) + self.shell_color.E_END
)
self.__buffer = os.popen(self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command
)).read()
self.get_buffer()
elif DEBUG_LEVEL == 2:
print(self.shell_color.H_OK_BLUE +
self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command) + self.shell_color.E_END
)
self.__buffer = os.popen(self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command
)).read()
elif DEBUG_LEVEL == 1:
self.__buffer = os.popen(self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command
)).read()
return self.__buffer
else:
os.system(self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command
))
def get_buffer(self, n=1024, BUFFER_OUT_PUT_LEVEL=1):
"""
:param n: buffer size default 1024 chars
:param BUFFER_OUT_PUT_LEVEL:
1 INFO - color blue
0 HELPER - color green
-1 WEARING - color red
:return:
"""
if BUFFER_OUT_PUT_LEVEL == 1:
print(self.shell_color.H_OK_BLUE + "[+] DEBUG INFO " + self.shell_color.E_END + "\n" +
self.__buffer[0:n])
elif BUFFER_OUT_PUT_LEVEL == -1:
print(self.shell_color.H_FAIL + "[+] DEBUG WARNING " + self.shell_color.E_END + "\n" +
self.__buffer[0:n])
elif BUFFER_OUT_PUT_LEVEL == 0:
print(self.shell_color.H_OK_GREEN + "[+] DEBUG HELPER " + self.shell_color.E_END + "\n" +
self.__buffer[0:n])
return self.__buffer[0:n]
def get_sub_screen(self, file_name, screen_range):
i = Image.open(self.SCREEN_SHOOT_SAVE_PATH + file_name)
i.crop(
(
screen_range[0][0],
screen_range[0][1],
screen_range[0][0] + screen_range[1][0],
screen_range[0][1] + screen_range[1][1]
)
).save(self.SCREEN_SHOOT_SAVE_PATH + file_name)
def get_screen_shoot(self, file_name="1.png", screen_range=None):
sleep(1)
if screen_range is None:
screen_range = []
self.__adb_tools = "shell"
self.__adb_command = "/system/bin/screencap -p /sdcard/screenshot.png"
self.run_cmd(1)
self.__adb_tools = "pull"
self.__adb_command = "/sdcard/screenshot.png {}".format(self.SCREEN_SHOOT_SAVE_PATH + file_name)
self.run_cmd(1)
self.__adb_tools = "shell"
self.__adb_command = "rm /sdcard/screen.png"
self.run_cmd(1)
# print(self.SCREEN_SHOOT_SAVE_PATH + file_name)
if screen_range.__len__() == 2:
self.get_sub_screen(file_name, screen_range)
def get_mouse_swipe(self, XY_mXmY=None, FLAG=None):
sleep(1)
XY, mXmY = XY_mXmY
self.__adb_tools = "shell"
self.__adb_command = "input swipe {X1} {Y1} {X2} {Y2}".format(
X1=XY[0], Y1=XY[1], X2=XY[0] + mXmY[0], Y2=XY[1] + mXmY[1]
)
self.run_cmd(DEBUG_LEVEL=0)
def get_mouse_click(self, XY=None, FLAG=None):
# sleep(10)
sleep(0.5)
self.__adb_tools = "shell"
if FLAG is not None:
# self.shell_color.info_text(XY.__str__())
# self.__adb_tools = "shell"
self.__adb_command = "input tap {} {}".format(XY[0] + randint(-FLAG[0], FLAG[0]),
XY[1] + randint(-FLAG[1], FLAG[1]))
# self.run_cmd(DEBUG_LEVEL=0)
else:
# self.shell_color.info_text(XY.__str__())
# self.__adb_tools = "shell"
self.__adb_command = "input tap {} {}".format(XY[0] + randint(-1, 1),
XY[1] + randint(-1, 1))
# self.run_cmd(DEBUG_LEVEL=0)
# print(self.__adb_command)
# 如果你遇到了问题,可以把这百年输出并把日志分享到群里。
self.run_cmd(DEBUG_LEVEL=0)
def mv_file(self, file_name, file_path="/sdcard/", RM=False):
self.__adb_tools = "pull"
self.__adb_command = "{} {}".format(
file_path + file_name,
SCREEN_SHOOT_SAVE_PATH + file_name
)
self.run_cmd(DEBUG_LEVEL=0)
if RM:
self.__adb_tools = "shell"
self.__adb_command = "rm {}".format(file_path + file_name)
@staticmethod
def img_difference(img1, img2):
img1 = Image.open(img1).convert('1')
img2 = Image.open(img2).convert('1')
hist1 = list(img1.getdata())
hist2 = list(img2.getdata())
sum1 = 0
for i in range(len(hist1)):
if hist1[i] == hist2[i]:
sum1 += 1
else:
sum1 += 1 - float(abs(hist1[i] - hist2[i])) / max(hist1[i], hist2[i])
return sum1 / len(hist1)
def ch_tools(self, tools):
self.__adb_tools = tools
def ch_abd_command(self, command):
self.__adb_command = command
if __name__ == '__main__':
a = ADBShell()
| 39.37037 | 108 | 0.549271 | import os
from config import ADB_ROOT, ADB_HOST, SCREEN_SHOOT_SAVE_PATH, ShellColor
from PIL import Image
from time import sleep
from random import randint
class ADBShell(object):
def __init__(self, adb_host=ADB_HOST):
self.SCREEN_SHOOT_SAVE_PATH = os.path.abspath(SCREEN_SHOOT_SAVE_PATH) + "\\"
self.ADB_ROOT = ADB_ROOT
self.ADB_HOST = adb_host
self.__buffer = ""
self.shell_color = ShellColor()
self.__adb_tools = ""
self.__adb_command = ""
self.DEVICE_NAME = self.__adb_device_name_detector()
self.__command = "\"" + self.ADB_ROOT + "\\adb.exe\" -s " + self.DEVICE_NAME + " {tools} {command} "
def __adb_device_name_detector(self):
self.__command = "\"" + self.ADB_ROOT + "\\adb.exe\" {tools} {command}"
self.__adb_tools = "devices"
content = self.run_cmd(DEBUG_LEVEL=1).strip().split("\n")
content.pop(0)
if content.__len__() == 1:
device_name = content[0].split("\t")[0]
else:
self.shell_color.helper_text("[!] 检测到多台设备,根据 ADB_HOST 参数将自动选择设备")
device_name = ""
for c in range(content.__len__()):
print("[*] " + c.__str__() + "\t" + content[c])
if self.ADB_HOST == content[c].split("\t")[0]:
device_name = self.ADB_HOST
if device_name == "":
print("自动选择设备失败,请根据上述内容自行输入数字并选择")
input_valid_flag = False
num = "0"
while not input_valid_flag:
num = input(">")
if num.isnumeric() and int(num) <= content.__len__():
input_valid_flag = True
else:
print("输入不合法,请重新输入")
device_name = content[int(num)].split("\t")[0]
self.shell_color.helper_text("[+] 确认设备名称\t" + device_name)
return device_name
def __adb_connect(self):
self.__adb_tools = "connect"
self.__adb_command = self.DEVICE_NAME
self.run_cmd(DEBUG_LEVEL=1)
if "device" in self.__buffer or "already connected to {}".format(self.DEVICE_NAME) in self.__buffer:
self.shell_color.warning_text("[+] Connect to DEVICE {} Success".format(self.DEVICE_NAME))
else:
self.shell_color.failure_text("[-] Connect to DEVICE {} Failed".format(self.DEVICE_NAME))
def run_cmd(self, DEBUG_LEVEL=2):
if DEBUG_LEVEL == 3:
print(self.shell_color.H_OK_BLUE +
self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command) + self.shell_color.E_END
)
self.__buffer = os.popen(self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command
)).read()
self.get_buffer()
elif DEBUG_LEVEL == 2:
print(self.shell_color.H_OK_BLUE +
self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command) + self.shell_color.E_END
)
self.__buffer = os.popen(self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command
)).read()
elif DEBUG_LEVEL == 1:
self.__buffer = os.popen(self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command
)).read()
return self.__buffer
else:
os.system(self.__command.format(
tools=self.__adb_tools,
command=self.__adb_command
))
def get_buffer(self, n=1024, BUFFER_OUT_PUT_LEVEL=1):
if BUFFER_OUT_PUT_LEVEL == 1:
print(self.shell_color.H_OK_BLUE + "[+] DEBUG INFO " + self.shell_color.E_END + "\n" +
self.__buffer[0:n])
elif BUFFER_OUT_PUT_LEVEL == -1:
print(self.shell_color.H_FAIL + "[+] DEBUG WARNING " + self.shell_color.E_END + "\n" +
self.__buffer[0:n])
elif BUFFER_OUT_PUT_LEVEL == 0:
print(self.shell_color.H_OK_GREEN + "[+] DEBUG HELPER " + self.shell_color.E_END + "\n" +
self.__buffer[0:n])
return self.__buffer[0:n]
def get_sub_screen(self, file_name, screen_range):
i = Image.open(self.SCREEN_SHOOT_SAVE_PATH + file_name)
i.crop(
(
screen_range[0][0],
screen_range[0][1],
screen_range[0][0] + screen_range[1][0],
screen_range[0][1] + screen_range[1][1]
)
).save(self.SCREEN_SHOOT_SAVE_PATH + file_name)
def get_screen_shoot(self, file_name="1.png", screen_range=None):
sleep(1)
if screen_range is None:
screen_range = []
self.__adb_tools = "shell"
self.__adb_command = "/system/bin/screencap -p /sdcard/screenshot.png"
self.run_cmd(1)
self.__adb_tools = "pull"
self.__adb_command = "/sdcard/screenshot.png {}".format(self.SCREEN_SHOOT_SAVE_PATH + file_name)
self.run_cmd(1)
self.__adb_tools = "shell"
self.__adb_command = "rm /sdcard/screen.png"
self.run_cmd(1)
if screen_range.__len__() == 2:
self.get_sub_screen(file_name, screen_range)
def get_mouse_swipe(self, XY_mXmY=None, FLAG=None):
sleep(1)
XY, mXmY = XY_mXmY
self.__adb_tools = "shell"
self.__adb_command = "input swipe {X1} {Y1} {X2} {Y2}".format(
X1=XY[0], Y1=XY[1], X2=XY[0] + mXmY[0], Y2=XY[1] + mXmY[1]
)
self.run_cmd(DEBUG_LEVEL=0)
def get_mouse_click(self, XY=None, FLAG=None):
sleep(0.5)
self.__adb_tools = "shell"
if FLAG is not None:
self.__adb_command = "input tap {} {}".format(XY[0] + randint(-FLAG[0], FLAG[0]),
XY[1] + randint(-FLAG[1], FLAG[1]))
else:
self.__adb_command = "input tap {} {}".format(XY[0] + randint(-1, 1),
XY[1] + randint(-1, 1))
self.run_cmd(DEBUG_LEVEL=0)
def mv_file(self, file_name, file_path="/sdcard/", RM=False):
self.__adb_tools = "pull"
self.__adb_command = "{} {}".format(
file_path + file_name,
SCREEN_SHOOT_SAVE_PATH + file_name
)
self.run_cmd(DEBUG_LEVEL=0)
if RM:
self.__adb_tools = "shell"
self.__adb_command = "rm {}".format(file_path + file_name)
@staticmethod
def img_difference(img1, img2):
img1 = Image.open(img1).convert('1')
img2 = Image.open(img2).convert('1')
hist1 = list(img1.getdata())
hist2 = list(img2.getdata())
sum1 = 0
for i in range(len(hist1)):
if hist1[i] == hist2[i]:
sum1 += 1
else:
sum1 += 1 - float(abs(hist1[i] - hist2[i])) / max(hist1[i], hist2[i])
return sum1 / len(hist1)
def ch_tools(self, tools):
self.__adb_tools = tools
def ch_abd_command(self, command):
self.__adb_command = command
if __name__ == '__main__':
a = ADBShell()
| true | true |
1c3fdb9f9201128eeca24377e0cb7fd4a8ed0437 | 9,923 | py | Python | libs/PureCloudPlatformClientV2/models/voicemail_group_policy.py | rocketbot-cl/genesysCloud | dd9d9b5ebb90a82bab98c0d88b9585c22c91f333 | [
"MIT"
] | 1 | 2021-10-08T20:46:45.000Z | 2021-10-08T20:46:45.000Z | libs/PureCloudPlatformClientV2/models/voicemail_group_policy.py | rocketbot-cl/genesysCloud | dd9d9b5ebb90a82bab98c0d88b9585c22c91f333 | [
"MIT"
] | null | null | null | libs/PureCloudPlatformClientV2/models/voicemail_group_policy.py | rocketbot-cl/genesysCloud | dd9d9b5ebb90a82bab98c0d88b9585c22c91f333 | [
"MIT"
] | null | null | null | # coding: utf-8
"""
Copyright 2016 SmartBear Software
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.
Ref: https://github.com/swagger-api/swagger-codegen
"""
from pprint import pformat
from six import iteritems
import re
import json
from ..utils import sanitize_for_serialization
class VoicemailGroupPolicy(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
VoicemailGroupPolicy - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'name': 'str',
'group': 'Group',
'enabled': 'bool',
'send_email_notifications': 'bool',
'rotate_calls_secs': 'int',
'stop_ringing_after_rotations': 'int',
'overflow_group_id': 'str',
'group_alert_type': 'str'
}
self.attribute_map = {
'name': 'name',
'group': 'group',
'enabled': 'enabled',
'send_email_notifications': 'sendEmailNotifications',
'rotate_calls_secs': 'rotateCallsSecs',
'stop_ringing_after_rotations': 'stopRingingAfterRotations',
'overflow_group_id': 'overflowGroupId',
'group_alert_type': 'groupAlertType'
}
self._name = None
self._group = None
self._enabled = None
self._send_email_notifications = None
self._rotate_calls_secs = None
self._stop_ringing_after_rotations = None
self._overflow_group_id = None
self._group_alert_type = None
@property
def name(self):
"""
Gets the name of this VoicemailGroupPolicy.
:return: The name of this VoicemailGroupPolicy.
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""
Sets the name of this VoicemailGroupPolicy.
:param name: The name of this VoicemailGroupPolicy.
:type: str
"""
self._name = name
@property
def group(self):
"""
Gets the group of this VoicemailGroupPolicy.
The group associated with the policy
:return: The group of this VoicemailGroupPolicy.
:rtype: Group
"""
return self._group
@group.setter
def group(self, group):
"""
Sets the group of this VoicemailGroupPolicy.
The group associated with the policy
:param group: The group of this VoicemailGroupPolicy.
:type: Group
"""
self._group = group
@property
def enabled(self):
"""
Gets the enabled of this VoicemailGroupPolicy.
Whether voicemail is enabled for the group
:return: The enabled of this VoicemailGroupPolicy.
:rtype: bool
"""
return self._enabled
@enabled.setter
def enabled(self, enabled):
"""
Sets the enabled of this VoicemailGroupPolicy.
Whether voicemail is enabled for the group
:param enabled: The enabled of this VoicemailGroupPolicy.
:type: bool
"""
self._enabled = enabled
@property
def send_email_notifications(self):
"""
Gets the send_email_notifications of this VoicemailGroupPolicy.
Whether email notifications are sent to group members when a new voicemail is received
:return: The send_email_notifications of this VoicemailGroupPolicy.
:rtype: bool
"""
return self._send_email_notifications
@send_email_notifications.setter
def send_email_notifications(self, send_email_notifications):
"""
Sets the send_email_notifications of this VoicemailGroupPolicy.
Whether email notifications are sent to group members when a new voicemail is received
:param send_email_notifications: The send_email_notifications of this VoicemailGroupPolicy.
:type: bool
"""
self._send_email_notifications = send_email_notifications
@property
def rotate_calls_secs(self):
"""
Gets the rotate_calls_secs of this VoicemailGroupPolicy.
How many seconds to ring before rotating to the next member in the group
:return: The rotate_calls_secs of this VoicemailGroupPolicy.
:rtype: int
"""
return self._rotate_calls_secs
@rotate_calls_secs.setter
def rotate_calls_secs(self, rotate_calls_secs):
"""
Sets the rotate_calls_secs of this VoicemailGroupPolicy.
How many seconds to ring before rotating to the next member in the group
:param rotate_calls_secs: The rotate_calls_secs of this VoicemailGroupPolicy.
:type: int
"""
self._rotate_calls_secs = rotate_calls_secs
@property
def stop_ringing_after_rotations(self):
"""
Gets the stop_ringing_after_rotations of this VoicemailGroupPolicy.
How many rotations to go through
:return: The stop_ringing_after_rotations of this VoicemailGroupPolicy.
:rtype: int
"""
return self._stop_ringing_after_rotations
@stop_ringing_after_rotations.setter
def stop_ringing_after_rotations(self, stop_ringing_after_rotations):
"""
Sets the stop_ringing_after_rotations of this VoicemailGroupPolicy.
How many rotations to go through
:param stop_ringing_after_rotations: The stop_ringing_after_rotations of this VoicemailGroupPolicy.
:type: int
"""
self._stop_ringing_after_rotations = stop_ringing_after_rotations
@property
def overflow_group_id(self):
"""
Gets the overflow_group_id of this VoicemailGroupPolicy.
A fallback group to contact when all of the members in this group did not answer the call.
:return: The overflow_group_id of this VoicemailGroupPolicy.
:rtype: str
"""
return self._overflow_group_id
@overflow_group_id.setter
def overflow_group_id(self, overflow_group_id):
"""
Sets the overflow_group_id of this VoicemailGroupPolicy.
A fallback group to contact when all of the members in this group did not answer the call.
:param overflow_group_id: The overflow_group_id of this VoicemailGroupPolicy.
:type: str
"""
self._overflow_group_id = overflow_group_id
@property
def group_alert_type(self):
"""
Gets the group_alert_type of this VoicemailGroupPolicy.
Specifies if the members in this group should be contacted randomly, in a specific order, or by round-robin.
:return: The group_alert_type of this VoicemailGroupPolicy.
:rtype: str
"""
return self._group_alert_type
@group_alert_type.setter
def group_alert_type(self, group_alert_type):
"""
Sets the group_alert_type of this VoicemailGroupPolicy.
Specifies if the members in this group should be contacted randomly, in a specific order, or by round-robin.
:param group_alert_type: The group_alert_type of this VoicemailGroupPolicy.
:type: str
"""
allowed_values = ["RANDOM", "ROUND_ROBIN", "SEQUENTIAL"]
if group_alert_type.lower() not in map(str.lower, allowed_values):
# print("Invalid value for group_alert_type -> " + group_alert_type)
self._group_alert_type = "outdated_sdk_version"
else:
self._group_alert_type = group_alert_type
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_json(self):
"""
Returns the model as raw JSON
"""
return json.dumps(sanitize_for_serialization(self.to_dict()))
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| 31.302839 | 116 | 0.623299 |
from pprint import pformat
from six import iteritems
import re
import json
from ..utils import sanitize_for_serialization
class VoicemailGroupPolicy(object):
def __init__(self):
self.swagger_types = {
'name': 'str',
'group': 'Group',
'enabled': 'bool',
'send_email_notifications': 'bool',
'rotate_calls_secs': 'int',
'stop_ringing_after_rotations': 'int',
'overflow_group_id': 'str',
'group_alert_type': 'str'
}
self.attribute_map = {
'name': 'name',
'group': 'group',
'enabled': 'enabled',
'send_email_notifications': 'sendEmailNotifications',
'rotate_calls_secs': 'rotateCallsSecs',
'stop_ringing_after_rotations': 'stopRingingAfterRotations',
'overflow_group_id': 'overflowGroupId',
'group_alert_type': 'groupAlertType'
}
self._name = None
self._group = None
self._enabled = None
self._send_email_notifications = None
self._rotate_calls_secs = None
self._stop_ringing_after_rotations = None
self._overflow_group_id = None
self._group_alert_type = None
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def group(self):
return self._group
@group.setter
def group(self, group):
self._group = group
@property
def enabled(self):
return self._enabled
@enabled.setter
def enabled(self, enabled):
self._enabled = enabled
@property
def send_email_notifications(self):
return self._send_email_notifications
@send_email_notifications.setter
def send_email_notifications(self, send_email_notifications):
self._send_email_notifications = send_email_notifications
@property
def rotate_calls_secs(self):
return self._rotate_calls_secs
@rotate_calls_secs.setter
def rotate_calls_secs(self, rotate_calls_secs):
self._rotate_calls_secs = rotate_calls_secs
@property
def stop_ringing_after_rotations(self):
return self._stop_ringing_after_rotations
@stop_ringing_after_rotations.setter
def stop_ringing_after_rotations(self, stop_ringing_after_rotations):
self._stop_ringing_after_rotations = stop_ringing_after_rotations
@property
def overflow_group_id(self):
return self._overflow_group_id
@overflow_group_id.setter
def overflow_group_id(self, overflow_group_id):
self._overflow_group_id = overflow_group_id
@property
def group_alert_type(self):
return self._group_alert_type
@group_alert_type.setter
def group_alert_type(self, group_alert_type):
allowed_values = ["RANDOM", "ROUND_ROBIN", "SEQUENTIAL"]
if group_alert_type.lower() not in map(str.lower, allowed_values):
self._group_alert_type = "outdated_sdk_version"
else:
self._group_alert_type = group_alert_type
def to_dict(self):
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_json(self):
return json.dumps(sanitize_for_serialization(self.to_dict()))
def to_str(self):
return pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
1c3fdc8113753c7644cdee8192c0a0284c64bf30 | 68,259 | py | Python | se/se_epub_lint.py | jggimi/tools | b4aa35f986b22ab1b92dae1e0bfad9c4d94b6cf7 | [
"CC0-1.0"
] | null | null | null | se/se_epub_lint.py | jggimi/tools | b4aa35f986b22ab1b92dae1e0bfad9c4d94b6cf7 | [
"CC0-1.0"
] | null | null | null | se/se_epub_lint.py | jggimi/tools | b4aa35f986b22ab1b92dae1e0bfad9c4d94b6cf7 | [
"CC0-1.0"
] | null | null | null | #!/usr/bin/env python3
"""
Contains the LintMessage class and the Lint function, which is broken out of
the SeEpub class for readability and maintainability.
Strictly speaking, the lint() function should be a class member of SeEpub. But
the function is very big and it makes editing easier to put in a separate file.
"""
import filecmp
import glob
import html
import io
import os
import unicodedata
from pathlib import Path
from typing import Dict, List
import importlib_resources
import lxml.cssselect
import lxml.etree as etree
import regex
import roman
from bs4 import BeautifulSoup, NavigableString
import se
import se.easy_xml
import se.formatting
import se.images
COLOPHON_VARIABLES = ["TITLE", "YEAR", "AUTHOR_WIKI_URL", "AUTHOR", "PRODUCER_URL", "PRODUCER", "PG_YEAR", "TRANSCRIBER_1", "TRANSCRIBER_2", "PG_URL", "IA_URL", "PAINTING", "ARTIST_WIKI_URL", "ARTIST"]
EPUB_SEMANTIC_VOCABULARY = ["cover", "frontmatter", "bodymatter", "backmatter", "volume", "part", "chapter", "division", "foreword", "preface", "prologue", "introduction", "preamble", "conclusion", "epilogue", "afterword", "epigraph", "toc", "landmarks", "loa", "loi", "lot", "lov", "appendix", "colophon", "index", "index-headnotes", "index-legend", "index-group", "index-entry-list", "index-entry", "index-term", "index-editor-note", "index-locator", "index-locator-list", "index-locator-range", "index-xref-preferred", "index-xref-related", "index-term-category", "index-term-categories", "glossary", "glossterm", "glossdef", "bibliography", "biblioentry", "titlepage", "halftitlepage", "copyright-page", "acknowledgments", "imprint", "imprimatur", "contributors", "other-credits", "errata", "dedication", "revision-history", "notice", "tip", "halftitle", "fulltitle", "covertitle", "title", "subtitle", "bridgehead", "learning-objective", "learning-resource", "assessment", "qna", "panel", "panel-group", "balloon", "text-area", "sound-area", "footnote", "endnote", "footnotes", "endnotes", "noteref", "keyword", "topic-sentence", "concluding-sentence", "pagebreak", "page-list", "table", "table-row", "table-cell", "list", "list-item", "figure", "aside"]
class LintMessage:
"""
An object representing an output message for the lint function.
Contains information like message text, severity, and the epub filename that generated the message.
"""
def __init__(self, text: str, message_type=se.MESSAGE_TYPE_WARNING, filename: str = "", submessages: List[str] = None):
self.text = text.strip()
self.filename = filename
self.message_type = message_type
self.submessages = submessages
def _get_malformed_urls(xhtml: str) -> list:
"""
Helper function used in self.lint()
Get a list of URLs in the epub that do not match SE standards.
INPUTS
xhtml: A string of XHTML to check
OUTPUTS
A list of strings representing any malformed URLs in the XHTML string
"""
messages = []
# Check for non-https URLs
if "http://gutenberg.org" in xhtml or "https://gutenberg.org" in xhtml:
messages.append(LintMessage("gutenberg.org URL missing leading www.", se.MESSAGE_TYPE_ERROR))
if "http://www.gutenberg.org" in xhtml:
messages.append(LintMessage("Non-https gutenberg.org URL.", se.MESSAGE_TYPE_ERROR))
if "http://www.pgdp.net" in xhtml:
messages.append(LintMessage("Non-https pgdp.net URL.", se.MESSAGE_TYPE_ERROR))
if "http://catalog.hathitrust.org" in xhtml:
messages.append(LintMessage("Non-https hathitrust.org URL.", se.MESSAGE_TYPE_ERROR))
if "http://archive.org" in xhtml:
messages.append(LintMessage("Non-https archive.org URL.", se.MESSAGE_TYPE_ERROR))
if "www.archive.org" in xhtml:
messages.append(LintMessage("archive.org URL should not have leading www.", se.MESSAGE_TYPE_ERROR))
if "http://en.wikipedia.org" in xhtml:
messages.append(LintMessage("Non-https en.wikipedia.org URL.", se.MESSAGE_TYPE_ERROR))
# Check for malformed canonical URLs
if regex.search(r"books\.google\.com/books\?id=.+?[&#]", xhtml):
messages.append(LintMessage("Non-canonical Google Books URL. Google Books URLs must look exactly like https://books.google.com/books?id=<BOOK-ID>"))
if "babel.hathitrust.org" in xhtml:
messages.append(LintMessage("Non-canonical HathiTrust URL. HathiTrust URLs must look exactly like https://catalog.hathitrust.org/Record/<BOOK-ID>"))
if ".gutenberg.org/files/" in xhtml:
messages.append(LintMessage("Non-canonical Project Gutenberg URL. Project Gutenberg URLs must look exactly like https://www.gutenberg.org/ebooks/<BOOK-ID>"))
if "archive.org/stream" in xhtml:
messages.append(LintMessage("Non-canonical archive.org URL. Internet Archive URLs must look exactly like https://archive.org/details/<BOOK-ID>"))
return messages
def _get_unused_selectors(self) -> List[str]:
"""
Helper function used in self.lint(); merge directly into lint()?
Get a list of CSS selectors that do not actually select HTML in the epub.
INPUTS
None
OUTPUTS
A list of strings representing CSS selectors that do not actually select HTML in the epub.
"""
try:
with open(self.path / "src" / "epub" / "css" / "local.css", encoding="utf-8") as file:
css = file.read()
except Exception:
raise FileNotFoundError("Couldn’t open {}".format(self.path / "src" / "epub" / "css" / "local.css"))
# Remove @supports directives, as the parser can't handle them
css = regex.sub(r"^@supports\(.+?\){(.+?)}\s*}", "\\1}", css, flags=regex.MULTILINE | regex.DOTALL)
# Remove actual content of css selectors
css = regex.sub(r"{[^}]+}", "", css)
# Remove trailing commas
css = regex.sub(r",", "", css)
# Remove comments
css = regex.sub(r"/\*.+?\*/", "", css, flags=regex.DOTALL)
# Remove @ defines
css = regex.sub(r"^@.+", "", css, flags=regex.MULTILINE)
# Construct a dictionary of selectors
selectors = {line for line in css.splitlines() if line != ""}
unused_selectors = set(selectors)
# Get a list of .xhtml files to search
filenames = glob.glob(str(self.path / "src" / "epub" / "text" / "*.xhtml"))
# Now iterate over each CSS selector and see if it's used in any of the files we found
for selector in selectors:
try:
sel = lxml.cssselect.CSSSelector(selector, translator="html", namespaces=se.XHTML_NAMESPACES)
except lxml.cssselect.ExpressionError:
# This gets thrown if we use pseudo-elements, which lxml doesn't support
unused_selectors.remove(selector)
continue
except lxml.cssselect.SelectorSyntaxError as ex:
raise se.InvalidCssException(f"Couldn’t parse CSS in or near this line: {selector}\n{ex}")
for filename in filenames:
if not filename.endswith("titlepage.xhtml") and not filename.endswith("imprint.xhtml") and not filename.endswith("uncopyright.xhtml"):
# We have to remove the default namespace declaration from our document, otherwise
# xpath won't find anything at all. See http://stackoverflow.com/questions/297239/why-doesnt-xpath-work-when-processing-an-xhtml-document-with-lxml-in-python
with open(filename, "r", encoding="utf-8") as file:
xhtml = file.read().replace(" xmlns=\"http://www.w3.org/1999/xhtml\"", "")
try:
tree = etree.fromstring(str.encode(xhtml))
except etree.XMLSyntaxError as ex:
raise se.InvalidXhtmlException("Couldn’t parse XHTML in file: {}, error: {}".format(filename, str(ex)))
except Exception:
raise se.InvalidXhtmlException(f"Couldn’t parse XHTML in file: {filename}")
if tree.xpath(sel.path, namespaces=se.XHTML_NAMESPACES):
unused_selectors.remove(selector)
break
return list(unused_selectors)
def lint(self, metadata_xhtml) -> list:
"""
Check this ebook for some common SE style errors.
INPUTS
None
OUTPUTS
A list of LintMessage objects.
"""
messages = []
has_halftitle = False
has_frontmatter = False
has_cover_source = False
cover_svg_title = ""
titlepage_svg_title = ""
xhtml_css_classes: Dict[str, int] = {}
headings: List[tuple] = []
# Get the ebook language, for later use
language = regex.search(r"<dc:language>([^>]+?)</dc:language>", metadata_xhtml).group(1)
# Check local.css for various items, for later use
abbr_elements: List[str] = []
css = ""
with open(self.path / "src" / "epub" / "css" / "local.css", "r", encoding="utf-8") as file:
css = file.read()
local_css_has_subtitle_style = "span[epub|type~=\"subtitle\"]" in css
abbr_styles = regex.findall(r"abbr\.[a-z]+", css)
matches = regex.findall(r"^h[0-6]\s*,?{?", css, flags=regex.MULTILINE)
if matches:
messages.append(LintMessage("Do not directly select h[0-6] elements, as they are used in template files; use more specific selectors.", se.MESSAGE_TYPE_ERROR, "local.css"))
# Check for presence of ./dist/ folder
if (self.path / "dist").exists():
messages.append(LintMessage("Illegal ./dist/ folder. Do not commit compiled versions of the source.", se.MESSAGE_TYPE_ERROR, "./dist/"))
# Check if there are non-typogrified quotes or em-dashes in metadata descriptions
if regex.search(r"#description\">[^<]+?(['\"]|\-\-)[^<]+?</meta>", metadata_xhtml.replace("\">", "").replace("=\"", "")) is not None:
messages.append(LintMessage("Non-typogrified \", ', or -- detected in metadata long description", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check if there are non-typogrified quotes or em-dashes in the title.
# The open-ended start and end of the regex also catches title-sort
if regex.search(r"title\">[^<]+?(['\"]|\-\-)[^<]+?<", metadata_xhtml) is not None:
messages.append(LintMessage("Non-typogrified \", ', or -- detected in metadata title", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for malformed long description HTML
long_description = regex.findall(r"<meta id=\"long-description\".+?>(.+?)</meta>", metadata_xhtml, flags=regex.DOTALL)
if long_description:
long_description = "<?xml version=\"1.0\"?><html xmlns=\"http://www.w3.org/1999/xhtml\">" + html.unescape(long_description[0]) + "</html>"
try:
etree.parse(io.StringIO(long_description))
except lxml.etree.XMLSyntaxError as ex:
messages.append(LintMessage("Metadata long description is not valid HTML. LXML says: " + str(ex), se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for double spacing
regex_string = fr"[{se.NO_BREAK_SPACE}{se.HAIR_SPACE} ]{{2,}}"
matches = regex.findall(regex_string, metadata_xhtml)
if matches:
messages.append(LintMessage("Double spacing detected in file. Sentences should be single-spaced.", se.MESSAGE_TYPE_ERROR, "content.opf"))
if regex.search(r"<dc:description id=\"description\">[^<]+?(['\"]|\-\-)[^<]+?</dc:description>", metadata_xhtml) is not None:
messages.append(LintMessage("Non-typogrified \", ', or -- detected in metadata dc:description.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for punctuation outside quotes. We don't check single quotes because contractions are too common.
matches = regex.findall(r"[a-zA-Z][”][,.]", metadata_xhtml)
if matches:
messages.append(LintMessage("Comma or period outside of double quote. Generally punctuation should go within single and double quotes.", se.MESSAGE_TYPE_WARNING, "content.opf"))
# Make sure long-description is escaped HTML
if "<meta id=\"long-description\" property=\"se:long-description\" refines=\"#description\">\n\t\t\t<p>" not in metadata_xhtml:
messages.append(LintMessage("Long description must be escaped HTML.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for HTML entities in long-description, but allow &amp;
if regex.search(r"&[a-z]+?;", metadata_xhtml.replace("&amp;", "")):
messages.append(LintMessage("HTML entites detected in metadata. Use Unicode equivalents instead.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for illegal em-dashes in <dc:subject>
if regex.search(r"<dc:subject id=\"[^\"]+?\">[^<]+?—[^<]+?</dc:subject>", metadata_xhtml) is not None:
messages.append(LintMessage("Illegal em-dash detected in dc:subject; use --", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for empty production notes
if "<meta property=\"se:production-notes\">Any special notes about the production of this ebook for future editors/producers? Remove this element if not.</meta>" in metadata_xhtml:
messages.append(LintMessage("Empty production-notes element in metadata.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for illegal VCS URLs
matches = regex.findall(r"<meta property=\"se:url\.vcs\.github\">([^<]+?)</meta>", metadata_xhtml)
if matches:
for match in matches:
if not match.startswith("https://github.com/standardebooks/"):
messages.append(LintMessage(f"Illegal se:url.vcs.github. VCS URLs must begin with https://github.com/standardebooks/: {match}", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for HathiTrust scan URLs instead of actual record URLs
if "babel.hathitrust.org" in metadata_xhtml or "hdl.handle.net" in metadata_xhtml:
messages.append(LintMessage("Use HathiTrust record URLs, not page scan URLs, in metadata, imprint, and colophon. Record URLs look like: https://catalog.hathitrust.org/Record/<RECORD-ID>", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for illegal se:subject tags
matches = regex.findall(r"<meta property=\"se:subject\">([^<]+?)</meta>", metadata_xhtml)
if matches:
for match in matches:
if match not in se.SE_GENRES:
messages.append(LintMessage(f"Illegal se:subject: {match}", se.MESSAGE_TYPE_ERROR, "content.opf"))
else:
messages.append(LintMessage("No se:subject <meta> element found.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for CDATA tags
if "<![CDATA[" in metadata_xhtml:
messages.append(LintMessage("<![CDATA[ detected. Run `clean` to canonicalize <![CDATA[ sections.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check that our provided identifier matches the generated identifier
identifier = regex.sub(r"<.+?>", "", regex.findall(r"<dc:identifier id=\"uid\">.+?</dc:identifier>", metadata_xhtml)[0])
if identifier != self.generated_identifier:
messages.append(LintMessage(f"<dc:identifier> does not match expected: {self.generated_identifier}", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check that the GitHub repo URL is as expected
if ("<meta property=\"se:url.vcs.github\">" + self.generated_github_repo_url + "</meta>") not in metadata_xhtml:
messages.append(LintMessage(f"GitHub repo URL does not match expected: {self.generated_github_repo_url}", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check if se:name.person.full-name matches their titlepage name
matches = regex.findall(r"<meta property=\"se:name\.person\.full-name\" refines=\"#([^\"]+?)\">([^<]*?)</meta>", metadata_xhtml)
duplicate_names = []
for match in matches:
name_matches = regex.findall(fr"<([a-z:]+)[^<]+?id=\"{match[0]}\"[^<]*?>([^<]*?)</\1>", metadata_xhtml)
for name_match in name_matches:
if name_match[1] == match[1]:
duplicate_names.append(name_match[1])
if duplicate_names:
messages.append(LintMessage("se:name.person.full-name property identical to regular name. If the two are identical the full name <meta> element must be removed.", se.MESSAGE_TYPE_ERROR, "content.opf", duplicate_names))
# Check for malformed URLs
for message in _get_malformed_urls(metadata_xhtml):
message.filename = "content.opf"
messages.append(message)
if regex.search(r"id\.loc\.gov/authorities/names/[^\.]+\.html", metadata_xhtml):
messages.append(LintMessage("id.loc.gov URL ending with illegal .html", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Does the manifest match the generated manifest?
for manifest in regex.findall(r"<manifest>.*?</manifest>", metadata_xhtml, flags=regex.DOTALL):
manifest = regex.sub(r"[\n\t]", "", manifest)
expected_manifest = regex.sub(r"[\n\t]", "", self.generate_manifest())
if manifest != expected_manifest:
messages.append(LintMessage("<manifest> does not match expected structure.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Make sure some static files are unchanged
try:
with importlib_resources.path("se.data.templates", "LICENSE.md") as license_file_path:
if not filecmp.cmp(license_file_path, self.path / "LICENSE.md"):
messages.append(LintMessage(f"LICENSE.md does not match {license_file_path}", se.MESSAGE_TYPE_ERROR, "LICENSE.md"))
except Exception:
messages.append(LintMessage("Missing ./LICENSE.md", se.MESSAGE_TYPE_ERROR, "LICENSE.md"))
with importlib_resources.path("se.data.templates", "core.css") as core_css_file_path:
if not filecmp.cmp(core_css_file_path, self.path / "src" / "epub" / "css" / "core.css"):
messages.append(LintMessage(f"core.css does not match {core_css_file_path}", se.MESSAGE_TYPE_ERROR, "core.css"))
with importlib_resources.path("se.data.templates", "logo.svg") as logo_svg_file_path:
if not filecmp.cmp(logo_svg_file_path, self.path / "src" / "epub" / "images" / "logo.svg"):
messages.append(LintMessage(f"logo.svg does not match {logo_svg_file_path}", se.MESSAGE_TYPE_ERROR, "logo.svg"))
with importlib_resources.path("se.data.templates", "uncopyright.xhtml") as uncopyright_file_path:
if not filecmp.cmp(uncopyright_file_path, self.path / "src" / "epub" / "text" / "uncopyright.xhtml"):
messages.append(LintMessage(f"uncopyright.xhtml does not match {uncopyright_file_path}", se.MESSAGE_TYPE_ERROR, "uncopyright.xhtml"))
# Check for unused selectors
unused_selectors = _get_unused_selectors(self)
if unused_selectors:
messages.append(LintMessage("Unused CSS selectors:", se.MESSAGE_TYPE_ERROR, "local.css", unused_selectors))
# Now iterate over individual files for some checks
for root, _, filenames in os.walk(self.path):
for filename in sorted(filenames, key=se.natural_sort_key):
if ".git" in str(Path(root) / filename):
continue
if filename.startswith("cover.source."):
has_cover_source = True
if filename != "LICENSE.md" and regex.findall(r"[A-Z]", filename):
messages.append(LintMessage("Illegal uppercase letter in filename", se.MESSAGE_TYPE_ERROR, filename))
if "-0" in filename:
messages.append(LintMessage("Illegal leading 0 in filename", se.MESSAGE_TYPE_ERROR, filename))
if filename.endswith(tuple(se.BINARY_EXTENSIONS)) or filename.endswith("core.css"):
continue
if filename.startswith(".") or filename.startswith("README"):
if filename == ".gitignore":
# .gitignore is optional, because our standard gitignore ignores itself.
# So if it's present, it must match our template.
with importlib_resources.path("se.data.templates", "gitignore") as gitignore_file_path:
if not filecmp.cmp(gitignore_file_path, str(self.path / ".gitignore")):
messages.append(LintMessage(f".gitignore does not match {gitignore_file_path}", se.MESSAGE_TYPE_ERROR, ".gitignore"))
continue
else:
messages.append(LintMessage(f"Illegal {filename} file detected in {root}", se.MESSAGE_TYPE_ERROR))
continue
with open(Path(root) / filename, "r", encoding="utf-8") as file:
try:
file_contents = file.read()
except UnicodeDecodeError:
# This is more to help developers find weird files that might choke 'lint', hopefully unnecessary for end users
messages.append(LintMessage("Problem decoding file as utf-8", se.MESSAGE_TYPE_ERROR, filename))
continue
if "http://standardebooks.org" in file_contents:
messages.append(LintMessage("Non-HTTPS Standard Ebooks URL detected.", se.MESSAGE_TYPE_ERROR, filename))
if "UTF-8" in file_contents:
messages.append(LintMessage("String \"UTF-8\" must always be lowercase.", se.MESSAGE_TYPE_ERROR, filename))
if filename == "halftitle.xhtml":
has_halftitle = True
if "<title>Half Title</title>" not in file_contents:
messages.append(LintMessage("Half title <title> elements must contain exactly: \"Half Title\".", se.MESSAGE_TYPE_ERROR, filename))
if filename == "colophon.xhtml":
if "<a href=\"{}\">{}</a>".format(self.generated_identifier.replace("url:", ""), self.generated_identifier.replace("url:https://", "")) not in file_contents:
messages.append(LintMessage(f"Unexpected SE identifier in colophon. Expected: {self.generated_identifier}", se.MESSAGE_TYPE_ERROR, filename))
if ">trl<" in metadata_xhtml and "translated from" not in file_contents:
messages.append(LintMessage("Translator detected in metadata, but no “translated from LANG” block in colophon", se.MESSAGE_TYPE_ERROR, filename))
# Check if we forgot to fill any variable slots
for variable in COLOPHON_VARIABLES:
if regex.search(fr"\b{variable}\b", file_contents):
messages.append(LintMessage(f"Missing data in colophon: {variable}", se.MESSAGE_TYPE_ERROR, filename))
# Are the sources represented correctly?
# We don't have a standard yet for more than two sources (transcription and scan) so just ignore that case for now.
matches = regex.findall(r"<dc:source>([^<]+?)</dc:source>", metadata_xhtml)
if len(matches) <= 2:
for link in matches:
if "gutenberg.org" in link and f"<a href=\"{link}\">Project Gutenberg</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in colophon.xhtml. Expected: <a href=\"{link}\">Project Gutenberg</a>", se.MESSAGE_TYPE_WARNING, filename))
if "hathitrust.org" in link and f"the<br/>\n\t\t\t<a href=\"{link}\">HathiTrust Digital Library</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in colophon.xhtml. Expected: the<br/> <a href=\"{link}\">HathiTrust Digital Library</a>", se.MESSAGE_TYPE_WARNING, filename))
if "archive.org" in link and f"the<br/>\n\t\t\t<a href=\"{link}\">Internet Archive</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in colophon.xhtml. Expected: the<br/> <a href=\"{link}\">Internet Archive</a>", se.MESSAGE_TYPE_WARNING, filename))
if "books.google.com" in link and f"<a href=\"{link}\">Google Books</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in colophon.xhtml. Expected: <a href=\"{link}\">Google Books</a>", se.MESSAGE_TYPE_WARNING, filename))
if filename == "titlepage.xhtml":
if "<title>Titlepage</title>" not in file_contents:
messages.append(LintMessage("Titlepage <title> elements must contain exactly: \"Titlepage\".", se.MESSAGE_TYPE_ERROR, filename))
if filename.endswith(".svg"):
# Check for fill: #000 which should simply be removed
matches = regex.findall(r"fill=\"\s*#000", file_contents) + regex.findall(r"style=\"[^\"]*?fill:\s*#000", file_contents)
if matches:
messages.append(LintMessage("Illegal style=\"fill: #000\" or fill=\"#000\".", se.MESSAGE_TYPE_ERROR, filename))
# Check for illegal height or width on root <svg> element
if filename != "logo.svg": # Do as I say, not as I do...
matches = regex.findall(r"<svg[^>]*?(height|width)=[^>]*?>", file_contents)
if matches:
messages.append(LintMessage("Illegal height or width on root <svg> element. Size SVGs using the viewbox attribute only.", se.MESSAGE_TYPE_ERROR, filename))
# Check for illegal transform attribute
matches = regex.findall(r"<[a-z]+[^>]*?transform=[^>]*?>", file_contents)
if matches:
messages.append(LintMessage("Illegal transform attribute. SVGs should be optimized to remove use of transform. Try using Inkscape to save as an \"optimized SVG\".", se.MESSAGE_TYPE_ERROR, filename))
if os.sep + "src" + os.sep not in root:
# Check that cover and titlepage images are in all caps
if filename == "cover.svg":
matches = regex.findall(r"<text[^>]+?>.*[a-z].*</text>", file_contents)
if matches:
messages.append(LintMessage("Lowercase letters in cover. Cover text must be all uppercase.", se.MESSAGE_TYPE_ERROR, filename))
# Save for later comparison with titlepage
matches = regex.findall(r"<title>(.*?)</title>", file_contents)
for match in matches:
cover_svg_title = match.replace("The cover for ", "")
if filename == "titlepage.svg":
matches = regex.findall(r"<text[^>]+?>(.*[a-z].*)</text>", html.unescape(file_contents))
for match in matches:
if match not in ("translated by", "illustrated by", "and"):
messages.append(LintMessage("Lowercase letters in titlepage. Titlepage text must be all uppercase except \"translated by\" and \"illustrated by\".", se.MESSAGE_TYPE_ERROR, filename))
# For later comparison with cover
matches = regex.findall(r"<title>(.*?)</title>", file_contents)
for match in matches:
titlepage_svg_title = match.replace("The titlepage for ", "")
if filename.endswith(".css"):
# Check CSS style
# First remove @supports selectors and normalize indentation within them
matches = regex.findall(r"^@supports\(.+?\){.+?}\s*}", file_contents, flags=regex.MULTILINE | regex.DOTALL)
for match in matches:
processed_match = regex.sub(r"^@supports\(.+?\){\s*(.+?)\s*}\s*}", "\\1", match.replace("\n\t", "\n") + "\n}", flags=regex.MULTILINE | regex.DOTALL)
file_contents = file_contents.replace(match, processed_match)
# Remove comments that are on their own line
file_contents = regex.sub(r"^/\*.+?\*/\n", "", file_contents, flags=regex.MULTILINE | regex.DOTALL)
# Check for unneeded white-space nowrap in abbr selectors
matches = regex.findall(r"abbr[^{]*?{[^}]*?white-space:\s*nowrap;[^}]*?}", css, regex.DOTALL)
if matches:
messages.append(LintMessage("abbr selector does not need white-space: nowrap; as it inherits it from core.css.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Don't specify border color
matches = regex.findall(r"(?:border|color).+?(?:#[a-f0-9]{0,6}|black|white|red)", file_contents, flags=regex.IGNORECASE)
if matches:
messages.append(LintMessage("Don’t specify border colors, so that reading systems can adjust for night mode.", se.MESSAGE_TYPE_WARNING, filename, matches))
# If we select on the xml namespace, make sure we define the namespace in the CSS, otherwise the selector won't work
matches = regex.findall(r"\[\s*xml\s*\|", file_contents)
if matches and "@namespace xml \"http://www.w3.org/XML/1998/namespace\";" not in file_contents:
messages.append(LintMessage("[xml|attr] selector in CSS, but no XML namespace declared (@namespace xml \"http://www.w3.org/XML/1998/namespace\";).", se.MESSAGE_TYPE_ERROR, filename))
if filename.endswith(".xhtml"):
for message in _get_malformed_urls(file_contents):
message.filename = filename
messages.append(message)
# Check if this is a frontmatter file
if filename not in ("titlepage.xhtml", "imprint.xhtml", "toc.xhtml"):
matches = regex.findall(r"epub:type=\"[^\"]*?frontmatter[^\"]*?\"", file_contents)
if matches:
has_frontmatter = True
# Add new CSS classes to global list
if filename not in se.IGNORED_FILENAMES:
matches = regex.findall(r"(?:class=\")[^\"]+?(?:\")", file_contents)
for match in matches:
for css_class in match.replace("class=", "").replace("\"", "").split():
if css_class in xhtml_css_classes:
xhtml_css_classes[css_class] += 1
else:
xhtml_css_classes[css_class] = 1
#xhtml_css_classes = xhtml_css_classes + match.replace("class=", "").replace("\"", "").split()
# Read file contents into a DOM for querying
dom = BeautifulSoup(file_contents, "lxml")
# Store all headings to check for ToC references later
if filename != "toc.xhtml":
for match in dom.select("h1,h2,h3,h4,h5,h6"):
# Remove any links to the endnotes
endnote_ref = match.find("a", attrs={"epub:type": regex.compile("^.*noteref.*$")})
if endnote_ref:
endnote_ref.extract()
# Decide whether to remove subheadings based on the following logic:
# If the closest parent <section> is a part or division, then keep subtitle
# Else, if the closest parent <section> is a halftitlepage, then discard subtitle
# Else, if the first child of the heading is not z3998:roman, then also discard subtitle
# Else, keep the subtitle.
heading_subtitle = match.find(attrs={"epub:type": regex.compile("^.*subtitle.*$")})
if heading_subtitle:
# If an <h#> tag has a subtitle, the non-subtitle text must also be wrapped in a <span>.
# This invocation of match.find() returns all text nodes. We don't want any text nodes, so if it returns anything then we know we're
# missing a <span> somewhere.
if match.find(text=True, recursive=False).strip():
messages.append(LintMessage(f"<{match.name}> element has subtitle <span>, but first line is not wrapped in a <span>. See semantics manual for structure of headers with subtitles.", se.MESSAGE_TYPE_ERROR, filename))
# OK, move on with processing headers.
parent_section = match.find_parents("section")
# Sometimes we might not have a parent <section>, like in Keats' Poetry
if not parent_section:
parent_section = match.find_parents("body")
closest_section_epub_type = parent_section[0].get("epub:type") or ""
heading_first_child_epub_type = match.find("span", recursive=False).get("epub:type") or ""
if regex.findall(r"^.*(part|division|volume).*$", closest_section_epub_type) and not regex.findall(r"^.*se:short-story.*$", closest_section_epub_type):
remove_subtitle = False
elif regex.findall(r"^.*halftitlepage.*$", closest_section_epub_type):
remove_subtitle = True
elif not regex.findall(r"^.*z3998:roman.*$", heading_first_child_epub_type):
remove_subtitle = True
else:
remove_subtitle = False
if remove_subtitle:
heading_subtitle.extract()
normalized_text = " ".join(match.get_text().split())
headings = headings + [(normalized_text, filename)]
# Check for direct z3998:roman spans that should have their semantic pulled into the parent element
matches = regex.findall(r"<([a-z0-9]+)[^>]*?>\s*(<span epub:type=\"z3998:roman\">[^<]+?</span>)\s*</\1>", file_contents, flags=regex.DOTALL)
if matches:
messages.append(LintMessage("If <span> exists only for the z3998:roman semantic, then z3998:roman should be pulled into parent element instead.", se.MESSAGE_TYPE_WARNING, filename, [match[1] for match in matches]))
# Check for "Hathi Trust" instead of "HathiTrust"
if "Hathi Trust" in file_contents:
messages.append(LintMessage("`Hathi Trust` should be `HathiTrust`", se.MESSAGE_TYPE_ERROR, filename))
# Check for uppercase letters in IDs or classes
matches = dom.select("[id],[class]")
for match in matches:
if match.has_attr("id"):
normalized_id = unicodedata.normalize("NFKD", match["id"])
uppercase_matches = regex.findall(r"[A-Z]+", normalized_id)
if uppercase_matches:
messages.append(LintMessage("Uppercase ID attribute. Attribute values must be all lowercase.", se.MESSAGE_TYPE_ERROR, filename, uppercase_matches))
number_matches = regex.findall(r"^[0-9]+.+", normalized_id)
if number_matches:
messages.append(LintMessage("ID starting with a number is illegal XHTML.", se.MESSAGE_TYPE_ERROR, filename, number_matches))
if match.has_attr("class"):
for css_class in match["class"]:
uppercase_matches = regex.findall(r"[A-Z]+", unicodedata.normalize("NFKD", css_class))
if uppercase_matches:
messages.append(LintMessage("Uppercase class attribute. Attribute values must be all lowercase.", se.MESSAGE_TYPE_ERROR, filename, uppercase_matches))
matches = [x for x in dom.select("section") if not x.has_attr("id")]
if matches:
messages.append(LintMessage("<section> element without id attribute.", se.MESSAGE_TYPE_ERROR, filename))
# Check for empty title tags
if "<title/>" in file_contents or "<title></title>" in file_contents:
messages.append(LintMessage("Empty <title> element.", se.MESSAGE_TYPE_ERROR, filename))
# Check for numeric entities
matches = regex.findall(r"&#[0-9]+?;", file_contents)
if matches:
messages.append(LintMessage("Illegal numeric entity (like Α) in file.", se.MESSAGE_TYPE_ERROR, filename))
# Check nested <blockquote> elements
matches = regex.findall(r"<blockquote[^>]*?>\s*<blockquote", file_contents, flags=regex.DOTALL)
if matches:
messages.append(LintMessage("Nested <blockquote> element.", se.MESSAGE_TYPE_WARNING, filename))
# Check for <hr> tags before the end of a section, which is a common PG artifact
matches = regex.findall(r"<hr[^>]*?/?>\s*</section>", file_contents, flags=regex.DOTALL)
if matches:
messages.append(LintMessage("Illegal <hr/> before the end of a section.", se.MESSAGE_TYPE_ERROR, filename))
# Check for double greater-than at the end of a tag
matches = regex.findall(r"(>>|>>)", file_contents)
if matches:
messages.append(LintMessage("Elements should end with a single >.", se.MESSAGE_TYPE_WARNING, filename))
# Ignore the title page here, because we often have publishers with ampersands as
# translators, but in alt tags. Like "George Allen & Unwin".
if filename != "titlepage.xhtml":
# Before we process this, we remove the eoc class from <abbr class="name"> because negative lookbehind
# must be fixed-width. I.e. we can't do `class="name( eoc)?"`
temp_file_contents = file_contents.replace("\"name eoc\"", "\"name\"")
# Check for nbsp before ampersand (&)
matches = regex.findall(fr"(?<!\<abbr class=\"name\")>[^>]*?[^{se.NO_BREAK_SPACE}]\&", temp_file_contents)
if matches:
messages.append(LintMessage("Required nbsp not found before &", se.MESSAGE_TYPE_WARNING, filename))
# Check for nbsp after ampersand (&)
matches = regex.findall(fr"(?<!\<abbr class=\"name\")>[^>]*?\&[^{se.NO_BREAK_SPACE}]", temp_file_contents)
if matches:
messages.append(LintMessage("Required nbsp not found after &", se.MESSAGE_TYPE_WARNING, filename))
# Check for nbsp before times
matches = regex.findall(fr"[0-9]+[^{se.NO_BREAK_SPACE}]<abbr class=\"time", file_contents)
if matches:
messages.append(LintMessage("Required nbsp not found before <abbr class=\"time\">", se.MESSAGE_TYPE_WARNING, filename))
# Check for low-hanging misquoted fruit
matches = regex.findall(r"[A-Za-z]+[“‘]", file_contents)
if matches:
messages.append(LintMessage("Possible mis-curled quotation mark.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check that times have colons and not periods
matches = regex.findall(r"[0-9]\.[0-9]+\s<abbr class=\"time", file_contents) + regex.findall(r"at [0-9]\.[0-9]+", file_contents)
if matches:
messages.append(LintMessage("Times must be separated by colons (:) not periods (.)", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for leading 0 in IDs (note: not the same as checking for IDs that start with an integer)
matches = regex.findall(r"id=\"[^\"]+?\-0[0-9]+[^\"]*?\"", file_contents)
if matches:
messages.append(LintMessage("Illegal leading 0 in ID attribute", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for stage direction that ends in ?! but also has a trailing period
matches = regex.findall(r"<i epub:type=\"z3998:stage-direction\">(?:(?!<i).)*?\.</i>[,:;!?]", file_contents)
if matches:
messages.append(LintMessage("Stage direction ending in period next to other punctuation. Remove trailing periods in stage direction.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for ending punctuation inside italics that have semantics.
# Ignore the colophon because paintings might have punctuation in their names
if filename != "colophon.xhtml":
matches = regex.findall(r"(<([ib]) epub:type=\"[^\"]*?se:name\.[^\"]*?\">[^<]+?[\.,\!\?]</\2>)", file_contents)
filtered_matches = []
for match in matches:
if "z3998:stage-direction" not in match[0]:
filtered_matches.append(match[0])
# ...and also check for ending punctuation inside em tags, if it looks like a *part* of a clause
# instead of a whole clause. If the <em> is preceded by an em dash or quotes then it's
# presumed to be a whole clause.
matches = regex.findall(r"(?:[^—“‘])<em>(?:\w+?\s*){1,2}?[\.,\!\?]<\/em>", file_contents)
for match in matches:
if match[4].islower():
filtered_matches.append(match)
if filtered_matches:
messages.append(LintMessage("Ending punctuation inside italics.", se.MESSAGE_TYPE_WARNING, filename, filtered_matches))
# Check for money not separated by commas
matches = regex.findall(r"[£\$][0-9]{4,}", file_contents)
if matches:
messages.append(LintMessage("Numbers not grouped by commas. Separate numbers greater than 1,000 with commas at every three numerals.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for deprecated MathML elements
matches = regex.findall(r"<(?:m:)?mfenced[^>]*?>.+?</(?:m:)?mfenced>", file_contents)
if matches:
messages.append(LintMessage("<m:mfenced> is deprecated in the MathML spec. Use <m:mrow><m:mo fence=\"true\">(</m:mo>...<m:mo fence=\"true\">)</m:mo></m:mrow>.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for period following Roman numeral, which is an old-timey style we must fix
# But ignore the numeral if it's the first item in a <p> tag, as that suggests it might be a kind of list item.
matches = regex.findall(r"(?<!<p[^>]*?>)<span epub:type=\"z3998:roman\">[^<]+?</span>\.\s+[a-z]", file_contents)
if matches:
messages.append(LintMessage("Roman numeral followed by a period. When in mid-sentence Roman numerals must not be followed by a period.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for two em dashes in a row
matches = regex.findall(fr"—{se.WORD_JOINER}*—+", file_contents)
if matches:
messages.append(LintMessage("Two or more em-dashes in a row detected. Elided words should use the two- or three-em-dash Unicode character, and dialog ending in em-dashes should only end in a single em-dash.", se.MESSAGE_TYPE_ERROR, filename))
# Check for <abbr class="name"> that does not contain spaces
matches = regex.findall(r"<abbr class=\"name\">[^<]*?[A-Z]\.[A-Z]\.[^<]*?</abbr>", file_contents)
if matches:
messages.append(LintMessage("Initials in <abbr class=\"name\"> not separated by spaces.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for empty <h2> missing epub:type="title" attribute
if "<h2>" in file_contents:
messages.append(LintMessage("<h2> element without `epub:type=\"title\"` attribute.", se.MESSAGE_TYPE_WARNING, filename))
# Check for a common typo
if "z3998:nonfiction" in file_contents:
messages.append(LintMessage("z3998:nonfiction should be z3998:non-fiction", se.MESSAGE_TYPE_ERROR, filename))
# Check for empty <p> tags
matches = regex.findall(r"<p[^>]*?>\s*</p>", file_contents)
if "<p/>" in file_contents or matches:
messages.append(LintMessage("Empty <p> element. Use <hr/> for thematic breaks if appropriate.", se.MESSAGE_TYPE_ERROR, filename))
# Check for <p> tags that end with <br/>
matches = regex.findall(r"(\s*<br/?>\s*)+</p>", file_contents)
if matches:
messages.append(LintMessage("<br/> element found before closing </p> tag.", se.MESSAGE_TYPE_ERROR, filename))
# Check for single words that are in italics, but that have closing punctuation outside italics
# Outer wrapping match is so that .findall returns the entire match and not the subgroup
# The first regex also matches the first few characters before the first double quote; we use those for more sophisticated
# checks below, to give fewer false positives like `with its downy red hairs and its “<i xml:lang="fr">doigts de faune</i>.”`
matches = regex.findall(r"((?:.{1,2}\s)?“<(i|em)[^>]*?>[^<]+?</\2>[\!\?\.])", file_contents) + regex.findall(r"([\.\!\?] <(i|em)[^>]*?>[^<]+?</\2>[\!\?\.])", file_contents)
# But, if we've matched a name of something, don't include that as an error. For example, `He said, “<i epub:type="se:name.publication.book">The Decameron</i>.”`
# We also exclude the match from the list if:
# 1. The double quote is directly preceded by a lowercase letter and a space: `with its downy red hairs and its “<i xml:lang="fr">doigts de faune</i>.”`
# 2. The double quote is directly preceded by a lowercase letter, a comma, and a space, and the first letter within the double quote is lowercase: In the original, “<i xml:lang="es">que era un Conde de Irlos</i>.”
matches = [x for x in matches if "epub:type=\"se:name." not in x[0] and "epub:type=\"z3998:taxonomy" not in x[0] and not regex.match(r"^[a-z’]+\s“", x[0]) and not regex.match(r"^[a-z’]+,\s“[a-z]", se.formatting.remove_tags(x[0]))]
if matches:
messages.append(LintMessage("When a complete clause is italicized, ending punctuation except commas must be within containing italics.", se.MESSAGE_TYPE_WARNING, filename, [match[0] for match in matches]))
# Run some checks on <i> elements
comma_matches = []
italicizing_matches = []
elements = dom.select("i")
for elem in elements:
next_sib = elem.nextSibling
# Check for trailing commas inside <i> tags at the close of dialog
# More sophisticated version of: \b[^\s]+?,</i>”
if isinstance(next_sib, NavigableString) and next_sib.startswith("”") and elem.text.endswith(","):
comma_matches.append(str(elem) + "”")
# Check for foreign phrases with italics going *outside* quotes
for attr in elem.attrs:
if attr == "xml:lang" and (elem.text.startswith("“") or elem.text.endswith("”")):
italicizing_matches.append(str(elem))
if comma_matches:
messages.append(LintMessage("Comma inside <i> element before closing dialog.", se.MESSAGE_TYPE_WARNING, filename, comma_matches))
if italicizing_matches:
messages.append(LintMessage("When italicizing language in dialog, italics go inside quotation marks.", se.MESSAGE_TYPE_WARNING, filename, italicizing_matches))
# Check for style attributes
matches = regex.findall(r"<.+?style=\"", file_contents)
if matches:
messages.append(LintMessage("Illegal style attribute. Do not use inline styles, any element can be targeted with a clever enough selector.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for uppercase HTML tags
if regex.findall(r"<[A-Z]+", file_contents):
messages.append(LintMessage("One or more uppercase HTML tags.", se.MESSAGE_TYPE_ERROR, filename))
# Check for nbsp within <abbr class="name">, which is redundant
matches = regex.findall(fr"<abbr[^>]+?class=\"name\"[^>]*?>[^<]*?{se.NO_BREAK_SPACE}[^<]*?</abbr>", file_contents)
if matches:
messages.append(LintMessage("No-break space detected in <abbr class=\"name\">. This is redundant.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for Roman numerals in <title> tag
if regex.findall(r"<title>[Cc]hapter [XxIiVv]+", file_contents):
messages.append(LintMessage("No Roman numerals allowed in <title> element; use decimal numbers.", se.MESSAGE_TYPE_ERROR, filename))
# Check for HTML tags in <title> tags
matches = regex.findall(r"<title>.*?[<].*?</title>", file_contents)
if matches:
messages.append(LintMessage("Element in <title> element", se.MESSAGE_TYPE_ERROR, filename, matches))
# If the chapter has a number and no subtitle, check the <title> tag...
matches = regex.findall(r"<h([0-6]) epub:type=\"title z3998:roman\">([^<]+)</h\1>", file_contents, flags=regex.DOTALL)
# ...But only make the correction if there's one <h#> tag. If there's more than one, then the xhtml file probably requires an overarching title
if matches and len(regex.findall(r"<h(?:[0-6])", file_contents)) == 1:
try:
chapter_number = roman.fromRoman(matches[0][1].upper())
regex_string = fr"<title>(Chapter|Section|Part) {chapter_number}"
if not regex.findall(regex_string, file_contents):
messages.append(LintMessage(f"<title> element doesn’t match expected value; should be `Chapter {chapter_number}`. (Beware hidden Unicode characters!)", se.MESSAGE_TYPE_ERROR, filename))
except Exception:
messages.append(LintMessage("<h#> element is marked with z3998:roman, but is not a Roman numeral", se.MESSAGE_TYPE_ERROR, filename))
# If the chapter has a number and subtitle, check the <title> tag...
matches = regex.findall(r"<h([0-6]) epub:type=\"title\">\s*<span epub:type=\"z3998:roman\">([^<]+)</span>\s*<span epub:type=\"subtitle\">(.+?)</span>\s*</h\1>", file_contents, flags=regex.DOTALL)
# ...But only make the correction if there's one <h#> tag. If there's more than one, then the xhtml file probably requires an overarching title
if matches and len(regex.findall(r"<h(?:[0-6])", file_contents)) == 1:
chapter_number = roman.fromRoman(matches[0][1].upper())
# First, remove endnotes in the subtitle, then remove all other tags (but not tag contents)
chapter_title = regex.sub(r"<a[^<]+?epub:type=\"noteref\"[^<]*?>[^<]+?</a>", "", matches[0][2]).strip()
chapter_title = regex.sub(r"<[^<]+?>", "", chapter_title)
regex_string = r"<title>(Chapter|Section|Part) {}: {}".format(chapter_number, regex.escape(chapter_title))
if not regex.findall(regex_string, file_contents):
messages.append(LintMessage(f"<title> element doesn’t match expected value; should be `Chapter {chapter_number}: {chapter_title}`. (Beware hidden Unicode characters!)", se.MESSAGE_TYPE_ERROR, filename))
# Check for missing subtitle styling
if "epub:type=\"subtitle\"" in file_contents and not local_css_has_subtitle_style:
messages.append(LintMessage("Subtitles detected, but no subtitle style detected in local.css.", se.MESSAGE_TYPE_ERROR, filename))
# Check for whitespace before noteref
matches = regex.findall(r"\s+<a href=\"endnotes\.xhtml#note-[0-9]+?\" id=\"noteref-[0-9]+?\" epub:type=\"noteref\">[0-9]+?</a>", file_contents)
if matches:
messages.append(LintMessage("Illegal white space before noteref.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for <li> elements that don't have a direct block child
if filename != "toc.xhtml":
matches = regex.findall(r"<li(?:\s[^>]*?>|>)\s*[^\s<]", file_contents)
if matches:
messages.append(LintMessage("<li> without direct block-level child.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for ldquo not correctly closed
# Ignore closing paragraphs, line breaks, and closing cells in case ldquo means "ditto mark"
matches = regex.findall(r"“[^‘”]+?“", file_contents)
matches = [x for x in matches if "</p" not in x and "<br/>" not in x and "</td>" not in x]
if matches:
messages.append(LintMessage("`“` missing matching `”`.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for lsquo not correctly closed
matches = regex.findall(r"‘[^“’]+?‘", file_contents)
matches = [x for x in matches if "</p" not in x and "<br/>" not in x]
if matches:
messages.append(LintMessage("`‘` missing matching `’`.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for IDs on <h#> tags
matches = regex.findall(r"<h[0-6][^>]*?id=[^>]*?>", file_contents, flags=regex.DOTALL)
if matches:
messages.append(LintMessage("<h#> element with id attribute. <h#> elements should be wrapped in <section> elements, which should hold the id attribute.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check to see if <h#> tags are correctly titlecased
matches = regex.finditer(r"<h([0-6])([^>]*?)>(.*?)</h\1>", file_contents, flags=regex.DOTALL)
for match in matches:
if "z3998:roman" not in match.group(2):
title = match.group(3).strip()
# Remove leading roman numerals first
title = regex.sub(r"^<span epub:type=\"[^\"]*?z3998:roman[^\"]*?\">(.*?)</span>", "", title, flags=regex.DOTALL)
# Remove leading leftover spacing and punctuation
title = regex.sub(r"^[\s\.\,\!\?\:\;]*", "", title)
# Remove endnotes
title = regex.sub(r"<a[^>]*?epub:type=\"noteref\"[^>]*?>[0-9]+</a>", "", title)
# Normalize whitespace
title = regex.sub(r"\s+", " ", title, flags=regex.DOTALL).strip()
# Remove nested <span>s in subtitles, which might trip up the next regex block
title = regex.sub(r"(<span epub:type=\"subtitle\">[^<]*?)<span[^>]*?>([^<]*?</span>)", r"\1\2", title, flags=regex.DOTALL)
title = regex.sub(r"(<span epub:type=\"subtitle\">[^<]*?)</span>([^<]*?</span>)", r"\1\2", title, flags=regex.DOTALL)
# Do we have a subtitle? If so the first letter of that must be capitalized, so we pull that out
subtitle_matches = regex.findall(r"(.*?)<span epub:type=\"subtitle\">(.*?)</span>(.*?)", title, flags=regex.DOTALL)
if subtitle_matches:
for title_header, subtitle, title_footer in subtitle_matches:
title_header = se.formatting.titlecase(se.formatting.remove_tags(title_header).strip())
subtitle = se.formatting.titlecase(se.formatting.remove_tags(subtitle).strip())
title_footer = se.formatting.titlecase(se.formatting.remove_tags(title_footer).strip())
titlecased_title = title_header + " " + subtitle + " " + title_footer
titlecased_title = titlecased_title.strip()
title = se.formatting.remove_tags(title).strip()
if title != titlecased_title:
messages.append(LintMessage(f"Title `{title}` not correctly titlecased. Expected: `{titlecased_title}`", se.MESSAGE_TYPE_WARNING, filename))
# No subtitle? Much more straightforward
else:
titlecased_title = se.formatting.remove_tags(se.formatting.titlecase(title))
title = se.formatting.remove_tags(title)
if title != titlecased_title:
messages.append(LintMessage(f"Title `{title}` not correctly titlecased. Expected: `{titlecased_title}`", se.MESSAGE_TYPE_WARNING, filename))
# Check for <figure> tags without id attributes
matches = regex.findall(r"<img[^>]*?id=\"[^>]+?>", file_contents)
if matches:
messages.append(LintMessage("<img> element with ID attribute. ID attributes go on parent <figure> elements.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for closing dialog without comma
matches = regex.findall(r"[a-z]+?” [a-zA-Z]+? said", file_contents)
if matches:
messages.append(LintMessage("Dialog without ending comma.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for non-typogrified img alt attributes
matches = regex.findall(r"alt=\"[^\"]*?('|--|")[^\"]*?\"", file_contents)
if matches:
messages.append(LintMessage("Non-typogrified ', \" (as "), or -- in image alt attribute.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check alt attributes not ending in punctuation
if filename not in se.IGNORED_FILENAMES:
matches = regex.findall(r"alt=\"[^\"]*?[a-zA-Z]\"", file_contents)
if matches:
messages.append(LintMessage("Alt attribute doesn’t appear to end with punctuation. Alt attributes must be composed of complete sentences ending in appropriate punctuation.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check alt attributes match image titles
images = dom.select("img[src$=svg]")
for image in images:
alt_text = image["alt"]
title_text = ""
image_ref = image["src"].split("/").pop()
try:
with open(self.path / "src" / "epub" / "images" / image_ref, "r", encoding="utf-8") as image_source:
try:
title_text = BeautifulSoup(image_source, "lxml").title.get_text()
except Exception:
messages.append(LintMessage(f"{image_ref} missing <title> element.", se.MESSAGE_TYPE_ERROR, image_ref))
if title_text != "" and alt_text != "" and title_text != alt_text:
messages.append(LintMessage(f"The <title> of {image_ref} doesn’t match the alt text in {filename}", se.MESSAGE_TYPE_ERROR, filename))
except FileNotFoundError:
messages.append(LintMessage(f"The image {image_ref} doesn’t exist", se.MESSAGE_TYPE_ERROR, filename))
# Check for punctuation after endnotes
regex_string = fr"<a[^>]*?epub:type=\"noteref\"[^>]*?>[0-9]+</a>[^\s<–\]\)—{se.WORD_JOINER}]"
matches = regex.findall(regex_string, file_contents)
if matches:
messages.append(LintMessage("Endnote links must be outside of punctuation, including quotation marks.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for nbsp in measurements, for example: 90 mm
matches = regex.findall(r"[0-9]+[\- ][mck][mgl]\b", file_contents)
if matches:
messages.append(LintMessage("Measurements must be separated by a no-break space, not a dash or regular space.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for line breaks after <br/> tags
matches = regex.findall(r"<br\s*?/>[^\n]", file_contents)
if matches:
messages.append(LintMessage("<br/> element must be followed by a newline, and subsequent content must be indented to the same level.", se.MESSAGE_TYPE_ERROR, filename))
# Check for <pre> tags
if "<pre" in file_contents:
messages.append(LintMessage("Illegal <pre> element.", se.MESSAGE_TYPE_ERROR, filename))
# Check for punctuation outside quotes. We don't check single quotes because contractions are too common.
matches = regex.findall(r"\b.+?”[,\.]", file_contents)
if matches:
messages.append(LintMessage("Comma or period outside of double quote. Generally punctuation should go within single and double quotes.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for double spacing
regex_string = fr"[{se.NO_BREAK_SPACE}{se.HAIR_SPACE} ]{{2,}}"
matches = regex.findall(regex_string, file_contents)
if matches:
messages.append(LintMessage("Double spacing detected in file. Sentences should be single-spaced. (Note that double spaces might include Unicode no-break spaces!)", se.MESSAGE_TYPE_ERROR, filename))
# Run some checks on epub:type values
incorrect_attrs = []
epub_type_attrs = regex.findall("epub:type=\"([^\"]+?)\"", file_contents)
for attrs in epub_type_attrs:
for attr in regex.split(r"\s", attrs):
# Did someone use colons instead of dots for SE identifiers? e.g. se:name:vessel:ship
matches = regex.findall(r"^se:[a-z]+:(?:[a-z]+:?)*", attr)
if matches:
messages.append(LintMessage(f"Illegal colon (:) detected in SE identifier. SE identifiers are separated by dots (.) not colons (:). E.g., `se:name.vessel.ship`", se.MESSAGE_TYPE_ERROR, filename, matches))
# Did someone use periods instead of colons for the SE namespace? e.g. se.name.vessel.ship
matches = regex.findall(r"^se\.[a-z]+(?:\.[a-z]+)*", attr)
if matches:
messages.append(LintMessage(f"SE namespace must be followed by a colon (:), not a dot (.). E.g., `se:name.vessel`", se.MESSAGE_TYPE_ERROR, filename, matches))
# Did we draw from the z3998 vocabulary when the item exists in the epub vocabulary?
if attr.startswith("z3998:"):
bare_attr = attr.replace("z3998:", "")
if bare_attr in EPUB_SEMANTIC_VOCABULARY:
incorrect_attrs.append((attr, bare_attr))
# Convert this into a unique set so we don't spam the console with repetitive messages
unique_incorrect_attrs = set(incorrect_attrs)
for (attr, bare_attr) in unique_incorrect_attrs:
messages.append(LintMessage(f"`{attr}` semantic used, but `{bare_attr}` is in the EPUB semantic inflection vocabulary.", se.MESSAGE_TYPE_ERROR, filename))
# Check for leftover asterisms
matches = regex.findall(r"<[a-z]+[^>]*?>\s*\*\s*(\*\s*)+", file_contents, flags=regex.DOTALL)
if matches:
messages.append(LintMessage("Illegal asterism (`***`) detected. Section/scene breaks must be defined by an `<hr/>` element.", se.MESSAGE_TYPE_ERROR, filename))
# Check for missing punctuation before closing quotes
matches = regex.findall(r"[a-z]+[”’]</p>", file_contents, flags=regex.IGNORECASE)
if matches:
messages.append(LintMessage("Missing punctuation before closing quotes.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for space before endnote backlinks
if filename == "endnotes.xhtml":
# Do we have to replace Ibid.?
matches = regex.findall(r"\bibid\b", file_contents, flags=regex.IGNORECASE)
if matches:
messages.append(LintMessage("Illegal `Ibid` in endnotes. “Ibid” means “The previous reference” which is meaningless with popup endnotes, and must be replaced by the actual thing `Ibid` refers to.", se.MESSAGE_TYPE_ERROR, filename))
endnote_referrers = dom.select("li[id^=note-] a")
bad_referrers = []
for referrer in endnote_referrers:
# We check against the attr value here because I couldn't figure out how to select an XML-namespaced attribute using BS4
if "epub:type" in referrer.attrs and referrer.attrs["epub:type"] == "backlink":
is_first_sib = True
for sib in referrer.previous_siblings:
if is_first_sib:
is_first_sib = False
if isinstance(sib, NavigableString):
if sib == "\n": # Referrer preceded by newline. Check if all previous sibs are tags.
continue
if sib == " " or str(sib) == se.NO_BREAK_SPACE or regex.search(r"[^\s] $", str(sib)): # Referrer preceded by a single space; we're OK
break
# Referrer preceded by a string that is not a newline and does not end with a single space
bad_referrers.append(referrer)
break
else:
# We got here because the first sib was a newline, or not a string. So, check all previous sibs.
if isinstance(sib, NavigableString) and sib != "\n":
bad_referrers.append(referrer)
break
if bad_referrers:
messages.append(LintMessage("Endnote referrer link not preceded by exactly one space, or a newline if all previous siblings are elements.", se.MESSAGE_TYPE_WARNING, filename, [str(referrer) for referrer in bad_referrers]))
# If we're in the imprint, are the sources represented correctly?
# We don't have a standard yet for more than two sources (transcription and scan) so just ignore that case for now.
if filename == "imprint.xhtml":
matches = regex.findall(r"<dc:source>([^<]+?)</dc:source>", metadata_xhtml)
if len(matches) <= 2:
for link in matches:
if "gutenberg.org" in link and f"<a href=\"{link}\">Project Gutenberg</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in imprint.xhtml. Expected: <a href=\"{link}\">Project Gutenberg</a>", se.MESSAGE_TYPE_WARNING, filename))
if "hathitrust.org" in link and f"the <a href=\"{link}\">HathiTrust Digital Library</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in imprint.xhtml. Expected: the <a href=\"{link}\">HathiTrust Digital Library</a>", se.MESSAGE_TYPE_WARNING, filename))
if "archive.org" in link and f"the <a href=\"{link}\">Internet Archive</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in imprint.xhtml. Expected: the <a href=\"{link}\">Internet Archive</a>", se.MESSAGE_TYPE_WARNING, filename))
if "books.google.com" in link and f"<a href=\"{link}\">Google Books</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in imprint.xhtml. Expected: <a href=\"{link}\">Google Books</a>", se.MESSAGE_TYPE_WARNING, filename))
# Collect abbr elements for later check
result = regex.findall("<abbr[^<]+?>", file_contents)
result = [item.replace("eoc", "").replace(" \"", "").strip() for item in result]
abbr_elements = list(set(result + abbr_elements))
# Check if language tags in individual files match the language in content.opf
if filename not in se.IGNORED_FILENAMES:
file_language = regex.search(r"<html[^<]+xml\:lang=\"([^\"]+)\"", file_contents).group(1)
if language != file_language:
messages.append(LintMessage(f"File language is {file_language}, but content.opf language is {language}", se.MESSAGE_TYPE_ERROR, filename))
# Check LoI descriptions to see if they match associated figcaptions
if filename == "loi.xhtml":
illustrations = dom.select("li > a")
for illustration in illustrations:
figure_ref = illustration["href"].split("#")[1]
chapter_ref = regex.findall(r"(.*?)#.*", illustration["href"])[0]
figcaption_text = ""
loi_text = illustration.get_text()
with open(self.path / "src" / "epub" / "text" / chapter_ref, "r", encoding="utf-8") as chapter:
try:
figure = BeautifulSoup(chapter, "lxml").select("#" + figure_ref)[0]
except Exception:
messages.append(LintMessage(f"#{figure_ref} not found in file {chapter_ref}", se.MESSAGE_TYPE_ERROR, 'loi.xhtml'))
continue
if figure.img:
figure_img_alt = figure.img.get('alt')
if figure.figcaption:
figcaption_text = figure.figcaption.get_text()
if (figcaption_text != "" and loi_text != "" and figcaption_text != loi_text) and (figure_img_alt != "" and loi_text != "" and figure_img_alt != loi_text):
messages.append(LintMessage(f"The <figcaption> element of {figure_ref} doesn’t match the text in its LoI entry", se.MESSAGE_TYPE_WARNING, chapter_ref))
# Check for missing MARC relators
if filename == "introduction.xhtml" and ">aui<" not in metadata_xhtml and ">win<" not in metadata_xhtml:
messages.append(LintMessage("introduction.xhtml found, but no MARC relator `aui` (Author of introduction, but not the chief author) or `win` (Writer of introduction)", se.MESSAGE_TYPE_WARNING, filename))
if filename == "preface.xhtml" and ">wpr<" not in metadata_xhtml:
messages.append(LintMessage("preface.xhtml found, but no MARC relator `wpr` (Writer of preface)", se.MESSAGE_TYPE_WARNING, filename))
if filename == "afterword.xhtml" and ">aft<" not in metadata_xhtml:
messages.append(LintMessage("afterword.xhtml found, but no MARC relator `aft` (Author of colophon, afterword, etc.)", se.MESSAGE_TYPE_WARNING, filename))
if filename == "endnotes.xhtml" and ">ann<" not in metadata_xhtml:
messages.append(LintMessage("endnotes.xhtml found, but no MARC relator `ann` (Annotator)", se.MESSAGE_TYPE_WARNING, filename))
if filename == "loi.xhtml" and ">ill<" not in metadata_xhtml:
messages.append(LintMessage("loi.xhtml found, but no MARC relator `ill` (Illustrator)", se.MESSAGE_TYPE_WARNING, filename))
# Check for wrong semantics in frontmatter/backmatter
if filename in se.FRONTMATTER_FILENAMES and "frontmatter" not in file_contents:
messages.append(LintMessage("No frontmatter semantic inflection for what looks like a frontmatter file", se.MESSAGE_TYPE_WARNING, filename))
if filename in se.BACKMATTER_FILENAMES and "backmatter" not in file_contents:
messages.append(LintMessage("No backmatter semantic inflection for what looks like a backmatter file", se.MESSAGE_TYPE_WARNING, filename))
if cover_svg_title != titlepage_svg_title:
messages.append(LintMessage("cover.svg and titlepage.svg <title> elements don’t match", se.MESSAGE_TYPE_ERROR))
if has_frontmatter and not has_halftitle:
messages.append(LintMessage("Frontmatter found, but no halftitle. Halftitle is required when frontmatter is present.", se.MESSAGE_TYPE_ERROR, "content.opf"))
if not has_cover_source:
messages.append(LintMessage("./images/cover.source.jpg not found", se.MESSAGE_TYPE_ERROR, "cover.source.jpg"))
single_use_css_classes = []
for css_class in xhtml_css_classes:
if css_class not in se.IGNORED_CLASSES:
if "." + css_class not in css:
messages.append(LintMessage(f"class `{css_class}` found in xhtml, but no style in local.css", se.MESSAGE_TYPE_ERROR, "local.css"))
if xhtml_css_classes[css_class] == 1 and css_class not in se.IGNORED_CLASSES and not regex.match(r"^i[0-9]$", css_class):
# Don't count ignored classes OR i[0-9] which are used for poetry styling
single_use_css_classes.append(css_class)
if single_use_css_classes:
messages.append(LintMessage("CSS class only used once. Can a clever selector be crafted instead of a single-use class? When possible classes should not be single-use style hooks.", se.MESSAGE_TYPE_WARNING, "local.css", single_use_css_classes))
headings = list(set(headings))
with open(self.path / "src" / "epub" / "toc.xhtml", "r", encoding="utf-8") as file:
toc = BeautifulSoup(file.read(), "lxml")
landmarks = toc.find("nav", attrs={"epub:type": "landmarks"})
toc = toc.find("nav", attrs={"epub:type": "toc"})
# Depth first search using recursiveChildGenerator to get the headings in order
toc_entries = []
for child in toc.recursiveChildGenerator():
if getattr(child, "name") == "a":
toc_entries.append(child)
# Match ToC headings against text headings
# Unlike main headings, ToC entries have a ‘:’ before the subheading so we need to strip these for comparison
toc_headings = []
for index, entry in enumerate(toc_entries):
entry_text = " ".join(entry.get_text().replace(":", "").split())
entry_file = regex.sub(r"^text\/(.*?\.xhtml).*$", r"\1", entry.get("href"))
toc_headings.append((entry_text, entry_file))
for heading in headings:
# Occasionally we find a heading with a colon, but as we’ve stripped our
# ToC-only colons above we also need to do that here for the comparison.
heading_without_colons = (heading[0].replace(":", ""), heading[1])
if heading_without_colons not in toc_headings:
messages.append(LintMessage(f"Heading `{heading[0]}` found, but not present for that file in the ToC.", se.MESSAGE_TYPE_ERROR, heading[1]))
# Check our ordered ToC entries against the spine
# To cover all possibilities, we combine the toc and the landmarks to get the full set of entries
with open(self.path / "src" / "epub" / "content.opf", "r", encoding="utf-8") as content_opf:
toc_files = []
for index, entry in enumerate(landmarks.find_all("a", attrs={"epub:type": regex.compile("^.*(frontmatter|bodymatter).*$")})):
entry_file = regex.sub(r"^text\/(.*?\.xhtml).*$", r"\1", entry.get("href"))
toc_files.append(entry_file)
for index, entry in enumerate(toc_entries):
entry_file = regex.sub(r"^text\/(.*?\.xhtml).*$", r"\1", entry.get("href"))
toc_files.append(entry_file)
unique_toc_files: List[str] = []
for toc_file in toc_files:
if toc_file not in unique_toc_files:
unique_toc_files.append(toc_file)
toc_files = unique_toc_files
spine_entries = BeautifulSoup(content_opf.read(), "lxml").find("spine").find_all("itemref")
if len(toc_files) != len(spine_entries):
messages.append(LintMessage("The number of elements in the spine ({}) does not match the number of elements in the ToC and landmarks ({}).".format(len(toc_files), len(spine_entries)), se.MESSAGE_TYPE_ERROR, "content.opf"))
for index, entry in enumerate(spine_entries):
if toc_files[index] != entry.attrs["idref"]:
messages.append(LintMessage(f"The spine order does not match the order of the ToC and landmarks. Expected {entry.attrs['idref']}, found {toc_files[index]}.", se.MESSAGE_TYPE_ERROR, "content.opf"))
break
for element in abbr_elements:
try:
css_class = regex.search(r"class=\"([^\"]+?)\"", element).group(1)
except Exception:
continue
if css_class and css_class in ("temperature", "era", "acronym") and "abbr." + css_class not in abbr_styles:
messages.append(LintMessage(f"abbr.{css_class} element found, but no required style in local.css (See typgoraphy manual for style)", se.MESSAGE_TYPE_ERROR, "local.css"))
return messages
| 57.312343 | 1,259 | 0.692934 |
import filecmp
import glob
import html
import io
import os
import unicodedata
from pathlib import Path
from typing import Dict, List
import importlib_resources
import lxml.cssselect
import lxml.etree as etree
import regex
import roman
from bs4 import BeautifulSoup, NavigableString
import se
import se.easy_xml
import se.formatting
import se.images
COLOPHON_VARIABLES = ["TITLE", "YEAR", "AUTHOR_WIKI_URL", "AUTHOR", "PRODUCER_URL", "PRODUCER", "PG_YEAR", "TRANSCRIBER_1", "TRANSCRIBER_2", "PG_URL", "IA_URL", "PAINTING", "ARTIST_WIKI_URL", "ARTIST"]
EPUB_SEMANTIC_VOCABULARY = ["cover", "frontmatter", "bodymatter", "backmatter", "volume", "part", "chapter", "division", "foreword", "preface", "prologue", "introduction", "preamble", "conclusion", "epilogue", "afterword", "epigraph", "toc", "landmarks", "loa", "loi", "lot", "lov", "appendix", "colophon", "index", "index-headnotes", "index-legend", "index-group", "index-entry-list", "index-entry", "index-term", "index-editor-note", "index-locator", "index-locator-list", "index-locator-range", "index-xref-preferred", "index-xref-related", "index-term-category", "index-term-categories", "glossary", "glossterm", "glossdef", "bibliography", "biblioentry", "titlepage", "halftitlepage", "copyright-page", "acknowledgments", "imprint", "imprimatur", "contributors", "other-credits", "errata", "dedication", "revision-history", "notice", "tip", "halftitle", "fulltitle", "covertitle", "title", "subtitle", "bridgehead", "learning-objective", "learning-resource", "assessment", "qna", "panel", "panel-group", "balloon", "text-area", "sound-area", "footnote", "endnote", "footnotes", "endnotes", "noteref", "keyword", "topic-sentence", "concluding-sentence", "pagebreak", "page-list", "table", "table-row", "table-cell", "list", "list-item", "figure", "aside"]
class LintMessage:
def __init__(self, text: str, message_type=se.MESSAGE_TYPE_WARNING, filename: str = "", submessages: List[str] = None):
self.text = text.strip()
self.filename = filename
self.message_type = message_type
self.submessages = submessages
def _get_malformed_urls(xhtml: str) -> list:
messages = []
if "http://gutenberg.org" in xhtml or "https://gutenberg.org" in xhtml:
messages.append(LintMessage("gutenberg.org URL missing leading www.", se.MESSAGE_TYPE_ERROR))
if "http://www.gutenberg.org" in xhtml:
messages.append(LintMessage("Non-https gutenberg.org URL.", se.MESSAGE_TYPE_ERROR))
if "http://www.pgdp.net" in xhtml:
messages.append(LintMessage("Non-https pgdp.net URL.", se.MESSAGE_TYPE_ERROR))
if "http://catalog.hathitrust.org" in xhtml:
messages.append(LintMessage("Non-https hathitrust.org URL.", se.MESSAGE_TYPE_ERROR))
if "http://archive.org" in xhtml:
messages.append(LintMessage("Non-https archive.org URL.", se.MESSAGE_TYPE_ERROR))
if "www.archive.org" in xhtml:
messages.append(LintMessage("archive.org URL should not have leading www.", se.MESSAGE_TYPE_ERROR))
if "http://en.wikipedia.org" in xhtml:
messages.append(LintMessage("Non-https en.wikipedia.org URL.", se.MESSAGE_TYPE_ERROR))
if regex.search(r"books\.google\.com/books\?id=.+?[&#]", xhtml):
messages.append(LintMessage("Non-canonical Google Books URL. Google Books URLs must look exactly like https://books.google.com/books?id=<BOOK-ID>"))
if "babel.hathitrust.org" in xhtml:
messages.append(LintMessage("Non-canonical HathiTrust URL. HathiTrust URLs must look exactly like https://catalog.hathitrust.org/Record/<BOOK-ID>"))
if ".gutenberg.org/files/" in xhtml:
messages.append(LintMessage("Non-canonical Project Gutenberg URL. Project Gutenberg URLs must look exactly like https://www.gutenberg.org/ebooks/<BOOK-ID>"))
if "archive.org/stream" in xhtml:
messages.append(LintMessage("Non-canonical archive.org URL. Internet Archive URLs must look exactly like https://archive.org/details/<BOOK-ID>"))
return messages
def _get_unused_selectors(self) -> List[str]:
try:
with open(self.path / "src" / "epub" / "css" / "local.css", encoding="utf-8") as file:
css = file.read()
except Exception:
raise FileNotFoundError("Couldn’t open {}".format(self.path / "src" / "epub" / "css" / "local.css"))
css = regex.sub(r"^@supports\(.+?\){(.+?)}\s*}", "\\1}", css, flags=regex.MULTILINE | regex.DOTALL)
# Remove actual content of css selectors
css = regex.sub(r"{[^}]+}", "", css)
# Remove trailing commas
css = regex.sub(r",", "", css)
# Remove comments
css = regex.sub(r"/\*.+?\*/", "", css, flags=regex.DOTALL)
# Remove @ defines
css = regex.sub(r"^@.+", "", css, flags=regex.MULTILINE)
# Construct a dictionary of selectors
selectors = {line for line in css.splitlines() if line != ""}
unused_selectors = set(selectors)
# Get a list of .xhtml files to search
filenames = glob.glob(str(self.path / "src" / "epub" / "text" / "*.xhtml"))
# Now iterate over each CSS selector and see if it's used in any of the files we found
for selector in selectors:
try:
sel = lxml.cssselect.CSSSelector(selector, translator="html", namespaces=se.XHTML_NAMESPACES)
except lxml.cssselect.ExpressionError:
unused_selectors.remove(selector)
continue
except lxml.cssselect.SelectorSyntaxError as ex:
raise se.InvalidCssException(f"Couldn’t parse CSS in or near this line: {selector}\n{ex}")
for filename in filenames:
if not filename.endswith("titlepage.xhtml") and not filename.endswith("imprint.xhtml") and not filename.endswith("uncopyright.xhtml"):
# We have to remove the default namespace declaration from our document, otherwise
# xpath won't find anything at all. See http://stackoverflow.com/questions/297239/why-doesnt-xpath-work-when-processing-an-xhtml-document-with-lxml-in-python
with open(filename, "r", encoding="utf-8") as file:
xhtml = file.read().replace(" xmlns=\"http://www.w3.org/1999/xhtml\"", "")
try:
tree = etree.fromstring(str.encode(xhtml))
except etree.XMLSyntaxError as ex:
raise se.InvalidXhtmlException("Couldn’t parse XHTML in file: {}, error: {}".format(filename, str(ex)))
except Exception:
raise se.InvalidXhtmlException(f"Couldn’t parse XHTML in file: {filename}")
if tree.xpath(sel.path, namespaces=se.XHTML_NAMESPACES):
unused_selectors.remove(selector)
break
return list(unused_selectors)
def lint(self, metadata_xhtml) -> list:
messages = []
has_halftitle = False
has_frontmatter = False
has_cover_source = False
cover_svg_title = ""
titlepage_svg_title = ""
xhtml_css_classes: Dict[str, int] = {}
headings: List[tuple] = []
language = regex.search(r"<dc:language>([^>]+?)</dc:language>", metadata_xhtml).group(1)
abbr_elements: List[str] = []
css = ""
with open(self.path / "src" / "epub" / "css" / "local.css", "r", encoding="utf-8") as file:
css = file.read()
local_css_has_subtitle_style = "span[epub|type~=\"subtitle\"]" in css
abbr_styles = regex.findall(r"abbr\.[a-z]+", css)
matches = regex.findall(r"^h[0-6]\s*,?{?", css, flags=regex.MULTILINE)
if matches:
messages.append(LintMessage("Do not directly select h[0-6] elements, as they are used in template files; use more specific selectors.", se.MESSAGE_TYPE_ERROR, "local.css"))
if (self.path / "dist").exists():
messages.append(LintMessage("Illegal ./dist/ folder. Do not commit compiled versions of the source.", se.MESSAGE_TYPE_ERROR, "./dist/"))
if regex.search(r"#description\">[^<]+?(['\"]|\-\-)[^<]+?</meta>", metadata_xhtml.replace("\">", "").replace("=\"", "")) is not None:
messages.append(LintMessage("Non-typogrified \", ', or -- detected in metadata long description", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check if there are non-typogrified quotes or em-dashes in the title.
# The open-ended start and end of the regex also catches title-sort
if regex.search(r"title\">[^<]+?(['\"]|\-\-)[^<]+?<", metadata_xhtml) is not None:
messages.append(LintMessage("Non-typogrified \", ', or -- detected in metadata title", se.MESSAGE_TYPE_ERROR, "content.opf"))
long_description = regex.findall(r"<meta id=\"long-description\".+?>(.+?)</meta>", metadata_xhtml, flags=regex.DOTALL)
if long_description:
long_description = "<?xml version=\"1.0\"?><html xmlns=\"http://www.w3.org/1999/xhtml\">" + html.unescape(long_description[0]) + "</html>"
try:
etree.parse(io.StringIO(long_description))
except lxml.etree.XMLSyntaxError as ex:
messages.append(LintMessage("Metadata long description is not valid HTML. LXML says: " + str(ex), se.MESSAGE_TYPE_ERROR, "content.opf"))
regex_string = fr"[{se.NO_BREAK_SPACE}{se.HAIR_SPACE} ]{{2,}}"
matches = regex.findall(regex_string, metadata_xhtml)
if matches:
messages.append(LintMessage("Double spacing detected in file. Sentences should be single-spaced.", se.MESSAGE_TYPE_ERROR, "content.opf"))
if regex.search(r"<dc:description id=\"description\">[^<]+?(['\"]|\-\-)[^<]+?</dc:description>", metadata_xhtml) is not None:
messages.append(LintMessage("Non-typogrified \", ', or -- detected in metadata dc:description.", se.MESSAGE_TYPE_ERROR, "content.opf"))
matches = regex.findall(r"[a-zA-Z][”][,.]", metadata_xhtml)
if matches:
messages.append(LintMessage("Comma or period outside of double quote. Generally punctuation should go within single and double quotes.", se.MESSAGE_TYPE_WARNING, "content.opf"))
# Make sure long-description is escaped HTML
if "<meta id=\"long-description\" property=\"se:long-description\" refines=\"#description\">\n\t\t\t<p>" not in metadata_xhtml:
messages.append(LintMessage("Long description must be escaped HTML.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for HTML entities in long-description, but allow &amp;
if regex.search(r"&[a-z]+?;", metadata_xhtml.replace("&amp;", "")):
messages.append(LintMessage("HTML entites detected in metadata. Use Unicode equivalents instead.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for illegal em-dashes in <dc:subject>
if regex.search(r"<dc:subject id=\"[^\"]+?\">[^<]+?—[^<]+?</dc:subject>", metadata_xhtml) is not None:
messages.append(LintMessage("Illegal em-dash detected in dc:subject; use --", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for empty production notes
if "<meta property=\"se:production-notes\">Any special notes about the production of this ebook for future editors/producers? Remove this element if not.</meta>" in metadata_xhtml:
messages.append(LintMessage("Empty production-notes element in metadata.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for illegal VCS URLs
matches = regex.findall(r"<meta property=\"se:url\.vcs\.github\">([^<]+?)</meta>", metadata_xhtml)
if matches:
for match in matches:
if not match.startswith("https://github.com/standardebooks/"):
messages.append(LintMessage(f"Illegal se:url.vcs.github. VCS URLs must begin with https://github.com/standardebooks/: {match}", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for HathiTrust scan URLs instead of actual record URLs
if "babel.hathitrust.org" in metadata_xhtml or "hdl.handle.net" in metadata_xhtml:
messages.append(LintMessage("Use HathiTrust record URLs, not page scan URLs, in metadata, imprint, and colophon. Record URLs look like: https://catalog.hathitrust.org/Record/<RECORD-ID>", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for illegal se:subject tags
matches = regex.findall(r"<meta property=\"se:subject\">([^<]+?)</meta>", metadata_xhtml)
if matches:
for match in matches:
if match not in se.SE_GENRES:
messages.append(LintMessage(f"Illegal se:subject: {match}", se.MESSAGE_TYPE_ERROR, "content.opf"))
else:
messages.append(LintMessage("No se:subject <meta> element found.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check for CDATA tags
if "<![CDATA[" in metadata_xhtml:
messages.append(LintMessage("<![CDATA[ detected. Run `clean` to canonicalize <![CDATA[ sections.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check that our provided identifier matches the generated identifier
identifier = regex.sub(r"<.+?>", "", regex.findall(r"<dc:identifier id=\"uid\">.+?</dc:identifier>", metadata_xhtml)[0])
if identifier != self.generated_identifier:
messages.append(LintMessage(f"<dc:identifier> does not match expected: {self.generated_identifier}", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check that the GitHub repo URL is as expected
if ("<meta property=\"se:url.vcs.github\">" + self.generated_github_repo_url + "</meta>") not in metadata_xhtml:
messages.append(LintMessage(f"GitHub repo URL does not match expected: {self.generated_github_repo_url}", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Check if se:name.person.full-name matches their titlepage name
matches = regex.findall(r"<meta property=\"se:name\.person\.full-name\" refines=\"#([^\"]+?)\">([^<]*?)</meta>", metadata_xhtml)
duplicate_names = []
for match in matches:
name_matches = regex.findall(fr"<([a-z:]+)[^<]+?id=\"{match[0]}\"[^<]*?>([^<]*?)</\1>", metadata_xhtml)
for name_match in name_matches:
if name_match[1] == match[1]:
duplicate_names.append(name_match[1])
if duplicate_names:
messages.append(LintMessage("se:name.person.full-name property identical to regular name. If the two are identical the full name <meta> element must be removed.", se.MESSAGE_TYPE_ERROR, "content.opf", duplicate_names))
# Check for malformed URLs
for message in _get_malformed_urls(metadata_xhtml):
message.filename = "content.opf"
messages.append(message)
if regex.search(r"id\.loc\.gov/authorities/names/[^\.]+\.html", metadata_xhtml):
messages.append(LintMessage("id.loc.gov URL ending with illegal .html", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Does the manifest match the generated manifest?
for manifest in regex.findall(r"<manifest>.*?</manifest>", metadata_xhtml, flags=regex.DOTALL):
manifest = regex.sub(r"[\n\t]", "", manifest)
expected_manifest = regex.sub(r"[\n\t]", "", self.generate_manifest())
if manifest != expected_manifest:
messages.append(LintMessage("<manifest> does not match expected structure.", se.MESSAGE_TYPE_ERROR, "content.opf"))
# Make sure some static files are unchanged
try:
with importlib_resources.path("se.data.templates", "LICENSE.md") as license_file_path:
if not filecmp.cmp(license_file_path, self.path / "LICENSE.md"):
messages.append(LintMessage(f"LICENSE.md does not match {license_file_path}", se.MESSAGE_TYPE_ERROR, "LICENSE.md"))
except Exception:
messages.append(LintMessage("Missing ./LICENSE.md", se.MESSAGE_TYPE_ERROR, "LICENSE.md"))
with importlib_resources.path("se.data.templates", "core.css") as core_css_file_path:
if not filecmp.cmp(core_css_file_path, self.path / "src" / "epub" / "css" / "core.css"):
messages.append(LintMessage(f"core.css does not match {core_css_file_path}", se.MESSAGE_TYPE_ERROR, "core.css"))
with importlib_resources.path("se.data.templates", "logo.svg") as logo_svg_file_path:
if not filecmp.cmp(logo_svg_file_path, self.path / "src" / "epub" / "images" / "logo.svg"):
messages.append(LintMessage(f"logo.svg does not match {logo_svg_file_path}", se.MESSAGE_TYPE_ERROR, "logo.svg"))
with importlib_resources.path("se.data.templates", "uncopyright.xhtml") as uncopyright_file_path:
if not filecmp.cmp(uncopyright_file_path, self.path / "src" / "epub" / "text" / "uncopyright.xhtml"):
messages.append(LintMessage(f"uncopyright.xhtml does not match {uncopyright_file_path}", se.MESSAGE_TYPE_ERROR, "uncopyright.xhtml"))
# Check for unused selectors
unused_selectors = _get_unused_selectors(self)
if unused_selectors:
messages.append(LintMessage("Unused CSS selectors:", se.MESSAGE_TYPE_ERROR, "local.css", unused_selectors))
# Now iterate over individual files for some checks
for root, _, filenames in os.walk(self.path):
for filename in sorted(filenames, key=se.natural_sort_key):
if ".git" in str(Path(root) / filename):
continue
if filename.startswith("cover.source."):
has_cover_source = True
if filename != "LICENSE.md" and regex.findall(r"[A-Z]", filename):
messages.append(LintMessage("Illegal uppercase letter in filename", se.MESSAGE_TYPE_ERROR, filename))
if "-0" in filename:
messages.append(LintMessage("Illegal leading 0 in filename", se.MESSAGE_TYPE_ERROR, filename))
if filename.endswith(tuple(se.BINARY_EXTENSIONS)) or filename.endswith("core.css"):
continue
if filename.startswith(".") or filename.startswith("README"):
if filename == ".gitignore":
# .gitignore is optional, because our standard gitignore ignores itself.
# So if it's present, it must match our template.
with importlib_resources.path("se.data.templates", "gitignore") as gitignore_file_path:
if not filecmp.cmp(gitignore_file_path, str(self.path / ".gitignore")):
messages.append(LintMessage(f".gitignore does not match {gitignore_file_path}", se.MESSAGE_TYPE_ERROR, ".gitignore"))
continue
else:
messages.append(LintMessage(f"Illegal {filename} file detected in {root}", se.MESSAGE_TYPE_ERROR))
continue
with open(Path(root) / filename, "r", encoding="utf-8") as file:
try:
file_contents = file.read()
except UnicodeDecodeError:
messages.append(LintMessage("Problem decoding file as utf-8", se.MESSAGE_TYPE_ERROR, filename))
continue
if "http://standardebooks.org" in file_contents:
messages.append(LintMessage("Non-HTTPS Standard Ebooks URL detected.", se.MESSAGE_TYPE_ERROR, filename))
if "UTF-8" in file_contents:
messages.append(LintMessage("String \"UTF-8\" must always be lowercase.", se.MESSAGE_TYPE_ERROR, filename))
if filename == "halftitle.xhtml":
has_halftitle = True
if "<title>Half Title</title>" not in file_contents:
messages.append(LintMessage("Half title <title> elements must contain exactly: \"Half Title\".", se.MESSAGE_TYPE_ERROR, filename))
if filename == "colophon.xhtml":
if "<a href=\"{}\">{}</a>".format(self.generated_identifier.replace("url:", ""), self.generated_identifier.replace("url:https://", "")) not in file_contents:
messages.append(LintMessage(f"Unexpected SE identifier in colophon. Expected: {self.generated_identifier}", se.MESSAGE_TYPE_ERROR, filename))
if ">trl<" in metadata_xhtml and "translated from" not in file_contents:
messages.append(LintMessage("Translator detected in metadata, but no “translated from LANG” block in colophon", se.MESSAGE_TYPE_ERROR, filename))
for variable in COLOPHON_VARIABLES:
if regex.search(fr"\b{variable}\b", file_contents):
messages.append(LintMessage(f"Missing data in colophon: {variable}", se.MESSAGE_TYPE_ERROR, filename))
matches = regex.findall(r"<dc:source>([^<]+?)</dc:source>", metadata_xhtml)
if len(matches) <= 2:
for link in matches:
if "gutenberg.org" in link and f"<a href=\"{link}\">Project Gutenberg</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in colophon.xhtml. Expected: <a href=\"{link}\">Project Gutenberg</a>", se.MESSAGE_TYPE_WARNING, filename))
if "hathitrust.org" in link and f"the<br/>\n\t\t\t<a href=\"{link}\">HathiTrust Digital Library</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in colophon.xhtml. Expected: the<br/> <a href=\"{link}\">HathiTrust Digital Library</a>", se.MESSAGE_TYPE_WARNING, filename))
if "archive.org" in link and f"the<br/>\n\t\t\t<a href=\"{link}\">Internet Archive</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in colophon.xhtml. Expected: the<br/> <a href=\"{link}\">Internet Archive</a>", se.MESSAGE_TYPE_WARNING, filename))
if "books.google.com" in link and f"<a href=\"{link}\">Google Books</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in colophon.xhtml. Expected: <a href=\"{link}\">Google Books</a>", se.MESSAGE_TYPE_WARNING, filename))
if filename == "titlepage.xhtml":
if "<title>Titlepage</title>" not in file_contents:
messages.append(LintMessage("Titlepage <title> elements must contain exactly: \"Titlepage\".", se.MESSAGE_TYPE_ERROR, filename))
if filename.endswith(".svg"):
# Check for fill: #000 which should simply be removed
matches = regex.findall(r"fill=\"\s*#000", file_contents) + regex.findall(r"style=\"[^\"]*?fill:\s*#000", file_contents)
if matches:
messages.append(LintMessage("Illegal style=\"fill: #000\" or fill=\"#000\".", se.MESSAGE_TYPE_ERROR, filename))
# Check for illegal height or width on root <svg> element
if filename != "logo.svg": # Do as I say, not as I do...
matches = regex.findall(r"<svg[^>]*?(height|width)=[^>]*?>", file_contents)
if matches:
messages.append(LintMessage("Illegal height or width on root <svg> element. Size SVGs using the viewbox attribute only.", se.MESSAGE_TYPE_ERROR, filename))
# Check for illegal transform attribute
matches = regex.findall(r"<[a-z]+[^>]*?transform=[^>]*?>", file_contents)
if matches:
messages.append(LintMessage("Illegal transform attribute. SVGs should be optimized to remove use of transform. Try using Inkscape to save as an \"optimized SVG\".", se.MESSAGE_TYPE_ERROR, filename))
if os.sep + "src" + os.sep not in root:
# Check that cover and titlepage images are in all caps
if filename == "cover.svg":
matches = regex.findall(r"<text[^>]+?>.*[a-z].*</text>", file_contents)
if matches:
messages.append(LintMessage("Lowercase letters in cover. Cover text must be all uppercase.", se.MESSAGE_TYPE_ERROR, filename))
# Save for later comparison with titlepage
matches = regex.findall(r"<title>(.*?)</title>", file_contents)
for match in matches:
cover_svg_title = match.replace("The cover for ", "")
if filename == "titlepage.svg":
matches = regex.findall(r"<text[^>]+?>(.*[a-z].*)</text>", html.unescape(file_contents))
for match in matches:
if match not in ("translated by", "illustrated by", "and"):
messages.append(LintMessage("Lowercase letters in titlepage. Titlepage text must be all uppercase except \"translated by\" and \"illustrated by\".", se.MESSAGE_TYPE_ERROR, filename))
# For later comparison with cover
matches = regex.findall(r"<title>(.*?)</title>", file_contents)
for match in matches:
titlepage_svg_title = match.replace("The titlepage for ", "")
if filename.endswith(".css"):
# Check CSS style
# First remove @supports selectors and normalize indentation within them
matches = regex.findall(r"^@supports\(.+?\){.+?}\s*}", file_contents, flags=regex.MULTILINE | regex.DOTALL)
for match in matches:
processed_match = regex.sub(r"^@supports\(.+?\){\s*(.+?)\s*}\s*}", "\\1", match.replace("\n\t", "\n") + "\n}", flags=regex.MULTILINE | regex.DOTALL)
file_contents = file_contents.replace(match, processed_match)
# Remove comments that are on their own line
file_contents = regex.sub(r"^/\*.+?\*/\n", "", file_contents, flags=regex.MULTILINE | regex.DOTALL)
# Check for unneeded white-space nowrap in abbr selectors
matches = regex.findall(r"abbr[^{]*?{[^}]*?white-space:\s*nowrap;[^}]*?}", css, regex.DOTALL)
if matches:
messages.append(LintMessage("abbr selector does not need white-space: nowrap; as it inherits it from core.css.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Don't specify border color
matches = regex.findall(r"(?:border|color).+?(?:
if matches:
messages.append(LintMessage("Don’t specify border colors, so that reading systems can adjust for night mode.", se.MESSAGE_TYPE_WARNING, filename, matches))
# If we select on the xml namespace, make sure we define the namespace in the CSS, otherwise the selector won't work
matches = regex.findall(r"\[\s*xml\s*\|", file_contents)
if matches and "@namespace xml \"http://www.w3.org/XML/1998/namespace\";" not in file_contents:
messages.append(LintMessage("[xml|attr] selector in CSS, but no XML namespace declared (@namespace xml \"http://www.w3.org/XML/1998/namespace\";).", se.MESSAGE_TYPE_ERROR, filename))
if filename.endswith(".xhtml"):
for message in _get_malformed_urls(file_contents):
message.filename = filename
messages.append(message)
# Check if this is a frontmatter file
if filename not in ("titlepage.xhtml", "imprint.xhtml", "toc.xhtml"):
matches = regex.findall(r"epub:type=\"[^\"]*?frontmatter[^\"]*?\"", file_contents)
if matches:
has_frontmatter = True
# Add new CSS classes to global list
if filename not in se.IGNORED_FILENAMES:
matches = regex.findall(r"(?:class=\")[^\"]+?(?:\")", file_contents)
for match in matches:
for css_class in match.replace("class=", "").replace("\"", "").split():
if css_class in xhtml_css_classes:
xhtml_css_classes[css_class] += 1
else:
xhtml_css_classes[css_class] = 1
#xhtml_css_classes = xhtml_css_classes + match.replace("class=", "").replace("\"", "").split()
# Read file contents into a DOM for querying
dom = BeautifulSoup(file_contents, "lxml")
# Store all headings to check for ToC references later
if filename != "toc.xhtml":
for match in dom.select("h1,h2,h3,h4,h5,h6"):
# Remove any links to the endnotes
endnote_ref = match.find("a", attrs={"epub:type": regex.compile("^.*noteref.*$")})
if endnote_ref:
endnote_ref.extract()
# Decide whether to remove subheadings based on the following logic:
# If the closest parent <section> is a part or division, then keep subtitle
# Else, if the closest parent <section> is a halftitlepage, then discard subtitle
# Else, if the first child of the heading is not z3998:roman, then also discard subtitle
# Else, keep the subtitle.
heading_subtitle = match.find(attrs={"epub:type": regex.compile("^.*subtitle.*$")})
if heading_subtitle:
# If an <h#> tag has a subtitle, the non-subtitle text must also be wrapped in a <span>.
# This invocation of match.find() returns all text nodes. We don't want any text nodes, so if it returns anything then we know we're
# missing a <span> somewhere.
if match.find(text=True, recursive=False).strip():
messages.append(LintMessage(f"<{match.name}> element has subtitle <span>, but first line is not wrapped in a <span>. See semantics manual for structure of headers with subtitles.", se.MESSAGE_TYPE_ERROR, filename))
# OK, move on with processing headers.
parent_section = match.find_parents("section")
# Sometimes we might not have a parent <section>, like in Keats' Poetry
if not parent_section:
parent_section = match.find_parents("body")
closest_section_epub_type = parent_section[0].get("epub:type") or ""
heading_first_child_epub_type = match.find("span", recursive=False).get("epub:type") or ""
if regex.findall(r"^.*(part|division|volume).*$", closest_section_epub_type) and not regex.findall(r"^.*se:short-story.*$", closest_section_epub_type):
remove_subtitle = False
elif regex.findall(r"^.*halftitlepage.*$", closest_section_epub_type):
remove_subtitle = True
elif not regex.findall(r"^.*z3998:roman.*$", heading_first_child_epub_type):
remove_subtitle = True
else:
remove_subtitle = False
if remove_subtitle:
heading_subtitle.extract()
normalized_text = " ".join(match.get_text().split())
headings = headings + [(normalized_text, filename)]
matches = regex.findall(r"<([a-z0-9]+)[^>]*?>\s*(<span epub:type=\"z3998:roman\">[^<]+?</span>)\s*</\1>", file_contents, flags=regex.DOTALL)
if matches:
messages.append(LintMessage("If <span> exists only for the z3998:roman semantic, then z3998:roman should be pulled into parent element instead.", se.MESSAGE_TYPE_WARNING, filename, [match[1] for match in matches]))
if "Hathi Trust" in file_contents:
messages.append(LintMessage("`Hathi Trust` should be `HathiTrust`", se.MESSAGE_TYPE_ERROR, filename))
matches = dom.select("[id],[class]")
for match in matches:
if match.has_attr("id"):
normalized_id = unicodedata.normalize("NFKD", match["id"])
uppercase_matches = regex.findall(r"[A-Z]+", normalized_id)
if uppercase_matches:
messages.append(LintMessage("Uppercase ID attribute. Attribute values must be all lowercase.", se.MESSAGE_TYPE_ERROR, filename, uppercase_matches))
number_matches = regex.findall(r"^[0-9]+.+", normalized_id)
if number_matches:
messages.append(LintMessage("ID starting with a number is illegal XHTML.", se.MESSAGE_TYPE_ERROR, filename, number_matches))
if match.has_attr("class"):
for css_class in match["class"]:
uppercase_matches = regex.findall(r"[A-Z]+", unicodedata.normalize("NFKD", css_class))
if uppercase_matches:
messages.append(LintMessage("Uppercase class attribute. Attribute values must be all lowercase.", se.MESSAGE_TYPE_ERROR, filename, uppercase_matches))
matches = [x for x in dom.select("section") if not x.has_attr("id")]
if matches:
messages.append(LintMessage("<section> element without id attribute.", se.MESSAGE_TYPE_ERROR, filename))
if "<title/>" in file_contents or "<title></title>" in file_contents:
messages.append(LintMessage("Empty <title> element.", se.MESSAGE_TYPE_ERROR, filename))
matches = regex.findall(r"&#[0-9]+?;", file_contents)
if matches:
messages.append(LintMessage("Illegal numeric entity (like Α) in file.", se.MESSAGE_TYPE_ERROR, filename))
matches = regex.findall(r"<blockquote[^>]*?>\s*<blockquote", file_contents, flags=regex.DOTALL)
if matches:
messages.append(LintMessage("Nested <blockquote> element.", se.MESSAGE_TYPE_WARNING, filename))
matches = regex.findall(r"<hr[^>]*?/?>\s*</section>", file_contents, flags=regex.DOTALL)
if matches:
messages.append(LintMessage("Illegal <hr/> before the end of a section.", se.MESSAGE_TYPE_ERROR, filename))
matches = regex.findall(r"(>>|>>)", file_contents)
if matches:
messages.append(LintMessage("Elements should end with a single >.", se.MESSAGE_TYPE_WARNING, filename))
if filename != "titlepage.xhtml":
temp_file_contents = file_contents.replace("\"name eoc\"", "\"name\"")
# Check for nbsp before ampersand (&)
matches = regex.findall(fr"(?<!\<abbr class=\"name\")>[^>]*?[^{se.NO_BREAK_SPACE}]\&", temp_file_contents)
if matches:
messages.append(LintMessage("Required nbsp not found before &", se.MESSAGE_TYPE_WARNING, filename))
# Check for nbsp after ampersand (&)
matches = regex.findall(fr"(?<!\<abbr class=\"name\")>[^>]*?\&[^{se.NO_BREAK_SPACE}]", temp_file_contents)
if matches:
messages.append(LintMessage("Required nbsp not found after &", se.MESSAGE_TYPE_WARNING, filename))
# Check for nbsp before times
matches = regex.findall(fr"[0-9]+[^{se.NO_BREAK_SPACE}]<abbr class=\"time", file_contents)
if matches:
messages.append(LintMessage("Required nbsp not found before <abbr class=\"time\">", se.MESSAGE_TYPE_WARNING, filename))
# Check for low-hanging misquoted fruit
matches = regex.findall(r"[A-Za-z]+[“‘]", file_contents)
if matches:
messages.append(LintMessage("Possible mis-curled quotation mark.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check that times have colons and not periods
matches = regex.findall(r"[0-9]\.[0-9]+\s<abbr class=\"time", file_contents) + regex.findall(r"at [0-9]\.[0-9]+", file_contents)
if matches:
messages.append(LintMessage("Times must be separated by colons (:) not periods (.)", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for leading 0 in IDs (note: not the same as checking for IDs that start with an integer)
matches = regex.findall(r"id=\"[^\"]+?\-0[0-9]+[^\"]*?\"", file_contents)
if matches:
messages.append(LintMessage("Illegal leading 0 in ID attribute", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for stage direction that ends in ?! but also has a trailing period
matches = regex.findall(r"<i epub:type=\"z3998:stage-direction\">(?:(?!<i).)*?\.</i>[,:;!?]", file_contents)
if matches:
messages.append(LintMessage("Stage direction ending in period next to other punctuation. Remove trailing periods in stage direction.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for ending punctuation inside italics that have semantics.
# Ignore the colophon because paintings might have punctuation in their names
if filename != "colophon.xhtml":
matches = regex.findall(r"(<([ib]) epub:type=\"[^\"]*?se:name\.[^\"]*?\">[^<]+?[\.,\!\?]</\2>)", file_contents)
filtered_matches = []
for match in matches:
if "z3998:stage-direction" not in match[0]:
filtered_matches.append(match[0])
# ...and also check for ending punctuation inside em tags, if it looks like a *part* of a clause
# instead of a whole clause. If the <em> is preceded by an em dash or quotes then it's
matches = regex.findall(r"(?:[^—“‘])<em>(?:\w+?\s*){1,2}?[\.,\!\?]<\/em>", file_contents)
for match in matches:
if match[4].islower():
filtered_matches.append(match)
if filtered_matches:
messages.append(LintMessage("Ending punctuation inside italics.", se.MESSAGE_TYPE_WARNING, filename, filtered_matches))
matches = regex.findall(r"[£\$][0-9]{4,}", file_contents)
if matches:
messages.append(LintMessage("Numbers not grouped by commas. Separate numbers greater than 1,000 with commas at every three numerals.", se.MESSAGE_TYPE_WARNING, filename, matches))
matches = regex.findall(r"<(?:m:)?mfenced[^>]*?>.+?</(?:m:)?mfenced>", file_contents)
if matches:
messages.append(LintMessage("<m:mfenced> is deprecated in the MathML spec. Use <m:mrow><m:mo fence=\"true\">(</m:mo>...<m:mo fence=\"true\">)</m:mo></m:mrow>.", se.MESSAGE_TYPE_ERROR, filename, matches))
matches = regex.findall(r"(?<!<p[^>]*?>)<span epub:type=\"z3998:roman\">[^<]+?</span>\.\s+[a-z]", file_contents)
if matches:
messages.append(LintMessage("Roman numeral followed by a period. When in mid-sentence Roman numerals must not be followed by a period.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for two em dashes in a row
matches = regex.findall(fr"—{se.WORD_JOINER}*—+", file_contents)
if matches:
messages.append(LintMessage("Two or more em-dashes in a row detected. Elided words should use the two- or three-em-dash Unicode character, and dialog ending in em-dashes should only end in a single em-dash.", se.MESSAGE_TYPE_ERROR, filename))
# Check for <abbr class="name"> that does not contain spaces
matches = regex.findall(r"<abbr class=\"name\">[^<]*?[A-Z]\.[A-Z]\.[^<]*?</abbr>", file_contents)
if matches:
messages.append(LintMessage("Initials in <abbr class=\"name\"> not separated by spaces.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for empty <h2> missing epub:type="title" attribute
if "<h2>" in file_contents:
messages.append(LintMessage("<h2> element without `epub:type=\"title\"` attribute.", se.MESSAGE_TYPE_WARNING, filename))
# Check for a common typo
if "z3998:nonfiction" in file_contents:
messages.append(LintMessage("z3998:nonfiction should be z3998:non-fiction", se.MESSAGE_TYPE_ERROR, filename))
# Check for empty <p> tags
matches = regex.findall(r"<p[^>]*?>\s*</p>", file_contents)
if "<p/>" in file_contents or matches:
messages.append(LintMessage("Empty <p> element. Use <hr/> for thematic breaks if appropriate.", se.MESSAGE_TYPE_ERROR, filename))
# Check for <p> tags that end with <br/>
matches = regex.findall(r"(\s*<br/?>\s*)+</p>", file_contents)
if matches:
messages.append(LintMessage("<br/> element found before closing </p> tag.", se.MESSAGE_TYPE_ERROR, filename))
# Check for single words that are in italics, but that have closing punctuation outside italics
# Outer wrapping match is so that .findall returns the entire match and not the subgroup
# The first regex also matches the first few characters before the first double quote; we use those for more sophisticated
# checks below, to give fewer false positives like `with its downy red hairs and its “<i xml:lang="fr">doigts de faune</i>.”`
matches = regex.findall(r"((?:.{1,2}\s)?“<(i|em)[^>]*?>[^<]+?</\2>[\!\?\.])", file_contents) + regex.findall(r"([\.\!\?] <(i|em)[^>]*?>[^<]+?</\2>[\!\?\.])", file_contents)
# But, if we've matched a name of something, don't include that as an error. For example, `He said, “<i epub:type="se:name.publication.book">The Decameron</i>.”`
# We also exclude the match from the list if:
# 1. The double quote is directly preceded by a lowercase letter and a space: `with its downy red hairs and its “<i xml:lang="fr">doigts de faune</i>.”`
# 2. The double quote is directly preceded by a lowercase letter, a comma, and a space, and the first letter within the double quote is lowercase: In the original, “<i xml:lang="es">que era un Conde de Irlos</i>.”
matches = [x for x in matches if "epub:type=\"se:name." not in x[0] and "epub:type=\"z3998:taxonomy" not in x[0] and not regex.match(r"^[a-z’]+\s“", x[0]) and not regex.match(r"^[a-z’]+,\s“[a-z]", se.formatting.remove_tags(x[0]))]
if matches:
messages.append(LintMessage("When a complete clause is italicized, ending punctuation except commas must be within containing italics.", se.MESSAGE_TYPE_WARNING, filename, [match[0] for match in matches]))
# Run some checks on <i> elements
comma_matches = []
italicizing_matches = []
elements = dom.select("i")
for elem in elements:
next_sib = elem.nextSibling
# Check for trailing commas inside <i> tags at the close of dialog
# More sophisticated version of: \b[^\s]+?,</i>”
if isinstance(next_sib, NavigableString) and next_sib.startswith("”") and elem.text.endswith(","):
comma_matches.append(str(elem) + "”")
# Check for foreign phrases with italics going *outside* quotes
for attr in elem.attrs:
if attr == "xml:lang" and (elem.text.startswith("“") or elem.text.endswith("”")):
italicizing_matches.append(str(elem))
if comma_matches:
messages.append(LintMessage("Comma inside <i> element before closing dialog.", se.MESSAGE_TYPE_WARNING, filename, comma_matches))
if italicizing_matches:
messages.append(LintMessage("When italicizing language in dialog, italics go inside quotation marks.", se.MESSAGE_TYPE_WARNING, filename, italicizing_matches))
# Check for style attributes
matches = regex.findall(r"<.+?style=\"", file_contents)
if matches:
messages.append(LintMessage("Illegal style attribute. Do not use inline styles, any element can be targeted with a clever enough selector.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for uppercase HTML tags
if regex.findall(r"<[A-Z]+", file_contents):
messages.append(LintMessage("One or more uppercase HTML tags.", se.MESSAGE_TYPE_ERROR, filename))
# Check for nbsp within <abbr class="name">, which is redundant
matches = regex.findall(fr"<abbr[^>]+?class=\"name\"[^>]*?>[^<]*?{se.NO_BREAK_SPACE}[^<]*?</abbr>", file_contents)
if matches:
messages.append(LintMessage("No-break space detected in <abbr class=\"name\">. This is redundant.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for Roman numerals in <title> tag
if regex.findall(r"<title>[Cc]hapter [XxIiVv]+", file_contents):
messages.append(LintMessage("No Roman numerals allowed in <title> element; use decimal numbers.", se.MESSAGE_TYPE_ERROR, filename))
# Check for HTML tags in <title> tags
matches = regex.findall(r"<title>.*?[<].*?</title>", file_contents)
if matches:
messages.append(LintMessage("Element in <title> element", se.MESSAGE_TYPE_ERROR, filename, matches))
# If the chapter has a number and no subtitle, check the <title> tag...
matches = regex.findall(r"<h([0-6]) epub:type=\"title z3998:roman\">([^<]+)</h\1>", file_contents, flags=regex.DOTALL)
# ...But only make the correction if there's one <h#> tag. If there's more than one, then the xhtml file probably requires an overarching title
if matches and len(regex.findall(r"<h(?:[0-6])", file_contents)) == 1:
try:
chapter_number = roman.fromRoman(matches[0][1].upper())
regex_string = fr"<title>(Chapter|Section|Part) {chapter_number}"
if not regex.findall(regex_string, file_contents):
messages.append(LintMessage(f"<title> element doesn’t match expected value; should be `Chapter {chapter_number}`. (Beware hidden Unicode characters!)", se.MESSAGE_TYPE_ERROR, filename))
except Exception:
messages.append(LintMessage("<h#> element is marked with z3998:roman, but is not a Roman numeral", se.MESSAGE_TYPE_ERROR, filename))
# If the chapter has a number and subtitle, check the <title> tag...
matches = regex.findall(r"<h([0-6]) epub:type=\"title\">\s*<span epub:type=\"z3998:roman\">([^<]+)</span>\s*<span epub:type=\"subtitle\">(.+?)</span>\s*</h\1>", file_contents, flags=regex.DOTALL)
# ...But only make the correction if there's one <h#> tag. If there's more than one, then the xhtml file probably requires an overarching title
if matches and len(regex.findall(r"<h(?:[0-6])", file_contents)) == 1:
chapter_number = roman.fromRoman(matches[0][1].upper())
# First, remove endnotes in the subtitle, then remove all other tags (but not tag contents)
chapter_title = regex.sub(r"<a[^<]+?epub:type=\"noteref\"[^<]*?>[^<]+?</a>", "", matches[0][2]).strip()
chapter_title = regex.sub(r"<[^<]+?>", "", chapter_title)
regex_string = r"<title>(Chapter|Section|Part) {}: {}".format(chapter_number, regex.escape(chapter_title))
if not regex.findall(regex_string, file_contents):
messages.append(LintMessage(f"<title> element doesn’t match expected value; should be `Chapter {chapter_number}: {chapter_title}`. (Beware hidden Unicode characters!)", se.MESSAGE_TYPE_ERROR, filename))
# Check for missing subtitle styling
if "epub:type=\"subtitle\"" in file_contents and not local_css_has_subtitle_style:
messages.append(LintMessage("Subtitles detected, but no subtitle style detected in local.css.", se.MESSAGE_TYPE_ERROR, filename))
# Check for whitespace before noteref
matches = regex.findall(r"\s+<a href=\"endnotes\.xhtml#note-[0-9]+?\" id=\"noteref-[0-9]+?\" epub:type=\"noteref\">[0-9]+?</a>", file_contents)
if matches:
messages.append(LintMessage("Illegal white space before noteref.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check for <li> elements that don't have a direct block child
if filename != "toc.xhtml":
matches = regex.findall(r"<li(?:\s[^>]*?>|>)\s*[^\s<]", file_contents)
if matches:
messages.append(LintMessage("<li> without direct block-level child.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for ldquo not correctly closed
# Ignore closing paragraphs, line breaks, and closing cells in case ldquo means "ditto mark"
matches = regex.findall(r"“[^‘”]+?“", file_contents)
matches = [x for x in matches if "</p" not in x and "<br/>" not in x and "</td>" not in x]
if matches:
messages.append(LintMessage("`“` missing matching `”`.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for lsquo not correctly closed
matches = regex.findall(r"‘[^“’]+?‘", file_contents)
matches = [x for x in matches if "</p" not in x and "<br/>" not in x]
if matches:
messages.append(LintMessage("`‘` missing matching `’`.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for IDs on <h#> tags
matches = regex.findall(r"<h[0-6][^>]*?id=[^>]*?>", file_contents, flags=regex.DOTALL)
if matches:
messages.append(LintMessage("<hts, flags=regex.DOTALL)
for match in matches:
if "z3998:roman" not in match.group(2):
title = match.group(3).strip()
# Remove leading roman numerals first
title = regex.sub(r"^<span epub:type=\"[^\"]*?z3998:roman[^\"]*?\">(.*?)</span>", "", title, flags=regex.DOTALL)
# Remove leading leftover spacing and punctuation
title = regex.sub(r"^[\s\.\,\!\?\:\;]*", "", title)
# Remove endnotes
title = regex.sub(r"<a[^>]*?epub:type=\"noteref\"[^>]*?>[0-9]+</a>", "", title)
# Normalize whitespace
title = regex.sub(r"\s+", " ", title, flags=regex.DOTALL).strip()
# Remove nested <span>s in subtitles, which might trip up the next regex block
title = regex.sub(r"(<span epub:type=\"subtitle\">[^<]*?)<span[^>]*?>([^<]*?</span>)", r"\1\2", title, flags=regex.DOTALL)
title = regex.sub(r"(<span epub:type=\"subtitle\">[^<]*?)</span>([^<]*?</span>)", r"\1\2", title, flags=regex.DOTALL)
# Do we have a subtitle? If so the first letter of that must be capitalized, so we pull that out
subtitle_matches = regex.findall(r"(.*?)<span epub:type=\"subtitle\">(.*?)</span>(.*?)", title, flags=regex.DOTALL)
if subtitle_matches:
for title_header, subtitle, title_footer in subtitle_matches:
title_header = se.formatting.titlecase(se.formatting.remove_tags(title_header).strip())
subtitle = se.formatting.titlecase(se.formatting.remove_tags(subtitle).strip())
title_footer = se.formatting.titlecase(se.formatting.remove_tags(title_footer).strip())
titlecased_title = title_header + " " + subtitle + " " + title_footer
titlecased_title = titlecased_title.strip()
title = se.formatting.remove_tags(title).strip()
if title != titlecased_title:
messages.append(LintMessage(f"Title `{title}` not correctly titlecased. Expected: `{titlecased_title}`", se.MESSAGE_TYPE_WARNING, filename))
# No subtitle? Much more straightforward
else:
titlecased_title = se.formatting.remove_tags(se.formatting.titlecase(title))
title = se.formatting.remove_tags(title)
if title != titlecased_title:
messages.append(LintMessage(f"Title `{title}` not correctly titlecased. Expected: `{titlecased_title}`", se.MESSAGE_TYPE_WARNING, filename))
# Check for <figure> tags without id attributes
matches = regex.findall(r"<img[^>]*?id=\"[^>]+?>", file_contents)
if matches:
messages.append(LintMessage("<img> element with ID attribute. ID attributes go on parent <figure> elements.", se.MESSAGE_TYPE_ERROR, filename, matches))
matches = regex.findall(r"[a-z]+?” [a-zA-Z]+? said", file_contents)
if matches:
messages.append(LintMessage("Dialog without ending comma.", se.MESSAGE_TYPE_WARNING, filename, matches))
matches = regex.findall(r"alt=\"[^\"]*?('|--|")[^\"]*?\"", file_contents)
if matches:
messages.append(LintMessage("Non-typogrified ', \" (as "), or -- in image alt attribute.", se.MESSAGE_TYPE_ERROR, filename, matches))
# Check alt attributes not ending in punctuation
if filename not in se.IGNORED_FILENAMES:
matches = regex.findall(r"alt=\"[^\"]*?[a-zA-Z]\"", file_contents)
if matches:
messages.append(LintMessage("Alt attribute doesn’t appear to end with punctuation. Alt attributes must be composed of complete sentences ending in appropriate punctuation.", se.MESSAGE_TYPE_ERROR, filename, matches))
images = dom.select("img[src$=svg]")
for image in images:
alt_text = image["alt"]
title_text = ""
image_ref = image["src"].split("/").pop()
try:
with open(self.path / "src" / "epub" / "images" / image_ref, "r", encoding="utf-8") as image_source:
try:
title_text = BeautifulSoup(image_source, "lxml").title.get_text()
except Exception:
messages.append(LintMessage(f"{image_ref} missing <title> element.", se.MESSAGE_TYPE_ERROR, image_ref))
if title_text != "" and alt_text != "" and title_text != alt_text:
messages.append(LintMessage(f"The <title> of {image_ref} doesn’t match the alt text in {filename}", se.MESSAGE_TYPE_ERROR, filename))
except FileNotFoundError:
messages.append(LintMessage(f"The image {image_ref} doesn’t exist", se.MESSAGE_TYPE_ERROR, filename))
regex_string = fr"<a[^>]*?epub:type=\"noteref\"[^>]*?>[0-9]+</a>[^\s<–\]\)—{se.WORD_JOINER}]"
matches = regex.findall(regex_string, file_contents)
if matches:
messages.append(LintMessage("Endnote links must be outside of punctuation, including quotation marks.", se.MESSAGE_TYPE_WARNING, filename, matches))
matches = regex.findall(r"[0-9]+[\- ][mck][mgl]\b", file_contents)
if matches:
messages.append(LintMessage("Measurements must be separated by a no-break space, not a dash or regular space.", se.MESSAGE_TYPE_ERROR, filename, matches))
matches = regex.findall(r"<br\s*?/>[^\n]", file_contents)
if matches:
messages.append(LintMessage("<br/> element must be followed by a newline, and subsequent content must be indented to the same level.", se.MESSAGE_TYPE_ERROR, filename))
if "<pre" in file_contents:
messages.append(LintMessage("Illegal <pre> element.", se.MESSAGE_TYPE_ERROR, filename))
matches = regex.findall(r"\b.+?”[,\.]", file_contents)
if matches:
messages.append(LintMessage("Comma or period outside of double quote. Generally punctuation should go within single and double quotes.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for double spacing
regex_string = fr"[{se.NO_BREAK_SPACE}{se.HAIR_SPACE} ]{{2,}}"
matches = regex.findall(regex_string, file_contents)
if matches:
messages.append(LintMessage("Double spacing detected in file. Sentences should be single-spaced. (Note that double spaces might include Unicode no-break spaces!)", se.MESSAGE_TYPE_ERROR, filename))
# Run some checks on epub:type values
incorrect_attrs = []
epub_type_attrs = regex.findall("epub:type=\"([^\"]+?)\"", file_contents)
for attrs in epub_type_attrs:
for attr in regex.split(r"\s", attrs):
# Did someone use colons instead of dots for SE identifiers? e.g. se:name:vessel:ship
matches = regex.findall(r"^se:[a-z]+:(?:[a-z]+:?)*", attr)
if matches:
messages.append(LintMessage(f"Illegal colon (:) detected in SE identifier. SE identifiers are separated by dots (.) not colons (:). E.g., `se:name.vessel.ship`", se.MESSAGE_TYPE_ERROR, filename, matches))
# Did someone use periods instead of colons for the SE namespace? e.g. se.name.vessel.ship
matches = regex.findall(r"^se\.[a-z]+(?:\.[a-z]+)*", attr)
if matches:
messages.append(LintMessage(f"SE namespace must be followed by a colon (:), not a dot (.). E.g., `se:name.vessel`", se.MESSAGE_TYPE_ERROR, filename, matches))
# Did we draw from the z3998 vocabulary when the item exists in the epub vocabulary?
if attr.startswith("z3998:"):
bare_attr = attr.replace("z3998:", "")
if bare_attr in EPUB_SEMANTIC_VOCABULARY:
incorrect_attrs.append((attr, bare_attr))
# Convert this into a unique set so we don't spam the console with repetitive messages
unique_incorrect_attrs = set(incorrect_attrs)
for (attr, bare_attr) in unique_incorrect_attrs:
messages.append(LintMessage(f"`{attr}` semantic used, but `{bare_attr}` is in the EPUB semantic inflection vocabulary.", se.MESSAGE_TYPE_ERROR, filename))
# Check for leftover asterisms
matches = regex.findall(r"<[a-z]+[^>]*?>\s*\*\s*(\*\s*)+", file_contents, flags=regex.DOTALL)
if matches:
messages.append(LintMessage("Illegal asterism (`***`) detected. Section/scene breaks must be defined by an `<hr/>` element.", se.MESSAGE_TYPE_ERROR, filename))
# Check for missing punctuation before closing quotes
matches = regex.findall(r"[a-z]+[”’]</p>", file_contents, flags=regex.IGNORECASE)
if matches:
messages.append(LintMessage("Missing punctuation before closing quotes.", se.MESSAGE_TYPE_WARNING, filename, matches))
# Check for space before endnote backlinks
if filename == "endnotes.xhtml":
# Do we have to replace Ibid.?
matches = regex.findall(r"\bibid\b", file_contents, flags=regex.IGNORECASE)
if matches:
messages.append(LintMessage("Illegal `Ibid` in endnotes. “Ibid” means “The previous reference” which is meaningless with popup endnotes, and must be replaced by the actual thing `Ibid` refers to.", se.MESSAGE_TYPE_ERROR, filename))
endnote_referrers = dom.select("li[id^=note-] a")
bad_referrers = []
for referrer in endnote_referrers:
# We check against the attr value here because I couldn't figure out how to select an XML-namespaced attribute using BS4
if "epub:type" in referrer.attrs and referrer.attrs["epub:type"] == "backlink":
is_first_sib = True
for sib in referrer.previous_siblings:
if is_first_sib:
is_first_sib = False
if isinstance(sib, NavigableString):
if sib == "\n": # Referrer preceded by newline. Check if all previous sibs are tags.
continue
if sib == " " or str(sib) == se.NO_BREAK_SPACE or regex.search(r"[^\s] $", str(sib)): # Referrer preceded by a single space; we're OK
break
# Referrer preceded by a string that is not a newline and does not end with a single space
bad_referrers.append(referrer)
break
else:
# We got here because the first sib was a newline, or not a string. So, check all previous sibs.
if isinstance(sib, NavigableString) and sib != "\n":
bad_referrers.append(referrer)
break
if bad_referrers:
messages.append(LintMessage("Endnote referrer link not preceded by exactly one space, or a newline if all previous siblings are elements.", se.MESSAGE_TYPE_WARNING, filename, [str(referrer) for referrer in bad_referrers]))
# If we're in the imprint, are the sources represented correctly?
# We don't have a standard yet for more than two sources (transcription and scan) so just ignore that case for now.
if filename == "imprint.xhtml":
matches = regex.findall(r"<dc:source>([^<]+?)</dc:source>", metadata_xhtml)
if len(matches) <= 2:
for link in matches:
if "gutenberg.org" in link and f"<a href=\"{link}\">Project Gutenberg</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in imprint.xhtml. Expected: <a href=\"{link}\">Project Gutenberg</a>", se.MESSAGE_TYPE_WARNING, filename))
if "hathitrust.org" in link and f"the <a href=\"{link}\">HathiTrust Digital Library</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in imprint.xhtml. Expected: the <a href=\"{link}\">HathiTrust Digital Library</a>", se.MESSAGE_TYPE_WARNING, filename))
if "archive.org" in link and f"the <a href=\"{link}\">Internet Archive</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in imprint.xhtml. Expected: the <a href=\"{link}\">Internet Archive</a>", se.MESSAGE_TYPE_WARNING, filename))
if "books.google.com" in link and f"<a href=\"{link}\">Google Books</a>" not in file_contents:
messages.append(LintMessage(f"Source not represented in imprint.xhtml. Expected: <a href=\"{link}\">Google Books</a>", se.MESSAGE_TYPE_WARNING, filename))
# Collect abbr elements for later check
result = regex.findall("<abbr[^<]+?>", file_contents)
result = [item.replace("eoc", "").replace(" \"", "").strip() for item in result]
abbr_elements = list(set(result + abbr_elements))
if filename not in se.IGNORED_FILENAMES:
file_language = regex.search(r"<html[^<]+xml\:lang=\"([^\"]+)\"", file_contents).group(1)
if language != file_language:
messages.append(LintMessage(f"File language is {file_language}, but content.opf language is {language}", se.MESSAGE_TYPE_ERROR, filename))
# Check LoI descriptions to see if they match associated figcaptions
if filename == "loi.xhtml":
illustrations = dom.select("li > a")
for illustration in illustrations:
figure_ref = illustration["href"].split("
chapter_ref = regex.findall(r"(.*?)
figcaption_text = ""
loi_text = illustration.get_text()
with open(self.path / "src" / "epub" / "text" / chapter_ref, "r", encoding="utf-8") as chapter:
try:
figure = BeautifulSoup(chapter, "lxml").select("
except Exception:
messages.append(LintMessage(f"
continue
if figure.img:
figure_img_alt = figure.img.get('alt')
if figure.figcaption:
figcaption_text = figure.figcaption.get_text()
if (figcaption_text != "" and loi_text != "" and figcaption_text != loi_text) and (figure_img_alt != "" and loi_text != "" and figure_img_alt != loi_text):
messages.append(LintMessage(f"The <figcaption> element of {figure_ref} doesn’t match the text in its LoI entry", se.MESSAGE_TYPE_WARNING, chapter_ref))
# Check for missing MARC relators
if filename == "introduction.xhtml" and ">aui<" not in metadata_xhtml and ">win<" not in metadata_xhtml:
messages.append(LintMessage("introduction.xhtml found, but no MARC relator `aui` (Author of introduction, but not the chief author) or `win` (Writer of introduction)", se.MESSAGE_TYPE_WARNING, filename))
if filename == "preface.xhtml" and ">wpr<" not in metadata_xhtml:
messages.append(LintMessage("preface.xhtml found, but no MARC relator `wpr` (Writer of preface)", se.MESSAGE_TYPE_WARNING, filename))
if filename == "afterword.xhtml" and ">aft<" not in metadata_xhtml:
messages.append(LintMessage("afterword.xhtml found, but no MARC relator `aft` (Author of colophon, afterword, etc.)", se.MESSAGE_TYPE_WARNING, filename))
if filename == "endnotes.xhtml" and ">ann<" not in metadata_xhtml:
messages.append(LintMessage("endnotes.xhtml found, but no MARC relator `ann` (Annotator)", se.MESSAGE_TYPE_WARNING, filename))
if filename == "loi.xhtml" and ">ill<" not in metadata_xhtml:
messages.append(LintMessage("loi.xhtml found, but no MARC relator `ill` (Illustrator)", se.MESSAGE_TYPE_WARNING, filename))
# Check for wrong semantics in frontmatter/backmatter
if filename in se.FRONTMATTER_FILENAMES and "frontmatter" not in file_contents:
messages.append(LintMessage("No frontmatter semantic inflection for what looks like a frontmatter file", se.MESSAGE_TYPE_WARNING, filename))
if filename in se.BACKMATTER_FILENAMES and "backmatter" not in file_contents:
messages.append(LintMessage("No backmatter semantic inflection for what looks like a backmatter file", se.MESSAGE_TYPE_WARNING, filename))
if cover_svg_title != titlepage_svg_title:
messages.append(LintMessage("cover.svg and titlepage.svg <title> elements don’t match", se.MESSAGE_TYPE_ERROR))
if has_frontmatter and not has_halftitle:
messages.append(LintMessage("Frontmatter found, but no halftitle. Halftitle is required when frontmatter is present.", se.MESSAGE_TYPE_ERROR, "content.opf"))
if not has_cover_source:
messages.append(LintMessage("./images/cover.source.jpg not found", se.MESSAGE_TYPE_ERROR, "cover.source.jpg"))
single_use_css_classes = []
for css_class in xhtml_css_classes:
if css_class not in se.IGNORED_CLASSES:
if "." + css_class not in css:
messages.append(LintMessage(f"class `{css_class}` found in xhtml, but no style in local.css", se.MESSAGE_TYPE_ERROR, "local.css"))
if xhtml_css_classes[css_class] == 1 and css_class not in se.IGNORED_CLASSES and not regex.match(r"^i[0-9]$", css_class):
# Don't count ignored classes OR i[0-9] which are used for poetry styling
single_use_css_classes.append(css_class)
if single_use_css_classes:
messages.append(LintMessage("CSS class only used once. Can a clever selector be crafted instead of a single-use class? When possible classes should not be single-use style hooks.", se.MESSAGE_TYPE_WARNING, "local.css", single_use_css_classes))
headings = list(set(headings))
with open(self.path / "src" / "epub" / "toc.xhtml", "r", encoding="utf-8") as file:
toc = BeautifulSoup(file.read(), "lxml")
landmarks = toc.find("nav", attrs={"epub:type": "landmarks"})
toc = toc.find("nav", attrs={"epub:type": "toc"})
# Depth first search using recursiveChildGenerator to get the headings in order
toc_entries = []
for child in toc.recursiveChildGenerator():
if getattr(child, "name") == "a":
toc_entries.append(child)
# Match ToC headings against text headings
# Unlike main headings, ToC entries have a ‘:’ before the subheading so we need to strip these for comparison
toc_headings = []
for index, entry in enumerate(toc_entries):
entry_text = " ".join(entry.get_text().replace(":", "").split())
entry_file = regex.sub(r"^text\/(.*?\.xhtml).*$", r"\1", entry.get("href"))
toc_headings.append((entry_text, entry_file))
for heading in headings:
# Occasionally we find a heading with a colon, but as we’ve stripped our
# ToC-only colons above we also need to do that here for the comparison.
heading_without_colons = (heading[0].replace(":", ""), heading[1])
if heading_without_colons not in toc_headings:
messages.append(LintMessage(f"Heading `{heading[0]}` found, but not present for that file in the ToC.", se.MESSAGE_TYPE_ERROR, heading[1]))
# Check our ordered ToC entries against the spine
# To cover all possibilities, we combine the toc and the landmarks to get the full set of entries
with open(self.path / "src" / "epub" / "content.opf", "r", encoding="utf-8") as content_opf:
toc_files = []
for index, entry in enumerate(landmarks.find_all("a", attrs={"epub:type": regex.compile("^.*(frontmatter|bodymatter).*$")})):
entry_file = regex.sub(r"^text\/(.*?\.xhtml).*$", r"\1", entry.get("href"))
toc_files.append(entry_file)
for index, entry in enumerate(toc_entries):
entry_file = regex.sub(r"^text\/(.*?\.xhtml).*$", r"\1", entry.get("href"))
toc_files.append(entry_file)
unique_toc_files: List[str] = []
for toc_file in toc_files:
if toc_file not in unique_toc_files:
unique_toc_files.append(toc_file)
toc_files = unique_toc_files
spine_entries = BeautifulSoup(content_opf.read(), "lxml").find("spine").find_all("itemref")
if len(toc_files) != len(spine_entries):
messages.append(LintMessage("The number of elements in the spine ({}) does not match the number of elements in the ToC and landmarks ({}).".format(len(toc_files), len(spine_entries)), se.MESSAGE_TYPE_ERROR, "content.opf"))
for index, entry in enumerate(spine_entries):
if toc_files[index] != entry.attrs["idref"]:
messages.append(LintMessage(f"The spine order does not match the order of the ToC and landmarks. Expected {entry.attrs['idref']}, found {toc_files[index]}.", se.MESSAGE_TYPE_ERROR, "content.opf"))
break
for element in abbr_elements:
try:
css_class = regex.search(r"class=\"([^\"]+?)\"", element).group(1)
except Exception:
continue
if css_class and css_class in ("temperature", "era", "acronym") and "abbr." + css_class not in abbr_styles:
messages.append(LintMessage(f"abbr.{css_class} element found, but no required style in local.css (See typgoraphy manual for style)", se.MESSAGE_TYPE_ERROR, "local.css"))
return messages
| true | true |
1c3fdd4f966d9a2d8fcf67855782831abc65b4ad | 337 | py | Python | modules/first_module.py | BigMountainTiger/p-virtualenv-excercise | 8f1f32de59f9b4b2be2ed9d212842385d3d48f1b | [
"MIT"
] | null | null | null | modules/first_module.py | BigMountainTiger/p-virtualenv-excercise | 8f1f32de59f9b4b2be2ed9d212842385d3d48f1b | [
"MIT"
] | null | null | null | modules/first_module.py | BigMountainTiger/p-virtualenv-excercise | 8f1f32de59f9b4b2be2ed9d212842385d3d48f1b | [
"MIT"
] | null | null | null | class _FirstClass:
def __init__(self, name, age):
self.name = name
self.age = age
firstObject = _FirstClass('Song', 20)
class ANumber:
def __init__(self, n):
self.number = n
a_number = ANumber(50)
def set_a_number(n):
a_number.number = n
def get_a_number():
return a_number
print('first_module initiated ....') | 16.047619 | 37 | 0.682493 | class _FirstClass:
def __init__(self, name, age):
self.name = name
self.age = age
firstObject = _FirstClass('Song', 20)
class ANumber:
def __init__(self, n):
self.number = n
a_number = ANumber(50)
def set_a_number(n):
a_number.number = n
def get_a_number():
return a_number
print('first_module initiated ....') | true | true |
1c3fdd509254afc2cb7712d828b5d4ce54dab04e | 430 | py | Python | npbench/benchmarks/nbody/nbody.py | frahlg/npbench | 1bc4d9e2e22f3ca67fa2bc7f40e2e751a9c8dd26 | [
"BSD-3-Clause"
] | 27 | 2021-05-10T11:49:13.000Z | 2022-03-22T18:07:19.000Z | npbench/benchmarks/nbody/nbody.py | frahlg/npbench | 1bc4d9e2e22f3ca67fa2bc7f40e2e751a9c8dd26 | [
"BSD-3-Clause"
] | 3 | 2021-12-01T13:03:17.000Z | 2022-03-17T10:53:00.000Z | npbench/benchmarks/nbody/nbody.py | frahlg/npbench | 1bc4d9e2e22f3ca67fa2bc7f40e2e751a9c8dd26 | [
"BSD-3-Clause"
] | 7 | 2021-06-24T03:40:25.000Z | 2022-01-26T09:04:33.000Z | # Copyright 2021 ETH Zurich and the NPBench authors. All rights reserved.
import numpy as np
def initialize(N, tEnd, dt):
from numpy.random import default_rng
rng = default_rng(42)
mass = 20.0 * np.ones((N, 1)) / N # total mass of particles is 20
pos = rng.random((N, 3)) # randomly selected positions and velocities
vel = rng.random((N, 3))
Nt = int(np.ceil(tEnd / dt))
return mass, pos, vel, Nt
| 30.714286 | 74 | 0.65814 |
import numpy as np
def initialize(N, tEnd, dt):
from numpy.random import default_rng
rng = default_rng(42)
mass = 20.0 * np.ones((N, 1)) / N
pos = rng.random((N, 3))
vel = rng.random((N, 3))
Nt = int(np.ceil(tEnd / dt))
return mass, pos, vel, Nt
| true | true |
1c3fdd608b5db1307869afe943ad188d63c4110b | 197 | py | Python | tests/mytest.py | UmboCV/logutils | 3f9d37f1dc649f3a01c7a1593b3a40f77aafa89f | [
"BSD-3-Clause"
] | null | null | null | tests/mytest.py | UmboCV/logutils | 3f9d37f1dc649f3a01c7a1593b3a40f77aafa89f | [
"BSD-3-Clause"
] | null | null | null | tests/mytest.py | UmboCV/logutils | 3f9d37f1dc649f3a01c7a1593b3a40f77aafa89f | [
"BSD-3-Clause"
] | null | null | null | from __future__ import absolute_import
from logutils.testing import TestHandler, Matcher
class MyTestHandler(TestHandler):
def __init__(self):
TestHandler.__init__(self, Matcher())
| 19.7 | 49 | 0.771574 | from __future__ import absolute_import
from logutils.testing import TestHandler, Matcher
class MyTestHandler(TestHandler):
def __init__(self):
TestHandler.__init__(self, Matcher())
| true | true |
1c3fdd659991042710d33ea957b1e3751d39955f | 742 | py | Python | instagram/urls.py | enock24/Instagram-clone | 6f213b1f42ddd2d0c7b6694b09ace990182c6245 | [
"MIT"
] | null | null | null | instagram/urls.py | enock24/Instagram-clone | 6f213b1f42ddd2d0c7b6694b09ace990182c6245 | [
"MIT"
] | 3 | 2020-03-08T20:18:54.000Z | 2022-03-12T00:23:17.000Z | instagram/urls.py | enock24/Instagram-clone | 6f213b1f42ddd2d0c7b6694b09ace990182c6245 | [
"MIT"
] | null | null | null | from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
url(r'^$', views.index, name='index'),
url(r'^profile/$', views.profile,name='profile'),
url(r'^edit/$', views.edit_profile,name='edit_profile'),
url(r'^user/$',views.search_username,name='search_username'),
url(r'^image/$', views.upload_image,name='upload_image'),
url(r'^likes/(\d+)/$' , views.image_likes, name='likes'),
url(r'^new_comment/(\d+)/$' ,views.add_comment,name='Comments'),
url(r'^post/$', views.create_post,name='create_post'),
]
if settings.DEBUG:
urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
| 30.916667 | 81 | 0.67655 | from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
url(r'^$', views.index, name='index'),
url(r'^profile/$', views.profile,name='profile'),
url(r'^edit/$', views.edit_profile,name='edit_profile'),
url(r'^user/$',views.search_username,name='search_username'),
url(r'^image/$', views.upload_image,name='upload_image'),
url(r'^likes/(\d+)/$' , views.image_likes, name='likes'),
url(r'^new_comment/(\d+)/$' ,views.add_comment,name='Comments'),
url(r'^post/$', views.create_post,name='create_post'),
]
if settings.DEBUG:
urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
| true | true |
1c3fdd83082337c34febe14b2fa59434882d5ad3 | 38,457 | py | Python | python/taichi/lang/kernel_impl.py | Lyken17/taichi | 888a1792bd8566c31afc960c64b3c5fe838d444d | [
"MIT"
] | null | null | null | python/taichi/lang/kernel_impl.py | Lyken17/taichi | 888a1792bd8566c31afc960c64b3c5fe838d444d | [
"MIT"
] | null | null | null | python/taichi/lang/kernel_impl.py | Lyken17/taichi | 888a1792bd8566c31afc960c64b3c5fe838d444d | [
"MIT"
] | null | null | null | import ast
import functools
import inspect
import re
import sys
import textwrap
import traceback
import numpy as np
import taichi.lang
from taichi.core.util import ti_core as _ti_core
from taichi.lang import impl, util
from taichi.lang.ast.checkers import KernelSimplicityASTChecker
from taichi.lang.ast.transformer import ASTTransformerTotal
from taichi.lang.enums import Layout
from taichi.lang.exception import TaichiSyntaxError
from taichi.lang.shell import _shell_pop_print, oinspect
from taichi.lang.util import to_taichi_type
from taichi.linalg.sparse_matrix import sparse_matrix_builder
from taichi.misc.util import obsolete
from taichi.type import any_arr, primitive_types, template
import taichi as ti
if util.has_pytorch():
import torch
def func(fn):
"""Marks a function as callable in Taichi-scope.
This decorator transforms a Python function into a Taichi one. Taichi
will JIT compile it into native instructions.
Args:
fn (Callable): The Python function to be decorated
Returns:
Callable: The decorated function
Example::
>>> @ti.func
>>> def foo(x):
>>> return x + 2
>>>
>>> @ti.kernel
>>> def run():
>>> print(foo(40)) # 42
"""
is_classfunc = _inside_class(level_of_class_stackframe=3)
_taichi_skip_traceback = 1
fun = Func(fn, classfunc=is_classfunc)
@functools.wraps(fn)
def decorated(*args):
_taichi_skip_traceback = 1
return fun.__call__(*args)
decorated._is_taichi_function = True
return decorated
def pyfunc(fn):
"""Marks a function as callable in both Taichi and Python scopes.
When called inside the Taichi scope, Taichi will JIT compile it into
native instructions. Otherwise it will be invoked directly as a
Python function.
See also :func:`~taichi.lang.kernel_impl.func`.
Args:
fn (Callable): The Python function to be decorated
Returns:
Callable: The decorated function
"""
is_classfunc = _inside_class(level_of_class_stackframe=3)
fun = Func(fn, classfunc=is_classfunc, pyfunc=True)
@functools.wraps(fn)
def decorated(*args):
_taichi_skip_traceback = 1
return fun.__call__(*args)
decorated._is_taichi_function = True
return decorated
def _get_tree_and_global_vars(self, args):
src = textwrap.dedent(oinspect.getsource(self.func))
tree = ast.parse(src)
func_body = tree.body[0]
func_body.decorator_list = []
global_vars = _get_global_vars(self.func)
for i, arg in enumerate(func_body.args.args):
anno = arg.annotation
if isinstance(anno, ast.Name):
global_vars[anno.id] = self.argument_annotations[i]
if isinstance(func_body.returns, ast.Name):
global_vars[func_body.returns.id] = self.return_type
# inject template parameters into globals
for i in self.template_slot_locations:
template_var_name = self.argument_names[i]
global_vars[template_var_name] = args[i]
return tree, global_vars
class Func:
function_counter = 0
def __init__(self, func, classfunc=False, pyfunc=False):
self.func = func
self.func_id = Func.function_counter
Func.function_counter += 1
self.compiled = None
self.classfunc = classfunc
self.pyfunc = pyfunc
self.argument_annotations = []
self.argument_names = []
_taichi_skip_traceback = 1
self.return_type = None
self.extract_arguments()
self.template_slot_locations = []
for i, anno in enumerate(self.argument_annotations):
if isinstance(anno, template):
self.template_slot_locations.append(i)
self.mapper = TaichiCallableTemplateMapper(
self.argument_annotations, self.template_slot_locations)
self.taichi_functions = {} # The |Function| class in C++
def __call__(self, *args):
_taichi_skip_traceback = 1
if not impl.inside_kernel():
if not self.pyfunc:
raise TaichiSyntaxError(
"Taichi functions cannot be called from Python-scope."
" Use @ti.pyfunc if you wish to call Taichi functions "
"from both Python-scope and Taichi-scope.")
return self.func(*args)
if impl.get_runtime().experimental_ast_refactor:
if impl.get_runtime().experimental_real_function:
if impl.get_runtime().current_kernel.is_grad:
raise TaichiSyntaxError(
"Real function in gradient kernels unsupported.")
instance_id, _ = self.mapper.lookup(args)
key = _ti_core.FunctionKey(self.func.__name__, self.func_id,
instance_id)
if self.compiled is None:
self.compiled = {}
if key.instance_id not in self.compiled:
self.do_compile_ast_refactor(key=key, args=args)
return self.func_call_rvalue(key=key, args=args)
tree, global_vars = _get_tree_and_global_vars(self, args)
visitor = ASTTransformerTotal(is_kernel=False,
func=self,
globals=global_vars)
return visitor.visit(tree, *args)
if impl.get_runtime().experimental_real_function:
if impl.get_runtime().current_kernel.is_grad:
raise TaichiSyntaxError(
"Real function in gradient kernels unsupported.")
instance_id, _ = self.mapper.lookup(args)
key = _ti_core.FunctionKey(self.func.__name__, self.func_id,
instance_id)
if self.compiled is None:
self.compiled = {}
if key.instance_id not in self.compiled:
self.do_compile(key=key, args=args)
return self.func_call_rvalue(key=key, args=args)
if self.compiled is None:
self.do_compile(key=None, args=args)
ret = self.compiled(*args)
return ret
def func_call_rvalue(self, key, args):
# Skip the template args, e.g., |self|
assert impl.get_runtime().experimental_real_function
non_template_args = []
for i, anno in enumerate(self.argument_annotations):
if not isinstance(anno, template):
non_template_args.append(args[i])
non_template_args = impl.make_expr_group(non_template_args)
return ti.Expr(
_ti_core.make_func_call_expr(
self.taichi_functions[key.instance_id], non_template_args))
def do_compile(self, key, args):
src = textwrap.dedent(oinspect.getsource(self.func))
tree = ast.parse(src)
func_body = tree.body[0]
func_body.decorator_list = []
visitor = ASTTransformerTotal(is_kernel=False, func=self)
visitor.visit(tree)
ast.increment_lineno(tree, oinspect.getsourcelines(self.func)[1] - 1)
local_vars = {}
global_vars = _get_global_vars(self.func)
if impl.get_runtime().experimental_real_function:
# inject template parameters into globals
for i in self.template_slot_locations:
template_var_name = self.argument_names[i]
global_vars[template_var_name] = args[i]
exec(
compile(tree,
filename=oinspect.getsourcefile(self.func),
mode='exec'), global_vars, local_vars)
if impl.get_runtime().experimental_real_function:
self.compiled[key.instance_id] = local_vars[self.func.__name__]
self.taichi_functions[key.instance_id] = _ti_core.create_function(
key)
self.taichi_functions[key.instance_id].set_function_body(
self.compiled[key.instance_id])
else:
self.compiled = local_vars[self.func.__name__]
def do_compile_ast_refactor(self, key, args):
src = textwrap.dedent(oinspect.getsource(self.func))
tree = ast.parse(src)
func_body = tree.body[0]
func_body.decorator_list = []
ast.increment_lineno(tree, oinspect.getsourcelines(self.func)[1] - 1)
global_vars = _get_global_vars(self.func)
# inject template parameters into globals
for i in self.template_slot_locations:
template_var_name = self.argument_names[i]
global_vars[template_var_name] = args[i]
visitor = ASTTransformerTotal(is_kernel=False,
func=self,
globals=global_vars)
self.compiled[key.instance_id] = lambda: visitor.visit(tree)
self.taichi_functions[key.instance_id] = _ti_core.create_function(key)
self.taichi_functions[key.instance_id].set_function_body(
self.compiled[key.instance_id])
def extract_arguments(self):
sig = inspect.signature(self.func)
if sig.return_annotation not in (inspect._empty, None):
self.return_type = sig.return_annotation
params = sig.parameters
arg_names = params.keys()
for i, arg_name in enumerate(arg_names):
param = params[arg_name]
if param.kind == inspect.Parameter.VAR_KEYWORD:
raise KernelDefError(
'Taichi functions do not support variable keyword parameters (i.e., **kwargs)'
)
if param.kind == inspect.Parameter.VAR_POSITIONAL:
raise KernelDefError(
'Taichi functions do not support variable positional parameters (i.e., *args)'
)
if param.kind == inspect.Parameter.KEYWORD_ONLY:
raise KernelDefError(
'Taichi functions do not support keyword parameters')
if param.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD:
raise KernelDefError(
'Taichi functions only support "positional or keyword" parameters'
)
annotation = param.annotation
if annotation is inspect.Parameter.empty:
if i == 0 and self.classfunc:
annotation = template()
# TODO: pyfunc also need type annotation check when real function is enabled,
# but that has to happen at runtime when we know which scope it's called from.
elif not self.pyfunc and impl.get_runtime(
).experimental_real_function:
raise KernelDefError(
f'Taichi function `{self.func.__name__}` parameter `{arg_name}` must be type annotated'
)
else:
if not id(annotation
) in primitive_types.type_ids and not isinstance(
annotation, template):
raise KernelDefError(
f'Invalid type annotation (argument {i}) of Taichi function: {annotation}'
)
self.argument_annotations.append(annotation)
self.argument_names.append(param.name)
class TaichiCallableTemplateMapper:
def __init__(self, annotations, template_slot_locations):
self.annotations = annotations
self.num_args = len(annotations)
self.template_slot_locations = template_slot_locations
self.mapping = {}
@staticmethod
def extract_arg(arg, anno):
if isinstance(anno, template):
if isinstance(arg, taichi.lang.snode.SNode):
return arg.ptr
if isinstance(arg, taichi.lang.expr.Expr):
return arg.ptr.get_underlying_ptr_address()
if isinstance(arg, _ti_core.Expr):
return arg.get_underlying_ptr_address()
if isinstance(arg, tuple):
return tuple(
TaichiCallableTemplateMapper.extract_arg(item, anno)
for item in arg)
return arg
if isinstance(anno, any_arr):
if isinstance(arg, taichi.lang._ndarray.ScalarNdarray):
anno.check_element_dim(arg, 0)
return arg.dtype, len(arg.shape), (), Layout.AOS
if isinstance(arg, taichi.lang.matrix.VectorNdarray):
anno.check_element_dim(arg, 1)
anno.check_layout(arg)
return arg.dtype, len(arg.shape) + 1, (arg.n, ), arg.layout
if isinstance(arg, taichi.lang.matrix.MatrixNdarray):
anno.check_element_dim(arg, 2)
anno.check_layout(arg)
return arg.dtype, len(arg.shape) + 2, (arg.n,
arg.m), arg.layout
# external arrays
element_dim = 0 if anno.element_dim is None else anno.element_dim
layout = Layout.AOS if anno.layout is None else anno.layout
shape = tuple(arg.shape)
if len(shape) < element_dim:
raise ValueError(
f"Invalid argument into ti.any_arr() - required element_dim={element_dim}, but the argument has only {len(shape)} dimensions"
)
element_shape = (
) if element_dim == 0 else shape[:
element_dim] if layout == Layout.SOA else shape[
-element_dim:]
return to_taichi_type(arg.dtype), len(shape), element_shape, layout
return (type(arg).__name__, )
def extract(self, args):
extracted = []
for arg, anno in zip(args, self.annotations):
extracted.append(self.extract_arg(arg, anno))
return tuple(extracted)
def lookup(self, args):
if len(args) != self.num_args:
_taichi_skip_traceback = 1
raise TypeError(
f'{self.num_args} argument(s) needed but {len(args)} provided.'
)
key = self.extract(args)
if key not in self.mapping:
count = len(self.mapping)
self.mapping[key] = count
return self.mapping[key], key
class KernelDefError(Exception):
pass
class KernelArgError(Exception):
def __init__(self, pos, needed, provided):
message = f'Argument {pos} (type={provided}) cannot be converted into required type {needed}'
super().__init__(message)
self.pos = pos
self.needed = needed
self.provided = provided
def _get_global_vars(func):
closure_vars = inspect.getclosurevars(func)
if impl.get_runtime().experimental_ast_refactor:
return {
**closure_vars.globals,
**closure_vars.nonlocals,
**closure_vars.builtins
}
return {**closure_vars.globals, **closure_vars.nonlocals}
class Kernel:
counter = 0
def __init__(self, func, is_grad, classkernel=False):
self.func = func
self.kernel_counter = Kernel.counter
Kernel.counter += 1
self.is_grad = is_grad
self.grad = None
self.argument_annotations = []
self.argument_names = []
self.return_type = None
self.classkernel = classkernel
_taichi_skip_traceback = 1
self.extract_arguments()
del _taichi_skip_traceback
self.template_slot_locations = []
for i, anno in enumerate(self.argument_annotations):
if isinstance(anno, template):
self.template_slot_locations.append(i)
self.mapper = TaichiCallableTemplateMapper(
self.argument_annotations, self.template_slot_locations)
impl.get_runtime().kernels.append(self)
self.reset()
self.kernel_cpp = None
def reset(self):
self.runtime = impl.get_runtime()
if self.is_grad:
self.compiled_functions = self.runtime.compiled_grad_functions
else:
self.compiled_functions = self.runtime.compiled_functions
def extract_arguments(self):
sig = inspect.signature(self.func)
if sig.return_annotation not in (inspect._empty, None):
self.return_type = sig.return_annotation
params = sig.parameters
arg_names = params.keys()
for i, arg_name in enumerate(arg_names):
param = params[arg_name]
if param.kind == inspect.Parameter.VAR_KEYWORD:
raise KernelDefError(
'Taichi kernels do not support variable keyword parameters (i.e., **kwargs)'
)
if param.kind == inspect.Parameter.VAR_POSITIONAL:
raise KernelDefError(
'Taichi kernels do not support variable positional parameters (i.e., *args)'
)
if param.default is not inspect.Parameter.empty:
raise KernelDefError(
'Taichi kernels do not support default values for arguments'
)
if param.kind == inspect.Parameter.KEYWORD_ONLY:
raise KernelDefError(
'Taichi kernels do not support keyword parameters')
if param.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD:
raise KernelDefError(
'Taichi kernels only support "positional or keyword" parameters'
)
annotation = param.annotation
if param.annotation is inspect.Parameter.empty:
if i == 0 and self.classkernel: # The |self| parameter
annotation = template()
else:
_taichi_skip_traceback = 1
raise KernelDefError(
'Taichi kernels parameters must be type annotated')
else:
if isinstance(annotation, (template, any_arr)):
pass
elif id(annotation) in primitive_types.type_ids:
pass
elif isinstance(annotation, sparse_matrix_builder):
pass
else:
_taichi_skip_traceback = 1
raise KernelDefError(
f'Invalid type annotation (argument {i}) of Taichi kernel: {annotation}'
)
self.argument_annotations.append(annotation)
self.argument_names.append(param.name)
def materialize(self, key=None, args=None, arg_features=None):
if impl.get_runtime().experimental_ast_refactor:
return self.materialize_ast_refactor(key=key,
args=args,
arg_features=arg_features)
_taichi_skip_traceback = 1
if key is None:
key = (self.func, 0)
self.runtime.materialize()
if key in self.compiled_functions:
return None
grad_suffix = ""
if self.is_grad:
grad_suffix = "_grad"
kernel_name = f"{self.func.__name__}_c{ self.kernel_counter}_{key[1]}{grad_suffix}"
ti.trace(f"Compiling kernel {kernel_name}...")
src = textwrap.dedent(oinspect.getsource(self.func))
tree = ast.parse(src)
func_body = tree.body[0]
func_body.decorator_list = []
local_vars = {}
global_vars = _get_global_vars(self.func)
for i, arg in enumerate(func_body.args.args):
anno = arg.annotation
if isinstance(anno, ast.Name):
global_vars[anno.id] = self.argument_annotations[i]
if isinstance(func_body.returns, ast.Name):
global_vars[func_body.returns.id] = self.return_type
if self.is_grad:
KernelSimplicityASTChecker(self.func).visit(tree)
visitor = ASTTransformerTotal(
excluded_parameters=self.template_slot_locations,
func=self,
arg_features=arg_features)
visitor.visit(tree)
ast.increment_lineno(tree, oinspect.getsourcelines(self.func)[1] - 1)
# inject template parameters into globals
for i in self.template_slot_locations:
template_var_name = self.argument_names[i]
global_vars[template_var_name] = args[i]
exec(
compile(tree,
filename=oinspect.getsourcefile(self.func),
mode='exec'), global_vars, local_vars)
compiled = local_vars[self.func.__name__]
# Do not change the name of 'taichi_ast_generator'
# The warning system needs this identifier to remove unnecessary messages
def taichi_ast_generator():
_taichi_skip_traceback = 1
if self.runtime.inside_kernel:
raise TaichiSyntaxError(
"Kernels cannot call other kernels. I.e., nested kernels are not allowed. Please check if you have direct/indirect invocation of kernels within kernels. Note that some methods provided by the Taichi standard library may invoke kernels, and please move their invocations to Python-scope."
)
self.runtime.inside_kernel = True
self.runtime.current_kernel = self
try:
compiled()
finally:
self.runtime.inside_kernel = False
self.runtime.current_kernel = None
taichi_kernel = _ti_core.create_kernel(taichi_ast_generator,
kernel_name, self.is_grad)
self.kernel_cpp = taichi_kernel
assert key not in self.compiled_functions
self.compiled_functions[key] = self.get_function_body(taichi_kernel)
return None
def materialize_ast_refactor(self, key=None, args=None, arg_features=None):
_taichi_skip_traceback = 1
if key is None:
key = (self.func, 0)
self.runtime.materialize()
if key in self.compiled_functions:
return
grad_suffix = ""
if self.is_grad:
grad_suffix = "_grad"
kernel_name = f"{self.func.__name__}_c{self.kernel_counter}_{key[1]}{grad_suffix}"
ti.trace(f"Compiling kernel {kernel_name}...")
tree, global_vars = _get_tree_and_global_vars(self, args)
if self.is_grad:
KernelSimplicityASTChecker(self.func).visit(tree)
visitor = ASTTransformerTotal(
excluded_parameters=self.template_slot_locations,
func=self,
arg_features=arg_features,
globals=global_vars)
ast.increment_lineno(tree, oinspect.getsourcelines(self.func)[1] - 1)
# Do not change the name of 'taichi_ast_generator'
# The warning system needs this identifier to remove unnecessary messages
def taichi_ast_generator():
_taichi_skip_traceback = 1
if self.runtime.inside_kernel:
raise TaichiSyntaxError(
"Kernels cannot call other kernels. I.e., nested kernels are not allowed. Please check if you have direct/indirect invocation of kernels within kernels. Note that some methods provided by the Taichi standard library may invoke kernels, and please move their invocations to Python-scope."
)
self.runtime.inside_kernel = True
self.runtime.current_kernel = self
try:
visitor.visit(tree)
finally:
self.runtime.inside_kernel = False
self.runtime.current_kernel = None
taichi_kernel = _ti_core.create_kernel(taichi_ast_generator,
kernel_name, self.is_grad)
self.kernel_cpp = taichi_kernel
assert key not in self.compiled_functions
self.compiled_functions[key] = self.get_function_body(taichi_kernel)
def get_function_body(self, t_kernel):
# The actual function body
def func__(*args):
assert len(args) == len(
self.argument_annotations
), f'{len(self.argument_annotations)} arguments needed but {len(args)} provided'
tmps = []
callbacks = []
has_external_arrays = False
actual_argument_slot = 0
launch_ctx = t_kernel.make_launch_context()
for i, v in enumerate(args):
needed = self.argument_annotations[i]
if isinstance(needed, template):
continue
provided = type(v)
# Note: do not use sth like "needed == f32". That would be slow.
if id(needed) in primitive_types.real_type_ids:
if not isinstance(v, (float, int)):
raise KernelArgError(i, needed.to_string(), provided)
launch_ctx.set_arg_float(actual_argument_slot, float(v))
elif id(needed) in primitive_types.integer_type_ids:
if not isinstance(v, int):
raise KernelArgError(i, needed.to_string(), provided)
launch_ctx.set_arg_int(actual_argument_slot, int(v))
elif isinstance(needed, sparse_matrix_builder):
# Pass only the base pointer of the ti.linalg.sparse_matrix_builder() argument
launch_ctx.set_arg_int(actual_argument_slot, v.get_addr())
elif isinstance(needed, any_arr) and (
self.match_ext_arr(v)
or isinstance(v, taichi.lang._ndarray.Ndarray)):
is_ndarray = False
if isinstance(v, taichi.lang._ndarray.Ndarray):
v = v.arr
is_ndarray = True
has_external_arrays = True
ndarray_use_torch = self.runtime.prog.config.ndarray_use_torch
has_torch = util.has_pytorch()
is_numpy = isinstance(v, np.ndarray)
if is_numpy:
tmp = np.ascontiguousarray(v)
# Purpose: DO NOT GC |tmp|!
tmps.append(tmp)
launch_ctx.set_arg_external_array(
actual_argument_slot, int(tmp.ctypes.data),
tmp.nbytes)
elif is_ndarray and not ndarray_use_torch:
# Use ndarray's own memory allocator
tmp = v
launch_ctx.set_arg_external_array(
actual_argument_slot, int(tmp.data_ptr()),
tmp.element_size() * tmp.nelement())
else:
def get_call_back(u, v):
def call_back():
u.copy_(v)
return call_back
assert has_torch
assert isinstance(v, torch.Tensor)
tmp = v
taichi_arch = self.runtime.prog.config.arch
if str(v.device).startswith('cuda'):
# External tensor on cuda
if taichi_arch != _ti_core.Arch.cuda:
# copy data back to cpu
host_v = v.to(device='cpu', copy=True)
tmp = host_v
callbacks.append(get_call_back(v, host_v))
else:
# External tensor on cpu
if taichi_arch == _ti_core.Arch.cuda:
gpu_v = v.cuda()
tmp = gpu_v
callbacks.append(get_call_back(v, gpu_v))
launch_ctx.set_arg_external_array(
actual_argument_slot, int(tmp.data_ptr()),
tmp.element_size() * tmp.nelement())
shape = v.shape
max_num_indices = _ti_core.get_max_num_indices()
assert len(
shape
) <= max_num_indices, f"External array cannot have > {max_num_indices} indices"
for ii, s in enumerate(shape):
launch_ctx.set_extra_arg_int(actual_argument_slot, ii,
s)
else:
raise ValueError(
f'Argument type mismatch. Expecting {needed}, got {type(v)}.'
)
actual_argument_slot += 1
# Both the class kernels and the plain-function kernels are unified now.
# In both cases, |self.grad| is another Kernel instance that computes the
# gradient. For class kernels, args[0] is always the kernel owner.
if not self.is_grad and self.runtime.target_tape and not self.runtime.grad_replaced:
self.runtime.target_tape.insert(self, args)
t_kernel(launch_ctx)
ret = None
ret_dt = self.return_type
has_ret = ret_dt is not None
if has_external_arrays or has_ret:
ti.sync()
if has_ret:
if id(ret_dt) in primitive_types.integer_type_ids:
ret = t_kernel.get_ret_int(0)
else:
ret = t_kernel.get_ret_float(0)
if callbacks:
for c in callbacks:
c()
return ret
return func__
@staticmethod
def match_ext_arr(v):
has_array = isinstance(v, np.ndarray)
if not has_array and util.has_pytorch():
has_array = isinstance(v, torch.Tensor)
return has_array
def ensure_compiled(self, *args):
instance_id, arg_features = self.mapper.lookup(args)
key = (self.func, instance_id)
self.materialize(key=key, args=args, arg_features=arg_features)
return key
# For small kernels (< 3us), the performance can be pretty sensitive to overhead in __call__
# Thus this part needs to be fast. (i.e. < 3us on a 4 GHz x64 CPU)
@_shell_pop_print
def __call__(self, *args, **kwargs):
_taichi_skip_traceback = 1
assert len(kwargs) == 0, 'kwargs not supported for Taichi kernels'
key = self.ensure_compiled(*args)
return self.compiled_functions[key](*args)
# For a Taichi class definition like below:
#
# @ti.data_oriented
# class X:
# @ti.kernel
# def foo(self):
# ...
#
# When ti.kernel runs, the stackframe's |code_context| of Python 3.8(+) is
# different from that of Python 3.7 and below. In 3.8+, it is 'class X:',
# whereas in <=3.7, it is '@ti.data_oriented'. More interestingly, if the class
# inherits, i.e. class X(object):, then in both versions, |code_context| is
# 'class X(object):'...
_KERNEL_CLASS_STACKFRAME_STMT_RES = [
re.compile(r'@(\w+\.)?data_oriented'),
re.compile(r'class '),
]
def _inside_class(level_of_class_stackframe):
frames = oinspect.stack()
try:
maybe_class_frame = frames[level_of_class_stackframe]
statement_list = maybe_class_frame[4]
first_statment = statement_list[0].strip()
for pat in _KERNEL_CLASS_STACKFRAME_STMT_RES:
if pat.match(first_statment):
return True
except:
pass
return False
def _kernel_impl(func, level_of_class_stackframe, verbose=False):
# Can decorators determine if a function is being defined inside a class?
# https://stackoverflow.com/a/8793684/12003165
is_classkernel = _inside_class(level_of_class_stackframe + 1)
_taichi_skip_traceback = 1
if verbose:
print(f'kernel={func.__name__} is_classkernel={is_classkernel}')
primal = Kernel(func, is_grad=False, classkernel=is_classkernel)
adjoint = Kernel(func, is_grad=True, classkernel=is_classkernel)
# Having |primal| contains |grad| makes the tape work.
primal.grad = adjoint
if is_classkernel:
# For class kernels, their primal/adjoint callables are constructed
# when the kernel is accessed via the instance inside
# _BoundedDifferentiableMethod.
# This is because we need to bind the kernel or |grad| to the instance
# owning the kernel, which is not known until the kernel is accessed.
#
# See also: _BoundedDifferentiableMethod, data_oriented.
@functools.wraps(func)
def wrapped(*args, **kwargs):
_taichi_skip_traceback = 1
# If we reach here (we should never), it means the class is not decorated
# with @ti.data_oriented, otherwise getattr would have intercepted the call.
clsobj = type(args[0])
assert not hasattr(clsobj, '_data_oriented')
raise KernelDefError(
f'Please decorate class {clsobj.__name__} with @ti.data_oriented'
)
else:
@functools.wraps(func)
def wrapped(*args, **kwargs):
_taichi_skip_traceback = 1
try:
return primal(*args, **kwargs)
except RuntimeError as e:
if str(e).startswith("TypeError: "):
tb = e.__traceback__
while tb:
if tb.tb_frame.f_code.co_name == 'taichi_ast_generator':
tb = tb.tb_next
if sys.version_info < (3, 7):
# The traceback object is read-only on Python < 3.7,
# print the traceback and raise
traceback.print_tb(tb,
limit=1,
file=sys.stderr)
raise TypeError(str(e)[11:]) from None
# Otherwise, modify the traceback object
tb.tb_next = None
raise TypeError(
str(e)[11:]).with_traceback(tb) from None
tb = tb.tb_next
raise
wrapped.grad = adjoint
wrapped._is_wrapped_kernel = True
wrapped._is_classkernel = is_classkernel
wrapped._primal = primal
wrapped._adjoint = adjoint
return wrapped
def kernel(fn):
"""Marks a function as a Taichi kernel.
A Taichi kernel is a function written in Python, and gets JIT compiled by
Taichi into native CPU/GPU instructions (e.g. a series of CUDA kernels).
The top-level ``for`` loops are automatically parallelized, and distributed
to either a CPU thread pool or massively parallel GPUs.
Kernel's gradient kernel would be generated automatically by the AutoDiff system.
See also https://docs.taichi.graphics/lang/articles/basic/syntax#kernels.
Args:
fn (Callable): the Python function to be decorated
Returns:
Callable: The decorated function
Example::
>>> x = ti.field(ti.i32, shape=(4, 8))
>>>
>>> @ti.kernel
>>> def run():
>>> # Assigns all the elements of `x` in parallel.
>>> for i in x:
>>> x[i] = i
"""
_taichi_skip_traceback = 1
return _kernel_impl(fn, level_of_class_stackframe=3)
classfunc = obsolete('@ti.classfunc', '@ti.func directly')
classkernel = obsolete('@ti.classkernel', '@ti.kernel directly')
class _BoundedDifferentiableMethod:
def __init__(self, kernel_owner, wrapped_kernel_func):
clsobj = type(kernel_owner)
if not getattr(clsobj, '_data_oriented', False):
raise KernelDefError(
f'Please decorate class {clsobj.__name__} with @ti.data_oriented'
)
self._kernel_owner = kernel_owner
self._primal = wrapped_kernel_func._primal
self._adjoint = wrapped_kernel_func._adjoint
self._is_staticmethod = wrapped_kernel_func._is_staticmethod
self.__name__ = None
def __call__(self, *args, **kwargs):
_taichi_skip_traceback = 1
if self._is_staticmethod:
return self._primal(*args, **kwargs)
return self._primal(self._kernel_owner, *args, **kwargs)
def grad(self, *args, **kwargs):
_taichi_skip_traceback = 1
return self._adjoint(self._kernel_owner, *args, **kwargs)
def data_oriented(cls):
"""Marks a class as Taichi compatible.
To allow for modularized code, Taichi provides this decorator so that
Taichi kernels can be defined inside a class.
See also https://docs.taichi.graphics/lang/articles/advanced/odop
Example::
>>> @ti.data_oriented
>>> class TiArray:
>>> def __init__(self, n):
>>> self.x = ti.field(ti.f32, shape=n)
>>>
>>> @ti.kernel
>>> def inc(self):
>>> for i in self.x:
>>> self.x[i] += 1.0
>>>
>>> a = TiArray(32)
>>> a.inc()
Args:
cls (Class): the class to be decorated
Returns:
The decorated class.
"""
def _getattr(self, item):
_taichi_skip_traceback = 1
method = cls.__dict__.get(item, None)
is_property = method.__class__ == property
is_staticmethod = method.__class__ == staticmethod
if is_property:
x = method.fget
else:
x = super(cls, self).__getattribute__(item)
if hasattr(x, '_is_wrapped_kernel'):
if inspect.ismethod(x):
wrapped = x.__func__
else:
wrapped = x
wrapped._is_staticmethod = is_staticmethod
assert inspect.isfunction(wrapped)
if wrapped._is_classkernel:
ret = _BoundedDifferentiableMethod(self, wrapped)
ret.__name__ = wrapped.__name__
if is_property:
return ret()
return ret
if is_property:
return x(self)
return x
cls.__getattribute__ = _getattr
cls._data_oriented = True
return cls
| 39.28192 | 307 | 0.584575 | import ast
import functools
import inspect
import re
import sys
import textwrap
import traceback
import numpy as np
import taichi.lang
from taichi.core.util import ti_core as _ti_core
from taichi.lang import impl, util
from taichi.lang.ast.checkers import KernelSimplicityASTChecker
from taichi.lang.ast.transformer import ASTTransformerTotal
from taichi.lang.enums import Layout
from taichi.lang.exception import TaichiSyntaxError
from taichi.lang.shell import _shell_pop_print, oinspect
from taichi.lang.util import to_taichi_type
from taichi.linalg.sparse_matrix import sparse_matrix_builder
from taichi.misc.util import obsolete
from taichi.type import any_arr, primitive_types, template
import taichi as ti
if util.has_pytorch():
import torch
def func(fn):
is_classfunc = _inside_class(level_of_class_stackframe=3)
_taichi_skip_traceback = 1
fun = Func(fn, classfunc=is_classfunc)
@functools.wraps(fn)
def decorated(*args):
_taichi_skip_traceback = 1
return fun.__call__(*args)
decorated._is_taichi_function = True
return decorated
def pyfunc(fn):
is_classfunc = _inside_class(level_of_class_stackframe=3)
fun = Func(fn, classfunc=is_classfunc, pyfunc=True)
@functools.wraps(fn)
def decorated(*args):
_taichi_skip_traceback = 1
return fun.__call__(*args)
decorated._is_taichi_function = True
return decorated
def _get_tree_and_global_vars(self, args):
src = textwrap.dedent(oinspect.getsource(self.func))
tree = ast.parse(src)
func_body = tree.body[0]
func_body.decorator_list = []
global_vars = _get_global_vars(self.func)
for i, arg in enumerate(func_body.args.args):
anno = arg.annotation
if isinstance(anno, ast.Name):
global_vars[anno.id] = self.argument_annotations[i]
if isinstance(func_body.returns, ast.Name):
global_vars[func_body.returns.id] = self.return_type
for i in self.template_slot_locations:
template_var_name = self.argument_names[i]
global_vars[template_var_name] = args[i]
return tree, global_vars
class Func:
function_counter = 0
def __init__(self, func, classfunc=False, pyfunc=False):
self.func = func
self.func_id = Func.function_counter
Func.function_counter += 1
self.compiled = None
self.classfunc = classfunc
self.pyfunc = pyfunc
self.argument_annotations = []
self.argument_names = []
_taichi_skip_traceback = 1
self.return_type = None
self.extract_arguments()
self.template_slot_locations = []
for i, anno in enumerate(self.argument_annotations):
if isinstance(anno, template):
self.template_slot_locations.append(i)
self.mapper = TaichiCallableTemplateMapper(
self.argument_annotations, self.template_slot_locations)
self.taichi_functions = {}
def __call__(self, *args):
_taichi_skip_traceback = 1
if not impl.inside_kernel():
if not self.pyfunc:
raise TaichiSyntaxError(
"Taichi functions cannot be called from Python-scope."
" Use @ti.pyfunc if you wish to call Taichi functions "
"from both Python-scope and Taichi-scope.")
return self.func(*args)
if impl.get_runtime().experimental_ast_refactor:
if impl.get_runtime().experimental_real_function:
if impl.get_runtime().current_kernel.is_grad:
raise TaichiSyntaxError(
"Real function in gradient kernels unsupported.")
instance_id, _ = self.mapper.lookup(args)
key = _ti_core.FunctionKey(self.func.__name__, self.func_id,
instance_id)
if self.compiled is None:
self.compiled = {}
if key.instance_id not in self.compiled:
self.do_compile_ast_refactor(key=key, args=args)
return self.func_call_rvalue(key=key, args=args)
tree, global_vars = _get_tree_and_global_vars(self, args)
visitor = ASTTransformerTotal(is_kernel=False,
func=self,
globals=global_vars)
return visitor.visit(tree, *args)
if impl.get_runtime().experimental_real_function:
if impl.get_runtime().current_kernel.is_grad:
raise TaichiSyntaxError(
"Real function in gradient kernels unsupported.")
instance_id, _ = self.mapper.lookup(args)
key = _ti_core.FunctionKey(self.func.__name__, self.func_id,
instance_id)
if self.compiled is None:
self.compiled = {}
if key.instance_id not in self.compiled:
self.do_compile(key=key, args=args)
return self.func_call_rvalue(key=key, args=args)
if self.compiled is None:
self.do_compile(key=None, args=args)
ret = self.compiled(*args)
return ret
def func_call_rvalue(self, key, args):
assert impl.get_runtime().experimental_real_function
non_template_args = []
for i, anno in enumerate(self.argument_annotations):
if not isinstance(anno, template):
non_template_args.append(args[i])
non_template_args = impl.make_expr_group(non_template_args)
return ti.Expr(
_ti_core.make_func_call_expr(
self.taichi_functions[key.instance_id], non_template_args))
def do_compile(self, key, args):
src = textwrap.dedent(oinspect.getsource(self.func))
tree = ast.parse(src)
func_body = tree.body[0]
func_body.decorator_list = []
visitor = ASTTransformerTotal(is_kernel=False, func=self)
visitor.visit(tree)
ast.increment_lineno(tree, oinspect.getsourcelines(self.func)[1] - 1)
local_vars = {}
global_vars = _get_global_vars(self.func)
if impl.get_runtime().experimental_real_function:
for i in self.template_slot_locations:
template_var_name = self.argument_names[i]
global_vars[template_var_name] = args[i]
exec(
compile(tree,
filename=oinspect.getsourcefile(self.func),
mode='exec'), global_vars, local_vars)
if impl.get_runtime().experimental_real_function:
self.compiled[key.instance_id] = local_vars[self.func.__name__]
self.taichi_functions[key.instance_id] = _ti_core.create_function(
key)
self.taichi_functions[key.instance_id].set_function_body(
self.compiled[key.instance_id])
else:
self.compiled = local_vars[self.func.__name__]
def do_compile_ast_refactor(self, key, args):
src = textwrap.dedent(oinspect.getsource(self.func))
tree = ast.parse(src)
func_body = tree.body[0]
func_body.decorator_list = []
ast.increment_lineno(tree, oinspect.getsourcelines(self.func)[1] - 1)
global_vars = _get_global_vars(self.func)
for i in self.template_slot_locations:
template_var_name = self.argument_names[i]
global_vars[template_var_name] = args[i]
visitor = ASTTransformerTotal(is_kernel=False,
func=self,
globals=global_vars)
self.compiled[key.instance_id] = lambda: visitor.visit(tree)
self.taichi_functions[key.instance_id] = _ti_core.create_function(key)
self.taichi_functions[key.instance_id].set_function_body(
self.compiled[key.instance_id])
def extract_arguments(self):
sig = inspect.signature(self.func)
if sig.return_annotation not in (inspect._empty, None):
self.return_type = sig.return_annotation
params = sig.parameters
arg_names = params.keys()
for i, arg_name in enumerate(arg_names):
param = params[arg_name]
if param.kind == inspect.Parameter.VAR_KEYWORD:
raise KernelDefError(
'Taichi functions do not support variable keyword parameters (i.e., **kwargs)'
)
if param.kind == inspect.Parameter.VAR_POSITIONAL:
raise KernelDefError(
'Taichi functions do not support variable positional parameters (i.e., *args)'
)
if param.kind == inspect.Parameter.KEYWORD_ONLY:
raise KernelDefError(
'Taichi functions do not support keyword parameters')
if param.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD:
raise KernelDefError(
'Taichi functions only support "positional or keyword" parameters'
)
annotation = param.annotation
if annotation is inspect.Parameter.empty:
if i == 0 and self.classfunc:
annotation = template()
elif not self.pyfunc and impl.get_runtime(
).experimental_real_function:
raise KernelDefError(
f'Taichi function `{self.func.__name__}` parameter `{arg_name}` must be type annotated'
)
else:
if not id(annotation
) in primitive_types.type_ids and not isinstance(
annotation, template):
raise KernelDefError(
f'Invalid type annotation (argument {i}) of Taichi function: {annotation}'
)
self.argument_annotations.append(annotation)
self.argument_names.append(param.name)
class TaichiCallableTemplateMapper:
def __init__(self, annotations, template_slot_locations):
self.annotations = annotations
self.num_args = len(annotations)
self.template_slot_locations = template_slot_locations
self.mapping = {}
@staticmethod
def extract_arg(arg, anno):
if isinstance(anno, template):
if isinstance(arg, taichi.lang.snode.SNode):
return arg.ptr
if isinstance(arg, taichi.lang.expr.Expr):
return arg.ptr.get_underlying_ptr_address()
if isinstance(arg, _ti_core.Expr):
return arg.get_underlying_ptr_address()
if isinstance(arg, tuple):
return tuple(
TaichiCallableTemplateMapper.extract_arg(item, anno)
for item in arg)
return arg
if isinstance(anno, any_arr):
if isinstance(arg, taichi.lang._ndarray.ScalarNdarray):
anno.check_element_dim(arg, 0)
return arg.dtype, len(arg.shape), (), Layout.AOS
if isinstance(arg, taichi.lang.matrix.VectorNdarray):
anno.check_element_dim(arg, 1)
anno.check_layout(arg)
return arg.dtype, len(arg.shape) + 1, (arg.n, ), arg.layout
if isinstance(arg, taichi.lang.matrix.MatrixNdarray):
anno.check_element_dim(arg, 2)
anno.check_layout(arg)
return arg.dtype, len(arg.shape) + 2, (arg.n,
arg.m), arg.layout
# external arrays
element_dim = 0 if anno.element_dim is None else anno.element_dim
layout = Layout.AOS if anno.layout is None else anno.layout
shape = tuple(arg.shape)
if len(shape) < element_dim:
raise ValueError(
f"Invalid argument into ti.any_arr() - required element_dim={element_dim}, but the argument has only {len(shape)} dimensions"
)
element_shape = (
) if element_dim == 0 else shape[:
element_dim] if layout == Layout.SOA else shape[
-element_dim:]
return to_taichi_type(arg.dtype), len(shape), element_shape, layout
return (type(arg).__name__, )
def extract(self, args):
extracted = []
for arg, anno in zip(args, self.annotations):
extracted.append(self.extract_arg(arg, anno))
return tuple(extracted)
def lookup(self, args):
if len(args) != self.num_args:
_taichi_skip_traceback = 1
raise TypeError(
f'{self.num_args} argument(s) needed but {len(args)} provided.'
)
key = self.extract(args)
if key not in self.mapping:
count = len(self.mapping)
self.mapping[key] = count
return self.mapping[key], key
class KernelDefError(Exception):
pass
class KernelArgError(Exception):
def __init__(self, pos, needed, provided):
message = f'Argument {pos} (type={provided}) cannot be converted into required type {needed}'
super().__init__(message)
self.pos = pos
self.needed = needed
self.provided = provided
def _get_global_vars(func):
closure_vars = inspect.getclosurevars(func)
if impl.get_runtime().experimental_ast_refactor:
return {
**closure_vars.globals,
**closure_vars.nonlocals,
**closure_vars.builtins
}
return {**closure_vars.globals, **closure_vars.nonlocals}
class Kernel:
counter = 0
def __init__(self, func, is_grad, classkernel=False):
self.func = func
self.kernel_counter = Kernel.counter
Kernel.counter += 1
self.is_grad = is_grad
self.grad = None
self.argument_annotations = []
self.argument_names = []
self.return_type = None
self.classkernel = classkernel
_taichi_skip_traceback = 1
self.extract_arguments()
del _taichi_skip_traceback
self.template_slot_locations = []
for i, anno in enumerate(self.argument_annotations):
if isinstance(anno, template):
self.template_slot_locations.append(i)
self.mapper = TaichiCallableTemplateMapper(
self.argument_annotations, self.template_slot_locations)
impl.get_runtime().kernels.append(self)
self.reset()
self.kernel_cpp = None
def reset(self):
self.runtime = impl.get_runtime()
if self.is_grad:
self.compiled_functions = self.runtime.compiled_grad_functions
else:
self.compiled_functions = self.runtime.compiled_functions
def extract_arguments(self):
sig = inspect.signature(self.func)
if sig.return_annotation not in (inspect._empty, None):
self.return_type = sig.return_annotation
params = sig.parameters
arg_names = params.keys()
for i, arg_name in enumerate(arg_names):
param = params[arg_name]
if param.kind == inspect.Parameter.VAR_KEYWORD:
raise KernelDefError(
'Taichi kernels do not support variable keyword parameters (i.e., **kwargs)'
)
if param.kind == inspect.Parameter.VAR_POSITIONAL:
raise KernelDefError(
'Taichi kernels do not support variable positional parameters (i.e., *args)'
)
if param.default is not inspect.Parameter.empty:
raise KernelDefError(
'Taichi kernels do not support default values for arguments'
)
if param.kind == inspect.Parameter.KEYWORD_ONLY:
raise KernelDefError(
'Taichi kernels do not support keyword parameters')
if param.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD:
raise KernelDefError(
'Taichi kernels only support "positional or keyword" parameters'
)
annotation = param.annotation
if param.annotation is inspect.Parameter.empty:
if i == 0 and self.classkernel: # The |self| parameter
annotation = template()
else:
_taichi_skip_traceback = 1
raise KernelDefError(
'Taichi kernels parameters must be type annotated')
else:
if isinstance(annotation, (template, any_arr)):
pass
elif id(annotation) in primitive_types.type_ids:
pass
elif isinstance(annotation, sparse_matrix_builder):
pass
else:
_taichi_skip_traceback = 1
raise KernelDefError(
f'Invalid type annotation (argument {i}) of Taichi kernel: {annotation}'
)
self.argument_annotations.append(annotation)
self.argument_names.append(param.name)
def materialize(self, key=None, args=None, arg_features=None):
if impl.get_runtime().experimental_ast_refactor:
return self.materialize_ast_refactor(key=key,
args=args,
arg_features=arg_features)
_taichi_skip_traceback = 1
if key is None:
key = (self.func, 0)
self.runtime.materialize()
if key in self.compiled_functions:
return None
grad_suffix = ""
if self.is_grad:
grad_suffix = "_grad"
kernel_name = f"{self.func.__name__}_c{ self.kernel_counter}_{key[1]}{grad_suffix}"
ti.trace(f"Compiling kernel {kernel_name}...")
src = textwrap.dedent(oinspect.getsource(self.func))
tree = ast.parse(src)
func_body = tree.body[0]
func_body.decorator_list = []
local_vars = {}
global_vars = _get_global_vars(self.func)
for i, arg in enumerate(func_body.args.args):
anno = arg.annotation
if isinstance(anno, ast.Name):
global_vars[anno.id] = self.argument_annotations[i]
if isinstance(func_body.returns, ast.Name):
global_vars[func_body.returns.id] = self.return_type
if self.is_grad:
KernelSimplicityASTChecker(self.func).visit(tree)
visitor = ASTTransformerTotal(
excluded_parameters=self.template_slot_locations,
func=self,
arg_features=arg_features)
visitor.visit(tree)
ast.increment_lineno(tree, oinspect.getsourcelines(self.func)[1] - 1)
# inject template parameters into globals
for i in self.template_slot_locations:
template_var_name = self.argument_names[i]
global_vars[template_var_name] = args[i]
exec(
compile(tree,
filename=oinspect.getsourcefile(self.func),
mode='exec'), global_vars, local_vars)
compiled = local_vars[self.func.__name__]
# Do not change the name of 'taichi_ast_generator'
# The warning system needs this identifier to remove unnecessary messages
def taichi_ast_generator():
_taichi_skip_traceback = 1
if self.runtime.inside_kernel:
raise TaichiSyntaxError(
"Kernels cannot call other kernels. I.e., nested kernels are not allowed. Please check if you have direct/indirect invocation of kernels within kernels. Note that some methods provided by the Taichi standard library may invoke kernels, and please move their invocations to Python-scope."
)
self.runtime.inside_kernel = True
self.runtime.current_kernel = self
try:
compiled()
finally:
self.runtime.inside_kernel = False
self.runtime.current_kernel = None
taichi_kernel = _ti_core.create_kernel(taichi_ast_generator,
kernel_name, self.is_grad)
self.kernel_cpp = taichi_kernel
assert key not in self.compiled_functions
self.compiled_functions[key] = self.get_function_body(taichi_kernel)
return None
def materialize_ast_refactor(self, key=None, args=None, arg_features=None):
_taichi_skip_traceback = 1
if key is None:
key = (self.func, 0)
self.runtime.materialize()
if key in self.compiled_functions:
return
grad_suffix = ""
if self.is_grad:
grad_suffix = "_grad"
kernel_name = f"{self.func.__name__}_c{self.kernel_counter}_{key[1]}{grad_suffix}"
ti.trace(f"Compiling kernel {kernel_name}...")
tree, global_vars = _get_tree_and_global_vars(self, args)
if self.is_grad:
KernelSimplicityASTChecker(self.func).visit(tree)
visitor = ASTTransformerTotal(
excluded_parameters=self.template_slot_locations,
func=self,
arg_features=arg_features,
globals=global_vars)
ast.increment_lineno(tree, oinspect.getsourcelines(self.func)[1] - 1)
# Do not change the name of 'taichi_ast_generator'
# The warning system needs this identifier to remove unnecessary messages
def taichi_ast_generator():
_taichi_skip_traceback = 1
if self.runtime.inside_kernel:
raise TaichiSyntaxError(
"Kernels cannot call other kernels. I.e., nested kernels are not allowed. Please check if you have direct/indirect invocation of kernels within kernels. Note that some methods provided by the Taichi standard library may invoke kernels, and please move their invocations to Python-scope."
)
self.runtime.inside_kernel = True
self.runtime.current_kernel = self
try:
visitor.visit(tree)
finally:
self.runtime.inside_kernel = False
self.runtime.current_kernel = None
taichi_kernel = _ti_core.create_kernel(taichi_ast_generator,
kernel_name, self.is_grad)
self.kernel_cpp = taichi_kernel
assert key not in self.compiled_functions
self.compiled_functions[key] = self.get_function_body(taichi_kernel)
def get_function_body(self, t_kernel):
# The actual function body
def func__(*args):
assert len(args) == len(
self.argument_annotations
), f'{len(self.argument_annotations)} arguments needed but {len(args)} provided'
tmps = []
callbacks = []
has_external_arrays = False
actual_argument_slot = 0
launch_ctx = t_kernel.make_launch_context()
for i, v in enumerate(args):
needed = self.argument_annotations[i]
if isinstance(needed, template):
continue
provided = type(v)
# Note: do not use sth like "needed == f32". That would be slow.
if id(needed) in primitive_types.real_type_ids:
if not isinstance(v, (float, int)):
raise KernelArgError(i, needed.to_string(), provided)
launch_ctx.set_arg_float(actual_argument_slot, float(v))
elif id(needed) in primitive_types.integer_type_ids:
if not isinstance(v, int):
raise KernelArgError(i, needed.to_string(), provided)
launch_ctx.set_arg_int(actual_argument_slot, int(v))
elif isinstance(needed, sparse_matrix_builder):
# Pass only the base pointer of the ti.linalg.sparse_matrix_builder() argument
launch_ctx.set_arg_int(actual_argument_slot, v.get_addr())
elif isinstance(needed, any_arr) and (
self.match_ext_arr(v)
or isinstance(v, taichi.lang._ndarray.Ndarray)):
is_ndarray = False
if isinstance(v, taichi.lang._ndarray.Ndarray):
v = v.arr
is_ndarray = True
has_external_arrays = True
ndarray_use_torch = self.runtime.prog.config.ndarray_use_torch
has_torch = util.has_pytorch()
is_numpy = isinstance(v, np.ndarray)
if is_numpy:
tmp = np.ascontiguousarray(v)
# Purpose: DO NOT GC |tmp|!
tmps.append(tmp)
launch_ctx.set_arg_external_array(
actual_argument_slot, int(tmp.ctypes.data),
tmp.nbytes)
elif is_ndarray and not ndarray_use_torch:
# Use ndarray's own memory allocator
tmp = v
launch_ctx.set_arg_external_array(
actual_argument_slot, int(tmp.data_ptr()),
tmp.element_size() * tmp.nelement())
else:
def get_call_back(u, v):
def call_back():
u.copy_(v)
return call_back
assert has_torch
assert isinstance(v, torch.Tensor)
tmp = v
taichi_arch = self.runtime.prog.config.arch
if str(v.device).startswith('cuda'):
if taichi_arch != _ti_core.Arch.cuda:
host_v = v.to(device='cpu', copy=True)
tmp = host_v
callbacks.append(get_call_back(v, host_v))
else:
if taichi_arch == _ti_core.Arch.cuda:
gpu_v = v.cuda()
tmp = gpu_v
callbacks.append(get_call_back(v, gpu_v))
launch_ctx.set_arg_external_array(
actual_argument_slot, int(tmp.data_ptr()),
tmp.element_size() * tmp.nelement())
shape = v.shape
max_num_indices = _ti_core.get_max_num_indices()
assert len(
shape
) <= max_num_indices, f"External array cannot have > {max_num_indices} indices"
for ii, s in enumerate(shape):
launch_ctx.set_extra_arg_int(actual_argument_slot, ii,
s)
else:
raise ValueError(
f'Argument type mismatch. Expecting {needed}, got {type(v)}.'
)
actual_argument_slot += 1
if not self.is_grad and self.runtime.target_tape and not self.runtime.grad_replaced:
self.runtime.target_tape.insert(self, args)
t_kernel(launch_ctx)
ret = None
ret_dt = self.return_type
has_ret = ret_dt is not None
if has_external_arrays or has_ret:
ti.sync()
if has_ret:
if id(ret_dt) in primitive_types.integer_type_ids:
ret = t_kernel.get_ret_int(0)
else:
ret = t_kernel.get_ret_float(0)
if callbacks:
for c in callbacks:
c()
return ret
return func__
@staticmethod
def match_ext_arr(v):
has_array = isinstance(v, np.ndarray)
if not has_array and util.has_pytorch():
has_array = isinstance(v, torch.Tensor)
return has_array
def ensure_compiled(self, *args):
instance_id, arg_features = self.mapper.lookup(args)
key = (self.func, instance_id)
self.materialize(key=key, args=args, arg_features=arg_features)
return key
@_shell_pop_print
def __call__(self, *args, **kwargs):
_taichi_skip_traceback = 1
assert len(kwargs) == 0, 'kwargs not supported for Taichi kernels'
key = self.ensure_compiled(*args)
return self.compiled_functions[key](*args)
# different from that of Python 3.7 and below. In 3.8+, it is 'class X:',
# whereas in <=3.7, it is '@ti.data_oriented'. More interestingly, if the class
# inherits, i.e. class X(object):, then in both versions, |code_context| is
# 'class X(object):'...
_KERNEL_CLASS_STACKFRAME_STMT_RES = [
re.compile(r'@(\w+\.)?data_oriented'),
re.compile(r'class '),
]
def _inside_class(level_of_class_stackframe):
frames = oinspect.stack()
try:
maybe_class_frame = frames[level_of_class_stackframe]
statement_list = maybe_class_frame[4]
first_statment = statement_list[0].strip()
for pat in _KERNEL_CLASS_STACKFRAME_STMT_RES:
if pat.match(first_statment):
return True
except:
pass
return False
def _kernel_impl(func, level_of_class_stackframe, verbose=False):
# Can decorators determine if a function is being defined inside a class?
# https://stackoverflow.com/a/8793684/12003165
is_classkernel = _inside_class(level_of_class_stackframe + 1)
_taichi_skip_traceback = 1
if verbose:
print(f'kernel={func.__name__} is_classkernel={is_classkernel}')
primal = Kernel(func, is_grad=False, classkernel=is_classkernel)
adjoint = Kernel(func, is_grad=True, classkernel=is_classkernel)
# Having |primal| contains |grad| makes the tape work.
primal.grad = adjoint
if is_classkernel:
# For class kernels, their primal/adjoint callables are constructed
# when the kernel is accessed via the instance inside
# _BoundedDifferentiableMethod.
# This is because we need to bind the kernel or |grad| to the instance
# owning the kernel, which is not known until the kernel is accessed.
#
# See also: _BoundedDifferentiableMethod, data_oriented.
@functools.wraps(func)
def wrapped(*args, **kwargs):
_taichi_skip_traceback = 1
# If we reach here (we should never), it means the class is not decorated
# with @ti.data_oriented, otherwise getattr would have intercepted the call.
clsobj = type(args[0])
assert not hasattr(clsobj, '_data_oriented')
raise KernelDefError(
f'Please decorate class {clsobj.__name__} with @ti.data_oriented'
)
else:
@functools.wraps(func)
def wrapped(*args, **kwargs):
_taichi_skip_traceback = 1
try:
return primal(*args, **kwargs)
except RuntimeError as e:
if str(e).startswith("TypeError: "):
tb = e.__traceback__
while tb:
if tb.tb_frame.f_code.co_name == 'taichi_ast_generator':
tb = tb.tb_next
if sys.version_info < (3, 7):
# The traceback object is read-only on Python < 3.7,
# print the traceback and raise
traceback.print_tb(tb,
limit=1,
file=sys.stderr)
raise TypeError(str(e)[11:]) from None
# Otherwise, modify the traceback object
tb.tb_next = None
raise TypeError(
str(e)[11:]).with_traceback(tb) from None
tb = tb.tb_next
raise
wrapped.grad = adjoint
wrapped._is_wrapped_kernel = True
wrapped._is_classkernel = is_classkernel
wrapped._primal = primal
wrapped._adjoint = adjoint
return wrapped
def kernel(fn):
_taichi_skip_traceback = 1
return _kernel_impl(fn, level_of_class_stackframe=3)
classfunc = obsolete('@ti.classfunc', '@ti.func directly')
classkernel = obsolete('@ti.classkernel', '@ti.kernel directly')
class _BoundedDifferentiableMethod:
def __init__(self, kernel_owner, wrapped_kernel_func):
clsobj = type(kernel_owner)
if not getattr(clsobj, '_data_oriented', False):
raise KernelDefError(
f'Please decorate class {clsobj.__name__} with @ti.data_oriented'
)
self._kernel_owner = kernel_owner
self._primal = wrapped_kernel_func._primal
self._adjoint = wrapped_kernel_func._adjoint
self._is_staticmethod = wrapped_kernel_func._is_staticmethod
self.__name__ = None
def __call__(self, *args, **kwargs):
_taichi_skip_traceback = 1
if self._is_staticmethod:
return self._primal(*args, **kwargs)
return self._primal(self._kernel_owner, *args, **kwargs)
def grad(self, *args, **kwargs):
_taichi_skip_traceback = 1
return self._adjoint(self._kernel_owner, *args, **kwargs)
def data_oriented(cls):
def _getattr(self, item):
_taichi_skip_traceback = 1
method = cls.__dict__.get(item, None)
is_property = method.__class__ == property
is_staticmethod = method.__class__ == staticmethod
if is_property:
x = method.fget
else:
x = super(cls, self).__getattribute__(item)
if hasattr(x, '_is_wrapped_kernel'):
if inspect.ismethod(x):
wrapped = x.__func__
else:
wrapped = x
wrapped._is_staticmethod = is_staticmethod
assert inspect.isfunction(wrapped)
if wrapped._is_classkernel:
ret = _BoundedDifferentiableMethod(self, wrapped)
ret.__name__ = wrapped.__name__
if is_property:
return ret()
return ret
if is_property:
return x(self)
return x
cls.__getattribute__ = _getattr
cls._data_oriented = True
return cls
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.