Add 300 CheckerBench tasks, dataset card, and restoration tools (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/pre_context.mdAdded+24
- tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task.jsonAdded+44
- tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task_prompt.mdAdded+82
- tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/patch.diffAdded+168
- tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/post_context.mdAdded+1823
- tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/pre_context.mdAdded+1755
- tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task.jsonAdded+71
- tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task_prompt.mdAdded+82
- tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/patch.diffAdded+60
- tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/post_context.mdAdded+64
- tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/pre_context.mdAdded+59
- tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task.jsonAdded+46
- tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task_prompt.mdAdded+82
- tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/patch.diffAdded+33
- tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/post_context.mdAdded+17
- tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/pre_context.mdAdded+23
- tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task.jsonAdded+47
- tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task_prompt.mdAdded+82
- tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/patch.diffAdded+39
- tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/post_context.mdAdded+244
- tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/pre_context.mdAdded+244
- tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task.jsonAdded+49
- tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task_prompt.mdAdded+82
- tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/patch.diffAdded+39
- tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/post_context.mdAdded+40
- tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/pre_context.mdAdded+40
- tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task.jsonAdded+46
- tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task_prompt.mdAdded+82
- tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/patch.diffAdded+32
- tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/post_context.mdAdded+130
- tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/pre_context.mdAdded+128
- tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task.jsonAdded+50
- tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task_prompt.mdAdded+82
- tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/patch.diffAdded+53
- tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/post_context.mdAdded+314
- tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/pre_context.mdAdded+280
- tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task.jsonAdded+51
- tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task_prompt.mdAdded+82
- tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/patch.diffAdded+912
- tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/post_context.mdAdded+140
- tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/pre_context.mdAdded+145
- tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task.jsonAdded+57
- tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task_prompt.mdAdded+82
- tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/patch.diffAdded+80
- tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/post_context.mdAdded+1683
- tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/pre_context.mdAdded+1668
- tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task.jsonAdded+59
- tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task_prompt.mdAdded+82
- tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/patch.diffAdded+184
- tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/post_context.mdAdded+169
123456789101112131415161718192021222324# Patch-overlapping Python context before the fix
## `mlflow/utils/file_utils.py` — `function:make_tarfile` (lines 284-301)
```pythondef make_tarfile(output_filename, source_dir, archive_name, custom_filter=None): # Helper for filtering out modification timestamps def _filter_timestamps(tar_info): tar_info.mtime = 0 return tar_info if custom_filter is None else custom_filter(tar_info)
unzipped_filename = tempfile.mktemp() try: with tarfile.open(unzipped_filename, "w") as tar: tar.add(source_dir, arcname=archive_name, filter=_filter_timestamps) # When gzipping the tar, don't include the tar's filename or modification time in the # zipped archive (see https://docs.python.org/3/library/gzip.html#gzip.GzipFile) with gzip.GzipFile( filename="", fileobj=open(output_filename, "wb"), mode="wb", mtime=0 ) as gzipped_tar, open(unzipped_filename, "rb") as tar: gzipped_tar.write(tar.read()) finally: os.remove(unzipped_filename)```1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "schema_version": "synthesis-task-v1", "task": { "pair_id": "pyvul-1a630dd8f83b2e29740d", "dataset_id": "PyVul", "dataset_item_id": "pyvul-1a630dd8f83b2e29740d", "project_id": "pyvul__mlflow__mlflow", "language": "python", "backend": "codeql" }, "changed_python_files": [ "mlflow/utils/file_utils.py" ], "patch_units": { "before": [ "function:make_tarfile" ], "after": [ "function:make_tarfile" ] }, "runtime_assets": { "before": { "database": "assets/19fa596228b1fb4b86e469be665edd7d7dbeb9b0b3686da07895004356b280c4/database", "cache_key": "19fa596228b1fb4b86e469be665edd7d7dbeb9b0b3686da07895004356b280c4", "codeql_version": "2.26.4" }, "after": { "database": "assets/6542ed4eb6001d9e9ca948df5dfeebb2e57bc60e826ac0604d9041b761dd7fcf/database", "cache_key": "6542ed4eb6001d9e9ca948df5dfeebb2e57bc60e826ac0604d9041b761dd7fcf", "codeql_version": "2.26.4" }, "refine": { "database": "assets/f5ac0d40fec4af9c5fe47b810e939639e7cc56bf5fc589efd3262e3aab0aae88/database", "cache_key": "f5ac0d40fec4af9c5fe47b810e939639e7cc56bf5fc589efd3262e3aab0aae88", "codeql_version": "2.26.4" } }, "benchmark_contract": { "agent_visible": true, "reference_query_location": "references/pyvul-1a630dd8f83b2e29740d/query/ (do not mount into agent)", "evaluator_location": "evaluator/pyvul-1a630dd8f83b2e29740d/ (do not mount into agent)" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Python CodeQL detector synthesis
You are cc operating in `/work`. Starting only from the supplied patch,before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQLdetector for the vulnerability fixed by the patch. This is one fresh session. You may iterate insidethis session, but no later framework repair or resume will occur.
## Inputs and owned outputs
- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.- Read `references/codeql/convergence_protocol.md` and `references/codeql/api_navigation.md` before experimenting. Read the remaining `references/codeql/` files for the selected mechanism.- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is uncertain. Do not guess predicate names or build a large family of inspection queries.- Complete the design contract in `state.json` and `scope_statement.md` before final validation.- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the fixed offline dependency in `query/qlpack.yml`.- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This task-unique metadata must never be used in a query predicate.- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
## Required reasoning contract
Before coding, record this mapping in `state.json`:
```textvulnerable operation / trigger / patch safety condition → CodeQL-observable evidence → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism → source, sink/report site, guard/barrier and query predicates```
Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches requirereal path/control-flow semantics; provenance-sensitive patches require value flow. Do not replaceeither with source-text matching or with the mere presence of patch-added syntax.
## Mandatory convergence contract
The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query isa failure; an early compilable semantic candidate can be improved. Follow the checkpoints in`references/codeql/convergence_protocol.md`:
1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` immediately. Do not wait until every CodeQL API detail is known.2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled definition with `scripts/search_codeql_api.sh` or simplify the mechanism.3. Obtain a compiling minimal main query before broadening it. Compile the main query after every meaningful mechanism change.4. Move in order from compile → relevant before finding → after elimination → final contract. Do not continue API exploration after the intended before/after differential is established.5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all exploration, preserve the best compiling query, finish the contract files, and exit.
## Semantic and generalization rules
- Report at the vulnerable call, operator, access, or sink.- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary matching condition. Stable library/framework APIs or public project APIs are allowed only when `scope_statement.md` explains why they define the intended vulnerability family.- The safety condition introduced by the patch must be represented by the query.- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it changed in the patch.
## Final validation protocol
1. Compile the final query.2. Run it on before and inspect `raw/before.sarif` for the intended report location.3. Run the identical query on after and inspect `raw/after.sarif`.4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, and absence of patch-local hardcoding.5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
Do not modify the runtime databases, references, patch, context, or validation scripts except fornormal CodeQL-generated database caches produced by the provided run scripts.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168diff --git a/DESCRIPTION.md b/DESCRIPTION.mdindex 5e6684a2..0f626e3a 100644--- a/DESCRIPTION.md+++ b/DESCRIPTION.md@@ -11,6 +11,7 @@ Source code is also available at: https://github.com/snowflakedb/snowflake-conne - v2.8.2(November 18,2022) - Improved performance of OCSP response caching+ - Improved performance of regexes used for PUT/GET SQL statement detection - v2.8.1(October 30,2022) diff --git a/src/snowflake/connector/_sql_util.py b/src/snowflake/connector/_sql_util.pynew file mode 100644index 00000000..51a9d090--- /dev/null+++ b/src/snowflake/connector/_sql_util.py@@ -0,0 +1,52 @@+#+# Copyright (c) 2012-2021 Snowflake Computing Inc. All rights reserved.+#++from __future__ import annotations++import re++from .constants import FileTransferType++COMMENT_START_SQL_RE = re.compile(+ r"""+ ^\s*(?:+ /\*[\w\W]*?\*/+ )""",+ re.VERBOSE,+)++PUT_SQL_RE = re.compile(r"^\s*put", flags=re.IGNORECASE)+GET_SQL_RE = re.compile(r"^\s*get", flags=re.IGNORECASE)+++def remove_starting_comments(sql: str) -> str:+ """Remove all comments from the start of a SQL statement."""+ commentless_sql = sql+ while True:+ start_comment = COMMENT_START_SQL_RE.match(commentless_sql)+ if start_comment is None:+ break+ commentless_sql = commentless_sql[start_comment.end() :]+ return commentless_sql+++def get_file_transfer_type(sql: str) -> FileTransferType | None:+ """Decide whether a SQL is a file transfer and return its type.++ None is returned if the SQL isn't a file transfer so that this function can be+ used in an if-statement.+ """+ commentless_sql = remove_starting_comments(sql)+ if PUT_SQL_RE.match(commentless_sql):+ return FileTransferType.PUT+ elif GET_SQL_RE.match(commentless_sql):+ return FileTransferType.GET+++def is_put_statement(sql: str) -> bool:+ return get_file_transfer_type(sql) == FileTransferType.PUT+++def is_get_statement(sql: str) -> bool:+ return get_file_transfer_type(sql) == FileTransferType.GETdiff --git a/src/snowflake/connector/cursor.py b/src/snowflake/connector/cursor.pyindex 2a8089b0..a367a987 100644--- a/src/snowflake/connector/cursor.py+++ b/src/snowflake/connector/cursor.py@@ -32,6 +32,7 @@ from snowflake.connector.result_batch import create_batches_from_response from snowflake.connector.result_set import ResultSet from . import compat+from ._sql_util import get_file_transfer_type from .bind_upload_agent import BindUploadAgent, BindUploadError from .constants import ( FIELD_NAME_TO_ID,@@ -183,8 +184,6 @@ class SnowflakeCursor: Calling a function is expensive in Python and most of these getters are unnecessary. """ - PUT_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*put\s+", flags=re.IGNORECASE)- GET_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*get\s+", flags=re.IGNORECASE) INSERT_SQL_RE = re.compile(r"^insert\s+into", flags=re.IGNORECASE) COMMENT_SQL_RE = re.compile(r"/\*.*\*/") INSERT_SQL_VALUES_RE = re.compile(@@ -202,11 +201,7 @@ class SnowflakeCursor: None is returned if the SQL isn't a file transfer so that this function can be used in an if-statement. """- if SnowflakeCursor.PUT_SQL_RE.match(sql):- return FileTransferType.PUT- elif SnowflakeCursor.GET_SQL_RE.match(sql):- return FileTransferType.GET- return None+ return get_file_transfer_type(sql) def __init__( self,@@ -464,9 +459,7 @@ class SnowflakeCursor: self._is_file_transfer = _is_put_get else: # or detect it.- self._is_file_transfer = self.PUT_SQL_RE.match(- query- ) or self.GET_SQL_RE.match(query)+ self._is_file_transfer = get_file_transfer_type(query) is not None logger.debug("is_file_transfer: %s", self._is_file_transfer is not None) real_timeout = (diff --git a/src/snowflake/connector/gcs_storage_client.py b/src/snowflake/connector/gcs_storage_client.pyindex b3709be3..e113e459 100644--- a/src/snowflake/connector/gcs_storage_client.py+++ b/src/snowflake/connector/gcs_storage_client.py@@ -10,6 +10,7 @@ import os from logging import getLogger from typing import TYPE_CHECKING, Any, NamedTuple +from ._sql_util import is_put_statement from .compat import quote from .constants import ( FILE_PROTOCOL,@@ -269,9 +270,7 @@ class SnowflakeGCSRestClient(SnowflakeStorageClient): The local file path. """ command = self._command- if FILE_PROTOCOL not in self._command or not self._cursor.PUT_SQL_RE.match(- command- ):+ if FILE_PROTOCOL not in self._command or not is_put_statement(command): return None file_path_begin_index = command.find(FILE_PROTOCOL)diff --git a/test/unit/test_cursor.py b/test/unit/test_cursor.pyindex 37c118c1..bc43a559 100644--- a/test/unit/test_cursor.py+++ b/test/unit/test_cursor.py@@ -27,9 +27,24 @@ class FakeConnection(SnowflakeConnection): @pytest.mark.parametrize( "sql,_type", (+ ("", None),+ ("select 1;", None), ("PUT file:///tmp/data/mydata.csv @my_int_stage;", FileTransferType.PUT), ("GET @%mytable file:///tmp/data/;", FileTransferType.GET),- ("select 1;", None),+ ("/**/PUT file:///tmp/data/mydata.csv @my_int_stage;", FileTransferType.PUT),+ ("/**/ GET @%mytable file:///tmp/data/;", FileTransferType.GET),+ pytest.param(+ "/**/\n"+ + "\t/*/get\t*/\t/**/\n" * 10000+ + "\t*/get @~/test.csv file:///tmp\n",+ None,+ id="long_incorrect",+ ),+ pytest.param(+ "/**/\n" + "\t/*/put\t*/\t/**/\n" * 10000 + "put file:///tmp/data.csv @~",+ FileTransferType.PUT,+ id="long_correct",+ ), ), ) def test_get_filetransfer_type(sql, _type):12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823# Patch-overlapping Python context after the fix
## `src/snowflake/connector/_sql_util.py` — `function:remove_starting_comments` (lines 23-31)
```pythondef remove_starting_comments(sql: str) -> str: """Remove all comments from the start of a SQL statement.""" commentless_sql = sql while True: start_comment = COMMENT_START_SQL_RE.match(commentless_sql) if start_comment is None: break commentless_sql = commentless_sql[start_comment.end() :] return commentless_sql```
## `src/snowflake/connector/_sql_util.py` — `function:get_file_transfer_type` (lines 34-44)
```pythondef get_file_transfer_type(sql: str) -> FileTransferType | None: """Decide whether a SQL is a file transfer and return its type.
None is returned if the SQL isn't a file transfer so that this function can be used in an if-statement. """ commentless_sql = remove_starting_comments(sql) if PUT_SQL_RE.match(commentless_sql): return FileTransferType.PUT elif GET_SQL_RE.match(commentless_sql): return FileTransferType.GET```
## `src/snowflake/connector/_sql_util.py` — `function:is_put_statement` (lines 47-48)
```pythondef is_put_statement(sql: str) -> bool: return get_file_transfer_type(sql) == FileTransferType.PUT```
## `src/snowflake/connector/_sql_util.py` — `function:is_get_statement` (lines 51-52)
```pythondef is_get_statement(sql: str) -> bool: return get_file_transfer_type(sql) == FileTransferType.GET```
## `src/snowflake/connector/_sql_util.py` — `module:<module>@5` (lines 5-5)
```pythonfrom __future__ import annotations```
## `src/snowflake/connector/_sql_util.py` — `module:<module>@7` (lines 7-7)
```pythonimport re```
## `src/snowflake/connector/_sql_util.py` — `module:<module>@9` (lines 9-9)
```pythonfrom .constants import FileTransferType```
## `src/snowflake/connector/_sql_util.py` — `module:<module>@11` (lines 11-17)
```pythonCOMMENT_START_SQL_RE = re.compile( r""" ^\s*(?: /\*[\w\W]*?\*/ )""", re.VERBOSE,)```
## `src/snowflake/connector/_sql_util.py` — `module:<module>@19` (lines 19-19)
```pythonPUT_SQL_RE = re.compile(r"^\s*put", flags=re.IGNORECASE)```
## `src/snowflake/connector/_sql_util.py` — `module:<module>@20` (lines 20-20)
```pythonGET_SQL_RE = re.compile(r"^\s*get", flags=re.IGNORECASE)```
## `src/snowflake/connector/cursor.py` — `class:SnowflakeCursor` (lines 159-1301)
```pythonclass SnowflakeCursor: """Implementation of Cursor object that is returned from Connection.cursor() method.
Attributes: description: A list of namedtuples about metadata for all columns. rowcount: The number of records updated or selected. If not clear, -1 is returned. rownumber: The current 0-based index of the cursor in the result set or None if the index cannot be determined. sfqid: Snowflake query id in UUID form. Include this in the problem report to the customer support. sqlstate: Snowflake SQL State code. timestamp_output_format: Snowflake timestamp_output_format for timestamps. timestamp_ltz_output_format: Snowflake output format for LTZ timestamps. timestamp_tz_output_format: Snowflake output format for TZ timestamps. timestamp_ntz_output_format: Snowflake output format for NTZ timestamps. date_output_format: Snowflake output format for dates. time_output_format: Snowflake output format for times. timezone: Snowflake timezone. binary_output_format: Snowflake output format for binary fields. arraysize: The default number of rows fetched by fetchmany. connection: The connection object by which the cursor was created. errorhandle: The class that handles error handling. is_file_transfer: Whether, or not the current command is a put, or get.
TODO: Most of these attributes have no reason to be properties, we could just store them in public variables. Calling a function is expensive in Python and most of these getters are unnecessary. """
INSERT_SQL_RE = re.compile(r"^insert\s+into", flags=re.IGNORECASE) COMMENT_SQL_RE = re.compile(r"/\*.*\*/") INSERT_SQL_VALUES_RE = re.compile( r".*VALUES\s*(\(.*\)).*", re.IGNORECASE | re.MULTILINE | re.DOTALL ) ALTER_SESSION_RE = re.compile( r"alter\s+session\s+set\s+(.*)=\'?([^\']+)\'?\s*;", flags=re.IGNORECASE | re.MULTILINE | re.DOTALL, )
@staticmethod def get_file_transfer_type(sql: str) -> FileTransferType | None: """Decide whether a SQL is a file transfer and return its type.
None is returned if the SQL isn't a file transfer so that this function can be used in an if-statement. """ return get_file_transfer_type(sql)
def __init__( self, connection: SnowflakeConnection, use_dict_result: bool = False, ) -> None: """Inits a SnowflakeCursor with a connection.
Args: connection: The connection that created this cursor. use_dict_result: Decides whether to use dict result or not. """ self._connection: SnowflakeConnection = connection
self._errorhandler: Callable[ [SnowflakeConnection, SnowflakeCursor, type[Error], dict[str, str]], None, ] = Error.default_errorhandler self.messages: list[ tuple[type[Error] | type[Exception], dict[str, str | bool]] ] = [] self._timebomb: Timer | None = None # must be here for abort_exit method self._description: list[ResultMetadata] | None = None self._column_idx_to_name = None self._sfqid = None self._sqlstate = None self._total_rowcount = -1 self._sequence_counter = -1 self._request_id = None self._is_file_transfer = False
self._timestamp_output_format = None self._timestamp_ltz_output_format = None self._timestamp_ntz_output_format = None self._timestamp_tz_output_format = None self._date_output_format = None self._time_output_format = None self._timezone = None self._binary_output_format = None self._result: Iterator[tuple] | Iterator[dict] | None = None self._result_set: ResultSet | None = None self._result_state: ResultState = ResultState.DEFAULT self._use_dict_result = use_dict_result self.query: str | None = None # TODO: self._query_result_format could be defined as an enum self._query_result_format: str | None = None
self._arraysize = 1 # PEP-0249: defaults to 1
self._lock_canceling = Lock()
self._first_chunk_time = None
self._log_max_query_length = connection.log_max_query_length self._inner_cursor: SnowflakeCursor | None = None self._prefetch_hook = None self._rownumber: int | None = None
self.reset()
def __del__(self) -> None: # pragma: no cover try: self.close() except compat.BASE_EXCEPTION_CLASS as e: if logger.getEffectiveLevel() <= logging.INFO: logger.info(e)
@property def description(self) -> list[ResultMetadata]: return self._description
@property def rowcount(self): return self._total_rowcount if self._total_rowcount >= 0 else None
@property def rownumber(self): return self._rownumber if self._rownumber >= 0 else None
@property def sfqid(self): return self._sfqid
@property def sqlstate(self): return self._sqlstate
@property def timestamp_output_format(self): return self._timestamp_output_format
@property def timestamp_ltz_output_format(self): return ( self._timestamp_ltz_output_format if self._timestamp_ltz_output_format else self._timestamp_output_format )
@property def timestamp_tz_output_format(self): return ( self._timestamp_tz_output_format if self._timestamp_tz_output_format else self._timestamp_output_format )
@property def timestamp_ntz_output_format(self): return ( self._timestamp_ntz_output_format if self._timestamp_ntz_output_format else self._timestamp_output_format )
@property def date_output_format(self): return self._date_output_format
@property def time_output_format(self): return self._time_output_format
@property def timezone(self): return self._timezone
@property def binary_output_format(self): return self._binary_output_format
@property def arraysize(self): return self._arraysize
@arraysize.setter def arraysize(self, value): self._arraysize = int(value)
@property def connection(self): return self._connection
@property def errorhandler(self): return self._errorhandler
@errorhandler.setter def errorhandler(self, value): logger.debug("setting errorhandler: %s", value) if value is None: raise ProgrammingError("Invalid errorhandler is specified") self._errorhandler = value
@property def is_file_transfer(self): """Whether the command is PUT or GET.""" return hasattr(self, "_is_file_transfer") and self._is_file_transfer
@property def lastrowid(self) -> None: """Snowflake does not support lastrowid in which case None should be returned as per PEP249.""" return None
def callproc(self, procname: str, args: T = ()) -> T: """Call a stored procedure.
Args: procname: The stored procedure to be called. args: Parameters to be passed into the stored procedure.
Returns: The input parameters. """ marker_format = "%s" if self._connection.is_pyformat else "?" command = ( f"CALL {procname}({', '.join([marker_format for _ in range(len(args))])})" ) self.execute(command, args) return args
def close(self) -> bool | None: """Closes the cursor object.
Returns whether the cursor was closed during this call. """ try: if self.is_closed(): return False
with self._lock_canceling: self.reset(closing=True) self._connection = None del self.messages[:] return True except Exception: pass
def is_closed(self): return self._connection is None or self._connection.is_closed()
def _execute_helper( self, query: str, timeout: int = 0, statement_params: dict[str, str] | None = None, binding_params: tuple | dict[str, dict[str, str]] = None, binding_stage: str | None = None, is_internal: bool = False, describe_only: bool = False, _no_results: bool = False, _is_put_get=None, _no_retry: bool = False, ): del self.messages[:]
if statement_params is not None and not isinstance(statement_params, dict): Error.errorhandler_wrapper( self.connection, self, ProgrammingError, { "msg": "The data type of statement params is invalid. It must be dict.", "errno": ER_INVALID_VALUE, }, )
# check if current installation include arrow extension or not, # if not, we set statement level query result format to be JSON if not CAN_USE_ARROW_RESULT_FORMAT: logger.debug("Cannot use arrow result format, fallback to json format") if statement_params is None: statement_params = { PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON" } else: result_format_val = statement_params.get( PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT ) if str(result_format_val).upper() == "ARROW": self.check_can_use_arrow_resultset() elif result_format_val is None: statement_params[ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT ] = "JSON"
self._sequence_counter = self._connection._next_sequence_counter() self._request_id = uuid.uuid4()
logger.debug(f"Request id: {self._request_id}")
logger.debug("running query [%s]", self._format_query_for_log(query)) if _is_put_get is not None: # if told the query is PUT or GET, use the information self._is_file_transfer = _is_put_get else: # or detect it. self._is_file_transfer = get_file_transfer_type(query) is not None logger.debug("is_file_transfer: %s", self._is_file_transfer is not None)
real_timeout = ( timeout if timeout and timeout > 0 else self._connection.network_timeout )
if real_timeout is not None: self._timebomb = Timer(real_timeout, self.__cancel_query, [query]) self._timebomb.start() logger.debug("started timebomb in %ss", real_timeout) else: self._timebomb = None
original_sigint = signal.getsignal(signal.SIGINT)
def interrupt_handler(*_): # pragma: no cover try: signal.signal(signal.SIGINT, exit_handler) except (ValueError, TypeError): # ignore failures pass try: if self._timebomb is not None: self._timebomb.cancel() logger.debug("cancelled timebomb in finally") self._timebomb = None self.__cancel_query(query) finally: if original_sigint: try: signal.signal(signal.SIGINT, original_sigint) except (ValueError, TypeError): # ignore failures pass raise KeyboardInterrupt
try: if not original_sigint == exit_handler: signal.signal(signal.SIGINT, interrupt_handler) except ValueError: # pragma: no cover logger.debug( "Failed to set SIGINT handler. " "Not in main thread. Ignored..." ) ret = {"data": {}} try: ret = self._connection.cmd_query( query, self._sequence_counter, self._request_id, binding_params=binding_params, binding_stage=binding_stage, is_file_transfer=bool(self._is_file_transfer), statement_params=statement_params, is_internal=is_internal, describe_only=describe_only, _no_results=_no_results, _no_retry=_no_retry, ) finally: try: if original_sigint: signal.signal(signal.SIGINT, original_sigint) except (ValueError, TypeError): # pragma: no cover logger.debug( "Failed to reset SIGINT handler. Not in main " "thread. Ignored..." ) if self._timebomb is not None: self._timebomb.cancel() logger.debug("cancelled timebomb in finally")
if "data" in ret and "parameters" in ret["data"]: parameters = ret["data"]["parameters"] # Set session parameters for cursor object for kv in parameters: if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]: self._timestamp_output_format = kv["value"] if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_ntz_output_format = kv["value"] if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_ltz_output_format = kv["value"] if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_tz_output_format = kv["value"] if "DATE_OUTPUT_FORMAT" in kv["name"]: self._date_output_format = kv["value"] if "TIME_OUTPUT_FORMAT" in kv["name"]: self._time_output_format = kv["value"] if "TIMEZONE" in kv["name"]: self._timezone = kv["value"] if "BINARY_OUTPUT_FORMAT" in kv["name"]: self._binary_output_format = kv["value"] # Set session parameters for connection object self._connection._update_parameters( {p["name"]: p["value"] for p in parameters} )
self.query = query self._sequence_counter = -1 return ret
def execute( self, command: str, params: Sequence[Any] | dict[Any, Any] | None = None, _bind_stage: str | None = None, timeout: int | None = None, _exec_async: bool = False, _no_retry: bool = False, _do_reset: bool = True, _put_callback: SnowflakeProgressPercentage = None, _put_azure_callback: SnowflakeProgressPercentage = None, _put_callback_output_stream: IO[str] = sys.stdout, _get_callback: SnowflakeProgressPercentage = None, _get_azure_callback: SnowflakeProgressPercentage = None, _get_callback_output_stream: IO[str] = sys.stdout, _show_progress_bar: bool = True, _statement_params: dict[str, str] | None = None, _is_internal: bool = False, _describe_only: bool = False, _no_results: bool = False, _is_put_get: bool | None = None, _raise_put_get_error: bool = True, _force_put_overwrite: bool = False, file_stream: IO[bytes] | None = None, ) -> SnowflakeCursor | None: """Executes a command/query.
Args: command: The SQL command to be executed. params: Parameters to be bound into the SQL statement. _bind_stage: Path in temporary stage where binding parameters are uploaded as CSV files. timeout: Number of seconds after which to abort the query. _exec_async: Whether to execute this query asynchronously. _no_retry: Whether or not to retry on known errors. _do_reset: Whether or not the result set needs to be reset before executing query. _put_callback: Function to which GET command should call back to. _put_azure_callback: Function to which an Azure GET command should call back to. _put_callback_output_stream: The output stream a PUT command's callback should report on. _get_callback: Function to which GET command should call back to. _get_azure_callback: Function to which an Azure GET command should call back to. _get_callback_output_stream: The output stream a GET command's callback should report on. _show_progress_bar: Whether or not to show progress bar. _statement_params: Extra information that should be sent to Snowflake with query. _is_internal: This flag indicates whether the query is issued internally by the connector. _describe_only: If true, the query will not be executed but return the schema/description of this query. _no_results: This flag tells the back-end to not return the result, just fire the query and return the response returned by Snowflake's server. _use_ijson: This flag doesn't do anything as ijson support has ended. _is_put_get: Force decision of this SQL query being a PUT, or GET command. This is detected otherwise. _raise_put_get_error: Whether to raise PUT and GET errors. _force_put_overwrite: If the SQL query is a PUT, then this flag can force overwriting of an already existing file on stage. file_stream: File-like object to be uploaded with PUT
Returns: The cursor itself, or None if some error happened, or the response returned by Snowflake if the _no_results flag is on. """ if _exec_async: _no_results = True logger.debug("executing SQL/command") if self.is_closed(): Error.errorhandler_wrapper( self.connection, self, InterfaceError, {"msg": "Cursor is closed in execute.", "errno": ER_CURSOR_IS_CLOSED}, )
if _do_reset: self.reset() command = command.strip(" \t\n\r") if command else None if not command: logger.warning("execute: no query is given to execute") return
kwargs = { "timeout": timeout, "statement_params": _statement_params, "is_internal": _is_internal, "describe_only": _describe_only, "_no_results": _no_results, "_is_put_get": _is_put_get, "_no_retry": _no_retry, }
if self._connection.is_pyformat: # pyformat/format paramstyle # client side binding processed_params = self._connection._process_params_pyformat(params, self) # SNOW-513061 collect telemetry for empty sequence usage before we make the breaking change announcement if params is not None and len(params) == 0: self._log_telemetry_job_data( TelemetryField.EMPTY_SEQ_INTERPOLATION, TelemetryData.TRUE if self.connection._interpolate_empty_sequences else TelemetryData.FALSE, ) if logger.getEffectiveLevel() <= logging.DEBUG: logger.debug( f"binding: [{self._format_query_for_log(command)}] " f"with input=[{params}], " f"processed=[{processed_params}]", ) if ( self.connection._interpolate_empty_sequences and processed_params is not None ) or ( not self.connection._interpolate_empty_sequences and len(processed_params) > 0 ): query = command % processed_params else: query = command else: # qmark and numeric paramstyle query = command if _bind_stage: kwargs["binding_stage"] = _bind_stage else: if params is not None and not isinstance(params, (list, tuple)): errorvalue = { "msg": f"Binding parameters must be a list: {params}", "errno": ER_FAILED_PROCESSING_PYFORMAT, } Error.errorhandler_wrapper( self.connection, self, ProgrammingError, errorvalue )
kwargs["binding_params"] = self._connection._process_params_qmarks( params, self )
m = DESC_TABLE_RE.match(query) if m: query1 = f"describe table {m.group(1)}" if logger.getEffectiveLevel() <= logging.WARNING: logger.info( "query was rewritten: org=%s, new=%s", " ".join(line.strip() for line in query.split("\n")), query1, ) query = query1
if logger.getEffectiveLevel() <= logging.INFO: logger.info("query: [%s]", self._format_query_for_log(query)) ret = self._execute_helper(query, **kwargs) self._sfqid = ( ret["data"]["queryId"] if "data" in ret and "queryId" in ret["data"] else None ) self._sqlstate = ( ret["data"]["sqlState"] if "data" in ret and "sqlState" in ret["data"] else None ) self._first_chunk_time = get_time_millis()
# if server gives a send time, log the time it took to arrive if "data" in ret and "sendResultTime" in ret["data"]: time_consume_first_result = ( self._first_chunk_time - ret["data"]["sendResultTime"] ) self._log_telemetry_job_data( TelemetryField.TIME_CONSUME_FIRST_RESULT, time_consume_first_result ) logger.debug("sfqid: %s", self.sfqid)
logger.info("query execution done") if ret["success"]: logger.debug("SUCCESS") data = ret["data"]
logger.debug("PUT OR GET: %s", self.is_file_transfer) if self.is_file_transfer: # Decide whether to use the old, or new code path sf_file_transfer_agent = SnowflakeFileTransferAgent( self, query, ret, put_callback=_put_callback, put_azure_callback=_put_azure_callback, put_callback_output_stream=_put_callback_output_stream, get_callback=_get_callback, get_azure_callback=_get_azure_callback, get_callback_output_stream=_get_callback_output_stream, show_progress_bar=_show_progress_bar, raise_put_get_error=_raise_put_get_error, force_put_overwrite=_force_put_overwrite or data.get("overwrite", False), source_from_stream=file_stream, multipart_threshold=data.get("threshold"), use_s3_regional_url=self._connection.enable_stage_s3_privatelink_for_us_east_1, ) sf_file_transfer_agent.execute() data = sf_file_transfer_agent.result() self._total_rowcount = len(data["rowset"]) if "rowset" in data else -1 m = self.ALTER_SESSION_RE.match(query) if m: # session parameters param = m.group(1).upper() value = m.group(2) self._connection.converter.set_parameter(param, value)
if _exec_async: self.connection._async_sfqids[self._sfqid] = None if _no_results: self._total_rowcount = ( ret["data"]["total"] if "data" in ret and "total" in ret["data"] else -1 ) return data self._init_result_and_meta(data) else: self._total_rowcount = ( ret["data"]["total"] if "data" in ret and "total" in ret["data"] else -1 ) logger.debug(ret) err = ret["message"] code = ret.get("code", -1) if "data" in ret: err += ret["data"].get("errorMessage", "") errvalue = { "msg": err, "errno": int(code), "sqlstate": self._sqlstate, "sfqid": self._sfqid, } is_integrity_error = ( code == "100072" ) # NULL result in a non-nullable column error_class = IntegrityError if is_integrity_error else ProgrammingError Error.errorhandler_wrapper(self.connection, self, error_class, errvalue) return self
def execute_async(self, *args, **kwargs): """Convenience function to execute a query without waiting for results (asynchronously).
This function takes the same arguments as execute, please refer to that function for documentation. """ kwargs["_exec_async"] = True return self.execute(*args, **kwargs)
def describe(self, *args, **kwargs) -> list[ResultMetadata]: """Obtain the schema of the result without executing the query.
This function takes the same arguments as execute, please refer to that function for documentation.
Returns: The schema of the result. """ kwargs["_describe_only"] = kwargs["_is_internal"] = True self.execute(*args, **kwargs) return self._description
def _format_query_for_log(self, query): return self._connection._format_query_for_log(query)
def _is_dml(self, data): return ( "statementTypeId" in data and int(data["statementTypeId"]) in STATEMENT_TYPE_ID_DML_SET )
def _init_result_and_meta(self, data): is_dml = self._is_dml(data) self._query_result_format = data.get("queryResultFormat", "json") logger.debug("Query result format: %s", self._query_result_format)
if self._total_rowcount == -1 and not is_dml and data.get("total") is not None: self._total_rowcount = data["total"]
self._description: list[ResultMetadata] = [ ResultMetadata.from_column(col) for col in data["rowtype"] ]
result_chunks = create_batches_from_response( self, self._query_result_format, data, self._description )
if not (is_dml or self.is_file_transfer): logger.info( "Number of results in first chunk: %s", result_chunks[0].rowcount )
self._result_set = ResultSet( self, result_chunks, self._connection.client_prefetch_threads, ) self._rownumber = -1 self._result_state = ResultState.VALID
# don't update the row count when the result is returned from `describe` method if is_dml and "rowset" in data and len(data["rowset"]) > 0: updated_rows = 0 for idx, desc in enumerate(self._description): if desc[0] in ( "number of rows updated", "number of multi-joined rows updated", "number of rows deleted", ) or desc[0].startswith("number of rows inserted"): updated_rows += int(data["rowset"][0][idx]) if self._total_rowcount == -1: self._total_rowcount = updated_rows else: self._total_rowcount += updated_rows
def check_can_use_arrow_resultset(self): global CAN_USE_ARROW_RESULT_FORMAT
if not CAN_USE_ARROW_RESULT_FORMAT: if self._connection.application == "SnowSQL": msg = "Currently SnowSQL doesn't support the result set in Apache Arrow format." errno = ER_NO_PYARROW_SNOWSQL else: msg = "The result set in Apache Arrow format is not supported for the platform." errno = ER_NO_ARROW_RESULT
Error.errorhandler_wrapper( self.connection, self, ProgrammingError, { "msg": msg, "errno": errno, }, )
def check_can_use_pandas(self): if not installed_pandas: msg = ( "Optional dependency: 'pandas' is not installed, please see the following link for install " "instructions: https://docs.snowflake.com/en/user-guide/python-connector-pandas.html#installation" ) errno = ER_NO_PYARROW
Error.errorhandler_wrapper( self.connection, self, ProgrammingError, { "msg": msg, "errno": errno, }, )
def query_result(self, qid): url = f"/queries/{qid}/result" ret = self._connection.rest.request(url=url, method="get") self._sfqid = ( ret["data"]["queryId"] if "data" in ret and "queryId" in ret["data"] else None ) self._sqlstate = ( ret["data"]["sqlState"] if "data" in ret and "sqlState" in ret["data"] else None ) logger.debug("sfqid=%s", self._sfqid)
if ret.get("success"): data = ret.get("data") self._init_result_and_meta(data) else: logger.info("failed") logger.debug(ret) err = ret["message"] code = ret.get("code", -1) if "data" in ret: err += ret["data"].get("errorMessage", "") errvalue = { "msg": err, "errno": int(code), "sqlstate": self._sqlstate, "sfqid": self._sfqid, } Error.errorhandler_wrapper( self.connection, self, ProgrammingError, errvalue ) return self
def fetch_arrow_batches(self) -> Iterator[Table]: self.check_can_use_arrow_resultset() if self._query_result_format != "arrow": raise NotSupportedError self._log_telemetry_job_data( TelemetryField.ARROW_FETCH_BATCHES, TelemetryData.TRUE ) return self._result_set._fetch_arrow_batches()
def fetch_arrow_all(self) -> Table | None: self.check_can_use_arrow_resultset() if self._query_result_format != "arrow": raise NotSupportedError self._log_telemetry_job_data(TelemetryField.ARROW_FETCH_ALL, TelemetryData.TRUE) return self._result_set._fetch_arrow_all()
def fetch_pandas_batches(self, **kwargs) -> Iterator[pandas.DataFrame]: """Fetches a single Arrow Table.""" self.check_can_use_pandas() if self._prefetch_hook is not None: self._prefetch_hook() if self._query_result_format != "arrow": raise NotSupportedError self._log_telemetry_job_data( TelemetryField.PANDAS_FETCH_BATCHES, TelemetryData.TRUE ) return self._result_set._fetch_pandas_batches(**kwargs)
def fetch_pandas_all(self, **kwargs) -> pandas.DataFrame: """Fetch Pandas dataframes in batches, where 'batch' refers to Snowflake Chunk.""" self.check_can_use_pandas() if self._prefetch_hook is not None: self._prefetch_hook() if self._query_result_format != "arrow": raise NotSupportedError self._log_telemetry_job_data( TelemetryField.PANDAS_FETCH_ALL, TelemetryData.TRUE ) return self._result_set._fetch_pandas_all(**kwargs)
def abort_query(self, qid): url = f"/queries/{qid}/abort-request" ret = self._connection.rest.request(url=url, method="post") return ret.get("success")
def executemany( self, command: str, seqparams: Sequence[Any] | dict[str, Any], **kwargs: dict[str, Any], ) -> SnowflakeCursor: """Executes a command/query with the given set of parameters sequentially.""" logger.debug("executing many SQLs/commands") command = command.strip(" \t\n\r") if command else None
if not seqparams: return self
if self.INSERT_SQL_RE.match(command): if self._connection.is_pyformat: logger.debug("rewriting INSERT query") command_wo_comments = re.sub(self.COMMENT_SQL_RE, "", command) m = self.INSERT_SQL_VALUES_RE.match(command_wo_comments) if not m: Error.errorhandler_wrapper( self.connection, self, InterfaceError, { "msg": "Failed to rewrite multi-row insert", "errno": ER_FAILED_TO_REWRITE_MULTI_ROW_INSERT, }, )
fmt = m.group(1) values = [] for param in seqparams: logger.debug(f"parameter: {param}") values.append( fmt % self._connection._process_params_pyformat(param, self) ) command = command.replace(fmt, ",".join(values), 1) self.execute(command, **kwargs) return self else: logger.debug("bulk insert") # sanity check row_size = len(seqparams[0]) for row in seqparams: if len(row) != row_size: error_value = { "msg": f"Bulk data size don't match. expected: {row_size}, " f"got: {len(row)}, command: {command}", "errno": ER_INVALID_VALUE, } Error.errorhandler_wrapper( self.connection, self, InterfaceError, error_value ) return self bind_size = len(seqparams) * row_size bind_stage = None if ( bind_size > self.connection._session_parameters[ "CLIENT_STAGE_ARRAY_BINDING_THRESHOLD" ] > 0 ): # bind stage optimization try: rows = self.connection._write_params_to_byte_rows(seqparams) bind_uploader = BindUploadAgent(self, rows) bind_uploader.upload() bind_stage = bind_uploader.stage_path except BindUploadError: logger.debug( "Failed to upload binds to stage, sending binds to " "Snowflake instead." ) binding_param = ( None if bind_stage else list(map(list, zip(*seqparams))) ) # transpose self.execute( command, params=binding_param, _bind_stage=bind_stage, **kwargs ) return self
self.reset() for param in seqparams: self.execute(command, params=param, _do_reset=False, **kwargs) return self
def _result_iterator( self, ) -> Generator[dict, None, None] | Generator[tuple, None, None]: """Yields the elements from _result and raises an exception when appropriate.""" try: for _next in self._result: if isinstance(_next, Exception): Error.errorhandler_wrapper_from_ready_exception( self._connection, self, _next, ) self._rownumber += 1 yield _next except TypeError as err: if self._result_state == ResultState.DEFAULT: raise err else: yield None
def fetchone(self) -> dict | tuple | None: """Fetches one row.""" if self._prefetch_hook is not None: self._prefetch_hook() if self._result is None and self._result_set is not None: self._result = iter(self._result_set) self._result_state = ResultState.VALID try: return next(self._result_iterator()) except StopIteration: return None
def fetchmany(self, size=None): """Fetches the number of specified rows.""" if size is None: size = self.arraysize
if size < 0: errorvalue = { "msg": ( "The number of rows is not zero or " "positive number: {}" ).format(size), "errno": ER_NOT_POSITIVE_SIZE, } Error.errorhandler_wrapper( self.connection, self, ProgrammingError, errorvalue ) ret = [] while size > 0: row = self.fetchone() if row is None: break ret.append(row) if size is not None: size -= 1
return ret
def fetchall(self) -> list[tuple] | list[dict]: """Fetches all of the results.""" ret = [] while True: row = self.fetchone() if row is None: break ret.append(row) return ret
def nextset(self): """Not supported.""" logger.debug("nop") return None
def setinputsizes(self, _): """Not supported.""" logger.debug("nop")
def setoutputsize(self, _, column=None): """Not supported.""" del column logger.debug("nop")
def scroll(self, value, mode="relative"): Error.errorhandler_wrapper( self.connection, self, NotSupportedError, { "msg": "scroll is not supported.", "errno": ER_UNSUPPORTED_METHOD, "sqlstate": SQLSTATE_FEATURE_NOT_SUPPORTED, }, )
def reset(self, closing=False): """Resets the result set.""" # SNOW-647539: Do not erase the rowcount # information when closing the cursor if not closing: self._total_rowcount = -1 if self._result_state != ResultState.DEFAULT: self._result_state = ResultState.RESET if self._result is not None: self._result = None if self._inner_cursor is not None: self._inner_cursor.reset(closing=closing) self._result = None self._inner_cursor = None self._prefetch_hook = None if not self.connection._reuse_results: self._result_set = None
def __iter__(self) -> Iterator[dict] | Iterator[tuple]: """Iteration over the result set.""" # set _result if _result_set is not None if self._result is None and self._result_set is not None: self._result = iter(self._result_set) self._result_state = ResultState.VALID return self._result_iterator()
def __cancel_query(self, query): if self._sequence_counter >= 0 and not self.is_closed(): logger.debug("canceled. %s, request_id: %s", query, self._request_id) with self._lock_canceling: self._connection._cancel_query(query, self._request_id)
def _log_telemetry_job_data( self, telemetry_field: TelemetryField, value: Any ) -> None: """Builds an instance of TelemetryData with the given field and logs it.""" ts = get_time_millis() try: self._connection._log_telemetry( TelemetryData.from_telemetry_data_dict( from_dict={ TelemetryField.KEY_TYPE.value: telemetry_field.value, TelemetryField.KEY_SFQID.value: self._sfqid, TelemetryField.KEY_VALUE.value: value, }, timestamp=ts, connection=self._connection, ) ) except AttributeError: logger.warning( "Cursor failed to log to telemetry. Connection object may be None.", exc_info=True, )
def __enter__(self): """Context manager.""" return self
def __exit__(self, exc_type, exc_val, exc_tb): """Context manager with commit or rollback.""" self.close()
def get_results_from_sfqid(self, sfqid: str): """Gets the results from previously ran query."""
def wait_until_ready(): """Makes sure query has finished executing and once it has retrieves results.""" no_data_counter = 0 retry_pattern_pos = 0 while True: status = self.connection.get_query_status(sfqid) if not self.connection.is_still_running(status): break if status == QueryStatus.NO_DATA: # pragma: no cover no_data_counter += 1 if no_data_counter > ASYNC_NO_DATA_MAX_RETRY: raise DatabaseError( "Cannot retrieve data on the status of this query. No information returned " "from server for query '{}'" ) time.sleep( 0.5 * ASYNC_RETRY_PATTERN[retry_pattern_pos] ) # Same wait as JDBC # If we can advance in ASYNC_RETRY_PATTERN then do so if retry_pattern_pos < (len(ASYNC_RETRY_PATTERN) - 1): retry_pattern_pos += 1 if status != QueryStatus.SUCCESS: raise DatabaseError( "Status of query '{}' is {}, results are unavailable".format( sfqid, status.name ) ) self._inner_cursor.execute(f"select * from table(result_scan('{sfqid}'))") self._result = self._inner_cursor._result self._query_result_format = self._inner_cursor._query_result_format self._total_rowcount = self._inner_cursor._total_rowcount self._description = self._inner_cursor._description self._result_set = self._inner_cursor._result_set self._result_state = ResultState.VALID self._rownumber = 0 # Unset this function, so that we don't block anymore self._prefetch_hook = None
self.connection.get_query_status_throw_if_error( sfqid ) # Trigger an exception if query failed klass = self.__class__ self._inner_cursor = klass(self.connection) self._sfqid = sfqid self._prefetch_hook = wait_until_ready
def get_result_batches(self) -> list[ResultBatch] | None: """Get the previously executed query's ``ResultBatch`` s if available.
If they are unavailable, in case nothing has been executed yet None will be returned.
For a detailed description of ``ResultBatch`` s please see the docstring of: ``snowflake.connector.result_batches.ResultBatch`` """ if self._result_set is None: return None self._log_telemetry_job_data( TelemetryField.GET_PARTITIONS_USED, TelemetryData.TRUE ) return self._result_set.batches```
## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor.get_file_transfer_type` (lines 197-204)
```python def get_file_transfer_type(sql: str) -> FileTransferType | None: """Decide whether a SQL is a file transfer and return its type.
None is returned if the SQL isn't a file transfer so that this function can be used in an if-statement. """ return get_file_transfer_type(sql)```
## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor._execute_helper` (lines 406-560)
```python def _execute_helper( self, query: str, timeout: int = 0, statement_params: dict[str, str] | None = None, binding_params: tuple | dict[str, dict[str, str]] = None, binding_stage: str | None = None, is_internal: bool = False, describe_only: bool = False, _no_results: bool = False, _is_put_get=None, _no_retry: bool = False, ): del self.messages[:]
if statement_params is not None and not isinstance(statement_params, dict): Error.errorhandler_wrapper( self.connection, self, ProgrammingError, { "msg": "The data type of statement params is invalid. It must be dict.", "errno": ER_INVALID_VALUE, }, )
# check if current installation include arrow extension or not, # if not, we set statement level query result format to be JSON if not CAN_USE_ARROW_RESULT_FORMAT: logger.debug("Cannot use arrow result format, fallback to json format") if statement_params is None: statement_params = { PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON" } else: result_format_val = statement_params.get( PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT ) if str(result_format_val).upper() == "ARROW": self.check_can_use_arrow_resultset() elif result_format_val is None: statement_params[ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT ] = "JSON"
self._sequence_counter = self._connection._next_sequence_counter() self._request_id = uuid.uuid4()
logger.debug(f"Request id: {self._request_id}")
logger.debug("running query [%s]", self._format_query_for_log(query)) if _is_put_get is not None: # if told the query is PUT or GET, use the information self._is_file_transfer = _is_put_get else: # or detect it. self._is_file_transfer = get_file_transfer_type(query) is not None logger.debug("is_file_transfer: %s", self._is_file_transfer is not None)
real_timeout = ( timeout if timeout and timeout > 0 else self._connection.network_timeout )
if real_timeout is not None: self._timebomb = Timer(real_timeout, self.__cancel_query, [query]) self._timebomb.start() logger.debug("started timebomb in %ss", real_timeout) else: self._timebomb = None
original_sigint = signal.getsignal(signal.SIGINT)
def interrupt_handler(*_): # pragma: no cover try: signal.signal(signal.SIGINT, exit_handler) except (ValueError, TypeError): # ignore failures pass try: if self._timebomb is not None: self._timebomb.cancel() logger.debug("cancelled timebomb in finally") self._timebomb = None self.__cancel_query(query) finally: if original_sigint: try: signal.signal(signal.SIGINT, original_sigint) except (ValueError, TypeError): # ignore failures pass raise KeyboardInterrupt
try: if not original_sigint == exit_handler: signal.signal(signal.SIGINT, interrupt_handler) except ValueError: # pragma: no cover logger.debug( "Failed to set SIGINT handler. " "Not in main thread. Ignored..." ) ret = {"data": {}} try: ret = self._connection.cmd_query( query, self._sequence_counter, self._request_id, binding_params=binding_params, binding_stage=binding_stage, is_file_transfer=bool(self._is_file_transfer), statement_params=statement_params, is_internal=is_internal, describe_only=describe_only, _no_results=_no_results, _no_retry=_no_retry, ) finally: try: if original_sigint: signal.signal(signal.SIGINT, original_sigint) except (ValueError, TypeError): # pragma: no cover logger.debug( "Failed to reset SIGINT handler. Not in main " "thread. Ignored..." ) if self._timebomb is not None: self._timebomb.cancel() logger.debug("cancelled timebomb in finally")
if "data" in ret and "parameters" in ret["data"]: parameters = ret["data"]["parameters"] # Set session parameters for cursor object for kv in parameters: if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]: self._timestamp_output_format = kv["value"] if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_ntz_output_format = kv["value"] if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_ltz_output_format = kv["value"] if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_tz_output_format = kv["value"] if "DATE_OUTPUT_FORMAT" in kv["name"]: self._date_output_format = kv["value"] if "TIME_OUTPUT_FORMAT" in kv["name"]: self._time_output_format = kv["value"] if "TIMEZONE" in kv["name"]: self._timezone = kv["value"] if "BINARY_OUTPUT_FORMAT" in kv["name"]: self._binary_output_format = kv["value"] # Set session parameters for connection object self._connection._update_parameters( {p["name"]: p["value"] for p in parameters} )
self.query = query self._sequence_counter = -1 return ret```
## `src/snowflake/connector/cursor.py` — `module:<module>@35` (lines 35-35)
```pythonfrom ._sql_util import get_file_transfer_type```
## `src/snowflake/connector/gcs_storage_client.py` — `class:SnowflakeGCSRestClient` (lines 48-395)
```pythonclass SnowflakeGCSRestClient(SnowflakeStorageClient): def __init__( self, meta: SnowflakeFileMeta, credentials: StorageCredential, stage_info: dict[str, Any], cnx: SnowflakeConnection, command: str, use_s3_regional_url=False, ) -> None: """Creates a client object with given stage credentials.
Args: stage_info: Access credentials and info of a stage.
Returns: The client to communicate with GCS. """ super().__init__( meta, stage_info, -1, credentials=credentials, chunked_transfer=False ) self.stage_info = stage_info self._command = command self.meta = meta self._cursor = cnx.cursor() # presigned_url in meta is for downloading self.presigned_url: str = meta.presigned_url or stage_info.get("presignedUrl") self.security_token = credentials.creds.get("GCS_ACCESS_TOKEN")
if self.security_token: logger.debug(f"len(GCS_ACCESS_TOKEN): {len(self.security_token)}") else: logger.debug("No access token received from GS, requesting presigned url") self._update_presigned_url()
def _has_expired_token(self, response: requests.Response) -> bool: return self.security_token and response.status_code == 401
def _has_expired_presigned_url(self, response: requests.Response) -> bool: # Presigned urls can be generated for any xml-api operation # offered by GCS. Hence the error codes expected are similar # to xml api. # https://cloud.google.com/storage/docs/xml-api/reference-status
presigned_url_expired = ( not self.security_token ) and response.status_code == 400 if presigned_url_expired and self.last_err_is_presigned_url: logger.debug("Presigned url expiration error two times in a row.") response.raise_for_status() self.last_err_is_presigned_url = presigned_url_expired return presigned_url_expired
def _upload_chunk(self, chunk_id: int, chunk: bytes) -> None: meta = self.meta
content_encoding = "" if meta.dst_compression_type is not None: content_encoding = meta.dst_compression_type.name.lower()
# We set the contentEncoding to blank for GZIP files. We don't # want GCS to think our gzip files are gzips because it makes # them download uncompressed, and none of the other providers do # that. There's essentially no way for us to prevent that # behavior. Bad Google. if content_encoding and content_encoding == "gzip": content_encoding = ""
gcs_headers = { HTTP_HEADER_CONTENT_ENCODING: content_encoding, GCS_METADATA_SFC_DIGEST: meta.sha256_digest, }
if self.encryption_metadata: gcs_headers.update( { GCS_METADATA_ENCRYPTIONDATAPROP: json.dumps( { "EncryptionMode": "FullBlob", "WrappedContentKey": { "KeyId": "symmKey1", "EncryptedKey": self.encryption_metadata.key, "Algorithm": "AES_CBC_256", }, "EncryptionAgent": { "Protocol": "1.0", "EncryptionAlgorithm": "AES_CBC_256", }, "ContentEncryptionIV": self.encryption_metadata.iv, "KeyWrappingMetadata": {"EncryptionLibrary": "Java 5.3.0"}, } ), GCS_METADATA_MATDESC_KEY: self.encryption_metadata.matdesc, } )
def generate_url_and_rest_args() -> tuple[ str, dict[str, dict[str | Any, str | None] | bytes] ]: if not self.presigned_url: upload_url = self.generate_file_url( self.stage_info["location"], meta.dst_file_name.lstrip("/") ) access_token = self.security_token else: upload_url = self.presigned_url access_token: str | None = None if access_token: gcs_headers.update({"Authorization": f"Bearer {access_token}"}) rest_args = {"headers": gcs_headers, "data": chunk} return upload_url, rest_args
response = self._send_request_with_retry( "PUT", generate_url_and_rest_args, chunk_id ) response.raise_for_status() meta.gcs_file_header_digest = gcs_headers[GCS_METADATA_SFC_DIGEST] meta.gcs_file_header_content_length = meta.upload_size meta.gcs_file_header_encryption_metadata = json.loads( gcs_headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, "null") )
def download_chunk(self, chunk_id: int) -> None: meta = self.meta
def generate_url_and_rest_args() -> tuple[ str, dict[str, dict[str, str] | bool] ]: gcs_headers = {} if not self.presigned_url: download_url = self.generate_file_url( self.stage_info["location"], meta.src_file_name.lstrip("/") ) access_token = self.security_token gcs_headers["Authorization"] = f"Bearer {access_token}" else: download_url = self.presigned_url rest_args = {"headers": gcs_headers, "stream": True} return download_url, rest_args
response = self._send_request_with_retry( "GET", generate_url_and_rest_args, chunk_id ) response.raise_for_status()
self.write_downloaded_chunk(chunk_id, response.content)
encryption_metadata = None
if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None): encryptiondata = json.loads( response.headers[GCS_METADATA_ENCRYPTIONDATAPROP] )
if encryptiondata: encryption_metadata = EncryptionMetadata( key=encryptiondata["WrappedContentKey"]["EncryptedKey"], iv=encryptiondata["ContentEncryptionIV"], matdesc=response.headers[GCS_METADATA_MATDESC_KEY] if GCS_METADATA_MATDESC_KEY in response.headers else None, )
meta.gcs_file_header_digest = response.headers.get(GCS_METADATA_SFC_DIGEST) meta.gcs_file_header_content_length = len(response.content) meta.gcs_file_header_encryption_metadata = encryption_metadata
def finish_download(self) -> None: super().finish_download() # Sadly, we can only determine the src file size after we've # downloaded it, unlike the other cloud providers where the # metadata can be read beforehand. self.meta.src_file_size = os.path.getsize(self.intermediate_dst_path)
def _update_presigned_url(self) -> None: """Updates the file metas with presigned urls if any.
Currently only the file metas generated for PUT/GET on a GCP account need the presigned urls. """ logger.debug("Updating presigned url")
# Rewrite the command such that a new PUT call is made for each file # represented by the regex (if present) separately. This is the only # way to get the presigned url for that file. file_path_to_be_replaced = self._get_local_file_path_from_put_command()
if not file_path_to_be_replaced: # This prevents GET statements to proceed return
# At this point the connector has already figured out and # validated that the local file exists and has also decided # upon the destination file name and the compression type. # The only thing that's left to do is to get the presigned # url for the destination file. If the command originally # referred to a single file, then the presigned url got in # that case is simply ignore, since the file name is not what # we want.
# GS only looks at the file name at the end of local file # path to figure out the remote object name. Hence the prefix # for local path is not necessary in the reconstructed command. file_path_to_replace_with = self.meta.dst_file_name command_with_single_file = self._command command_with_single_file = command_with_single_file.replace( file_path_to_be_replaced, file_path_to_replace_with )
logger.debug("getting presigned url for %s", file_path_to_replace_with) ret = self._cursor._execute_helper(command_with_single_file)
stage_info = ret.get("data", dict()).get("stageInfo", dict()) self.meta.presigned_url = stage_info.get("presignedUrl") self.presigned_url = stage_info.get("presignedUrl")
def _get_local_file_path_from_put_command(self) -> str | None: """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita).
Args: command: Command to be parsed and get the local file path out of.
Returns: The local file path. """ command = self._command if FILE_PROTOCOL not in self._command or not is_put_statement(command): return None
file_path_begin_index = command.find(FILE_PROTOCOL) is_file_path_quoted = command[file_path_begin_index - 1] == "'" file_path_begin_index += len(FILE_PROTOCOL)
file_path = ""
if is_file_path_quoted: file_path_end_index = command.find("'", file_path_begin_index)
if file_path_end_index > file_path_begin_index: file_path = command[file_path_begin_index:file_path_end_index] else: index_list = [] for delimiter in [" ", "\n", ";"]: index = command.find(delimiter, file_path_begin_index) if index != -1: index_list += [index]
file_path_end_index = min(index_list) if index_list else -1
if file_path_end_index > file_path_begin_index: file_path = command[file_path_begin_index:file_path_end_index] elif file_path_end_index == -1: file_path = command[file_path_begin_index:]
return file_path
def get_file_header(self, filename: str) -> FileHeader | None: """Gets the remote file's metadata.
Args: filename: Not applicable to GCS.
Returns: The file header, with expected properties populated or None, based on how the request goes with the storage provider.
Notes: Sometimes this method is called to verify that the file has indeed been uploaded. In cases of presigned url, we have no way of verifying that, except with the http status code of 200 which we have already confirmed and set the meta.result_status = UPLOADED/DOWNLOADED. """ meta = self.meta if ( meta.result_status == ResultStatus.UPLOADED or meta.result_status == ResultStatus.DOWNLOADED ): return FileHeader( digest=meta.gcs_file_header_digest, content_length=meta.gcs_file_header_content_length, encryption_metadata=meta.gcs_file_header_encryption_metadata, ) elif self.presigned_url: meta.result_status = ResultStatus.NOT_FOUND_FILE else:
def generate_url_and_authenticated_headers(): url = self.generate_file_url( self.stage_info["location"], filename.lstrip("/") ) gcs_headers = {"Authorization": f"Bearer {self.security_token}"} rest_args = {"headers": gcs_headers} return url, rest_args
retry_id = "HEAD" self.retry_count[retry_id] = 0 response = self._send_request_with_retry( "HEAD", generate_url_and_authenticated_headers, retry_id ) if response.status_code == 404: meta.result_status = ResultStatus.NOT_FOUND_FILE return None elif response.status_code == 200: digest = response.headers.get(GCS_METADATA_SFC_DIGEST, None) content_length = int(response.headers.get("content-length", "0"))
encryption_metadata = EncryptionMetadata("", "", "") if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None): encryption_data = json.loads( response.headers[GCS_METADATA_ENCRYPTIONDATAPROP] )
if encryption_data: encryption_metadata = EncryptionMetadata( key=encryption_data["WrappedContentKey"]["EncryptedKey"], iv=encryption_data["ContentEncryptionIV"], matdesc=response.headers[GCS_METADATA_MATDESC_KEY] if GCS_METADATA_MATDESC_KEY in response.headers else None, ) meta.result_status = ResultStatus.UPLOADED return FileHeader( digest=digest, content_length=content_length, encryption_metadata=encryption_metadata, ) response.raise_for_status() return None
@staticmethod def extract_bucket_name_and_path(stage_location: str) -> GcsLocation: container_name = stage_location path = ""
# split stage location as bucket name and path if "/" in stage_location: container_name = stage_location[0 : stage_location.index("/")] path = stage_location[stage_location.index("/") + 1 :] if path and not path.endswith("/"): path += "/"
return GcsLocation(bucket_name=container_name, path=path)
@staticmethod def generate_file_url(stage_location: str, filename: str) -> str: gcs_location = SnowflakeGCSRestClient.extract_bucket_name_and_path( stage_location ) full_file_path = f"{gcs_location.path}{filename}" return f"https://storage.googleapis.com/{gcs_location.bucket_name}/{quote(full_file_path)}"```
## `src/snowflake/connector/gcs_storage_client.py` — `function:SnowflakeGCSRestClient._get_local_file_path_from_put_command` (lines 263-301)
```python def _get_local_file_path_from_put_command(self) -> str | None: """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita).
Args: command: Command to be parsed and get the local file path out of.
Returns: The local file path. """ command = self._command if FILE_PROTOCOL not in self._command or not is_put_statement(command): return None
file_path_begin_index = command.find(FILE_PROTOCOL) is_file_path_quoted = command[file_path_begin_index - 1] == "'" file_path_begin_index += len(FILE_PROTOCOL)
file_path = ""
if is_file_path_quoted: file_path_end_index = command.find("'", file_path_begin_index)
if file_path_end_index > file_path_begin_index: file_path = command[file_path_begin_index:file_path_end_index] else: index_list = [] for delimiter in [" ", "\n", ";"]: index = command.find(delimiter, file_path_begin_index) if index != -1: index_list += [index]
file_path_end_index = min(index_list) if index_list else -1
if file_path_end_index > file_path_begin_index: file_path = command[file_path_begin_index:file_path_end_index] elif file_path_end_index == -1: file_path = command[file_path_begin_index:]
return file_path```
## `src/snowflake/connector/gcs_storage_client.py` — `module:<module>@13` (lines 13-13)
```pythonfrom ._sql_util import is_put_statement```
## `test/unit/test_cursor.py` — `function:test_get_filetransfer_type` (lines 27-51)
```pythondef test_get_filetransfer_type(sql, _type): assert SnowflakeCursor.get_file_transfer_type(sql) == _type```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755# Patch-overlapping Python context before the fix
## `src/snowflake/connector/cursor.py` — `class:SnowflakeCursor` (lines 158-1308)
```pythonclass SnowflakeCursor: """Implementation of Cursor object that is returned from Connection.cursor() method.
Attributes: description: A list of namedtuples about metadata for all columns. rowcount: The number of records updated or selected. If not clear, -1 is returned. rownumber: The current 0-based index of the cursor in the result set or None if the index cannot be determined. sfqid: Snowflake query id in UUID form. Include this in the problem report to the customer support. sqlstate: Snowflake SQL State code. timestamp_output_format: Snowflake timestamp_output_format for timestamps. timestamp_ltz_output_format: Snowflake output format for LTZ timestamps. timestamp_tz_output_format: Snowflake output format for TZ timestamps. timestamp_ntz_output_format: Snowflake output format for NTZ timestamps. date_output_format: Snowflake output format for dates. time_output_format: Snowflake output format for times. timezone: Snowflake timezone. binary_output_format: Snowflake output format for binary fields. arraysize: The default number of rows fetched by fetchmany. connection: The connection object by which the cursor was created. errorhandle: The class that handles error handling. is_file_transfer: Whether, or not the current command is a put, or get.
TODO: Most of these attributes have no reason to be properties, we could just store them in public variables. Calling a function is expensive in Python and most of these getters are unnecessary. """
PUT_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*put\s+", flags=re.IGNORECASE) GET_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*get\s+", flags=re.IGNORECASE) INSERT_SQL_RE = re.compile(r"^insert\s+into", flags=re.IGNORECASE) COMMENT_SQL_RE = re.compile(r"/\*.*\*/") INSERT_SQL_VALUES_RE = re.compile( r".*VALUES\s*(\(.*\)).*", re.IGNORECASE | re.MULTILINE | re.DOTALL ) ALTER_SESSION_RE = re.compile( r"alter\s+session\s+set\s+(.*)=\'?([^\']+)\'?\s*;", flags=re.IGNORECASE | re.MULTILINE | re.DOTALL, )
@staticmethod def get_file_transfer_type(sql: str) -> FileTransferType | None: """Decide whether a SQL is a file transfer and return its type.
None is returned if the SQL isn't a file transfer so that this function can be used in an if-statement. """ if SnowflakeCursor.PUT_SQL_RE.match(sql): return FileTransferType.PUT elif SnowflakeCursor.GET_SQL_RE.match(sql): return FileTransferType.GET return None
def __init__( self, connection: SnowflakeConnection, use_dict_result: bool = False, ) -> None: """Inits a SnowflakeCursor with a connection.
Args: connection: The connection that created this cursor. use_dict_result: Decides whether to use dict result or not. """ self._connection: SnowflakeConnection = connection
self._errorhandler: Callable[ [SnowflakeConnection, SnowflakeCursor, type[Error], dict[str, str]], None, ] = Error.default_errorhandler self.messages: list[ tuple[type[Error] | type[Exception], dict[str, str | bool]] ] = [] self._timebomb: Timer | None = None # must be here for abort_exit method self._description: list[ResultMetadata] | None = None self._column_idx_to_name = None self._sfqid = None self._sqlstate = None self._total_rowcount = -1 self._sequence_counter = -1 self._request_id = None self._is_file_transfer = False
self._timestamp_output_format = None self._timestamp_ltz_output_format = None self._timestamp_ntz_output_format = None self._timestamp_tz_output_format = None self._date_output_format = None self._time_output_format = None self._timezone = None self._binary_output_format = None self._result: Iterator[tuple] | Iterator[dict] | None = None self._result_set: ResultSet | None = None self._result_state: ResultState = ResultState.DEFAULT self._use_dict_result = use_dict_result self.query: str | None = None # TODO: self._query_result_format could be defined as an enum self._query_result_format: str | None = None
self._arraysize = 1 # PEP-0249: defaults to 1
self._lock_canceling = Lock()
self._first_chunk_time = None
self._log_max_query_length = connection.log_max_query_length self._inner_cursor: SnowflakeCursor | None = None self._prefetch_hook = None self._rownumber: int | None = None
self.reset()
def __del__(self) -> None: # pragma: no cover try: self.close() except compat.BASE_EXCEPTION_CLASS as e: if logger.getEffectiveLevel() <= logging.INFO: logger.info(e)
@property def description(self) -> list[ResultMetadata]: return self._description
@property def rowcount(self): return self._total_rowcount if self._total_rowcount >= 0 else None
@property def rownumber(self): return self._rownumber if self._rownumber >= 0 else None
@property def sfqid(self): return self._sfqid
@property def sqlstate(self): return self._sqlstate
@property def timestamp_output_format(self): return self._timestamp_output_format
@property def timestamp_ltz_output_format(self): return ( self._timestamp_ltz_output_format if self._timestamp_ltz_output_format else self._timestamp_output_format )
@property def timestamp_tz_output_format(self): return ( self._timestamp_tz_output_format if self._timestamp_tz_output_format else self._timestamp_output_format )
@property def timestamp_ntz_output_format(self): return ( self._timestamp_ntz_output_format if self._timestamp_ntz_output_format else self._timestamp_output_format )
@property def date_output_format(self): return self._date_output_format
@property def time_output_format(self): return self._time_output_format
@property def timezone(self): return self._timezone
@property def binary_output_format(self): return self._binary_output_format
@property def arraysize(self): return self._arraysize
@arraysize.setter def arraysize(self, value): self._arraysize = int(value)
@property def connection(self): return self._connection
@property def errorhandler(self): return self._errorhandler
@errorhandler.setter def errorhandler(self, value): logger.debug("setting errorhandler: %s", value) if value is None: raise ProgrammingError("Invalid errorhandler is specified") self._errorhandler = value
@property def is_file_transfer(self): """Whether the command is PUT or GET.""" return hasattr(self, "_is_file_transfer") and self._is_file_transfer
@property def lastrowid(self) -> None: """Snowflake does not support lastrowid in which case None should be returned as per PEP249.""" return None
def callproc(self, procname: str, args: T = ()) -> T: """Call a stored procedure.
Args: procname: The stored procedure to be called. args: Parameters to be passed into the stored procedure.
Returns: The input parameters. """ marker_format = "%s" if self._connection.is_pyformat else "?" command = ( f"CALL {procname}({', '.join([marker_format for _ in range(len(args))])})" ) self.execute(command, args) return args
def close(self) -> bool | None: """Closes the cursor object.
Returns whether the cursor was closed during this call. """ try: if self.is_closed(): return False
with self._lock_canceling: self.reset(closing=True) self._connection = None del self.messages[:] return True except Exception: pass
def is_closed(self): return self._connection is None or self._connection.is_closed()
def _execute_helper( self, query: str, timeout: int = 0, statement_params: dict[str, str] | None = None, binding_params: tuple | dict[str, dict[str, str]] = None, binding_stage: str | None = None, is_internal: bool = False, describe_only: bool = False, _no_results: bool = False, _is_put_get=None, _no_retry: bool = False, ): del self.messages[:]
if statement_params is not None and not isinstance(statement_params, dict): Error.errorhandler_wrapper( self.connection, self, ProgrammingError, { "msg": "The data type of statement params is invalid. It must be dict.", "errno": ER_INVALID_VALUE, }, )
# check if current installation include arrow extension or not, # if not, we set statement level query result format to be JSON if not CAN_USE_ARROW_RESULT_FORMAT: logger.debug("Cannot use arrow result format, fallback to json format") if statement_params is None: statement_params = { PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON" } else: result_format_val = statement_params.get( PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT ) if str(result_format_val).upper() == "ARROW": self.check_can_use_arrow_resultset() elif result_format_val is None: statement_params[ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT ] = "JSON"
self._sequence_counter = self._connection._next_sequence_counter() self._request_id = uuid.uuid4()
logger.debug(f"Request id: {self._request_id}")
logger.debug("running query [%s]", self._format_query_for_log(query)) if _is_put_get is not None: # if told the query is PUT or GET, use the information self._is_file_transfer = _is_put_get else: # or detect it. self._is_file_transfer = self.PUT_SQL_RE.match( query ) or self.GET_SQL_RE.match(query) logger.debug("is_file_transfer: %s", self._is_file_transfer is not None)
real_timeout = ( timeout if timeout and timeout > 0 else self._connection.network_timeout )
if real_timeout is not None: self._timebomb = Timer(real_timeout, self.__cancel_query, [query]) self._timebomb.start() logger.debug("started timebomb in %ss", real_timeout) else: self._timebomb = None
original_sigint = signal.getsignal(signal.SIGINT)
def interrupt_handler(*_): # pragma: no cover try: signal.signal(signal.SIGINT, exit_handler) except (ValueError, TypeError): # ignore failures pass try: if self._timebomb is not None: self._timebomb.cancel() logger.debug("cancelled timebomb in finally") self._timebomb = None self.__cancel_query(query) finally: if original_sigint: try: signal.signal(signal.SIGINT, original_sigint) except (ValueError, TypeError): # ignore failures pass raise KeyboardInterrupt
try: if not original_sigint == exit_handler: signal.signal(signal.SIGINT, interrupt_handler) except ValueError: # pragma: no cover logger.debug( "Failed to set SIGINT handler. " "Not in main thread. Ignored..." ) ret = {"data": {}} try: ret = self._connection.cmd_query( query, self._sequence_counter, self._request_id, binding_params=binding_params, binding_stage=binding_stage, is_file_transfer=bool(self._is_file_transfer), statement_params=statement_params, is_internal=is_internal, describe_only=describe_only, _no_results=_no_results, _no_retry=_no_retry, ) finally: try: if original_sigint: signal.signal(signal.SIGINT, original_sigint) except (ValueError, TypeError): # pragma: no cover logger.debug( "Failed to reset SIGINT handler. Not in main " "thread. Ignored..." ) if self._timebomb is not None: self._timebomb.cancel() logger.debug("cancelled timebomb in finally")
if "data" in ret and "parameters" in ret["data"]: parameters = ret["data"]["parameters"] # Set session parameters for cursor object for kv in parameters: if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]: self._timestamp_output_format = kv["value"] if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_ntz_output_format = kv["value"] if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_ltz_output_format = kv["value"] if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_tz_output_format = kv["value"] if "DATE_OUTPUT_FORMAT" in kv["name"]: self._date_output_format = kv["value"] if "TIME_OUTPUT_FORMAT" in kv["name"]: self._time_output_format = kv["value"] if "TIMEZONE" in kv["name"]: self._timezone = kv["value"] if "BINARY_OUTPUT_FORMAT" in kv["name"]: self._binary_output_format = kv["value"] # Set session parameters for connection object self._connection._update_parameters( {p["name"]: p["value"] for p in parameters} )
self.query = query self._sequence_counter = -1 return ret
def execute( self, command: str, params: Sequence[Any] | dict[Any, Any] | None = None, _bind_stage: str | None = None, timeout: int | None = None, _exec_async: bool = False, _no_retry: bool = False, _do_reset: bool = True, _put_callback: SnowflakeProgressPercentage = None, _put_azure_callback: SnowflakeProgressPercentage = None, _put_callback_output_stream: IO[str] = sys.stdout, _get_callback: SnowflakeProgressPercentage = None, _get_azure_callback: SnowflakeProgressPercentage = None, _get_callback_output_stream: IO[str] = sys.stdout, _show_progress_bar: bool = True, _statement_params: dict[str, str] | None = None, _is_internal: bool = False, _describe_only: bool = False, _no_results: bool = False, _is_put_get: bool | None = None, _raise_put_get_error: bool = True, _force_put_overwrite: bool = False, file_stream: IO[bytes] | None = None, ) -> SnowflakeCursor | None: """Executes a command/query.
Args: command: The SQL command to be executed. params: Parameters to be bound into the SQL statement. _bind_stage: Path in temporary stage where binding parameters are uploaded as CSV files. timeout: Number of seconds after which to abort the query. _exec_async: Whether to execute this query asynchronously. _no_retry: Whether or not to retry on known errors. _do_reset: Whether or not the result set needs to be reset before executing query. _put_callback: Function to which GET command should call back to. _put_azure_callback: Function to which an Azure GET command should call back to. _put_callback_output_stream: The output stream a PUT command's callback should report on. _get_callback: Function to which GET command should call back to. _get_azure_callback: Function to which an Azure GET command should call back to. _get_callback_output_stream: The output stream a GET command's callback should report on. _show_progress_bar: Whether or not to show progress bar. _statement_params: Extra information that should be sent to Snowflake with query. _is_internal: This flag indicates whether the query is issued internally by the connector. _describe_only: If true, the query will not be executed but return the schema/description of this query. _no_results: This flag tells the back-end to not return the result, just fire the query and return the response returned by Snowflake's server. _use_ijson: This flag doesn't do anything as ijson support has ended. _is_put_get: Force decision of this SQL query being a PUT, or GET command. This is detected otherwise. _raise_put_get_error: Whether to raise PUT and GET errors. _force_put_overwrite: If the SQL query is a PUT, then this flag can force overwriting of an already existing file on stage. file_stream: File-like object to be uploaded with PUT
Returns: The cursor itself, or None if some error happened, or the response returned by Snowflake if the _no_results flag is on. """ if _exec_async: _no_results = True logger.debug("executing SQL/command") if self.is_closed(): Error.errorhandler_wrapper( self.connection, self, InterfaceError, {"msg": "Cursor is closed in execute.", "errno": ER_CURSOR_IS_CLOSED}, )
if _do_reset: self.reset() command = command.strip(" \t\n\r") if command else None if not command: logger.warning("execute: no query is given to execute") return
kwargs = { "timeout": timeout, "statement_params": _statement_params, "is_internal": _is_internal, "describe_only": _describe_only, "_no_results": _no_results, "_is_put_get": _is_put_get, "_no_retry": _no_retry, }
if self._connection.is_pyformat: # pyformat/format paramstyle # client side binding processed_params = self._connection._process_params_pyformat(params, self) # SNOW-513061 collect telemetry for empty sequence usage before we make the breaking change announcement if params is not None and len(params) == 0: self._log_telemetry_job_data( TelemetryField.EMPTY_SEQ_INTERPOLATION, TelemetryData.TRUE if self.connection._interpolate_empty_sequences else TelemetryData.FALSE, ) if logger.getEffectiveLevel() <= logging.DEBUG: logger.debug( f"binding: [{self._format_query_for_log(command)}] " f"with input=[{params}], " f"processed=[{processed_params}]", ) if ( self.connection._interpolate_empty_sequences and processed_params is not None ) or ( not self.connection._interpolate_empty_sequences and len(processed_params) > 0 ): query = command % processed_params else: query = command else: # qmark and numeric paramstyle query = command if _bind_stage: kwargs["binding_stage"] = _bind_stage else: if params is not None and not isinstance(params, (list, tuple)): errorvalue = { "msg": f"Binding parameters must be a list: {params}", "errno": ER_FAILED_PROCESSING_PYFORMAT, } Error.errorhandler_wrapper( self.connection, self, ProgrammingError, errorvalue )
kwargs["binding_params"] = self._connection._process_params_qmarks( params, self )
m = DESC_TABLE_RE.match(query) if m: query1 = f"describe table {m.group(1)}" if logger.getEffectiveLevel() <= logging.WARNING: logger.info( "query was rewritten: org=%s, new=%s", " ".join(line.strip() for line in query.split("\n")), query1, ) query = query1
if logger.getEffectiveLevel() <= logging.INFO: logger.info("query: [%s]", self._format_query_for_log(query)) ret = self._execute_helper(query, **kwargs) self._sfqid = ( ret["data"]["queryId"] if "data" in ret and "queryId" in ret["data"] else None ) self._sqlstate = ( ret["data"]["sqlState"] if "data" in ret and "sqlState" in ret["data"] else None ) self._first_chunk_time = get_time_millis()
# if server gives a send time, log the time it took to arrive if "data" in ret and "sendResultTime" in ret["data"]: time_consume_first_result = ( self._first_chunk_time - ret["data"]["sendResultTime"] ) self._log_telemetry_job_data( TelemetryField.TIME_CONSUME_FIRST_RESULT, time_consume_first_result ) logger.debug("sfqid: %s", self.sfqid)
logger.info("query execution done") if ret["success"]: logger.debug("SUCCESS") data = ret["data"]
logger.debug("PUT OR GET: %s", self.is_file_transfer) if self.is_file_transfer: # Decide whether to use the old, or new code path sf_file_transfer_agent = SnowflakeFileTransferAgent( self, query, ret, put_callback=_put_callback, put_azure_callback=_put_azure_callback, put_callback_output_stream=_put_callback_output_stream, get_callback=_get_callback, get_azure_callback=_get_azure_callback, get_callback_output_stream=_get_callback_output_stream, show_progress_bar=_show_progress_bar, raise_put_get_error=_raise_put_get_error, force_put_overwrite=_force_put_overwrite or data.get("overwrite", False), source_from_stream=file_stream, multipart_threshold=data.get("threshold"), use_s3_regional_url=self._connection.enable_stage_s3_privatelink_for_us_east_1, ) sf_file_transfer_agent.execute() data = sf_file_transfer_agent.result() self._total_rowcount = len(data["rowset"]) if "rowset" in data else -1 m = self.ALTER_SESSION_RE.match(query) if m: # session parameters param = m.group(1).upper() value = m.group(2) self._connection.converter.set_parameter(param, value)
if _exec_async: self.connection._async_sfqids[self._sfqid] = None if _no_results: self._total_rowcount = ( ret["data"]["total"] if "data" in ret and "total" in ret["data"] else -1 ) return data self._init_result_and_meta(data) else: self._total_rowcount = ( ret["data"]["total"] if "data" in ret and "total" in ret["data"] else -1 ) logger.debug(ret) err = ret["message"] code = ret.get("code", -1) if "data" in ret: err += ret["data"].get("errorMessage", "") errvalue = { "msg": err, "errno": int(code), "sqlstate": self._sqlstate, "sfqid": self._sfqid, } is_integrity_error = ( code == "100072" ) # NULL result in a non-nullable column error_class = IntegrityError if is_integrity_error else ProgrammingError Error.errorhandler_wrapper(self.connection, self, error_class, errvalue) return self
def execute_async(self, *args, **kwargs): """Convenience function to execute a query without waiting for results (asynchronously).
This function takes the same arguments as execute, please refer to that function for documentation. """ kwargs["_exec_async"] = True return self.execute(*args, **kwargs)
def describe(self, *args, **kwargs) -> list[ResultMetadata]: """Obtain the schema of the result without executing the query.
This function takes the same arguments as execute, please refer to that function for documentation.
Returns: The schema of the result. """ kwargs["_describe_only"] = kwargs["_is_internal"] = True self.execute(*args, **kwargs) return self._description
def _format_query_for_log(self, query): return self._connection._format_query_for_log(query)
def _is_dml(self, data): return ( "statementTypeId" in data and int(data["statementTypeId"]) in STATEMENT_TYPE_ID_DML_SET )
def _init_result_and_meta(self, data): is_dml = self._is_dml(data) self._query_result_format = data.get("queryResultFormat", "json") logger.debug("Query result format: %s", self._query_result_format)
if self._total_rowcount == -1 and not is_dml and data.get("total") is not None: self._total_rowcount = data["total"]
self._description: list[ResultMetadata] = [ ResultMetadata.from_column(col) for col in data["rowtype"] ]
result_chunks = create_batches_from_response( self, self._query_result_format, data, self._description )
if not (is_dml or self.is_file_transfer): logger.info( "Number of results in first chunk: %s", result_chunks[0].rowcount )
self._result_set = ResultSet( self, result_chunks, self._connection.client_prefetch_threads, ) self._rownumber = -1 self._result_state = ResultState.VALID
# don't update the row count when the result is returned from `describe` method if is_dml and "rowset" in data and len(data["rowset"]) > 0: updated_rows = 0 for idx, desc in enumerate(self._description): if desc[0] in ( "number of rows updated", "number of multi-joined rows updated", "number of rows deleted", ) or desc[0].startswith("number of rows inserted"): updated_rows += int(data["rowset"][0][idx]) if self._total_rowcount == -1: self._total_rowcount = updated_rows else: self._total_rowcount += updated_rows
def check_can_use_arrow_resultset(self): global CAN_USE_ARROW_RESULT_FORMAT
if not CAN_USE_ARROW_RESULT_FORMAT: if self._connection.application == "SnowSQL": msg = "Currently SnowSQL doesn't support the result set in Apache Arrow format." errno = ER_NO_PYARROW_SNOWSQL else: msg = "The result set in Apache Arrow format is not supported for the platform." errno = ER_NO_ARROW_RESULT
Error.errorhandler_wrapper( self.connection, self, ProgrammingError, { "msg": msg, "errno": errno, }, )
def check_can_use_pandas(self): if not installed_pandas: msg = ( "Optional dependency: 'pandas' is not installed, please see the following link for install " "instructions: https://docs.snowflake.com/en/user-guide/python-connector-pandas.html#installation" ) errno = ER_NO_PYARROW
Error.errorhandler_wrapper( self.connection, self, ProgrammingError, { "msg": msg, "errno": errno, }, )
def query_result(self, qid): url = f"/queries/{qid}/result" ret = self._connection.rest.request(url=url, method="get") self._sfqid = ( ret["data"]["queryId"] if "data" in ret and "queryId" in ret["data"] else None ) self._sqlstate = ( ret["data"]["sqlState"] if "data" in ret and "sqlState" in ret["data"] else None ) logger.debug("sfqid=%s", self._sfqid)
if ret.get("success"): data = ret.get("data") self._init_result_and_meta(data) else: logger.info("failed") logger.debug(ret) err = ret["message"] code = ret.get("code", -1) if "data" in ret: err += ret["data"].get("errorMessage", "") errvalue = { "msg": err, "errno": int(code), "sqlstate": self._sqlstate, "sfqid": self._sfqid, } Error.errorhandler_wrapper( self.connection, self, ProgrammingError, errvalue ) return self
def fetch_arrow_batches(self) -> Iterator[Table]: self.check_can_use_arrow_resultset() if self._query_result_format != "arrow": raise NotSupportedError self._log_telemetry_job_data( TelemetryField.ARROW_FETCH_BATCHES, TelemetryData.TRUE ) return self._result_set._fetch_arrow_batches()
def fetch_arrow_all(self) -> Table | None: self.check_can_use_arrow_resultset() if self._query_result_format != "arrow": raise NotSupportedError self._log_telemetry_job_data(TelemetryField.ARROW_FETCH_ALL, TelemetryData.TRUE) return self._result_set._fetch_arrow_all()
def fetch_pandas_batches(self, **kwargs) -> Iterator[pandas.DataFrame]: """Fetches a single Arrow Table.""" self.check_can_use_pandas() if self._prefetch_hook is not None: self._prefetch_hook() if self._query_result_format != "arrow": raise NotSupportedError self._log_telemetry_job_data( TelemetryField.PANDAS_FETCH_BATCHES, TelemetryData.TRUE ) return self._result_set._fetch_pandas_batches(**kwargs)
def fetch_pandas_all(self, **kwargs) -> pandas.DataFrame: """Fetch Pandas dataframes in batches, where 'batch' refers to Snowflake Chunk.""" self.check_can_use_pandas() if self._prefetch_hook is not None: self._prefetch_hook() if self._query_result_format != "arrow": raise NotSupportedError self._log_telemetry_job_data( TelemetryField.PANDAS_FETCH_ALL, TelemetryData.TRUE ) return self._result_set._fetch_pandas_all(**kwargs)
def abort_query(self, qid): url = f"/queries/{qid}/abort-request" ret = self._connection.rest.request(url=url, method="post") return ret.get("success")
def executemany( self, command: str, seqparams: Sequence[Any] | dict[str, Any], **kwargs: dict[str, Any], ) -> SnowflakeCursor: """Executes a command/query with the given set of parameters sequentially.""" logger.debug("executing many SQLs/commands") command = command.strip(" \t\n\r") if command else None
if not seqparams: return self
if self.INSERT_SQL_RE.match(command): if self._connection.is_pyformat: logger.debug("rewriting INSERT query") command_wo_comments = re.sub(self.COMMENT_SQL_RE, "", command) m = self.INSERT_SQL_VALUES_RE.match(command_wo_comments) if not m: Error.errorhandler_wrapper( self.connection, self, InterfaceError, { "msg": "Failed to rewrite multi-row insert", "errno": ER_FAILED_TO_REWRITE_MULTI_ROW_INSERT, }, )
fmt = m.group(1) values = [] for param in seqparams: logger.debug(f"parameter: {param}") values.append( fmt % self._connection._process_params_pyformat(param, self) ) command = command.replace(fmt, ",".join(values), 1) self.execute(command, **kwargs) return self else: logger.debug("bulk insert") # sanity check row_size = len(seqparams[0]) for row in seqparams: if len(row) != row_size: error_value = { "msg": f"Bulk data size don't match. expected: {row_size}, " f"got: {len(row)}, command: {command}", "errno": ER_INVALID_VALUE, } Error.errorhandler_wrapper( self.connection, self, InterfaceError, error_value ) return self bind_size = len(seqparams) * row_size bind_stage = None if ( bind_size > self.connection._session_parameters[ "CLIENT_STAGE_ARRAY_BINDING_THRESHOLD" ] > 0 ): # bind stage optimization try: rows = self.connection._write_params_to_byte_rows(seqparams) bind_uploader = BindUploadAgent(self, rows) bind_uploader.upload() bind_stage = bind_uploader.stage_path except BindUploadError: logger.debug( "Failed to upload binds to stage, sending binds to " "Snowflake instead." ) binding_param = ( None if bind_stage else list(map(list, zip(*seqparams))) ) # transpose self.execute( command, params=binding_param, _bind_stage=bind_stage, **kwargs ) return self
self.reset() for param in seqparams: self.execute(command, params=param, _do_reset=False, **kwargs) return self
def _result_iterator( self, ) -> Generator[dict, None, None] | Generator[tuple, None, None]: """Yields the elements from _result and raises an exception when appropriate.""" try: for _next in self._result: if isinstance(_next, Exception): Error.errorhandler_wrapper_from_ready_exception( self._connection, self, _next, ) self._rownumber += 1 yield _next except TypeError as err: if self._result_state == ResultState.DEFAULT: raise err else: yield None
def fetchone(self) -> dict | tuple | None: """Fetches one row.""" if self._prefetch_hook is not None: self._prefetch_hook() if self._result is None and self._result_set is not None: self._result = iter(self._result_set) self._result_state = ResultState.VALID try: return next(self._result_iterator()) except StopIteration: return None
def fetchmany(self, size=None): """Fetches the number of specified rows.""" if size is None: size = self.arraysize
if size < 0: errorvalue = { "msg": ( "The number of rows is not zero or " "positive number: {}" ).format(size), "errno": ER_NOT_POSITIVE_SIZE, } Error.errorhandler_wrapper( self.connection, self, ProgrammingError, errorvalue ) ret = [] while size > 0: row = self.fetchone() if row is None: break ret.append(row) if size is not None: size -= 1
return ret
def fetchall(self) -> list[tuple] | list[dict]: """Fetches all of the results.""" ret = [] while True: row = self.fetchone() if row is None: break ret.append(row) return ret
def nextset(self): """Not supported.""" logger.debug("nop") return None
def setinputsizes(self, _): """Not supported.""" logger.debug("nop")
def setoutputsize(self, _, column=None): """Not supported.""" del column logger.debug("nop")
def scroll(self, value, mode="relative"): Error.errorhandler_wrapper( self.connection, self, NotSupportedError, { "msg": "scroll is not supported.", "errno": ER_UNSUPPORTED_METHOD, "sqlstate": SQLSTATE_FEATURE_NOT_SUPPORTED, }, )
def reset(self, closing=False): """Resets the result set.""" # SNOW-647539: Do not erase the rowcount # information when closing the cursor if not closing: self._total_rowcount = -1 if self._result_state != ResultState.DEFAULT: self._result_state = ResultState.RESET if self._result is not None: self._result = None if self._inner_cursor is not None: self._inner_cursor.reset(closing=closing) self._result = None self._inner_cursor = None self._prefetch_hook = None if not self.connection._reuse_results: self._result_set = None
def __iter__(self) -> Iterator[dict] | Iterator[tuple]: """Iteration over the result set.""" # set _result if _result_set is not None if self._result is None and self._result_set is not None: self._result = iter(self._result_set) self._result_state = ResultState.VALID return self._result_iterator()
def __cancel_query(self, query): if self._sequence_counter >= 0 and not self.is_closed(): logger.debug("canceled. %s, request_id: %s", query, self._request_id) with self._lock_canceling: self._connection._cancel_query(query, self._request_id)
def _log_telemetry_job_data( self, telemetry_field: TelemetryField, value: Any ) -> None: """Builds an instance of TelemetryData with the given field and logs it.""" ts = get_time_millis() try: self._connection._log_telemetry( TelemetryData.from_telemetry_data_dict( from_dict={ TelemetryField.KEY_TYPE.value: telemetry_field.value, TelemetryField.KEY_SFQID.value: self._sfqid, TelemetryField.KEY_VALUE.value: value, }, timestamp=ts, connection=self._connection, ) ) except AttributeError: logger.warning( "Cursor failed to log to telemetry. Connection object may be None.", exc_info=True, )
def __enter__(self): """Context manager.""" return self
def __exit__(self, exc_type, exc_val, exc_tb): """Context manager with commit or rollback.""" self.close()
def get_results_from_sfqid(self, sfqid: str): """Gets the results from previously ran query."""
def wait_until_ready(): """Makes sure query has finished executing and once it has retrieves results.""" no_data_counter = 0 retry_pattern_pos = 0 while True: status = self.connection.get_query_status(sfqid) if not self.connection.is_still_running(status): break if status == QueryStatus.NO_DATA: # pragma: no cover no_data_counter += 1 if no_data_counter > ASYNC_NO_DATA_MAX_RETRY: raise DatabaseError( "Cannot retrieve data on the status of this query. No information returned " "from server for query '{}'" ) time.sleep( 0.5 * ASYNC_RETRY_PATTERN[retry_pattern_pos] ) # Same wait as JDBC # If we can advance in ASYNC_RETRY_PATTERN then do so if retry_pattern_pos < (len(ASYNC_RETRY_PATTERN) - 1): retry_pattern_pos += 1 if status != QueryStatus.SUCCESS: raise DatabaseError( "Status of query '{}' is {}, results are unavailable".format( sfqid, status.name ) ) self._inner_cursor.execute(f"select * from table(result_scan('{sfqid}'))") self._result = self._inner_cursor._result self._query_result_format = self._inner_cursor._query_result_format self._total_rowcount = self._inner_cursor._total_rowcount self._description = self._inner_cursor._description self._result_set = self._inner_cursor._result_set self._result_state = ResultState.VALID self._rownumber = 0 # Unset this function, so that we don't block anymore self._prefetch_hook = None
self.connection.get_query_status_throw_if_error( sfqid ) # Trigger an exception if query failed klass = self.__class__ self._inner_cursor = klass(self.connection) self._sfqid = sfqid self._prefetch_hook = wait_until_ready
def get_result_batches(self) -> list[ResultBatch] | None: """Get the previously executed query's ``ResultBatch`` s if available.
If they are unavailable, in case nothing has been executed yet None will be returned.
For a detailed description of ``ResultBatch`` s please see the docstring of: ``snowflake.connector.result_batches.ResultBatch`` """ if self._result_set is None: return None self._log_telemetry_job_data( TelemetryField.GET_PARTITIONS_USED, TelemetryData.TRUE ) return self._result_set.batches```
## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor.get_file_transfer_type` (lines 198-209)
```python def get_file_transfer_type(sql: str) -> FileTransferType | None: """Decide whether a SQL is a file transfer and return its type.
None is returned if the SQL isn't a file transfer so that this function can be used in an if-statement. """ if SnowflakeCursor.PUT_SQL_RE.match(sql): return FileTransferType.PUT elif SnowflakeCursor.GET_SQL_RE.match(sql): return FileTransferType.GET return None```
## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor._execute_helper` (lines 411-567)
```python def _execute_helper( self, query: str, timeout: int = 0, statement_params: dict[str, str] | None = None, binding_params: tuple | dict[str, dict[str, str]] = None, binding_stage: str | None = None, is_internal: bool = False, describe_only: bool = False, _no_results: bool = False, _is_put_get=None, _no_retry: bool = False, ): del self.messages[:]
if statement_params is not None and not isinstance(statement_params, dict): Error.errorhandler_wrapper( self.connection, self, ProgrammingError, { "msg": "The data type of statement params is invalid. It must be dict.", "errno": ER_INVALID_VALUE, }, )
# check if current installation include arrow extension or not, # if not, we set statement level query result format to be JSON if not CAN_USE_ARROW_RESULT_FORMAT: logger.debug("Cannot use arrow result format, fallback to json format") if statement_params is None: statement_params = { PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON" } else: result_format_val = statement_params.get( PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT ) if str(result_format_val).upper() == "ARROW": self.check_can_use_arrow_resultset() elif result_format_val is None: statement_params[ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT ] = "JSON"
self._sequence_counter = self._connection._next_sequence_counter() self._request_id = uuid.uuid4()
logger.debug(f"Request id: {self._request_id}")
logger.debug("running query [%s]", self._format_query_for_log(query)) if _is_put_get is not None: # if told the query is PUT or GET, use the information self._is_file_transfer = _is_put_get else: # or detect it. self._is_file_transfer = self.PUT_SQL_RE.match( query ) or self.GET_SQL_RE.match(query) logger.debug("is_file_transfer: %s", self._is_file_transfer is not None)
real_timeout = ( timeout if timeout and timeout > 0 else self._connection.network_timeout )
if real_timeout is not None: self._timebomb = Timer(real_timeout, self.__cancel_query, [query]) self._timebomb.start() logger.debug("started timebomb in %ss", real_timeout) else: self._timebomb = None
original_sigint = signal.getsignal(signal.SIGINT)
def interrupt_handler(*_): # pragma: no cover try: signal.signal(signal.SIGINT, exit_handler) except (ValueError, TypeError): # ignore failures pass try: if self._timebomb is not None: self._timebomb.cancel() logger.debug("cancelled timebomb in finally") self._timebomb = None self.__cancel_query(query) finally: if original_sigint: try: signal.signal(signal.SIGINT, original_sigint) except (ValueError, TypeError): # ignore failures pass raise KeyboardInterrupt
try: if not original_sigint == exit_handler: signal.signal(signal.SIGINT, interrupt_handler) except ValueError: # pragma: no cover logger.debug( "Failed to set SIGINT handler. " "Not in main thread. Ignored..." ) ret = {"data": {}} try: ret = self._connection.cmd_query( query, self._sequence_counter, self._request_id, binding_params=binding_params, binding_stage=binding_stage, is_file_transfer=bool(self._is_file_transfer), statement_params=statement_params, is_internal=is_internal, describe_only=describe_only, _no_results=_no_results, _no_retry=_no_retry, ) finally: try: if original_sigint: signal.signal(signal.SIGINT, original_sigint) except (ValueError, TypeError): # pragma: no cover logger.debug( "Failed to reset SIGINT handler. Not in main " "thread. Ignored..." ) if self._timebomb is not None: self._timebomb.cancel() logger.debug("cancelled timebomb in finally")
if "data" in ret and "parameters" in ret["data"]: parameters = ret["data"]["parameters"] # Set session parameters for cursor object for kv in parameters: if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]: self._timestamp_output_format = kv["value"] if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_ntz_output_format = kv["value"] if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_ltz_output_format = kv["value"] if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]: self._timestamp_tz_output_format = kv["value"] if "DATE_OUTPUT_FORMAT" in kv["name"]: self._date_output_format = kv["value"] if "TIME_OUTPUT_FORMAT" in kv["name"]: self._time_output_format = kv["value"] if "TIMEZONE" in kv["name"]: self._timezone = kv["value"] if "BINARY_OUTPUT_FORMAT" in kv["name"]: self._binary_output_format = kv["value"] # Set session parameters for connection object self._connection._update_parameters( {p["name"]: p["value"] for p in parameters} )
self.query = query self._sequence_counter = -1 return ret```
## `src/snowflake/connector/cursor.py` — `module:<module>@35` (lines 35-35)
```pythonfrom .bind_upload_agent import BindUploadAgent, BindUploadError```
## `src/snowflake/connector/gcs_storage_client.py` — `class:SnowflakeGCSRestClient` (lines 47-396)
```pythonclass SnowflakeGCSRestClient(SnowflakeStorageClient): def __init__( self, meta: SnowflakeFileMeta, credentials: StorageCredential, stage_info: dict[str, Any], cnx: SnowflakeConnection, command: str, use_s3_regional_url=False, ) -> None: """Creates a client object with given stage credentials.
Args: stage_info: Access credentials and info of a stage.
Returns: The client to communicate with GCS. """ super().__init__( meta, stage_info, -1, credentials=credentials, chunked_transfer=False ) self.stage_info = stage_info self._command = command self.meta = meta self._cursor = cnx.cursor() # presigned_url in meta is for downloading self.presigned_url: str = meta.presigned_url or stage_info.get("presignedUrl") self.security_token = credentials.creds.get("GCS_ACCESS_TOKEN")
if self.security_token: logger.debug(f"len(GCS_ACCESS_TOKEN): {len(self.security_token)}") else: logger.debug("No access token received from GS, requesting presigned url") self._update_presigned_url()
def _has_expired_token(self, response: requests.Response) -> bool: return self.security_token and response.status_code == 401
def _has_expired_presigned_url(self, response: requests.Response) -> bool: # Presigned urls can be generated for any xml-api operation # offered by GCS. Hence the error codes expected are similar # to xml api. # https://cloud.google.com/storage/docs/xml-api/reference-status
presigned_url_expired = ( not self.security_token ) and response.status_code == 400 if presigned_url_expired and self.last_err_is_presigned_url: logger.debug("Presigned url expiration error two times in a row.") response.raise_for_status() self.last_err_is_presigned_url = presigned_url_expired return presigned_url_expired
def _upload_chunk(self, chunk_id: int, chunk: bytes) -> None: meta = self.meta
content_encoding = "" if meta.dst_compression_type is not None: content_encoding = meta.dst_compression_type.name.lower()
# We set the contentEncoding to blank for GZIP files. We don't # want GCS to think our gzip files are gzips because it makes # them download uncompressed, and none of the other providers do # that. There's essentially no way for us to prevent that # behavior. Bad Google. if content_encoding and content_encoding == "gzip": content_encoding = ""
gcs_headers = { HTTP_HEADER_CONTENT_ENCODING: content_encoding, GCS_METADATA_SFC_DIGEST: meta.sha256_digest, }
if self.encryption_metadata: gcs_headers.update( { GCS_METADATA_ENCRYPTIONDATAPROP: json.dumps( { "EncryptionMode": "FullBlob", "WrappedContentKey": { "KeyId": "symmKey1", "EncryptedKey": self.encryption_metadata.key, "Algorithm": "AES_CBC_256", }, "EncryptionAgent": { "Protocol": "1.0", "EncryptionAlgorithm": "AES_CBC_256", }, "ContentEncryptionIV": self.encryption_metadata.iv, "KeyWrappingMetadata": {"EncryptionLibrary": "Java 5.3.0"}, } ), GCS_METADATA_MATDESC_KEY: self.encryption_metadata.matdesc, } )
def generate_url_and_rest_args() -> tuple[ str, dict[str, dict[str | Any, str | None] | bytes] ]: if not self.presigned_url: upload_url = self.generate_file_url( self.stage_info["location"], meta.dst_file_name.lstrip("/") ) access_token = self.security_token else: upload_url = self.presigned_url access_token: str | None = None if access_token: gcs_headers.update({"Authorization": f"Bearer {access_token}"}) rest_args = {"headers": gcs_headers, "data": chunk} return upload_url, rest_args
response = self._send_request_with_retry( "PUT", generate_url_and_rest_args, chunk_id ) response.raise_for_status() meta.gcs_file_header_digest = gcs_headers[GCS_METADATA_SFC_DIGEST] meta.gcs_file_header_content_length = meta.upload_size meta.gcs_file_header_encryption_metadata = json.loads( gcs_headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, "null") )
def download_chunk(self, chunk_id: int) -> None: meta = self.meta
def generate_url_and_rest_args() -> tuple[ str, dict[str, dict[str, str] | bool] ]: gcs_headers = {} if not self.presigned_url: download_url = self.generate_file_url( self.stage_info["location"], meta.src_file_name.lstrip("/") ) access_token = self.security_token gcs_headers["Authorization"] = f"Bearer {access_token}" else: download_url = self.presigned_url rest_args = {"headers": gcs_headers, "stream": True} return download_url, rest_args
response = self._send_request_with_retry( "GET", generate_url_and_rest_args, chunk_id ) response.raise_for_status()
self.write_downloaded_chunk(chunk_id, response.content)
encryption_metadata = None
if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None): encryptiondata = json.loads( response.headers[GCS_METADATA_ENCRYPTIONDATAPROP] )
if encryptiondata: encryption_metadata = EncryptionMetadata( key=encryptiondata["WrappedContentKey"]["EncryptedKey"], iv=encryptiondata["ContentEncryptionIV"], matdesc=response.headers[GCS_METADATA_MATDESC_KEY] if GCS_METADATA_MATDESC_KEY in response.headers else None, )
meta.gcs_file_header_digest = response.headers.get(GCS_METADATA_SFC_DIGEST) meta.gcs_file_header_content_length = len(response.content) meta.gcs_file_header_encryption_metadata = encryption_metadata
def finish_download(self) -> None: super().finish_download() # Sadly, we can only determine the src file size after we've # downloaded it, unlike the other cloud providers where the # metadata can be read beforehand. self.meta.src_file_size = os.path.getsize(self.intermediate_dst_path)
def _update_presigned_url(self) -> None: """Updates the file metas with presigned urls if any.
Currently only the file metas generated for PUT/GET on a GCP account need the presigned urls. """ logger.debug("Updating presigned url")
# Rewrite the command such that a new PUT call is made for each file # represented by the regex (if present) separately. This is the only # way to get the presigned url for that file. file_path_to_be_replaced = self._get_local_file_path_from_put_command()
if not file_path_to_be_replaced: # This prevents GET statements to proceed return
# At this point the connector has already figured out and # validated that the local file exists and has also decided # upon the destination file name and the compression type. # The only thing that's left to do is to get the presigned # url for the destination file. If the command originally # referred to a single file, then the presigned url got in # that case is simply ignore, since the file name is not what # we want.
# GS only looks at the file name at the end of local file # path to figure out the remote object name. Hence the prefix # for local path is not necessary in the reconstructed command. file_path_to_replace_with = self.meta.dst_file_name command_with_single_file = self._command command_with_single_file = command_with_single_file.replace( file_path_to_be_replaced, file_path_to_replace_with )
logger.debug("getting presigned url for %s", file_path_to_replace_with) ret = self._cursor._execute_helper(command_with_single_file)
stage_info = ret.get("data", dict()).get("stageInfo", dict()) self.meta.presigned_url = stage_info.get("presignedUrl") self.presigned_url = stage_info.get("presignedUrl")
def _get_local_file_path_from_put_command(self) -> str | None: """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita).
Args: command: Command to be parsed and get the local file path out of.
Returns: The local file path. """ command = self._command if FILE_PROTOCOL not in self._command or not self._cursor.PUT_SQL_RE.match( command ): return None
file_path_begin_index = command.find(FILE_PROTOCOL) is_file_path_quoted = command[file_path_begin_index - 1] == "'" file_path_begin_index += len(FILE_PROTOCOL)
file_path = ""
if is_file_path_quoted: file_path_end_index = command.find("'", file_path_begin_index)
if file_path_end_index > file_path_begin_index: file_path = command[file_path_begin_index:file_path_end_index] else: index_list = [] for delimiter in [" ", "\n", ";"]: index = command.find(delimiter, file_path_begin_index) if index != -1: index_list += [index]
file_path_end_index = min(index_list) if index_list else -1
if file_path_end_index > file_path_begin_index: file_path = command[file_path_begin_index:file_path_end_index] elif file_path_end_index == -1: file_path = command[file_path_begin_index:]
return file_path
def get_file_header(self, filename: str) -> FileHeader | None: """Gets the remote file's metadata.
Args: filename: Not applicable to GCS.
Returns: The file header, with expected properties populated or None, based on how the request goes with the storage provider.
Notes: Sometimes this method is called to verify that the file has indeed been uploaded. In cases of presigned url, we have no way of verifying that, except with the http status code of 200 which we have already confirmed and set the meta.result_status = UPLOADED/DOWNLOADED. """ meta = self.meta if ( meta.result_status == ResultStatus.UPLOADED or meta.result_status == ResultStatus.DOWNLOADED ): return FileHeader( digest=meta.gcs_file_header_digest, content_length=meta.gcs_file_header_content_length, encryption_metadata=meta.gcs_file_header_encryption_metadata, ) elif self.presigned_url: meta.result_status = ResultStatus.NOT_FOUND_FILE else:
def generate_url_and_authenticated_headers(): url = self.generate_file_url( self.stage_info["location"], filename.lstrip("/") ) gcs_headers = {"Authorization": f"Bearer {self.security_token}"} rest_args = {"headers": gcs_headers} return url, rest_args
retry_id = "HEAD" self.retry_count[retry_id] = 0 response = self._send_request_with_retry( "HEAD", generate_url_and_authenticated_headers, retry_id ) if response.status_code == 404: meta.result_status = ResultStatus.NOT_FOUND_FILE return None elif response.status_code == 200: digest = response.headers.get(GCS_METADATA_SFC_DIGEST, None) content_length = int(response.headers.get("content-length", "0"))
encryption_metadata = EncryptionMetadata("", "", "") if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None): encryption_data = json.loads( response.headers[GCS_METADATA_ENCRYPTIONDATAPROP] )
if encryption_data: encryption_metadata = EncryptionMetadata( key=encryption_data["WrappedContentKey"]["EncryptedKey"], iv=encryption_data["ContentEncryptionIV"], matdesc=response.headers[GCS_METADATA_MATDESC_KEY] if GCS_METADATA_MATDESC_KEY in response.headers else None, ) meta.result_status = ResultStatus.UPLOADED return FileHeader( digest=digest, content_length=content_length, encryption_metadata=encryption_metadata, ) response.raise_for_status() return None
@staticmethod def extract_bucket_name_and_path(stage_location: str) -> GcsLocation: container_name = stage_location path = ""
# split stage location as bucket name and path if "/" in stage_location: container_name = stage_location[0 : stage_location.index("/")] path = stage_location[stage_location.index("/") + 1 :] if path and not path.endswith("/"): path += "/"
return GcsLocation(bucket_name=container_name, path=path)
@staticmethod def generate_file_url(stage_location: str, filename: str) -> str: gcs_location = SnowflakeGCSRestClient.extract_bucket_name_and_path( stage_location ) full_file_path = f"{gcs_location.path}{filename}" return f"https://storage.googleapis.com/{gcs_location.bucket_name}/{quote(full_file_path)}"```
## `src/snowflake/connector/gcs_storage_client.py` — `function:SnowflakeGCSRestClient._get_local_file_path_from_put_command` (lines 262-302)
```python def _get_local_file_path_from_put_command(self) -> str | None: """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita).
Args: command: Command to be parsed and get the local file path out of.
Returns: The local file path. """ command = self._command if FILE_PROTOCOL not in self._command or not self._cursor.PUT_SQL_RE.match( command ): return None
file_path_begin_index = command.find(FILE_PROTOCOL) is_file_path_quoted = command[file_path_begin_index - 1] == "'" file_path_begin_index += len(FILE_PROTOCOL)
file_path = ""
if is_file_path_quoted: file_path_end_index = command.find("'", file_path_begin_index)
if file_path_end_index > file_path_begin_index: file_path = command[file_path_begin_index:file_path_end_index] else: index_list = [] for delimiter in [" ", "\n", ";"]: index = command.find(delimiter, file_path_begin_index) if index != -1: index_list += [index]
file_path_end_index = min(index_list) if index_list else -1
if file_path_end_index > file_path_begin_index: file_path = command[file_path_begin_index:file_path_end_index] elif file_path_end_index == -1: file_path = command[file_path_begin_index:]
return file_path```
## `src/snowflake/connector/gcs_storage_client.py` — `module:<module>@13` (lines 13-13)
```pythonfrom .compat import quote```
## `test/unit/test_cursor.py` — `function:test_get_filetransfer_type` (lines 27-36)
```pythondef test_get_filetransfer_type(sql, _type): assert SnowflakeCursor.get_file_transfer_type(sql) == _type```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071{ "schema_version": "synthesis-task-v1", "task": { "pair_id": "pyvul-1f5068a3fe5ca0192a07", "dataset_id": "PyVul", "dataset_item_id": "pyvul-1f5068a3fe5ca0192a07", "project_id": "pyvul__snowflakedb__snowflake-connector-python", "language": "python", "backend": "codeql" }, "changed_python_files": [ "src/snowflake/connector/_sql_util.py", "src/snowflake/connector/cursor.py", "src/snowflake/connector/gcs_storage_client.py", "test/unit/test_cursor.py" ], "patch_units": { "before": [ "class:SnowflakeCursor", "function:SnowflakeCursor.get_file_transfer_type", "function:SnowflakeCursor._execute_helper", "module:<module>@35", "class:SnowflakeGCSRestClient", "function:SnowflakeGCSRestClient._get_local_file_path_from_put_command", "module:<module>@13", "function:test_get_filetransfer_type" ], "after": [ "function:remove_starting_comments", "function:get_file_transfer_type", "function:is_put_statement", "function:is_get_statement", "module:<module>@5", "module:<module>@7", "module:<module>@9", "module:<module>@11", "module:<module>@19", "module:<module>@20", "class:SnowflakeCursor", "function:SnowflakeCursor.get_file_transfer_type", "function:SnowflakeCursor._execute_helper", "module:<module>@35", "class:SnowflakeGCSRestClient", "function:SnowflakeGCSRestClient._get_local_file_path_from_put_command", "module:<module>@13", "function:test_get_filetransfer_type" ] }, "runtime_assets": { "before": { "database": "assets/51887dcfe7b812bd843f3a90bce6ab7b253e5b2bcb4f7ac848f4c114825a4951/database", "cache_key": "51887dcfe7b812bd843f3a90bce6ab7b253e5b2bcb4f7ac848f4c114825a4951", "codeql_version": "2.26.4" }, "after": { "database": "assets/4fc5588b7743ee66216e918ba584f47435544a3f20dfa638a54387e954e61737/database", "cache_key": "4fc5588b7743ee66216e918ba584f47435544a3f20dfa638a54387e954e61737", "codeql_version": "2.26.4" }, "refine": { "database": "assets/da7a7cda9635f06af5e6e590e9e469862e58d247d08eb71840969ce954b37632/database", "cache_key": "da7a7cda9635f06af5e6e590e9e469862e58d247d08eb71840969ce954b37632", "codeql_version": "2.26.4" } }, "benchmark_contract": { "agent_visible": true, "reference_query_location": "references/pyvul-1f5068a3fe5ca0192a07/query/ (do not mount into agent)", "evaluator_location": "evaluator/pyvul-1f5068a3fe5ca0192a07/ (do not mount into agent)" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Python CodeQL detector synthesis
You are cc operating in `/work`. Starting only from the supplied patch,before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQLdetector for the vulnerability fixed by the patch. This is one fresh session. You may iterate insidethis session, but no later framework repair or resume will occur.
## Inputs and owned outputs
- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.- Read `references/codeql/convergence_protocol.md` and `references/codeql/api_navigation.md` before experimenting. Read the remaining `references/codeql/` files for the selected mechanism.- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is uncertain. Do not guess predicate names or build a large family of inspection queries.- Complete the design contract in `state.json` and `scope_statement.md` before final validation.- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the fixed offline dependency in `query/qlpack.yml`.- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This task-unique metadata must never be used in a query predicate.- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
## Required reasoning contract
Before coding, record this mapping in `state.json`:
```textvulnerable operation / trigger / patch safety condition → CodeQL-observable evidence → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism → source, sink/report site, guard/barrier and query predicates```
Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches requirereal path/control-flow semantics; provenance-sensitive patches require value flow. Do not replaceeither with source-text matching or with the mere presence of patch-added syntax.
## Mandatory convergence contract
The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query isa failure; an early compilable semantic candidate can be improved. Follow the checkpoints in`references/codeql/convergence_protocol.md`:
1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` immediately. Do not wait until every CodeQL API detail is known.2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled definition with `scripts/search_codeql_api.sh` or simplify the mechanism.3. Obtain a compiling minimal main query before broadening it. Compile the main query after every meaningful mechanism change.4. Move in order from compile → relevant before finding → after elimination → final contract. Do not continue API exploration after the intended before/after differential is established.5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all exploration, preserve the best compiling query, finish the contract files, and exit.
## Semantic and generalization rules
- Report at the vulnerable call, operator, access, or sink.- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary matching condition. Stable library/framework APIs or public project APIs are allowed only when `scope_statement.md` explains why they define the intended vulnerability family.- The safety condition introduced by the patch must be represented by the query.- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it changed in the patch.
## Final validation protocol
1. Compile the final query.2. Run it on before and inspect `raw/before.sarif` for the intended report location.3. Run the identical query on after and inspect `raw/after.sarif`.4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, and absence of patch-local hardcoding.5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
Do not modify the runtime databases, references, patch, context, or validation scripts except fornormal CodeQL-generated database caches produced by the provided run scripts.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960diff --git a/grappelli/views/switch.py b/grappelli/views/switch.pyindex 8e390b13..db2ee680 100644--- a/grappelli/views/switch.py+++ b/grappelli/views/switch.py@@ -8,6 +8,7 @@ from django.core.exceptions import ObjectDoesNotExist from django.http import Http404 from django.shortcuts import redirect from django.utils.html import escape+from django.utils.http import url_has_allowed_host_and_scheme from django.utils.translation import gettext_lazy as _ from grappelli.settings import SWITCH_USER_ORIGINAL, SWITCH_USER_TARGET@@ -28,30 +29,35 @@ def switch_user(request, object_id): # check redirect redirect_url = request.GET.get("redirect", None)- if redirect_url is None or not redirect_url.startswith("/"):+ if redirect_url is None or not \+ url_has_allowed_host_and_scheme(+ url=redirect_url,+ allowed_hosts={request.get_host()},+ require_https=request.is_secure(),+ ): raise Http404()-+ # check original_user try: original_user = User.objects.get(pk=session_user["id"], is_staff=True) if not SWITCH_USER_ORIGINAL(original_user): messages.add_message(request, messages.ERROR, _("Permission denied."))- return redirect(request.GET.get("redirect"))+ return redirect(redirect_url) except ObjectDoesNotExist: msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(session_user["id"])} messages.add_message(request, messages.ERROR, msg)- return redirect(request.GET.get("redirect"))+ return redirect(redirect_url) # check new user try: target_user = User.objects.get(pk=object_id, is_staff=True) if target_user != original_user and not SWITCH_USER_TARGET(original_user, target_user): messages.add_message(request, messages.ERROR, _("Permission denied."))- return redirect(request.GET.get("redirect"))+ return redirect(redirect_url) except ObjectDoesNotExist: msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(object_id)} messages.add_message(request, messages.ERROR, msg)- return redirect(request.GET.get("redirect"))+ return redirect(redirect_url) # find backend if not hasattr(target_user, 'backend'):@@ -66,4 +72,4 @@ def switch_user(request, object_id): if original_user.id != target_user.id: request.session["original_user"] = {"id": original_user.id, "username": original_user.get_username()} - return redirect(request.GET.get("redirect"))+ return redirect(redirect_url)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# Patch-overlapping Python context after the fix
## `grappelli/views/switch.py` — `function:switch_user` (lines 23-75)
```pythondef switch_user(request, object_id):
# current/session user current_user = request.user session_user = request.session.get("original_user", {"id": current_user.id, "username": current_user.get_username()})
# check redirect redirect_url = request.GET.get("redirect", None) if redirect_url is None or not \ url_has_allowed_host_and_scheme( url=redirect_url, allowed_hosts={request.get_host()}, require_https=request.is_secure(), ): raise Http404() # check original_user try: original_user = User.objects.get(pk=session_user["id"], is_staff=True) if not SWITCH_USER_ORIGINAL(original_user): messages.add_message(request, messages.ERROR, _("Permission denied.")) return redirect(redirect_url) except ObjectDoesNotExist: msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(session_user["id"])} messages.add_message(request, messages.ERROR, msg) return redirect(redirect_url)
# check new user try: target_user = User.objects.get(pk=object_id, is_staff=True) if target_user != original_user and not SWITCH_USER_TARGET(original_user, target_user): messages.add_message(request, messages.ERROR, _("Permission denied.")) return redirect(redirect_url) except ObjectDoesNotExist: msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(object_id)} messages.add_message(request, messages.ERROR, msg) return redirect(redirect_url)
# find backend if not hasattr(target_user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if target_user == load_backend(backend).get_user(target_user.pk): target_user.backend = backend break
# target user login, set original as session if hasattr(target_user, 'backend'): login(request, target_user) if original_user.id != target_user.id: request.session["original_user"] = {"id": original_user.id, "username": original_user.get_username()}
return redirect(redirect_url)```
## `grappelli/views/switch.py` — `module:<module>@11` (lines 11-11)
```pythonfrom django.utils.http import url_has_allowed_host_and_scheme```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# Patch-overlapping Python context before the fix
## `grappelli/views/switch.py` — `function:switch_user` (lines 22-69)
```pythondef switch_user(request, object_id):
# current/session user current_user = request.user session_user = request.session.get("original_user", {"id": current_user.id, "username": current_user.get_username()})
# check redirect redirect_url = request.GET.get("redirect", None) if redirect_url is None or not redirect_url.startswith("/"): raise Http404()
# check original_user try: original_user = User.objects.get(pk=session_user["id"], is_staff=True) if not SWITCH_USER_ORIGINAL(original_user): messages.add_message(request, messages.ERROR, _("Permission denied.")) return redirect(request.GET.get("redirect")) except ObjectDoesNotExist: msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(session_user["id"])} messages.add_message(request, messages.ERROR, msg) return redirect(request.GET.get("redirect"))
# check new user try: target_user = User.objects.get(pk=object_id, is_staff=True) if target_user != original_user and not SWITCH_USER_TARGET(original_user, target_user): messages.add_message(request, messages.ERROR, _("Permission denied.")) return redirect(request.GET.get("redirect")) except ObjectDoesNotExist: msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(object_id)} messages.add_message(request, messages.ERROR, msg) return redirect(request.GET.get("redirect"))
# find backend if not hasattr(target_user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if target_user == load_backend(backend).get_user(target_user.pk): target_user.backend = backend break
# target user login, set original as session if hasattr(target_user, 'backend'): login(request, target_user) if original_user.id != target_user.id: request.session["original_user"] = {"id": original_user.id, "username": original_user.get_username()}
return redirect(request.GET.get("redirect"))```
## `grappelli/views/switch.py` — `module:<module>@11` (lines 11-11)
```pythonfrom django.utils.translation import gettext_lazy as _```12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "schema_version": "synthesis-task-v1", "task": { "pair_id": "pyvul-2ab65d62986b80922362", "dataset_id": "PyVul", "dataset_item_id": "pyvul-2ab65d62986b80922362", "project_id": "pyvul__sehmaschine__django-grappelli", "language": "python", "backend": "codeql" }, "changed_python_files": [ "grappelli/views/switch.py" ], "patch_units": { "before": [ "function:switch_user", "module:<module>@11" ], "after": [ "function:switch_user", "module:<module>@11" ] }, "runtime_assets": { "before": { "database": "assets/a651d858d8c6a33884674a524fc8f61c7e7ccfccade3966409515abaecba586d/database", "cache_key": "a651d858d8c6a33884674a524fc8f61c7e7ccfccade3966409515abaecba586d", "codeql_version": "2.26.4" }, "after": { "database": "assets/346863e80f97754d1d2004217a3308ad91897bf7891ed868b01ecd17ed39d300/database", "cache_key": "346863e80f97754d1d2004217a3308ad91897bf7891ed868b01ecd17ed39d300", "codeql_version": "2.26.4" }, "refine": { "database": "assets/091b842c9e7302a8f7aee586e6738c61c6607f0befe3559f5296b1b32275785b/database", "cache_key": "091b842c9e7302a8f7aee586e6738c61c6607f0befe3559f5296b1b32275785b", "codeql_version": "2.26.4" } }, "benchmark_contract": { "agent_visible": true, "reference_query_location": "references/pyvul-2ab65d62986b80922362/query/ (do not mount into agent)", "evaluator_location": "evaluator/pyvul-2ab65d62986b80922362/ (do not mount into agent)" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Python CodeQL detector synthesis
You are cc operating in `/work`. Starting only from the supplied patch,before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQLdetector for the vulnerability fixed by the patch. This is one fresh session. You may iterate insidethis session, but no later framework repair or resume will occur.
## Inputs and owned outputs
- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.- Read `references/codeql/convergence_protocol.md` and `references/codeql/api_navigation.md` before experimenting. Read the remaining `references/codeql/` files for the selected mechanism.- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is uncertain. Do not guess predicate names or build a large family of inspection queries.- Complete the design contract in `state.json` and `scope_statement.md` before final validation.- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the fixed offline dependency in `query/qlpack.yml`.- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This task-unique metadata must never be used in a query predicate.- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
## Required reasoning contract
Before coding, record this mapping in `state.json`:
```textvulnerable operation / trigger / patch safety condition → CodeQL-observable evidence → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism → source, sink/report site, guard/barrier and query predicates```
Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches requirereal path/control-flow semantics; provenance-sensitive patches require value flow. Do not replaceeither with source-text matching or with the mere presence of patch-added syntax.
## Mandatory convergence contract
The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query isa failure; an early compilable semantic candidate can be improved. Follow the checkpoints in`references/codeql/convergence_protocol.md`:
1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` immediately. Do not wait until every CodeQL API detail is known.2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled definition with `scripts/search_codeql_api.sh` or simplify the mechanism.3. Obtain a compiling minimal main query before broadening it. Compile the main query after every meaningful mechanism change.4. Move in order from compile → relevant before finding → after elimination → final contract. Do not continue API exploration after the intended before/after differential is established.5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all exploration, preserve the best compiling query, finish the contract files, and exit.
## Semantic and generalization rules
- Report at the vulnerable call, operator, access, or sink.- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary matching condition. Stable library/framework APIs or public project APIs are allowed only when `scope_statement.md` explains why they define the intended vulnerability family.- The safety condition introduced by the patch must be represented by the query.- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it changed in the patch.
## Final validation protocol
1. Compile the final query.2. Run it on before and inspect `raw/before.sarif` for the intended report location.3. Run the identical query on after and inspect `raw/after.sarif`.4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, and absence of patch-local hardcoding.5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
Do not modify the runtime databases, references, patch, context, or validation scripts except fornormal CodeQL-generated database caches produced by the provided run scripts.123456789101112131415161718192021222324252627282930313233diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ba9187c0a3..6149f587ea 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -51,6 +51,9 @@ The types of changes are: - User preferences from cookie should always override experience preferences [#4405](https://github.com/ethyca/fides/pull/4405) - Allow fides_consent cookie to be set from a subdirectory [#4426](https://github.com/ethyca/fides/pull/4426) +### Security+-- Use a more cryptographically secure random function for security code generation+ ## [2.23.3](https://github.com/ethyca/fides/compare/2.23.2...2.23.3) ### Fixeddiff --git a/src/fides/api/service/privacy_request/request_runner_service.py b/src/fides/api/service/privacy_request/request_runner_service.pyindex d1154ba3e7..266a981cb1 100644--- a/src/fides/api/service/privacy_request/request_runner_service.py+++ b/src/fides/api/service/privacy_request/request_runner_service.py@@ -1,4 +1,4 @@-import random+import secrets from datetime import datetime, timedelta from typing import Any, Dict, List, Optional, Set, Tuple @@ -627,7 +627,7 @@ def generate_id_verification_code() -> str: """ Generate one-time identity verification code """- return str(random.choice(range(100000, 999999)))+ return str(secrets.choice(range(100000, 999999))) def _retrieve_child_results( # pylint: disable=R09111234567891011121314151617# Patch-overlapping Python context after the fix
## `src/fides/api/service/privacy_request/request_runner_service.py` — `function:generate_id_verification_code` (lines 626-630)
```pythondef generate_id_verification_code() -> str: """ Generate one-time identity verification code """ return str(secrets.choice(range(100000, 999999)))```
## `src/fides/api/service/privacy_request/request_runner_service.py` — `module:<module>@1` (lines 1-1)
```pythonimport secrets```1234567891011121314151617181920212223# Patch-overlapping Python context before the fix
## `src/fides/api/service/privacy_request/request_runner_service.py` — `function:generate_id_verification_code` (lines 626-630)
```pythondef generate_id_verification_code() -> str: """ Generate one-time identity verification code """ return str(random.choice(range(100000, 999999)))```
## `src/fides/api/service/privacy_request/request_runner_service.py` — `module:<module>@1` (lines 1-1)
```pythonimport random```
## `src/fides/api/service/privacy_request/request_runner_service.py` — `module:<module>@2` (lines 2-2)
```pythonfrom datetime import datetime, timedelta```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647{ "schema_version": "synthesis-task-v1", "task": { "pair_id": "pyvul-3062589ff0b3b95c2ed7", "dataset_id": "PyVul", "dataset_item_id": "pyvul-3062589ff0b3b95c2ed7", "project_id": "pyvul__ethyca__fides", "language": "python", "backend": "codeql" }, "changed_python_files": [ "src/fides/api/service/privacy_request/request_runner_service.py" ], "patch_units": { "before": [ "function:generate_id_verification_code", "module:<module>@1", "module:<module>@2" ], "after": [ "function:generate_id_verification_code", "module:<module>@1" ] }, "runtime_assets": { "before": { "database": "assets/291915565ab089440fa07a9c16ad27e6484f7368a306466a2d88660ed05eb343/database", "cache_key": "291915565ab089440fa07a9c16ad27e6484f7368a306466a2d88660ed05eb343", "codeql_version": "2.26.4" }, "after": { "database": "assets/d92a2bb5d4325e1848a36ffc9bc6d9851def586947106947d01f951ef76928e5/database", "cache_key": "d92a2bb5d4325e1848a36ffc9bc6d9851def586947106947d01f951ef76928e5", "codeql_version": "2.26.4" }, "refine": { "database": "assets/f593a9e7147144ea94ddd83cc757db32e281fcd6c70e757a340641032a902d52/database", "cache_key": "f593a9e7147144ea94ddd83cc757db32e281fcd6c70e757a340641032a902d52", "codeql_version": "2.26.4" } }, "benchmark_contract": { "agent_visible": true, "reference_query_location": "references/pyvul-3062589ff0b3b95c2ed7/query/ (do not mount into agent)", "evaluator_location": "evaluator/pyvul-3062589ff0b3b95c2ed7/ (do not mount into agent)" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Python CodeQL detector synthesis
You are cc operating in `/work`. Starting only from the supplied patch,before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQLdetector for the vulnerability fixed by the patch. This is one fresh session. You may iterate insidethis session, but no later framework repair or resume will occur.
## Inputs and owned outputs
- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.- Read `references/codeql/convergence_protocol.md` and `references/codeql/api_navigation.md` before experimenting. Read the remaining `references/codeql/` files for the selected mechanism.- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is uncertain. Do not guess predicate names or build a large family of inspection queries.- Complete the design contract in `state.json` and `scope_statement.md` before final validation.- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the fixed offline dependency in `query/qlpack.yml`.- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This task-unique metadata must never be used in a query predicate.- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
## Required reasoning contract
Before coding, record this mapping in `state.json`:
```textvulnerable operation / trigger / patch safety condition → CodeQL-observable evidence → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism → source, sink/report site, guard/barrier and query predicates```
Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches requirereal path/control-flow semantics; provenance-sensitive patches require value flow. Do not replaceeither with source-text matching or with the mere presence of patch-added syntax.
## Mandatory convergence contract
The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query isa failure; an early compilable semantic candidate can be improved. Follow the checkpoints in`references/codeql/convergence_protocol.md`:
1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` immediately. Do not wait until every CodeQL API detail is known.2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled definition with `scripts/search_codeql_api.sh` or simplify the mechanism.3. Obtain a compiling minimal main query before broadening it. Compile the main query after every meaningful mechanism change.4. Move in order from compile → relevant before finding → after elimination → final contract. Do not continue API exploration after the intended before/after differential is established.5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all exploration, preserve the best compiling query, finish the contract files, and exit.
## Semantic and generalization rules
- Report at the vulnerable call, operator, access, or sink.- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary matching condition. Stable library/framework APIs or public project APIs are allowed only when `scope_statement.md` explains why they define the intended vulnerability family.- The safety condition introduced by the patch must be represented by the query.- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it changed in the patch.
## Final validation protocol
1. Compile the final query.2. Run it on before and inspect `raw/before.sarif` for the intended report location.3. Run the identical query on after and inspect `raw/after.sarif`.4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, and absence of patch-local hardcoding.5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
Do not modify the runtime databases, references, patch, context, or validation scripts except fornormal CodeQL-generated database caches produced by the provided run scripts.123456789101112131415161718192021222324252627282930313233343536373839diff --git a/requirements.txt b/requirements.txtindex 7d2f3f5..9d73a97 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,7 +1,7 @@ Markdown==2.6.8 Pygments==1.6 Jinja2==2.7.3-PyYAML==3.11+PyYAML==5.1 docopt==0.6.1 ordereddict==1.1 watchdog==0.8.3diff --git a/simiki/config.py b/simiki/config.pyindex c0a1ef3..790178b 100644--- a/simiki/config.py+++ b/simiki/config.py@@ -61,7 +61,7 @@ def parse_config(config_file): default_config = _set_default_config() with io.open(config_file, "rt", encoding="utf-8") as fd:- config = yaml.load(fd)+ config = yaml.load(fd, Loader=yaml.FullLoader) default_config.update(config) config = _post_process(default_config)diff --git a/simiki/generators.py b/simiki/generators.pyindex 9816df0..148908b 100644--- a/simiki/generators.py+++ b/simiki/generators.py@@ -208,7 +208,7 @@ class PageGenerator(BaseGenerator): def parse_meta(self, yaml_str): """Parse meta from yaml string, and validate yaml filed, return dict""" try:- meta = yaml.load(yaml_str)+ meta = yaml.load(yaml_str, Loader=yaml.FullLoader) except yaml.YAMLError as e: e.extra_msg = 'yaml format error' raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244# Patch-overlapping Python context after the fix
## `simiki/config.py` — `function:parse_config` (lines 57-69)
```pythondef parse_config(config_file): if not os.path.exists(config_file): raise ConfigFileNotFound("{0} not exists".format(config_file))
default_config = _set_default_config()
with io.open(config_file, "rt", encoding="utf-8") as fd: config = yaml.load(fd, Loader=yaml.FullLoader)
default_config.update(config) config = _post_process(default_config)
return config```
## `simiki/generators.py` — `class:PageGenerator` (lines 92-284)
```pythonclass PageGenerator(BaseGenerator):
def __init__(self, site_config, base_path, tags=None): super(PageGenerator, self).__init__(site_config, base_path) self._tags = tags self._reset()
def _reset(self): """Reset the global self variables""" self._src_file = None # source file path relative to base_path self.meta = None self.content = None
def to_html(self, src_file, include_draft=False): """Load template, and generate html
:src_file: the filename of the source file. This can either be an absolute filename or a filename relative to the base path. :include_draft: True/False, include draft pages or not to generate """ self._reset() self._src_file = os.path.relpath(src_file, self.base_path) self.meta, self.content = self.get_meta_and_content() # Page set `draft: True' mark current page as draft, and will # be ignored if not forced generate include draft pages if not include_draft and self.meta.get('draft', False): return None layout = self.get_layout(self.meta) template_vars = self.get_template_vars(self.meta, self.content) template = self.get_template(layout) html = template.render(template_vars)
return html
@property def src_file(self): return self._src_file
@src_file.setter def src_file(self, filename): self._src_file = os.path.relpath(filename, self.base_path)
def get_meta_and_content(self, do_render=True): meta_str, content_str = self.extract_page(self._src_file) meta = self.parse_meta(meta_str) # This is the most time consuming part if do_render and meta.get('render', True): content = self._parse_markup(content_str) else: content = content_str
return meta, content
def get_layout(self, meta): """Get layout config in meta, default is `page'""" if "layout" in meta: # Compatible with previous version, which default layout is "post" # XXX Will remove this checker in v2.0 if meta["layout"] == "post": warn_msg = "{0}: layout `post' is deprecated, use `page'" \ .format(self._src_file) if is_py2: # XXX: warnings message require str, no matter whether # py2 or py3; but in py3, bytes message is ok in simple # test, but failed in unittest with py3.3, ok with py3.4? warn_msg = warn_msg.encode('utf-8') warnings.warn(warn_msg, DeprecationWarning) layout = "page" else: layout = meta["layout"] else: layout = "page"
return layout
def get_template_vars(self, meta, content): """Get template variables, include site config and page config""" template_vars = copy.deepcopy(self._template_vars) page = {"content": content} page.update(meta) page.update({'relation': self.get_relation()})
template_vars.update({'page': page})
return template_vars
def get_category_and_file(self): """Get the name of category and file(with extension)""" src_file_relpath_to_source = \ os.path.relpath(self._src_file, self.site_config['source']) category, filename = os.path.split(src_file_relpath_to_source) return (category, filename)
@staticmethod def extract_page(filename): """Split the page file texts by triple-dashed lines, return the mata and content.
:param filename: the filename of markup page
returns: meta_str (str): page's meta string content_str (str): html parsed from markdown or other markup text. """ regex = re.compile('(?sm)^---(?P<meta>.*?)^---(?P<body>.*)') with io.open(filename, "rt", encoding="utf-8") as fd: match_obj = re.match(regex, fd.read()) if match_obj: meta_str = match_obj.group('meta') content_str = match_obj.group('body') else: raise Exception('extracting page with format error, ' 'see <http://simiki.org/docs/metadata.html>')
return meta_str, content_str
def parse_meta(self, yaml_str): """Parse meta from yaml string, and validate yaml filed, return dict""" try: meta = yaml.load(yaml_str, Loader=yaml.FullLoader) except yaml.YAMLError as e: e.extra_msg = 'yaml format error' raise
category, src_fname = self.get_category_and_file() dst_fname = src_fname.replace( ".{0}".format(self.site_config['default_ext']), '.html') meta.update({'category': category, 'filename': dst_fname})
if 'tag' in meta: if isinstance(meta['tag'], basestring): _tags = [t.strip() for t in meta['tag'].split(',')] meta.update({'tag': _tags})
if "title" not in meta: raise Exception("no 'title' in meta")
return meta
def _parse_markup(self, markup_text): """Parse markup text to html
Only support Markdown for now. """ markdown_extensions = self._set_markdown_extensions()
html_content = markdown.markdown( markup_text, extensions=markdown_extensions, )
return html_content
def _set_markdown_extensions(self): """Set the extensions for markdown parser""" # Default enabled extensions markdown_extensions_config = { "fenced_code": {}, "nl2br": {}, "toc": {"title": "Table of Contents"}, "extra": {}, } # Handle pygments if self.site_config["pygments"]: markdown_extensions_config.update({ "codehilite": {"css_class": "hlcode"} }) # Handle markdown_ext # Ref: https://pythonhosted.org/Markdown/extensions/index.html#officially-supported-extensions # noqa if "markdown_ext" in self.site_config: markdown_extensions_config.update(self.site_config["markdown_ext"])
markdown_extensions = [] for k, v in markdown_extensions_config.items(): ext = import_string("markdown.extensions." + k).makeExtension() if v: for i, j in v.items(): ext.setConfig(i, j) markdown_extensions.append(ext)
return markdown_extensions
def get_relation(self): rn = [] if self._tags and 'tag' in self.meta: for t in self.meta['tag']: rn.extend(self._tags[t]) # remove itself rn = [r for r in rn if self.meta['title'] != r['title']] # remove the duplicate items # note this will change the items order rn = [r for n, r in enumerate(rn) if r not in rn[n+1:]] # noqa: E226 return rn```
## `simiki/generators.py` — `function:PageGenerator.parse_meta` (lines 208-229)
```python def parse_meta(self, yaml_str): """Parse meta from yaml string, and validate yaml filed, return dict""" try: meta = yaml.load(yaml_str, Loader=yaml.FullLoader) except yaml.YAMLError as e: e.extra_msg = 'yaml format error' raise
category, src_fname = self.get_category_and_file() dst_fname = src_fname.replace( ".{0}".format(self.site_config['default_ext']), '.html') meta.update({'category': category, 'filename': dst_fname})
if 'tag' in meta: if isinstance(meta['tag'], basestring): _tags = [t.strip() for t in meta['tag'].split(',')] meta.update({'tag': _tags})
if "title" not in meta: raise Exception("no 'title' in meta")
return meta```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244# Patch-overlapping Python context before the fix
## `simiki/config.py` — `function:parse_config` (lines 57-69)
```pythondef parse_config(config_file): if not os.path.exists(config_file): raise ConfigFileNotFound("{0} not exists".format(config_file))
default_config = _set_default_config()
with io.open(config_file, "rt", encoding="utf-8") as fd: config = yaml.load(fd)
default_config.update(config) config = _post_process(default_config)
return config```
## `simiki/generators.py` — `class:PageGenerator` (lines 92-284)
```pythonclass PageGenerator(BaseGenerator):
def __init__(self, site_config, base_path, tags=None): super(PageGenerator, self).__init__(site_config, base_path) self._tags = tags self._reset()
def _reset(self): """Reset the global self variables""" self._src_file = None # source file path relative to base_path self.meta = None self.content = None
def to_html(self, src_file, include_draft=False): """Load template, and generate html
:src_file: the filename of the source file. This can either be an absolute filename or a filename relative to the base path. :include_draft: True/False, include draft pages or not to generate """ self._reset() self._src_file = os.path.relpath(src_file, self.base_path) self.meta, self.content = self.get_meta_and_content() # Page set `draft: True' mark current page as draft, and will # be ignored if not forced generate include draft pages if not include_draft and self.meta.get('draft', False): return None layout = self.get_layout(self.meta) template_vars = self.get_template_vars(self.meta, self.content) template = self.get_template(layout) html = template.render(template_vars)
return html
@property def src_file(self): return self._src_file
@src_file.setter def src_file(self, filename): self._src_file = os.path.relpath(filename, self.base_path)
def get_meta_and_content(self, do_render=True): meta_str, content_str = self.extract_page(self._src_file) meta = self.parse_meta(meta_str) # This is the most time consuming part if do_render and meta.get('render', True): content = self._parse_markup(content_str) else: content = content_str
return meta, content
def get_layout(self, meta): """Get layout config in meta, default is `page'""" if "layout" in meta: # Compatible with previous version, which default layout is "post" # XXX Will remove this checker in v2.0 if meta["layout"] == "post": warn_msg = "{0}: layout `post' is deprecated, use `page'" \ .format(self._src_file) if is_py2: # XXX: warnings message require str, no matter whether # py2 or py3; but in py3, bytes message is ok in simple # test, but failed in unittest with py3.3, ok with py3.4? warn_msg = warn_msg.encode('utf-8') warnings.warn(warn_msg, DeprecationWarning) layout = "page" else: layout = meta["layout"] else: layout = "page"
return layout
def get_template_vars(self, meta, content): """Get template variables, include site config and page config""" template_vars = copy.deepcopy(self._template_vars) page = {"content": content} page.update(meta) page.update({'relation': self.get_relation()})
template_vars.update({'page': page})
return template_vars
def get_category_and_file(self): """Get the name of category and file(with extension)""" src_file_relpath_to_source = \ os.path.relpath(self._src_file, self.site_config['source']) category, filename = os.path.split(src_file_relpath_to_source) return (category, filename)
@staticmethod def extract_page(filename): """Split the page file texts by triple-dashed lines, return the mata and content.
:param filename: the filename of markup page
returns: meta_str (str): page's meta string content_str (str): html parsed from markdown or other markup text. """ regex = re.compile('(?sm)^---(?P<meta>.*?)^---(?P<body>.*)') with io.open(filename, "rt", encoding="utf-8") as fd: match_obj = re.match(regex, fd.read()) if match_obj: meta_str = match_obj.group('meta') content_str = match_obj.group('body') else: raise Exception('extracting page with format error, ' 'see <http://simiki.org/docs/metadata.html>')
return meta_str, content_str
def parse_meta(self, yaml_str): """Parse meta from yaml string, and validate yaml filed, return dict""" try: meta = yaml.load(yaml_str) except yaml.YAMLError as e: e.extra_msg = 'yaml format error' raise
category, src_fname = self.get_category_and_file() dst_fname = src_fname.replace( ".{0}".format(self.site_config['default_ext']), '.html') meta.update({'category': category, 'filename': dst_fname})
if 'tag' in meta: if isinstance(meta['tag'], basestring): _tags = [t.strip() for t in meta['tag'].split(',')] meta.update({'tag': _tags})
if "title" not in meta: raise Exception("no 'title' in meta")
return meta
def _parse_markup(self, markup_text): """Parse markup text to html
Only support Markdown for now. """ markdown_extensions = self._set_markdown_extensions()
html_content = markdown.markdown( markup_text, extensions=markdown_extensions, )
return html_content
def _set_markdown_extensions(self): """Set the extensions for markdown parser""" # Default enabled extensions markdown_extensions_config = { "fenced_code": {}, "nl2br": {}, "toc": {"title": "Table of Contents"}, "extra": {}, } # Handle pygments if self.site_config["pygments"]: markdown_extensions_config.update({ "codehilite": {"css_class": "hlcode"} }) # Handle markdown_ext # Ref: https://pythonhosted.org/Markdown/extensions/index.html#officially-supported-extensions # noqa if "markdown_ext" in self.site_config: markdown_extensions_config.update(self.site_config["markdown_ext"])
markdown_extensions = [] for k, v in markdown_extensions_config.items(): ext = import_string("markdown.extensions." + k).makeExtension() if v: for i, j in v.items(): ext.setConfig(i, j) markdown_extensions.append(ext)
return markdown_extensions
def get_relation(self): rn = [] if self._tags and 'tag' in self.meta: for t in self.meta['tag']: rn.extend(self._tags[t]) # remove itself rn = [r for r in rn if self.meta['title'] != r['title']] # remove the duplicate items # note this will change the items order rn = [r for n, r in enumerate(rn) if r not in rn[n+1:]] # noqa: E226 return rn```
## `simiki/generators.py` — `function:PageGenerator.parse_meta` (lines 208-229)
```python def parse_meta(self, yaml_str): """Parse meta from yaml string, and validate yaml filed, return dict""" try: meta = yaml.load(yaml_str) except yaml.YAMLError as e: e.extra_msg = 'yaml format error' raise
category, src_fname = self.get_category_and_file() dst_fname = src_fname.replace( ".{0}".format(self.site_config['default_ext']), '.html') meta.update({'category': category, 'filename': dst_fname})
if 'tag' in meta: if isinstance(meta['tag'], basestring): _tags = [t.strip() for t in meta['tag'].split(',')] meta.update({'tag': _tags})
if "title" not in meta: raise Exception("no 'title' in meta")
return meta```12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849{ "schema_version": "synthesis-task-v1", "task": { "pair_id": "pyvul-3187445bcbbf39128a26", "dataset_id": "PyVul", "dataset_item_id": "pyvul-3187445bcbbf39128a26", "project_id": "pyvul__tankywoo__simiki", "language": "python", "backend": "codeql" }, "changed_python_files": [ "simiki/config.py", "simiki/generators.py" ], "patch_units": { "before": [ "function:parse_config", "class:PageGenerator", "function:PageGenerator.parse_meta" ], "after": [ "function:parse_config", "class:PageGenerator", "function:PageGenerator.parse_meta" ] }, "runtime_assets": { "before": { "database": "assets/6c677522fd3c28ce7e1472d351798d0e087b50dd4e508e0f5fcc1bee0af173f1/database", "cache_key": "6c677522fd3c28ce7e1472d351798d0e087b50dd4e508e0f5fcc1bee0af173f1", "codeql_version": "2.26.4" }, "after": { "database": "assets/7e613b7efe30230563633a9a574d8c2fa71dcc345fff934fc4de7ceb656cf8fe/database", "cache_key": "7e613b7efe30230563633a9a574d8c2fa71dcc345fff934fc4de7ceb656cf8fe", "codeql_version": "2.26.4" }, "refine": { "database": "assets/8d8b60dfa034c14268f005e72f669accfdfac1fb52182a03fea8cd89a0322db3/database", "cache_key": "8d8b60dfa034c14268f005e72f669accfdfac1fb52182a03fea8cd89a0322db3", "codeql_version": "2.26.4" } }, "benchmark_contract": { "agent_visible": true, "reference_query_location": "references/pyvul-3187445bcbbf39128a26/query/ (do not mount into agent)", "evaluator_location": "evaluator/pyvul-3187445bcbbf39128a26/ (do not mount into agent)" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Python CodeQL detector synthesis
You are cc operating in `/work`. Starting only from the supplied patch,before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQLdetector for the vulnerability fixed by the patch. This is one fresh session. You may iterate insidethis session, but no later framework repair or resume will occur.
## Inputs and owned outputs
- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.- Read `references/codeql/convergence_protocol.md` and `references/codeql/api_navigation.md` before experimenting. Read the remaining `references/codeql/` files for the selected mechanism.- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is uncertain. Do not guess predicate names or build a large family of inspection queries.- Complete the design contract in `state.json` and `scope_statement.md` before final validation.- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the fixed offline dependency in `query/qlpack.yml`.- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This task-unique metadata must never be used in a query predicate.- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
## Required reasoning contract
Before coding, record this mapping in `state.json`:
```textvulnerable operation / trigger / patch safety condition → CodeQL-observable evidence → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism → source, sink/report site, guard/barrier and query predicates```
Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches requirereal path/control-flow semantics; provenance-sensitive patches require value flow. Do not replaceeither with source-text matching or with the mere presence of patch-added syntax.
## Mandatory convergence contract
The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query isa failure; an early compilable semantic candidate can be improved. Follow the checkpoints in`references/codeql/convergence_protocol.md`:
1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` immediately. Do not wait until every CodeQL API detail is known.2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled definition with `scripts/search_codeql_api.sh` or simplify the mechanism.3. Obtain a compiling minimal main query before broadening it. Compile the main query after every meaningful mechanism change.4. Move in order from compile → relevant before finding → after elimination → final contract. Do not continue API exploration after the intended before/after differential is established.5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all exploration, preserve the best compiling query, finish the contract files, and exit.
## Semantic and generalization rules
- Report at the vulnerable call, operator, access, or sink.- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary matching condition. Stable library/framework APIs or public project APIs are allowed only when `scope_statement.md` explains why they define the intended vulnerability family.- The safety condition introduced by the patch must be represented by the query.- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it changed in the patch.
## Final validation protocol
1. Compile the final query.2. Run it on before and inspect `raw/before.sarif` for the intended report location.3. Run the identical query on after and inspect `raw/after.sarif`.4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, and absence of patch-local hardcoding.5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
Do not modify the runtime databases, references, patch, context, or validation scripts except fornormal CodeQL-generated database caches produced by the provided run scripts.123456789101112131415161718192021222324252627282930313233343536373839diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 225fced44..7bfe08edb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -663,9 +663,13 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). - Fixed an issue where `HorovodStrategy.teardown()` did not complete gracefully if an exception was thrown during callback setup [#11752](https://github.com/PyTorchLightning/pytorch-lightning/pull/11752) + - Fixed security vulnerabilities CVE-2020-1747 and CVE-2020-14343 caused by the `PyYAML` dependency ([#11099](https://github.com/PyTorchLightning/pytorch-lightning/pull/11099)) +- Fixed security vulnerability "CWE-94: Improper Control of Generation of Code (Code Injection)" ([#12212](https://github.com/PyTorchLightning/pytorch-lightning/pull/12212))++ - Fixed logging on `{test,validation}_epoch_end` with multiple dataloaders ([#11132](https://github.com/PyTorchLightning/pytorch-lightning/pull/11132)) diff --git a/pytorch_lightning/utilities/argparse.py b/pytorch_lightning/utilities/argparse.pyindex e729f862c..8927ff093 100644--- a/pytorch_lightning/utilities/argparse.py+++ b/pytorch_lightning/utilities/argparse.py@@ -17,6 +17,7 @@ import inspect import os from abc import ABC from argparse import _ArgumentGroup, ArgumentParser, Namespace+from ast import literal_eval from contextlib import suppress from functools import wraps from typing import Any, Callable, cast, Dict, List, Tuple, Type, TypeVar, Union@@ -121,7 +122,7 @@ def parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name) # todo: specify the possible exception with suppress(Exception): # converting to native types like int/float/bool- val = eval(val)+ val = literal_eval(val) env_args[arg_name] = val return Namespace(**env_args) 12345678910111213141516171819202122232425262728293031323334353637383940# Patch-overlapping Python context after the fix
## `pytorch_lightning/utilities/argparse.py` — `function:parse_env_variables` (lines 100-127)
```pythondef parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name)s_%(cls_argument)s") -> Namespace: """Parse environment arguments if they are defined.
Examples:
>>> from pytorch_lightning import Trainer >>> parse_env_variables(Trainer) Namespace() >>> import os >>> os.environ["PL_TRAINER_GPUS"] = '42' >>> os.environ["PL_TRAINER_BLABLABLA"] = '1.23' >>> parse_env_variables(Trainer) Namespace(gpus=42) >>> del os.environ["PL_TRAINER_GPUS"] """ cls_arg_defaults = get_init_arguments_and_types(cls)
env_args = {} for arg_name, _, _ in cls_arg_defaults: env = template % {"cls_name": cls.__name__.upper(), "cls_argument": arg_name.upper()} val = os.environ.get(env) if not (val is None or val == ""): # todo: specify the possible exception with suppress(Exception): # converting to native types like int/float/bool val = literal_eval(val) env_args[arg_name] = val return Namespace(**env_args)```
## `pytorch_lightning/utilities/argparse.py` — `module:<module>@20` (lines 20-20)
```pythonfrom ast import literal_eval```12345678910111213141516171819202122232425262728293031323334353637383940# Patch-overlapping Python context before the fix
## `pytorch_lightning/utilities/argparse.py` — `function:parse_env_variables` (lines 99-126)
```pythondef parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name)s_%(cls_argument)s") -> Namespace: """Parse environment arguments if they are defined.
Examples:
>>> from pytorch_lightning import Trainer >>> parse_env_variables(Trainer) Namespace() >>> import os >>> os.environ["PL_TRAINER_GPUS"] = '42' >>> os.environ["PL_TRAINER_BLABLABLA"] = '1.23' >>> parse_env_variables(Trainer) Namespace(gpus=42) >>> del os.environ["PL_TRAINER_GPUS"] """ cls_arg_defaults = get_init_arguments_and_types(cls)
env_args = {} for arg_name, _, _ in cls_arg_defaults: env = template % {"cls_name": cls.__name__.upper(), "cls_argument": arg_name.upper()} val = os.environ.get(env) if not (val is None or val == ""): # todo: specify the possible exception with suppress(Exception): # converting to native types like int/float/bool val = eval(val) env_args[arg_name] = val return Namespace(**env_args)```
## `pytorch_lightning/utilities/argparse.py` — `module:<module>@20` (lines 20-20)
```pythonfrom contextlib import suppress```12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "schema_version": "synthesis-task-v1", "task": { "pair_id": "pyvul-36a40541d7c74a9a7777", "dataset_id": "PyVul", "dataset_item_id": "pyvul-36a40541d7c74a9a7777", "project_id": "pyvul__pytorchlightning__pytorch-lightning", "language": "python", "backend": "codeql" }, "changed_python_files": [ "pytorch_lightning/utilities/argparse.py" ], "patch_units": { "before": [ "function:parse_env_variables", "module:<module>@20" ], "after": [ "function:parse_env_variables", "module:<module>@20" ] }, "runtime_assets": { "before": { "database": "assets/f904a001805ca2a12850f3d3056b70f7b209467a621d3da7fe0e4e98faa4b9c9/database", "cache_key": "f904a001805ca2a12850f3d3056b70f7b209467a621d3da7fe0e4e98faa4b9c9", "codeql_version": "2.26.4" }, "after": { "database": "assets/f9a6566d69a61c361650443ebcecb4d650d674333e5dda7f6c57320a8ff0a764/database", "cache_key": "f9a6566d69a61c361650443ebcecb4d650d674333e5dda7f6c57320a8ff0a764", "codeql_version": "2.26.4" }, "refine": { "database": "assets/0e9729244a800a484f57498b45d84807d5007185f2cdaea70346b3a3ea9f43bc/database", "cache_key": "0e9729244a800a484f57498b45d84807d5007185f2cdaea70346b3a3ea9f43bc", "codeql_version": "2.26.4" } }, "benchmark_contract": { "agent_visible": true, "reference_query_location": "references/pyvul-36a40541d7c74a9a7777/query/ (do not mount into agent)", "evaluator_location": "evaluator/pyvul-36a40541d7c74a9a7777/ (do not mount into agent)" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Python CodeQL detector synthesis
You are cc operating in `/work`. Starting only from the supplied patch,before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQLdetector for the vulnerability fixed by the patch. This is one fresh session. You may iterate insidethis session, but no later framework repair or resume will occur.
## Inputs and owned outputs
- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.- Read `references/codeql/convergence_protocol.md` and `references/codeql/api_navigation.md` before experimenting. Read the remaining `references/codeql/` files for the selected mechanism.- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is uncertain. Do not guess predicate names or build a large family of inspection queries.- Complete the design contract in `state.json` and `scope_statement.md` before final validation.- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the fixed offline dependency in `query/qlpack.yml`.- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This task-unique metadata must never be used in a query predicate.- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
## Required reasoning contract
Before coding, record this mapping in `state.json`:
```textvulnerable operation / trigger / patch safety condition → CodeQL-observable evidence → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism → source, sink/report site, guard/barrier and query predicates```
Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches requirereal path/control-flow semantics; provenance-sensitive patches require value flow. Do not replaceeither with source-text matching or with the mere presence of patch-added syntax.
## Mandatory convergence contract
The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query isa failure; an early compilable semantic candidate can be improved. Follow the checkpoints in`references/codeql/convergence_protocol.md`:
1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` immediately. Do not wait until every CodeQL API detail is known.2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled definition with `scripts/search_codeql_api.sh` or simplify the mechanism.3. Obtain a compiling minimal main query before broadening it. Compile the main query after every meaningful mechanism change.4. Move in order from compile → relevant before finding → after elimination → final contract. Do not continue API exploration after the intended before/after differential is established.5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all exploration, preserve the best compiling query, finish the contract files, and exit.
## Semantic and generalization rules
- Report at the vulnerable call, operator, access, or sink.- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary matching condition. Stable library/framework APIs or public project APIs are allowed only when `scope_statement.md` explains why they define the intended vulnerability family.- The safety condition introduced by the patch must be represented by the query.- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it changed in the patch.
## Final validation protocol
1. Compile the final query.2. Run it on before and inspect `raw/before.sarif` for the intended report location.3. Run the identical query on after and inspect `raw/after.sarif`.4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, and absence of patch-local hardcoding.5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
Do not modify the runtime databases, references, patch, context, or validation scripts except fornormal CodeQL-generated database caches produced by the provided run scripts.1234567891011121314151617181920212223242526272829303132diff --git a/templated_dictionary/__init__.py b/templated_dictionary/__init__.pyindex 994166a..ec004c0 100644--- a/templated_dictionary/__init__.py+++ b/templated_dictionary/__init__.py@@ -2,7 +2,7 @@ # vim:expandtab:autoindent:tabstop=4:shiftwidth=4:filetype=python:textwidth=0: from collections.abc import MutableMapping-import jinja2+from jinja2 import sandbox # pylint: disable=no-member,unsupported-assignment-operation@@ -19,6 +19,8 @@ class TemplatedDictionary(MutableMapping): ''' self.__dict__.update(*args, **kwargs) + self.sandbox = sandbox.SandboxedEnvironment(keep_trailing_newline=True)+ self._aliases = {} if alias_spec: for aliased_to, aliases in alias_spec.items():@@ -80,8 +82,7 @@ class TemplatedDictionary(MutableMapping): orig = last = value max_recursion = self.__dict__.get('jinja_max_recursion', 5) for _ in range(max_recursion):- template = jinja2.Template(value, keep_trailing_newline=True)- value = _to_native(template.render(self.__dict__))+ value = _to_native(self.sandbox.from_string(value).render(self.__dict__, func=lambda:None)) if value == last: return value last = value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130# Patch-overlapping Python context after the fix
## `templated_dictionary/__init__.py` — `class:TemplatedDictionary` (lines 9-89)
```pythonclass TemplatedDictionary(MutableMapping): """ Dictionary where __getitem__() is run through Jinja2 template """ def __init__(self, *args, alias_spec=None, **kwargs): ''' Use the object dict.
Optional parameter 'alias_spec' is dictionary of form: {'aliased_to': ['alias_one', 'alias_two', ...], ...} When specified, and one of the aliases is accessed - the 'aliased_to' config option is returned. ''' self.__dict__.update(*args, **kwargs)
self.sandbox = sandbox.SandboxedEnvironment(keep_trailing_newline=True)
self._aliases = {} if alias_spec: for aliased_to, aliases in alias_spec.items(): for alias in aliases: self._aliases[alias] = aliased_to
# The next five methods are requirements of the ABC. def __setitem__(self, key, value): key = self._aliases.get(key, key) self.__dict__[key] = value
def __getitem__(self, key): key = self._aliases.get(key, key) if '__jinja_expand' in self.__dict__ and self.__dict__['__jinja_expand']: return self.__render_value(self.__dict__[key]) return self.__dict__[key]
def __delitem__(self, key): del self.__dict__[key]
def __iter__(self): return iter(self.__dict__)
def __len__(self): return len(self.__dict__)
# The final two methods aren't required, but nice to have def __str__(self): '''returns simple dict representation of the mapping''' return str(self.__dict__)
def __repr__(self): '''echoes class, id, & reproducible representation in the REPL''' return '{}, TemplatedDictionary({})'.format(super(TemplatedDictionary, self).__repr__(), self.__dict__)
def copy(self): return TemplatedDictionary(self.__dict__)
def __render_value(self, value): if isinstance(value, str): return self.__render_string(value) elif isinstance(value, list): # we cannot use list comprehension here, as we need to NOT modify the list (pointer to list) # and we need to modifiy only individual values in the list # If we would create new list, we cannot assign to it, which often happens in configs (e.g. plugins) for i in range(len(value)): # pylint: disable=consider-using-enumerate value[i] = self.__render_value(value[i]) return value elif isinstance(value, dict): # we cannot use list comprehension here, same reasoning as for `list` above for k in value.keys(): value[k] = self.__render_value(value[k]) return value else: return value
def __render_string(self, value): orig = last = value max_recursion = self.__dict__.get('jinja_max_recursion', 5) for _ in range(max_recursion): value = _to_native(self.sandbox.from_string(value).render(self.__dict__, func=lambda:None)) if value == last: return value last = value raise ValueError("too deep jinja re-evaluation on '{}'".format(orig))```
## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__init__` (lines 11-28)
```python def __init__(self, *args, alias_spec=None, **kwargs): ''' Use the object dict.
Optional parameter 'alias_spec' is dictionary of form: {'aliased_to': ['alias_one', 'alias_two', ...], ...} When specified, and one of the aliases is accessed - the 'aliased_to' config option is returned. ''' self.__dict__.update(*args, **kwargs)
self.sandbox = sandbox.SandboxedEnvironment(keep_trailing_newline=True)
self._aliases = {} if alias_spec: for aliased_to, aliases in alias_spec.items(): for alias in aliases: self._aliases[alias] = aliased_to```
## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__render_string` (lines 81-89)
```python def __render_string(self, value): orig = last = value max_recursion = self.__dict__.get('jinja_max_recursion', 5) for _ in range(max_recursion): value = _to_native(self.sandbox.from_string(value).render(self.__dict__, func=lambda:None)) if value == last: return value last = value raise ValueError("too deep jinja re-evaluation on '{}'".format(orig))```
## `templated_dictionary/__init__.py` — `module:<module>@5` (lines 5-5)
```pythonfrom jinja2 import sandbox```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128# Patch-overlapping Python context before the fix
## `templated_dictionary/__init__.py` — `class:TemplatedDictionary` (lines 9-88)
```pythonclass TemplatedDictionary(MutableMapping): """ Dictionary where __getitem__() is run through Jinja2 template """ def __init__(self, *args, alias_spec=None, **kwargs): ''' Use the object dict.
Optional parameter 'alias_spec' is dictionary of form: {'aliased_to': ['alias_one', 'alias_two', ...], ...} When specified, and one of the aliases is accessed - the 'aliased_to' config option is returned. ''' self.__dict__.update(*args, **kwargs)
self._aliases = {} if alias_spec: for aliased_to, aliases in alias_spec.items(): for alias in aliases: self._aliases[alias] = aliased_to
# The next five methods are requirements of the ABC. def __setitem__(self, key, value): key = self._aliases.get(key, key) self.__dict__[key] = value
def __getitem__(self, key): key = self._aliases.get(key, key) if '__jinja_expand' in self.__dict__ and self.__dict__['__jinja_expand']: return self.__render_value(self.__dict__[key]) return self.__dict__[key]
def __delitem__(self, key): del self.__dict__[key]
def __iter__(self): return iter(self.__dict__)
def __len__(self): return len(self.__dict__)
# The final two methods aren't required, but nice to have def __str__(self): '''returns simple dict representation of the mapping''' return str(self.__dict__)
def __repr__(self): '''echoes class, id, & reproducible representation in the REPL''' return '{}, TemplatedDictionary({})'.format(super(TemplatedDictionary, self).__repr__(), self.__dict__)
def copy(self): return TemplatedDictionary(self.__dict__)
def __render_value(self, value): if isinstance(value, str): return self.__render_string(value) elif isinstance(value, list): # we cannot use list comprehension here, as we need to NOT modify the list (pointer to list) # and we need to modifiy only individual values in the list # If we would create new list, we cannot assign to it, which often happens in configs (e.g. plugins) for i in range(len(value)): # pylint: disable=consider-using-enumerate value[i] = self.__render_value(value[i]) return value elif isinstance(value, dict): # we cannot use list comprehension here, same reasoning as for `list` above for k in value.keys(): value[k] = self.__render_value(value[k]) return value else: return value
def __render_string(self, value): orig = last = value max_recursion = self.__dict__.get('jinja_max_recursion', 5) for _ in range(max_recursion): template = jinja2.Template(value, keep_trailing_newline=True) value = _to_native(template.render(self.__dict__)) if value == last: return value last = value raise ValueError("too deep jinja re-evaluation on '{}'".format(orig))```
## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__init__` (lines 11-26)
```python def __init__(self, *args, alias_spec=None, **kwargs): ''' Use the object dict.
Optional parameter 'alias_spec' is dictionary of form: {'aliased_to': ['alias_one', 'alias_two', ...], ...} When specified, and one of the aliases is accessed - the 'aliased_to' config option is returned. ''' self.__dict__.update(*args, **kwargs)
self._aliases = {} if alias_spec: for aliased_to, aliases in alias_spec.items(): for alias in aliases: self._aliases[alias] = aliased_to```
## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__render_string` (lines 79-88)
```python def __render_string(self, value): orig = last = value max_recursion = self.__dict__.get('jinja_max_recursion', 5) for _ in range(max_recursion): template = jinja2.Template(value, keep_trailing_newline=True) value = _to_native(template.render(self.__dict__)) if value == last: return value last = value raise ValueError("too deep jinja re-evaluation on '{}'".format(orig))```
## `templated_dictionary/__init__.py` — `module:<module>@5` (lines 5-5)
```pythonimport jinja2```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950{ "schema_version": "synthesis-task-v1", "task": { "pair_id": "pyvul-3819b1a7530257524a75", "dataset_id": "PyVul", "dataset_item_id": "pyvul-3819b1a7530257524a75", "project_id": "pyvul__xsuchy__templated-dictionary", "language": "python", "backend": "codeql" }, "changed_python_files": [ "templated_dictionary/__init__.py" ], "patch_units": { "before": [ "class:TemplatedDictionary", "function:TemplatedDictionary.__init__", "function:TemplatedDictionary.__render_string", "module:<module>@5" ], "after": [ "class:TemplatedDictionary", "function:TemplatedDictionary.__init__", "function:TemplatedDictionary.__render_string", "module:<module>@5" ] }, "runtime_assets": { "before": { "database": "assets/60090dd1e3d668fdc545d407347c4a6ba0250326e30297f90b2d463919aae8b3/database", "cache_key": "60090dd1e3d668fdc545d407347c4a6ba0250326e30297f90b2d463919aae8b3", "codeql_version": "2.26.4" }, "after": { "database": "assets/95b9d1bbebc8c5a413369012e35afae0fd0b6205fae69cab5ce281dfe2a80f3d/database", "cache_key": "95b9d1bbebc8c5a413369012e35afae0fd0b6205fae69cab5ce281dfe2a80f3d", "codeql_version": "2.26.4" }, "refine": { "database": "assets/9782c933de0fe5c1d90834d158773b8aa4076e68abc282bfc920352b51cc5b7b/database", "cache_key": "9782c933de0fe5c1d90834d158773b8aa4076e68abc282bfc920352b51cc5b7b", "codeql_version": "2.26.4" } }, "benchmark_contract": { "agent_visible": true, "reference_query_location": "references/pyvul-3819b1a7530257524a75/query/ (do not mount into agent)", "evaluator_location": "evaluator/pyvul-3819b1a7530257524a75/ (do not mount into agent)" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Python CodeQL detector synthesis
You are cc operating in `/work`. Starting only from the supplied patch,before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQLdetector for the vulnerability fixed by the patch. This is one fresh session. You may iterate insidethis session, but no later framework repair or resume will occur.
## Inputs and owned outputs
- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.- Read `references/codeql/convergence_protocol.md` and `references/codeql/api_navigation.md` before experimenting. Read the remaining `references/codeql/` files for the selected mechanism.- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is uncertain. Do not guess predicate names or build a large family of inspection queries.- Complete the design contract in `state.json` and `scope_statement.md` before final validation.- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the fixed offline dependency in `query/qlpack.yml`.- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This task-unique metadata must never be used in a query predicate.- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
## Required reasoning contract
Before coding, record this mapping in `state.json`:
```textvulnerable operation / trigger / patch safety condition → CodeQL-observable evidence → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism → source, sink/report site, guard/barrier and query predicates```
Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches requirereal path/control-flow semantics; provenance-sensitive patches require value flow. Do not replaceeither with source-text matching or with the mere presence of patch-added syntax.
## Mandatory convergence contract
The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query isa failure; an early compilable semantic candidate can be improved. Follow the checkpoints in`references/codeql/convergence_protocol.md`:
1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` immediately. Do not wait until every CodeQL API detail is known.2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled definition with `scripts/search_codeql_api.sh` or simplify the mechanism.3. Obtain a compiling minimal main query before broadening it. Compile the main query after every meaningful mechanism change.4. Move in order from compile → relevant before finding → after elimination → final contract. Do not continue API exploration after the intended before/after differential is established.5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all exploration, preserve the best compiling query, finish the contract files, and exit.
## Semantic and generalization rules
- Report at the vulnerable call, operator, access, or sink.- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary matching condition. Stable library/framework APIs or public project APIs are allowed only when `scope_statement.md` explains why they define the intended vulnerability family.- The safety condition introduced by the patch must be represented by the query.- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it changed in the patch.
## Final validation protocol
1. Compile the final query.2. Run it on before and inspect `raw/before.sarif` for the intended report location.3. Run the identical query on after and inspect `raw/after.sarif`.4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, and absence of patch-local hardcoding.5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
Do not modify the runtime databases, references, patch, context, or validation scripts except fornormal CodeQL-generated database caches produced by the provided run scripts.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253diff --git a/petl/io/xml.py b/petl/io/xml.pyindex 983d9f6..b63287c 100644--- a/petl/io/xml.py+++ b/petl/io/xml.py@@ -133,6 +133,9 @@ def fromxml(source, *args, **kwargs): or list of paths can be provided, e.g., ``fromxml('example.html', './/tr', ('th', 'td'))``. + Optionally a custom parser can be provided, e.g.,+ ``etl.fromxml('example1.xml', 'tr', 'td', parser=my_parser)``.+ """ source = read_source_from_arg(source)@@ -162,14 +165,15 @@ class XmlView(Table): else: assert False, 'bad parameters' self.missing = kwargs.get('missing', None)+ self.user_parser = kwargs.get('parser', None) def __iter__(self): vmatch = self.vmatch vdict = self.vdict with self.source.open('rb') as xmlf:-- tree = etree.parse(xmlf)+ parser2 = _create_xml_parser(self.user_parser)+ tree = etree.parse(xmlf, parser=parser2) if not hasattr(tree, 'iterfind'): # Python 2.6 compatibility tree.iterfind = tree.findall@@ -219,6 +223,20 @@ class XmlView(Table): for f in flds) +def _create_xml_parser(user_parser):+ if user_parser is not None:+ return user_parser+ try:+ # Default lxml parser.+ # This will throw an error if parser is not set and lxml could not be imported+ # because Python's built XML parser doesn't like the `resolve_entities` kwarg.+ # return etree.XMLParser(resolve_entities=False)+ return etree.XMLParser(resolve_entities=False)+ except TypeError:+ # lxml not available+ return None++ def element_text_getter(missing): def _get(v): if len(v) > 1:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314# Patch-overlapping Python context after the fix
## `petl/io/xml.py` — `function:fromxml` (lines 22-142)
```pythondef fromxml(source, *args, **kwargs): """ Extract data from an XML file. E.g.::
>>> import petl as etl >>> # setup a file to demonstrate with ... d = '''<table> ... <tr> ... <td>foo</td><td>bar</td> ... </tr> ... <tr> ... <td>a</td><td>1</td> ... </tr> ... <tr> ... <td>b</td><td>2</td> ... </tr> ... <tr> ... <td>c</td><td>2</td> ... </tr> ... </table>''' >>> with open('example1.xml', 'w') as f: ... f.write(d) ... 212 >>> table1 = etl.fromxml('example1.xml', 'tr', 'td') >>> table1 +-----+-----+ | foo | bar | +=====+=====+ | 'a' | '1' | +-----+-----+ | 'b' | '2' | +-----+-----+ | 'c' | '2' | +-----+-----+
If the data values are stored in an attribute, provide the attribute name as an extra positional argument::
>>> d = '''<table> ... <tr> ... <td v='foo'/><td v='bar'/> ... </tr> ... <tr> ... <td v='a'/><td v='1'/> ... </tr> ... <tr> ... <td v='b'/><td v='2'/> ... </tr> ... <tr> ... <td v='c'/><td v='2'/> ... </tr> ... </table>''' >>> with open('example2.xml', 'w') as f: ... f.write(d) ... 220 >>> table2 = etl.fromxml('example2.xml', 'tr', 'td', 'v') >>> table2 +-----+-----+ | foo | bar | +=====+=====+ | 'a' | '1' | +-----+-----+ | 'b' | '2' | +-----+-----+ | 'c' | '2' | +-----+-----+
Data values can also be extracted by providing a mapping of field names to element paths::
>>> d = '''<table> ... <row> ... <foo>a</foo><baz><bar v='1'/><bar v='3'/></baz> ... </row> ... <row> ... <foo>b</foo><baz><bar v='2'/></baz> ... </row> ... <row> ... <foo>c</foo><baz><bar v='2'/></baz> ... </row> ... </table>''' >>> with open('example3.xml', 'w') as f: ... f.write(d) ... 223 >>> table3 = etl.fromxml('example3.xml', 'row', ... {'foo': 'foo', 'bar': ('baz/bar', 'v')}) >>> table3 +------------+-----+ | bar | foo | +============+=====+ | ('1', '3') | 'a' | +------------+-----+ | '2' | 'b' | +------------+-----+ | '2' | 'c' | +------------+-----+
If `lxml <http://lxml.de/>`_ is installed, full XPath expressions can be used.
Note that the implementation is currently **not** streaming, i.e., the whole document is loaded into memory.
If multiple elements match a given field, all values are reported as a tuple.
If there is more than one element name used for row values, a tuple or list of paths can be provided, e.g., ``fromxml('example.html', './/tr', ('th', 'td'))``.
Optionally a custom parser can be provided, e.g., ``etl.fromxml('example1.xml', 'tr', 'td', parser=my_parser)``.
"""
source = read_source_from_arg(source) return XmlView(source, *args, **kwargs)```
## `petl/io/xml.py` — `class:XmlView` (lines 145-223)
```pythonclass XmlView(Table):
def __init__(self, source, *args, **kwargs): self.source = source self.args = args if len(args) == 2 and isinstance(args[1], (string_types, tuple, list)): self.rmatch = args[0] self.vmatch = args[1] self.vdict = None self.attr = None elif len(args) == 2 and isinstance(args[1], dict): self.rmatch = args[0] self.vmatch = None self.vdict = args[1] self.attr = None elif len(args) == 3: self.rmatch = args[0] self.vmatch = args[1] self.vdict = None self.attr = args[2] else: assert False, 'bad parameters' self.missing = kwargs.get('missing', None) self.user_parser = kwargs.get('parser', None)
def __iter__(self): vmatch = self.vmatch vdict = self.vdict
with self.source.open('rb') as xmlf: parser2 = _create_xml_parser(self.user_parser) tree = etree.parse(xmlf, parser=parser2) if not hasattr(tree, 'iterfind'): # Python 2.6 compatibility tree.iterfind = tree.findall
if vmatch is not None: # simple case, all value paths are the same for rowelm in tree.iterfind(self.rmatch): if self.attr is None: getv = attrgetter('text') else: getv = lambda e: e.get(self.attr) if isinstance(vmatch, string_types): # match only one path velms = rowelm.findall(vmatch) else: # match multiple paths velms = itertools.chain(*[rowelm.findall(enm) for enm in vmatch]) yield tuple(getv(velm) for velm in velms)
else: # difficult case, deal with different paths for each field
# determine output header flds = tuple(sorted(map(text_type, vdict.keys()))) yield flds
# setup value getters vmatches = dict() vgetters = dict() for f in flds: vmatch = self.vdict[f] if isinstance(vmatch, string_types): # match element path vmatches[f] = vmatch vgetters[f] = element_text_getter(self.missing) else: # match element path and attribute name vmatches[f] = vmatch[0] attr = vmatch[1] vgetters[f] = attribute_text_getter(attr, self.missing)
# determine data rows for rowelm in tree.iterfind(self.rmatch): yield tuple(vgetters[f](rowelm.findall(vmatches[f])) for f in flds)```
## `petl/io/xml.py` — `function:XmlView.__init__` (lines 147-168)
```python def __init__(self, source, *args, **kwargs): self.source = source self.args = args if len(args) == 2 and isinstance(args[1], (string_types, tuple, list)): self.rmatch = args[0] self.vmatch = args[1] self.vdict = None self.attr = None elif len(args) == 2 and isinstance(args[1], dict): self.rmatch = args[0] self.vmatch = None self.vdict = args[1] self.attr = None elif len(args) == 3: self.rmatch = args[0] self.vmatch = args[1] self.vdict = None self.attr = args[2] else: assert False, 'bad parameters' self.missing = kwargs.get('missing', None) self.user_parser = kwargs.get('parser', None)```
## `petl/io/xml.py` — `function:XmlView.__iter__` (lines 170-223)
```python def __iter__(self): vmatch = self.vmatch vdict = self.vdict
with self.source.open('rb') as xmlf: parser2 = _create_xml_parser(self.user_parser) tree = etree.parse(xmlf, parser=parser2) if not hasattr(tree, 'iterfind'): # Python 2.6 compatibility tree.iterfind = tree.findall
if vmatch is not None: # simple case, all value paths are the same for rowelm in tree.iterfind(self.rmatch): if self.attr is None: getv = attrgetter('text') else: getv = lambda e: e.get(self.attr) if isinstance(vmatch, string_types): # match only one path velms = rowelm.findall(vmatch) else: # match multiple paths velms = itertools.chain(*[rowelm.findall(enm) for enm in vmatch]) yield tuple(getv(velm) for velm in velms)
else: # difficult case, deal with different paths for each field
# determine output header flds = tuple(sorted(map(text_type, vdict.keys()))) yield flds
# setup value getters vmatches = dict() vgetters = dict() for f in flds: vmatch = self.vdict[f] if isinstance(vmatch, string_types): # match element path vmatches[f] = vmatch vgetters[f] = element_text_getter(self.missing) else: # match element path and attribute name vmatches[f] = vmatch[0] attr = vmatch[1] vgetters[f] = attribute_text_getter(attr, self.missing)
# determine data rows for rowelm in tree.iterfind(self.rmatch): yield tuple(vgetters[f](rowelm.findall(vmatches[f])) for f in flds)```
## `petl/io/xml.py` — `function:_create_xml_parser` (lines 226-237)
```pythondef _create_xml_parser(user_parser): if user_parser is not None: return user_parser try: # Default lxml parser. # This will throw an error if parser is not set and lxml could not be imported # because Python's built XML parser doesn't like the `resolve_entities` kwarg. # return etree.XMLParser(resolve_entities=False) return etree.XMLParser(resolve_entities=False) except TypeError: # lxml not available return None```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280# Patch-overlapping Python context before the fix
## `petl/io/xml.py` — `function:fromxml` (lines 22-139)
```pythondef fromxml(source, *args, **kwargs): """ Extract data from an XML file. E.g.::
>>> import petl as etl >>> # setup a file to demonstrate with ... d = '''<table> ... <tr> ... <td>foo</td><td>bar</td> ... </tr> ... <tr> ... <td>a</td><td>1</td> ... </tr> ... <tr> ... <td>b</td><td>2</td> ... </tr> ... <tr> ... <td>c</td><td>2</td> ... </tr> ... </table>''' >>> with open('example1.xml', 'w') as f: ... f.write(d) ... 212 >>> table1 = etl.fromxml('example1.xml', 'tr', 'td') >>> table1 +-----+-----+ | foo | bar | +=====+=====+ | 'a' | '1' | +-----+-----+ | 'b' | '2' | +-----+-----+ | 'c' | '2' | +-----+-----+
If the data values are stored in an attribute, provide the attribute name as an extra positional argument::
>>> d = '''<table> ... <tr> ... <td v='foo'/><td v='bar'/> ... </tr> ... <tr> ... <td v='a'/><td v='1'/> ... </tr> ... <tr> ... <td v='b'/><td v='2'/> ... </tr> ... <tr> ... <td v='c'/><td v='2'/> ... </tr> ... </table>''' >>> with open('example2.xml', 'w') as f: ... f.write(d) ... 220 >>> table2 = etl.fromxml('example2.xml', 'tr', 'td', 'v') >>> table2 +-----+-----+ | foo | bar | +=====+=====+ | 'a' | '1' | +-----+-----+ | 'b' | '2' | +-----+-----+ | 'c' | '2' | +-----+-----+
Data values can also be extracted by providing a mapping of field names to element paths::
>>> d = '''<table> ... <row> ... <foo>a</foo><baz><bar v='1'/><bar v='3'/></baz> ... </row> ... <row> ... <foo>b</foo><baz><bar v='2'/></baz> ... </row> ... <row> ... <foo>c</foo><baz><bar v='2'/></baz> ... </row> ... </table>''' >>> with open('example3.xml', 'w') as f: ... f.write(d) ... 223 >>> table3 = etl.fromxml('example3.xml', 'row', ... {'foo': 'foo', 'bar': ('baz/bar', 'v')}) >>> table3 +------------+-----+ | bar | foo | +============+=====+ | ('1', '3') | 'a' | +------------+-----+ | '2' | 'b' | +------------+-----+ | '2' | 'c' | +------------+-----+
If `lxml <http://lxml.de/>`_ is installed, full XPath expressions can be used.
Note that the implementation is currently **not** streaming, i.e., the whole document is loaded into memory.
If multiple elements match a given field, all values are reported as a tuple.
If there is more than one element name used for row values, a tuple or list of paths can be provided, e.g., ``fromxml('example.html', './/tr', ('th', 'td'))``.
"""
source = read_source_from_arg(source) return XmlView(source, *args, **kwargs)```
## `petl/io/xml.py` — `class:XmlView` (lines 142-219)
```pythonclass XmlView(Table):
def __init__(self, source, *args, **kwargs): self.source = source self.args = args if len(args) == 2 and isinstance(args[1], (string_types, tuple, list)): self.rmatch = args[0] self.vmatch = args[1] self.vdict = None self.attr = None elif len(args) == 2 and isinstance(args[1], dict): self.rmatch = args[0] self.vmatch = None self.vdict = args[1] self.attr = None elif len(args) == 3: self.rmatch = args[0] self.vmatch = args[1] self.vdict = None self.attr = args[2] else: assert False, 'bad parameters' self.missing = kwargs.get('missing', None)
def __iter__(self): vmatch = self.vmatch vdict = self.vdict
with self.source.open('rb') as xmlf:
tree = etree.parse(xmlf) if not hasattr(tree, 'iterfind'): # Python 2.6 compatibility tree.iterfind = tree.findall
if vmatch is not None: # simple case, all value paths are the same for rowelm in tree.iterfind(self.rmatch): if self.attr is None: getv = attrgetter('text') else: getv = lambda e: e.get(self.attr) if isinstance(vmatch, string_types): # match only one path velms = rowelm.findall(vmatch) else: # match multiple paths velms = itertools.chain(*[rowelm.findall(enm) for enm in vmatch]) yield tuple(getv(velm) for velm in velms)
else: # difficult case, deal with different paths for each field
# determine output header flds = tuple(sorted(map(text_type, vdict.keys()))) yield flds
# setup value getters vmatches = dict() vgetters = dict() for f in flds: vmatch = self.vdict[f] if isinstance(vmatch, string_types): # match element path vmatches[f] = vmatch vgetters[f] = element_text_getter(self.missing) else: # match element path and attribute name vmatches[f] = vmatch[0] attr = vmatch[1] vgetters[f] = attribute_text_getter(attr, self.missing)
# determine data rows for rowelm in tree.iterfind(self.rmatch): yield tuple(vgetters[f](rowelm.findall(vmatches[f])) for f in flds)```
## `petl/io/xml.py` — `function:XmlView.__iter__` (lines 166-219)
```python def __iter__(self): vmatch = self.vmatch vdict = self.vdict
with self.source.open('rb') as xmlf:
tree = etree.parse(xmlf) if not hasattr(tree, 'iterfind'): # Python 2.6 compatibility tree.iterfind = tree.findall
if vmatch is not None: # simple case, all value paths are the same for rowelm in tree.iterfind(self.rmatch): if self.attr is None: getv = attrgetter('text') else: getv = lambda e: e.get(self.attr) if isinstance(vmatch, string_types): # match only one path velms = rowelm.findall(vmatch) else: # match multiple paths velms = itertools.chain(*[rowelm.findall(enm) for enm in vmatch]) yield tuple(getv(velm) for velm in velms)
else: # difficult case, deal with different paths for each field
# determine output header flds = tuple(sorted(map(text_type, vdict.keys()))) yield flds
# setup value getters vmatches = dict() vgetters = dict() for f in flds: vmatch = self.vdict[f] if isinstance(vmatch, string_types): # match element path vmatches[f] = vmatch vgetters[f] = element_text_getter(self.missing) else: # match element path and attribute name vmatches[f] = vmatch[0] attr = vmatch[1] vgetters[f] = attribute_text_getter(attr, self.missing)
# determine data rows for rowelm in tree.iterfind(self.rmatch): yield tuple(vgetters[f](rowelm.findall(vmatches[f])) for f in flds)```
## `petl/io/xml.py` — `function:element_text_getter` (lines 222-230)
```pythondef element_text_getter(missing): def _get(v): if len(v) > 1: return tuple(e.text for e in v) elif len(v) == 1: return v[0].text else: return missing return _get```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051{ "schema_version": "synthesis-task-v1", "task": { "pair_id": "pyvul-394adf7b067d96b356ca", "dataset_id": "PyVul", "dataset_item_id": "pyvul-394adf7b067d96b356ca", "project_id": "pyvul__petl-developers__petl", "language": "python", "backend": "codeql" }, "changed_python_files": [ "petl/io/xml.py" ], "patch_units": { "before": [ "function:fromxml", "class:XmlView", "function:XmlView.__iter__", "function:element_text_getter" ], "after": [ "function:fromxml", "class:XmlView", "function:XmlView.__init__", "function:XmlView.__iter__", "function:_create_xml_parser" ] }, "runtime_assets": { "before": { "database": "assets/fcb47a17185a332c24eecb3d2d4506cc6dd1ab2f313ab3bcf087aed38ddb4ecb/database", "cache_key": "fcb47a17185a332c24eecb3d2d4506cc6dd1ab2f313ab3bcf087aed38ddb4ecb", "codeql_version": "2.26.4" }, "after": { "database": "assets/c269b96e8d78a0ff93ceeec45f19adcb8bd0807c764fc5ff1ddf3e141ec1e71a/database", "cache_key": "c269b96e8d78a0ff93ceeec45f19adcb8bd0807c764fc5ff1ddf3e141ec1e71a", "codeql_version": "2.26.4" }, "refine": { "database": "assets/83698b843f83dfc980db192656c5e8ad2835066c6e096f242e89cf727ededf65/database", "cache_key": "83698b843f83dfc980db192656c5e8ad2835066c6e096f242e89cf727ededf65", "codeql_version": "2.26.4" } }, "benchmark_contract": { "agent_visible": true, "reference_query_location": "references/pyvul-394adf7b067d96b356ca/query/ (do not mount into agent)", "evaluator_location": "evaluator/pyvul-394adf7b067d96b356ca/ (do not mount into agent)" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Python CodeQL detector synthesis
You are cc operating in `/work`. Starting only from the supplied patch,before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQLdetector for the vulnerability fixed by the patch. This is one fresh session. You may iterate insidethis session, but no later framework repair or resume will occur.
## Inputs and owned outputs
- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.- Read `references/codeql/convergence_protocol.md` and `references/codeql/api_navigation.md` before experimenting. Read the remaining `references/codeql/` files for the selected mechanism.- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is uncertain. Do not guess predicate names or build a large family of inspection queries.- Complete the design contract in `state.json` and `scope_statement.md` before final validation.- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the fixed offline dependency in `query/qlpack.yml`.- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This task-unique metadata must never be used in a query predicate.- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
## Required reasoning contract
Before coding, record this mapping in `state.json`:
```textvulnerable operation / trigger / patch safety condition → CodeQL-observable evidence → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism → source, sink/report site, guard/barrier and query predicates```
Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches requirereal path/control-flow semantics; provenance-sensitive patches require value flow. Do not replaceeither with source-text matching or with the mere presence of patch-added syntax.
## Mandatory convergence contract
The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query isa failure; an early compilable semantic candidate can be improved. Follow the checkpoints in`references/codeql/convergence_protocol.md`:
1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` immediately. Do not wait until every CodeQL API detail is known.2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled definition with `scripts/search_codeql_api.sh` or simplify the mechanism.3. Obtain a compiling minimal main query before broadening it. Compile the main query after every meaningful mechanism change.4. Move in order from compile → relevant before finding → after elimination → final contract. Do not continue API exploration after the intended before/after differential is established.5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all exploration, preserve the best compiling query, finish the contract files, and exit.
## Semantic and generalization rules
- Report at the vulnerable call, operator, access, or sink.- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary matching condition. Stable library/framework APIs or public project APIs are allowed only when `scope_statement.md` explains why they define the intended vulnerability family.- The safety condition introduced by the patch must be represented by the query.- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it changed in the patch.
## Final validation protocol
1. Compile the final query.2. Run it on before and inspect `raw/before.sarif` for the intended report location.3. Run the identical query on after and inspect `raw/after.sarif`.4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, and absence of patch-local hardcoding.5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
Do not modify the runtime databases, references, patch, context, or validation scripts except fornormal CodeQL-generated database caches produced by the provided run scripts.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912diff --git a/poetry.lock b/poetry.lockindex a7197f5f28b..78b0adedf13 100644--- a/poetry.lock+++ b/poetry.lock@@ -242,14 +242,14 @@ numpy = ">=1.15.0" [[package]] name = "boto3"-version = "1.18.52"+version = "1.18.58" description = "The AWS SDK for Python" category = "main" optional = false python-versions = ">= 3.6" [package.dependencies]-botocore = ">=1.21.52,<1.22.0"+botocore = ">=1.21.58,<1.22.0" jmespath = ">=0.7.1,<1.0.0" s3transfer = ">=0.5.0,<0.6.0" @@ -258,7 +258,7 @@ crt = ["botocore[crt] (>=1.21.0,<2.0a0)"] [[package]] name = "botocore"-version = "1.21.52"+version = "1.21.58" description = "Low-level, data-driven core of boto 3." category = "main" optional = false@@ -302,7 +302,7 @@ zipp = {version = ">=0.5", markers = "python_version < \"3.8\""} [[package]] name = "certifi"-version = "2021.5.30"+version = "2021.10.8" description = "Python package for providing Mozilla's CA Bundle." category = "main" optional = false@@ -440,7 +440,7 @@ yaml = ["PyYAML (>=3.10)"] [[package]] name = "cryptography"-version = "3.4.8"+version = "35.0.0" description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." category = "main" optional = false@@ -453,9 +453,9 @@ cffi = ">=1.12" docs = ["sphinx (>=1.6.5,!=1.8.0,!=3.1.0,!=3.1.1)", "sphinx-rtd-theme"] docstest = ["doc8", "pyenchant (>=1.6.11)", "twine (>=1.12.0)", "sphinxcontrib-spelling (>=4.0.1)"] pep8test = ["black", "flake8", "flake8-import-order", "pep8-naming"]-sdist = ["setuptools-rust (>=0.11.4)"]+sdist = ["setuptools_rust (>=0.11.4)"] ssh = ["bcrypt (>=3.1.5)"]-test = ["pytest (>=6.0)", "pytest-cov", "pytest-subtests", "pytest-xdist", "pretend", "iso8601", "pytz", "hypothesis (>=1.11.4,!=3.79.2)"]+test = ["pytest (>=6.2.0)", "pytest-cov", "pytest-subtests", "pytest-xdist", "pretend", "iso8601", "pytz", "hypothesis (>=1.11.4,!=3.79.2)"] [[package]] name = "cycler"@@ -603,15 +603,15 @@ requests = ">=2.0" [[package]] name = "filelock"-version = "3.2.0"+version = "3.3.0" description = "A platform independent file lock." category = "main" optional = true-python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7"+python-versions = ">=3.6" [package.extras] docs = ["furo (>=2021.8.17b43)", "sphinx (>=4.1)", "sphinx-autodoc-typehints (>=1.12)"]-testing = ["coverage (>=4)", "pytest (>=4)", "pytest-cov", "pytest-timeout (>=1.4.2)"]+testing = ["covdefaults (>=1.2.0)", "coverage (>=4)", "pytest (>=4)", "pytest-cov", "pytest-timeout (>=1.4.2)"] [[package]] name = "flake8"@@ -717,7 +717,7 @@ typing-extensions = {version = ">=3.7.4.3", markers = "python_version < \"3.10\" [[package]] name = "google-api-core"-version = "2.0.1"+version = "2.1.0" description = "Google API client core library" category = "dev" optional = false@@ -770,7 +770,7 @@ tool = ["click (>=6.0.0)"] [[package]] name = "google-cloud-core"-version = "2.0.0"+version = "2.1.0" description = "Google Cloud API client core library" category = "dev" optional = false@@ -802,7 +802,7 @@ six = "*" [[package]] name = "google-crc32c"-version = "1.2.0"+version = "1.3.0" description = "A python wrapper of the C library 'Google CRC32C'" category = "dev" optional = false@@ -930,11 +930,11 @@ python-versions = ">=3.6" [[package]] name = "httplib2"-version = "0.19.1"+version = "0.20.1" description = "A comprehensive HTTP client library." category = "main" optional = false-python-versions = "*"+python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" [package.dependencies] pyparsing = ">=2.4.2,<3"@@ -1087,7 +1087,7 @@ python-versions = "*" [[package]] name = "jinja2"-version = "3.0.1"+version = "3.0.2" description = "A very fast and expressive template engine." category = "main" optional = false@@ -1706,11 +1706,11 @@ wcwidth = "*" [[package]] name = "protobuf"-version = "3.18.0"+version = "3.18.1" description = "Protocol Buffers" category = "main" optional = false-python-versions = "*"+python-versions = ">=3.5" [[package]] name = "psutil"@@ -1849,18 +1849,18 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" [[package]] name = "pyjwt"-version = "2.1.0"+version = "2.2.0" description = "JSON Web Token implementation in Python" category = "main" optional = false python-versions = ">=3.6" [package.dependencies]-cryptography = {version = ">=3.3.1,<4.0.0", optional = true, markers = "extra == \"crypto\""}+cryptography = {version = ">=3.3.1", optional = true, markers = "extra == \"crypto\""} [package.extras]-crypto = ["cryptography (>=3.3.1,<4.0.0)"]-dev = ["sphinx", "sphinx-rtd-theme", "zope.interface", "cryptography (>=3.3.1,<4.0.0)", "pytest (>=6.0.0,<7.0.0)", "coverage[toml] (==5.0.4)", "mypy", "pre-commit"]+crypto = ["cryptography (>=3.3.1)"]+dev = ["sphinx", "sphinx-rtd-theme", "zope.interface", "cryptography (>=3.3.1)", "pytest (>=6.0.0,<7.0.0)", "coverage[toml] (==5.0.4)", "mypy", "pre-commit"] docs = ["sphinx", "sphinx-rtd-theme", "zope.interface"] tests = ["pytest (>=6.0.0,<7.0.0)", "coverage[toml] (==5.0.4)"] @@ -2100,7 +2100,7 @@ client = ["requests (>=2.21.0)", "websocket-client (>=0.54.0)"] [[package]] name = "pytz"-version = "2021.1"+version = "2021.3" description = "World timezone definitions, modern and historical" category = "main" optional = false@@ -2656,6 +2656,14 @@ python-versions = "*" [package.extras] widechars = ["wcwidth"] +[[package]]+name = "tarsafe"+version = "0.0.3"+description = "A safe subclass of the TarFile class for interacting with tar files. Can be used as a direct drop-in replacement for safe usage of extractall()"+category = "main"+optional = false+python-versions = ">=3.6"+ [[package]] name = "tensorboard" version = "2.6.0"@@ -2854,7 +2862,7 @@ torch = ["torch (>=1.5.0)"] [[package]] name = "threadpoolctl"-version = "2.2.0"+version = "3.0.0" description = "threadpoolctl" category = "main" optional = false@@ -2970,7 +2978,7 @@ python-versions = "*" [[package]] name = "typeguard"-version = "2.12.1"+version = "2.13.0" description = "Run-time type checker for Python" category = "main" optional = false@@ -3066,11 +3074,11 @@ python-versions = ">=3.6" [[package]] name = "uritemplate"-version = "3.0.1"-description = "URI templates"+version = "4.0.0"+description = "Implementation of RFC 6570 URI Templates" category = "main" optional = true-python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"+python-versions = ">=3.6" [[package]] name = "urllib3"@@ -3144,7 +3152,7 @@ python-versions = ">=3.6" [[package]] name = "werkzeug"-version = "2.0.1"+version = "2.0.2" description = "The comprehensive WSGI web application library." category = "main" optional = false@@ -3174,7 +3182,7 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" [[package]] name = "yarl"-version = "1.6.3"+version = "1.7.0" description = "Yet another URL library" category = "main" optional = false@@ -3207,7 +3215,7 @@ transformers = ["transformers"] [metadata] lock-version = "1.1" python-versions = ">=3.6,<3.9"-content-hash = "209f285fcf47fff7c9fbcec651ed96156f03eb286f49b23c8047579fdd5adf8a"+content-hash = "2fc451ce1e7553b33a12596867363114792c8ab2cde3148b60f57126e6cc635c" [metadata.files] absl-py = [@@ -3333,12 +3341,12 @@ blis = [ {file = "blis-0.7.4.tar.gz", hash = "sha256:7daa615a97d4f28db0f332b710bfe1900b15d0c25841c6d727965e4fd91e09cf"}, ] boto3 = [- {file = "boto3-1.18.52-py3-none-any.whl", hash = "sha256:27824d3767c5213f0006f71e552b912bc4659241b77ca8b0be0b813cf0518a9e"},- {file = "boto3-1.18.52.tar.gz", hash = "sha256:5b585a279478bd6df4b07db7d6150f413ba6add1f38e68aaa533d3337efd0b22"},+ {file = "boto3-1.18.58-py3-none-any.whl", hash = "sha256:7309552da6ef9e610f8a9712c8abe29a8d3d45b514188cc3efad47bd1774bf77"},+ {file = "boto3-1.18.58.tar.gz", hash = "sha256:f680dee9c670d42ab4a6da5539ca3691d1ccbbcbf041e7021025029776864156"}, ] botocore = [- {file = "botocore-1.21.52-py3-none-any.whl", hash = "sha256:e8797c0933c660e130cf2f51667f5003950d7e592f4c3944e8f04f201493d17a"},- {file = "botocore-1.21.52.tar.gz", hash = "sha256:04c071aec4f1981b38e3be760838b976337fd6ebd95a31ceeca9f9e4b4733c1f"},+ {file = "botocore-1.21.58-py3-none-any.whl", hash = "sha256:9d84a97015c0565a81c0b6d55e60af5ab1a2da28039ad93976388014a14186da"},+ {file = "botocore-1.21.58.tar.gz", hash = "sha256:87e881569c32b218a1b82ecb607a4dddb4dca3b80a5d1016571b99b51cef3158"}, ] cached-property = [ {file = "cached-property-1.5.2.tar.gz", hash = "sha256:9fa5755838eecbb2d234c3aa390bd80fbd3ac6b6869109bfc1b499f7bd89a130"},@@ -3353,8 +3361,8 @@ catalogue = [ {file = "catalogue-2.0.6.tar.gz", hash = "sha256:336a35603f447167042ef504114d6befa46688f03f4c14dabdc633a44587b245"}, ] certifi = [- {file = "certifi-2021.5.30-py2.py3-none-any.whl", hash = "sha256:50b1e4f8446b06f41be7dd6338db18e0990601dce795c2b1686458aa7e8fa7d8"},- {file = "certifi-2021.5.30.tar.gz", hash = "sha256:2bbf76fd432960138b3ef6dda3dde0544f27cbf8546c458e60baf371917ba9ee"},+ {file = "certifi-2021.10.8-py2.py3-none-any.whl", hash = "sha256:d62a0163eb4c2344ac042ab2bdf75399a71a2d8c7d47eac2e2ee91b9d6339569"},+ {file = "certifi-2021.10.8.tar.gz", hash = "sha256:78884e7c1d4b00ce3cea67b44566851c4343c120abd683433ce934a68ea58872"}, ] cffi = [ {file = "cffi-1.14.6-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:22b9c3c320171c108e903d61a3723b51e37aaa8c81255b5e7ce102775bd01e2c"},@@ -3499,23 +3507,26 @@ coveralls = [ {file = "coveralls-3.2.0.tar.gz", hash = "sha256:15a987d9df877fff44cd81948c5806ffb6eafb757b3443f737888358e96156ee"}, ] cryptography = [- {file = "cryptography-3.4.8-cp36-abi3-macosx_10_10_x86_64.whl", hash = "sha256:a00cf305f07b26c351d8d4e1af84ad7501eca8a342dedf24a7acb0e7b7406e14"},- {file = "cryptography-3.4.8-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:f44d141b8c4ea5eb4dbc9b3ad992d45580c1d22bf5e24363f2fbf50c2d7ae8a7"},- {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:0a7dcbcd3f1913f664aca35d47c1331fce738d44ec34b7be8b9d332151b0b01e"},- {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:34dae04a0dce5730d8eb7894eab617d8a70d0c97da76b905de9efb7128ad7085"},- {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1eb7bb0df6f6f583dd8e054689def236255161ebbcf62b226454ab9ec663746b"},- {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_24_x86_64.whl", hash = "sha256:9965c46c674ba8cc572bc09a03f4c649292ee73e1b683adb1ce81e82e9a6a0fb"},- {file = "cryptography-3.4.8-cp36-abi3-win32.whl", hash = "sha256:21ca464b3a4b8d8e86ba0ee5045e103a1fcfac3b39319727bc0fc58c09c6aff7"},- {file = "cryptography-3.4.8-cp36-abi3-win_amd64.whl", hash = "sha256:3520667fda779eb788ea00080124875be18f2d8f0848ec00733c0ec3bb8219fc"},- {file = "cryptography-3.4.8-pp36-pypy36_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d2a6e5ef66503da51d2110edf6c403dc6b494cc0082f85db12f54e9c5d4c3ec5"},- {file = "cryptography-3.4.8-pp36-pypy36_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a305600e7a6b7b855cd798e00278161b681ad6e9b7eca94c721d5f588ab212af"},- {file = "cryptography-3.4.8-pp36-pypy36_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:3fa3a7ccf96e826affdf1a0a9432be74dc73423125c8f96a909e3835a5ef194a"},- {file = "cryptography-3.4.8-pp37-pypy37_pp73-macosx_10_10_x86_64.whl", hash = "sha256:d9ec0e67a14f9d1d48dd87a2531009a9b251c02ea42851c060b25c782516ff06"},- {file = "cryptography-3.4.8-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5b0fbfae7ff7febdb74b574055c7466da334a5371f253732d7e2e7525d570498"},- {file = "cryptography-3.4.8-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:94fff993ee9bc1b2440d3b7243d488c6a3d9724cc2b09cdb297f6a886d040ef7"},- {file = "cryptography-3.4.8-pp37-pypy37_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:8695456444f277af73a4877db9fc979849cd3ee74c198d04fc0776ebc3db52b9"},- {file = "cryptography-3.4.8-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:cd65b60cfe004790c795cc35f272e41a3df4631e2fb6b35aa7ac6ef2859d554e"},- {file = "cryptography-3.4.8.tar.gz", hash = "sha256:94cc5ed4ceaefcbe5bf38c8fba6a21fc1d365bb8fb826ea1688e3370b2e24a1c"},+ {file = "cryptography-35.0.0-cp36-abi3-macosx_10_10_x86_64.whl", hash = "sha256:d57e0cdc1b44b6cdf8af1d01807db06886f10177469312fbde8f44ccbb284bc9"},+ {file = "cryptography-35.0.0-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:ced40344e811d6abba00295ced98c01aecf0c2de39481792d87af4fa58b7b4d6"},+ {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:54b2605e5475944e2213258e0ab8696f4f357a31371e538ef21e8d61c843c28d"},+ {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:7b7ceeff114c31f285528ba8b390d3e9cfa2da17b56f11d366769a807f17cbaa"},+ {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2d69645f535f4b2c722cfb07a8eab916265545b3475fdb34e0be2f4ee8b0b15e"},+ {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4a2d0e0acc20ede0f06ef7aa58546eee96d2592c00f450c9acb89c5879b61992"},+ {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_24_x86_64.whl", hash = "sha256:07bb7fbfb5de0980590ddfc7f13081520def06dc9ed214000ad4372fb4e3c7f6"},+ {file = "cryptography-35.0.0-cp36-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:7eba2cebca600a7806b893cb1d541a6e910afa87e97acf2021a22b32da1df52d"},+ {file = "cryptography-35.0.0-cp36-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:18d90f4711bf63e2fb21e8c8e51ed8189438e6b35a6d996201ebd98a26abbbe6"},+ {file = "cryptography-35.0.0-cp36-abi3-win32.whl", hash = "sha256:c10c797ac89c746e488d2ee92bd4abd593615694ee17b2500578b63cad6b93a8"},+ {file = "cryptography-35.0.0-cp36-abi3-win_amd64.whl", hash = "sha256:7075b304cd567694dc692ffc9747f3e9cb393cc4aa4fb7b9f3abd6f5c4e43588"},+ {file = "cryptography-35.0.0-pp36-pypy36_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a688ebcd08250eab5bb5bca318cc05a8c66de5e4171a65ca51db6bd753ff8953"},+ {file = "cryptography-35.0.0-pp36-pypy36_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d99915d6ab265c22873f1b4d6ea5ef462ef797b4140be4c9d8b179915e0985c6"},+ {file = "cryptography-35.0.0-pp36-pypy36_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:928185a6d1ccdb816e883f56ebe92e975a262d31cc536429041921f8cb5a62fd"},+ {file = "cryptography-35.0.0-pp37-pypy37_pp73-macosx_10_10_x86_64.whl", hash = "sha256:ebeddd119f526bcf323a89f853afb12e225902a24d29b55fe18dd6fcb2838a76"},+ {file = "cryptography-35.0.0-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:22a38e96118a4ce3b97509443feace1d1011d0571fae81fc3ad35f25ba3ea999"},+ {file = "cryptography-35.0.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eb80e8a1f91e4b7ef8b33041591e6d89b2b8e122d787e87eeb2b08da71bb16ad"},+ {file = "cryptography-35.0.0-pp37-pypy37_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:abb5a361d2585bb95012a19ed9b2c8f412c5d723a9836418fab7aaa0243e67d2"},+ {file = "cryptography-35.0.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:1ed82abf16df40a60942a8c211251ae72858b25b7421ce2497c2eb7a1cee817c"},+ {file = "cryptography-35.0.0.tar.gz", hash = "sha256:9933f28f70d0517686bd7de36166dda42094eac49415459d9bdf5e7df3e0086d"}, ] cycler = [ {file = "cycler-0.10.0-py2.py3-none-any.whl", hash = "sha256:1d8a5ae1ff6c5cf9b93e8811e581232ad8920aeec647c37316ceac982b08cb2d"},@@ -3595,8 +3606,8 @@ fbmessenger = [ {file = "fbmessenger-6.0.0.tar.gz", hash = "sha256:6e42c4588a4c942547be228886278bbc7a084e0b34799c7e6ebd786129f021e6"}, ] filelock = [- {file = "filelock-3.2.0-py2.py3-none-any.whl", hash = "sha256:61a99e9b12b47b685d1389f4cf969c1eba0efd2348a8471f86e01e8c622267af"},- {file = "filelock-3.2.0.tar.gz", hash = "sha256:85ecb30757aa19d06bfcdad29cc332b9a3e4851bf59976aea1e8dadcbd9ef883"},+ {file = "filelock-3.3.0-py3-none-any.whl", hash = "sha256:bbc6a0382fe8ec4744ecdf6683a2e07f65eb10ff1aff53fc02a202565446cde0"},+ {file = "filelock-3.3.0.tar.gz", hash = "sha256:8c7eab13dc442dc249e95158bcc12dec724465919bdc9831fdbf0660f03d1785"}, ] flake8 = [ {file = "flake8-3.9.2-py2.py3-none-any.whl", hash = "sha256:bf8fd333346d844f616e8d47905ef3a3384edae6b4e9beb0c5101e25e3110907"},@@ -3634,8 +3645,8 @@ gitpython = [ {file = "GitPython-3.1.20.tar.gz", hash = "sha256:df0e072a200703a65387b0cfdf0466e3bab729c0458cf6b7349d0e9877636519"}, ] google-api-core = [- {file = "google-api-core-2.0.1.tar.gz", hash = "sha256:d6760f21b3a064a8397916b33be7383fc169d1a3c3d7fae7b47eb92bba7892b8"},- {file = "google_api_core-2.0.1-py2.py3-none-any.whl", hash = "sha256:b8ad41f72a70dd709dd13a08478936172aecf5f2d34a18ab378efa6d2d6ab575"},+ {file = "google-api-core-2.1.0.tar.gz", hash = "sha256:5ec27b942b34d04559cbf3674430bb83fc3d74e7d32b8bbd31c4466e71740b83"},+ {file = "google_api_core-2.1.0-py2.py3-none-any.whl", hash = "sha256:c344e1aacd8330527c5130bdfe03118d8859ce798bcf0e5d23770ab6873e0615"}, ] google-auth = [ {file = "google-auth-1.35.0.tar.gz", hash = "sha256:b7033be9028c188ee30200b204ea00ed82ea1162e8ac1df4aa6ded19a191d88e"},@@ -3646,57 +3657,57 @@ google-auth-oauthlib = [ {file = "google_auth_oauthlib-0.4.6-py2.py3-none-any.whl", hash = "sha256:3f2a6e802eebbb6fb736a370fbf3b055edcb6b52878bf2f26330b5e041316c73"}, ] google-cloud-core = [- {file = "google-cloud-core-2.0.0.tar.gz", hash = "sha256:90ee99648ccf9e11a16781a7fc58d13e58f662b439c737d48c24ef18662c2702"},- {file = "google_cloud_core-2.0.0-py2.py3-none-any.whl", hash = "sha256:31785d1e1d02f90ad3f1b020d4aed63db4865c3394ff7c128a296b6995eef31f"},+ {file = "google-cloud-core-2.1.0.tar.gz", hash = "sha256:35a1f5f02a86e0fa2e28c669f0db4a76d928671a28fbbbb493ab59ba9d1cb9a9"},+ {file = "google_cloud_core-2.1.0-py2.py3-none-any.whl", hash = "sha256:8d5fed11731dae8bc8656a2c9fa8ff17bdfdfd083cba97569324e35b94e7e002"}, ] google-cloud-storage = [ {file = "google-cloud-storage-1.42.3.tar.gz", hash = "sha256:7754d4dcaa45975514b404ece0da2bb4292acbc67ca559a69e12a19d54fcdb06"}, {file = "google_cloud_storage-1.42.3-py2.py3-none-any.whl", hash = "sha256:71ee3a0dcf2c139f034a054181cd7658f1ec8f12837d2769c450a8a00fcd4c6d"}, ] google-crc32c = [- {file = "google-crc32c-1.2.0.tar.gz", hash = "sha256:258caf72c4ab03d91e593ed9f988c13c118754f5ce46d8bcbc40b109d14cb8b7"},- {file = "google_crc32c-1.2.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b64bd23a66410883c22c156834b73515e3f3d8c890c0407620f960b4c25cc8a3"},- {file = "google_crc32c-1.2.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:61080f164ea51e156153c601b1de35ccb574d77efb669c11ade75f8635ce2d29"},- {file = "google_crc32c-1.2.0-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:f563a48074de0a4ebf1ef1d55aeb16bdaa6715c33091dad3b6a32716d2a5d4a4"},- {file = "google_crc32c-1.2.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:242274e127e349e6ede67d7232872bdac9f6c36da6233216e8e4f5923eef1a7c"},- {file = "google_crc32c-1.2.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:93f1377269cf30b15b296e760ac3f6e13ea52556a764739410fa2e7b32a39e93"},- {file = "google_crc32c-1.2.0-cp310-cp310-win32.whl", hash = "sha256:60f9e93e29cbaa47f57230907733af884685dbac78d462019ffe02d514bbfddc"},- {file = "google_crc32c-1.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:b28e81707257802d1e07aee4a2513d1316f623a1b48b78885c1ca2a9ec47949d"},- {file = "google_crc32c-1.2.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:837a17d940dac5b0d0a88868a2be924bbb31578de20c250620c09ac7c3f9d1fd"},- {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:966186c535fec30606cb7787e3caa283631f80c50cbd7226e7db1589ede0f177"},- {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:617ec1f65d769e670dd35d9e8db0244d03bb09b8728262e28ebeab82de8d1341"},- {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca0f7bcb47dbd1367bb8f2d7dfc90568a7f69e4062dd70b21a365fc361c9929d"},- {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:e7b98a2dabe06a460219ecad21113d1c9d793910ceeeae8b4fb64871ef203c4c"},- {file = "google_crc32c-1.2.0-cp36-cp36m-win32.whl", hash = "sha256:a6307368bc04f07d3bdf554109d5ebd64b350c12e1a3604686e7a2d913585b1e"},- {file = "google_crc32c-1.2.0-cp36-cp36m-win_amd64.whl", hash = "sha256:4b2f3a9f61f264029ffbaf9f503340da1e72e602650eb46d34940a431e3a2676"},- {file = "google_crc32c-1.2.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:ce877f9ce49db4f465d942ea910475d79148b390e5890efb2e505df9596d5ced"},- {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:c9a057c13a268c3a03d1fc8aa08358952b7ff560bb2893fe46dd5823cc0f47b7"},- {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:ad1cfabad6e9d4affd03684fde2763fa47b6d5a9696a03df3bb23f197cf55af1"},- {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b19ee0a14107fc29a24129982f16648908363b0c43cf6a2b68ece7768c4d038b"},- {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:fd55f480bb87e1f03b08a8bff13a0689efa7bf10426f1b58f2081168a05b3463"},- {file = "google_crc32c-1.2.0-cp37-cp37m-win32.whl", hash = "sha256:6690bbdbfafc39f7031e19e07965b28b91cf41f3a66267e9e9f75b7bcbcd8ac6"},- {file = "google_crc32c-1.2.0-cp37-cp37m-win_amd64.whl", hash = "sha256:8331f0cbf8d91e868858a95c3608c26c2b8872f0ed8464c58425995aa92cb70b"},- {file = "google_crc32c-1.2.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:96e7057e29abfe763db02877b7cafff8a076145feb446106409f4fc12549d281"},- {file = "google_crc32c-1.2.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:496d7d6ac406f3a8e9f1e2fea93bc5470d5ff02c6ea34745c9aa5f22c876f30e"},- {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:8a862ea73b86c3b6589847224195e1027a876c85dc1f87475509b58d2aaafcda"},- {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:eb32e021526e905500c08aa030461621e5af934bf68a910322f5ddebb8c2bbf9"},- {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6e720b0c9df6a58d4786c299407c2561993e9abd41d37c38e09d33288a3aca0d"},- {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:8aa4de2ffad9d5521d9ba105a1a59126423389598cb4f9af9d28d4da845c0414"},- {file = "google_crc32c-1.2.0-cp38-cp38-win32.whl", hash = "sha256:adb721315435d8530a9eabce2cf3731db015ca0af5f8f983bf5c6e5272385c02"},- {file = "google_crc32c-1.2.0-cp38-cp38-win_amd64.whl", hash = "sha256:a7920ea4770ec6b98a30e99f9ab90aacc0a447a316c165701f264234d8dbf731"},- {file = "google_crc32c-1.2.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:c242c82eef7fb75ee698ecc65596e324b3273ae3dd78a8e5f05bf3cb627caa3b"},- {file = "google_crc32c-1.2.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a6694773dd45c88b2babef6b702b6233723ae4f42cca0fbc68114e81ed389188"},- {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:70670518d50babd6012de3206472aa406a41b79acb11b6e46931f842e25a356a"},- {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:dc12aef85a7b8e5c52d7639cf23e27548f09fba798b8050f59fdd5bee08051f2"},- {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8e13c8f1fbde9b543f693c42c0f82ba6c57683d66cc2c5960c6c66fccb42a736"},- {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:483694ccb1d0ceab8219afc4f20939565b09f81531bf8dd2bf3efb3ea84766fe"},- {file = "google_crc32c-1.2.0-cp39-cp39-win32.whl", hash = "sha256:618c304e803fb5e4b1dbe4d529e1047450d913b64dc4e49826bb3e5a0ef73a9e"},- {file = "google_crc32c-1.2.0-cp39-cp39-win_amd64.whl", hash = "sha256:60c4f32d1fbd25234ff9468de24c1c8a9556e90ac94818a99c8cfc83328214d1"},- {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:4b8c7579269e3c64dda1d63cc9b9ba7615b51092c905b68d43c907be80fc641f"},- {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:c24e7e78756f617ebf006adcb0edb74aaf93a31a45440266e66f5fb2b8c75512"},- {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:81c2e088041fb38b099b5a7fb2407deff74ee9bec3b36c38180564b4686bc1fa"},- {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c422331bdeb5214ecc8a98f85dcbbc5b3222d173b1348874f1087b1f938313d8"},- {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:9caf25a7f2551b117e063ce1e1f3959ef64d8c4e96587e4ce6ee1be7b441b3b7"},+ {file = "google-crc32c-1.3.0.tar.gz", hash = "sha256:276de6273eb074a35bc598f8efbc00c7869c5cf2e29c90748fccc8c898c244df"},+ {file = "google_crc32c-1.3.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:cb6994fff247987c66a8a4e550ef374671c2b82e3c0d2115e689d21e511a652d"},+ {file = "google_crc32c-1.3.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c9da0a39b53d2fab3e5467329ed50e951eb91386e9d0d5b12daf593973c3b168"},+ {file = "google_crc32c-1.3.0-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:eb0b14523758e37802f27b7f8cd973f5f3d33be7613952c0df904b68c4842f0e"},+ {file = "google_crc32c-1.3.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:95c68a4b9b7828ba0428f8f7e3109c5d476ca44996ed9a5f8aac6269296e2d59"},+ {file = "google_crc32c-1.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9c3cf890c3c0ecfe1510a452a165431b5831e24160c5fcf2071f0f85ca5a47cd"},+ {file = "google_crc32c-1.3.0-cp310-cp310-win32.whl", hash = "sha256:3bbce1be3687bbfebe29abdb7631b83e6b25da3f4e1856a1611eb21854b689ea"},+ {file = "google_crc32c-1.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:c124b8c8779bf2d35d9b721e52d4adb41c9bfbde45e6a3f25f0820caa9aba73f"},+ {file = "google_crc32c-1.3.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:42ae4781333e331a1743445931b08ebdad73e188fd554259e772556fc4937c48"},+ {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:ff71073ebf0e42258a42a0b34f2c09ec384977e7f6808999102eedd5b49920e3"},+ {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:fe31de3002e7b08eb20823b3735b97c86c5926dd0581c7710a680b418a8709d4"},+ {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dd7760a88a8d3d705ff562aa93f8445ead54f58fd482e4f9e2bafb7e177375d4"},+ {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:a0b9e622c3b2b8d0ce32f77eba617ab0d6768b82836391e4f8f9e2074582bf02"},+ {file = "google_crc32c-1.3.0-cp36-cp36m-win32.whl", hash = "sha256:779cbf1ce375b96111db98fca913c1f5ec11b1d870e529b1dc7354b2681a8c3a"},+ {file = "google_crc32c-1.3.0-cp36-cp36m-win_amd64.whl", hash = "sha256:04e7c220798a72fd0f08242bc8d7a05986b2a08a0573396187fd32c1dcdd58b3"},+ {file = "google_crc32c-1.3.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:e7a539b9be7b9c00f11ef16b55486141bc2cdb0c54762f84e3c6fc091917436d"},+ {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:ca60076c388728d3b6ac3846842474f4250c91efbfe5afa872d3ffd69dd4b318"},+ {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:05340b60bf05b574159e9bd940152a47d38af3fb43803ffe71f11d704b7696a6"},+ {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:318f73f5484b5671f0c7f5f63741ab020a599504ed81d209b5c7129ee4667407"},+ {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:9f58099ad7affc0754ae42e6d87443299f15d739b0ce03c76f515153a5cda06c"},+ {file = "google_crc32c-1.3.0-cp37-cp37m-win32.whl", hash = "sha256:f52a4ad2568314ee713715b1e2d79ab55fab11e8b304fd1462ff5cccf4264b3e"},+ {file = "google_crc32c-1.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:bab4aebd525218bab4ee615786c4581952eadc16b1ff031813a2fd51f0cc7b08"},+ {file = "google_crc32c-1.3.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:dda4d8a3bb0b50f540f6ff4b6033f3a74e8bf0bd5320b70fab2c03e512a62812"},+ {file = "google_crc32c-1.3.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:fec221a051150eeddfdfcff162e6db92c65ecf46cb0f7bb1bf812a1520ec026b"},+ {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:226f2f9b8e128a6ca6a9af9b9e8384f7b53a801907425c9a292553a3a7218ce0"},+ {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a7f9cbea4245ee36190f85fe1814e2d7b1e5f2186381b082f5d59f99b7f11328"},+ {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6a4db36f9721fdf391646685ecffa404eb986cbe007a3289499020daf72e88a2"},+ {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:12674a4c3b56b706153a358eaa1018c4137a5a04635b92b4652440d3d7386206"},+ {file = "google_crc32c-1.3.0-cp38-cp38-win32.whl", hash = "sha256:650e2917660e696041ab3dcd7abac160b4121cd9a484c08406f24c5964099829"},+ {file = "google_crc32c-1.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:58be56ae0529c664cc04a9c76e68bb92b091e0194d6e3c50bea7e0f266f73713"},+ {file = "google_crc32c-1.3.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:96a8918a78d5d64e07c8ea4ed2bc44354e3f93f46a4866a40e8db934e4c0d74b"},+ {file = "google_crc32c-1.3.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:13af315c3a0eec8bb8b8d80b8b128cb3fcd17d7e4edafc39647846345a3f003a"},+ {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:6311853aa2bba4064d0c28ca54e7b50c4d48e3de04f6770f6c60ebda1e975267"},+ {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:ed447680ff21c14aaceb6a9f99a5f639f583ccfe4ce1a5e1d48eb41c3d6b3217"},+ {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d1c1d6236feab51200272d79b3d3e0f12cf2cbb12b208c835b175a21efdb0a73"},+ {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:e0f1ff55dde0ebcfbef027edc21f71c205845585fffe30d4ec4979416613e9b3"},+ {file = "google_crc32c-1.3.0-cp39-cp39-win32.whl", hash = "sha256:fbd60c6aaa07c31d7754edbc2334aef50601b7f1ada67a96eb1eb57c7c72378f"},+ {file = "google_crc32c-1.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:127f9cc3ac41b6a859bd9dc4321097b1a4f6aa7fdf71b4f9227b9e3ebffb4422"},+ {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:fc28e0db232c62ca0c3600884933178f0825c99be4474cdd645e378a10588125"},+ {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:1926fd8de0acb9d15ee757175ce7242e235482a783cd4ec711cc999fc103c24e"},+ {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5da2c81575cc3ccf05d9830f9e8d3c70954819ca9a63828210498c0774fda1a3"},+ {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:891f712ce54e0d631370e1f4997b3f182f3368179198efc30d477c75d1f44942"},+ {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:7f6fe42536d9dcd3e2ffb9d3053f5d05221ae3bbcefbe472bdf2c71c793e3183"}, ] google-pasta = [ {file = "google-pasta-0.2.0.tar.gz", hash = "sha256:c9f2c8dfc8f96d0d5808299920721be30c9eec37f2389f28904f454565c8a16e"},@@ -3841,8 +3852,8 @@ hstspreload = [ {file = "hstspreload-2021.10.1.tar.gz", hash = "sha256:5bb90f438bec40faf320170ee48cf1978f40423ee1ba39a57bb686f3f9c061c7"}, ] httplib2 = [- {file = "httplib2-0.19.1-py3-none-any.whl", hash = "sha256:2ad195faf9faf079723f6714926e9a9061f694d07724b846658ce08d40f522b4"},- {file = "httplib2-0.19.1.tar.gz", hash = "sha256:0b12617eeca7433d4c396a100eaecfa4b08ee99aa881e6df6e257a7aad5d533d"},+ {file = "httplib2-0.20.1-py3-none-any.whl", hash = "sha256:8fa4dbf2fbf839b71f8c7837a831e00fcdc860feca99b8bda58ceae4bc53d185"},+ {file = "httplib2-0.20.1.tar.gz", hash = "sha256:0efbcb8bfbfbc11578130d87d8afcc65c2274c6eb446e59fc674e4d7c972d327"}, ] httptools = [ {file = "httptools-0.3.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:4137137de8976511a392e27bfdcf231bd926ac13d375e0414e927b08217d779e"},@@ -3942,8 +3953,8 @@ jieba = [ {file = "jieba-0.42.1.tar.gz", hash = "sha256:055ca12f62674fafed09427f176506079bc135638a14e23e25be909131928db2"}, ] jinja2 = [- {file = "Jinja2-3.0.1-py3-none-any.whl", hash = "sha256:1f06f2da51e7b56b8f238affdd6b4e2c61e39598a378cc49345bc1bd42a978a4"},- {file = "Jinja2-3.0.1.tar.gz", hash = "sha256:703f484b47a6af502e743c9122595cc812b0271f661722403114f71a79d0f5a4"},+ {file = "Jinja2-3.0.2-py3-none-any.whl", hash = "sha256:8569982d3f0889eed11dd620c706d39b60c36d6d25843961f33f77fb6bc6b20c"},+ {file = "Jinja2-3.0.2.tar.gz", hash = "sha256:827a0e32839ab1600d4eb1c4c33ec5a8edfbc5cb42dafa13b81f182f97784b45"}, ] jmespath = [ {file = "jmespath-0.10.0-py2.py3-none-any.whl", hash = "sha256:cdf6525904cc597730141d61b36f2e4b8ecc257c420fa2f4549bac2c2d0cb72f"},@@ -3991,14 +4002,18 @@ kiwisolver = [ {file = "kiwisolver-1.3.1-cp37-cp37m-manylinux2014_ppc64le.whl", hash = "sha256:1e1bc12fb773a7b2ffdeb8380609f4f8064777877b2225dec3da711b421fda31"}, {file = "kiwisolver-1.3.1-cp37-cp37m-win32.whl", hash = "sha256:72c99e39d005b793fb7d3d4e660aed6b6281b502e8c1eaf8ee8346023c8e03bc"}, {file = "kiwisolver-1.3.1-cp37-cp37m-win_amd64.whl", hash = "sha256:8be8d84b7d4f2ba4ffff3665bcd0211318aa632395a1a41553250484a871d454"},+ {file = "kiwisolver-1.3.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:24cc411232d14c8abafbd0dddb83e1a4f54d77770b53db72edcfe1d611b3bf11"}, {file = "kiwisolver-1.3.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:31dfd2ac56edc0ff9ac295193eeaea1c0c923c0355bf948fbd99ed6018010b72"},+ {file = "kiwisolver-1.3.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:ef6eefcf3944e75508cdfa513c06cf80bafd7d179e14c1334ebdca9ebb8c2c66"}, {file = "kiwisolver-1.3.1-cp38-cp38-manylinux1_i686.whl", hash = "sha256:563c649cfdef27d081c84e72a03b48ea9408c16657500c312575ae9d9f7bc1c3"}, {file = "kiwisolver-1.3.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:78751b33595f7f9511952e7e60ce858c6d64db2e062afb325985ddbd34b5c131"}, {file = "kiwisolver-1.3.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:a357fd4f15ee49b4a98b44ec23a34a95f1e00292a139d6015c11f55774ef10de"}, {file = "kiwisolver-1.3.1-cp38-cp38-manylinux2014_ppc64le.whl", hash = "sha256:5989db3b3b34b76c09253deeaf7fbc2707616f130e166996606c284395da3f18"}, {file = "kiwisolver-1.3.1-cp38-cp38-win32.whl", hash = "sha256:c08e95114951dc2090c4a630c2385bef681cacf12636fb0241accdc6b303fd81"}, {file = "kiwisolver-1.3.1-cp38-cp38-win_amd64.whl", hash = "sha256:44a62e24d9b01ba94ae7a4a6c3fb215dc4af1dde817e7498d901e229aaf50e4e"},+ {file = "kiwisolver-1.3.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:6d9d8d9b31aa8c2d80a690693aebd8b5e2b7a45ab065bb78f1609995d2c79240"}, {file = "kiwisolver-1.3.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:50af681a36b2a1dee1d3c169ade9fdc59207d3c31e522519181e12f1b3ba7000"},+ {file = "kiwisolver-1.3.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:792e69140828babe9649de583e1a03a0f2ff39918a71782c76b3c683a67c6dfd"}, {file = "kiwisolver-1.3.1-cp39-cp39-manylinux1_i686.whl", hash = "sha256:a53d27d0c2a0ebd07e395e56a1fbdf75ffedc4a05943daf472af163413ce9598"}, {file = "kiwisolver-1.3.1-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:834ee27348c4aefc20b479335fd422a2c69db55f7d9ab61721ac8cd83eb78882"}, {file = "kiwisolver-1.3.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:5c3e6455341008a054cccee8c5d24481bcfe1acdbc9add30aa95798e95c65621"},@@ -4008,6 +4023,7 @@ kiwisolver = [ {file = "kiwisolver-1.3.1-pp36-pypy36_pp73-macosx_10_9_x86_64.whl", hash = "sha256:0cd53f403202159b44528498de18f9285b04482bab2a6fc3f5dd8dbb9352e30d"}, {file = "kiwisolver-1.3.1-pp36-pypy36_pp73-manylinux2010_x86_64.whl", hash = "sha256:33449715e0101e4d34f64990352bce4095c8bf13bed1b390773fc0a7295967b3"}, {file = "kiwisolver-1.3.1-pp36-pypy36_pp73-win32.whl", hash = "sha256:401a2e9afa8588589775fe34fc22d918ae839aaaf0c0e96441c0fdbce6d8ebe6"},+ {file = "kiwisolver-1.3.1-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:d6563ccd46b645e966b400bb8a95d3457ca6cf3bba1e908f9e0927901dfebeb1"}, {file = "kiwisolver-1.3.1.tar.gz", hash = "sha256:950a199911a8d94683a6b10321f9345d5a3a8433ec58b217ace979e18f16e248"}, ] markdown = [@@ -4015,12 +4031,22 @@ markdown = [ {file = "Markdown-3.3.4.tar.gz", hash = "sha256:31b5b491868dcc87d6c24b7e3d19a0d730d59d3e46f4eea6430a321bed387a49"}, ] markupsafe = [+ {file = "MarkupSafe-2.0.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d8446c54dc28c01e5a2dbac5a25f071f6653e6e40f3a8818e8b45d790fe6ef53"},+ {file = "MarkupSafe-2.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:36bc903cbb393720fad60fc28c10de6acf10dc6cc883f3e24ee4012371399a38"},+ {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2d7d807855b419fc2ed3e631034685db6079889a1f01d5d9dac950f764da3dad"},+ {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:add36cb2dbb8b736611303cd3bfcee00afd96471b09cda130da3581cbdc56a6d"},+ {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:168cd0a3642de83558a5153c8bd34f175a9a6e7f6dc6384b9655d2697312a646"},+ {file = "MarkupSafe-2.0.1-cp310-cp310-win32.whl", hash = "sha256:99df47edb6bda1249d3e80fdabb1dab8c08ef3975f69aed437cb69d0a5de1e28"},+ {file = "MarkupSafe-2.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:e0f138900af21926a02425cf736db95be9f4af72ba1bb21453432a07f6082134"}, {file = "MarkupSafe-2.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:f9081981fe268bd86831e5c75f7de206ef275defcb82bc70740ae6dc507aee51"}, {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:0955295dd5eec6cb6cc2fe1698f4c6d84af2e92de33fbcac4111913cd100a6ff"}, {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:0446679737af14f45767963a1a9ef7620189912317d095f2d9ffa183a4d25d2b"}, {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:f826e31d18b516f653fe296d967d700fddad5901ae07c622bb3705955e1faa94"}, {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:fa130dd50c57d53368c9d59395cb5526eda596d3ffe36666cd81a44d56e48872"}, {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:905fec760bd2fa1388bb5b489ee8ee5f7291d692638ea5f67982d968366bef9f"},+ {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bf5d821ffabf0ef3533c39c518f3357b171a1651c1ff6827325e4489b0e46c3c"},+ {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:0d4b31cc67ab36e3392bbf3862cfbadac3db12bdd8b02a2731f509ed5b829724"},+ {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:baa1a4e8f868845af802979fcdbf0bb11f94f1cb7ced4c4b8a351bb60d108145"}, {file = "MarkupSafe-2.0.1-cp36-cp36m-win32.whl", hash = "sha256:6c4ca60fa24e85fe25b912b01e62cb969d69a23a5d5867682dd3e80b5b02581d"}, {file = "MarkupSafe-2.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:b2f4bf27480f5e5e8ce285a8c8fd176c0b03e93dcc6646477d4630e83440c6a9"}, {file = "MarkupSafe-2.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:0717a7390a68be14b8c793ba258e075c6f4ca819f15edfc2a3a027c823718567"},@@ -4029,14 +4055,21 @@ markupsafe = [ {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:d7f9850398e85aba693bb640262d3611788b1f29a79f0c93c565694658f4071f"}, {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:6a7fae0dd14cf60ad5ff42baa2e95727c3d81ded453457771d02b7d2b3f9c0c2"}, {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:b7f2d075102dc8c794cbde1947378051c4e5180d52d276987b8d28a3bd58c17d"},+ {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e9936f0b261d4df76ad22f8fee3ae83b60d7c3e871292cd42f40b81b70afae85"},+ {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:2a7d351cbd8cfeb19ca00de495e224dea7e7d919659c2841bbb7f420ad03e2d6"},+ {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:60bf42e36abfaf9aff1f50f52644b336d4f0a3fd6d8a60ca0d054ac9f713a864"}, {file = "MarkupSafe-2.0.1-cp37-cp37m-win32.whl", hash = "sha256:a30e67a65b53ea0a5e62fe23682cfe22712e01f453b95233b25502f7c61cb415"}, {file = "MarkupSafe-2.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:611d1ad9a4288cf3e3c16014564df047fe08410e628f89805e475368bd304914"},+ {file = "MarkupSafe-2.0.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:5bb28c636d87e840583ee3adeb78172efc47c8b26127267f54a9c0ec251d41a9"}, {file = "MarkupSafe-2.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:be98f628055368795d818ebf93da628541e10b75b41c559fdf36d104c5787066"}, {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux1_i686.whl", hash = "sha256:1d609f577dc6e1aa17d746f8bd3c31aa4d258f4070d61b2aa5c4166c1539de35"}, {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:7d91275b0245b1da4d4cfa07e0faedd5b0812efc15b702576d103293e252af1b"}, {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:01a9b8ea66f1658938f65b93a85ebe8bc016e6769611be228d797c9d998dd298"}, {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:47ab1e7b91c098ab893b828deafa1203de86d0bc6ab587b160f78fe6c4011f75"}, {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:97383d78eb34da7e1fa37dd273c20ad4320929af65d156e35a5e2d89566d9dfb"},+ {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6fcf051089389abe060c9cd7caa212c707e58153afa2c649f00346ce6d260f1b"},+ {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:5855f8438a7d1d458206a2466bf82b0f104a3724bf96a1c781ab731e4201731a"},+ {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:3dd007d54ee88b46be476e293f48c85048603f5f516008bee124ddd891398ed6"}, {file = "MarkupSafe-2.0.1-cp38-cp38-win32.whl", hash = "sha256:023cb26ec21ece8dc3907c0e8320058b2e0cb3c55cf9564da612bc325bed5e64"}, {file = "MarkupSafe-2.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:984d76483eb32f1bcb536dc27e4ad56bba4baa70be32fa87152832cdd9db0833"}, {file = "MarkupSafe-2.0.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:2ef54abee730b502252bcdf31b10dacb0a416229b72c18b19e24a4509f273d26"},@@ -4046,6 +4079,9 @@ markupsafe = [ {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2010_i686.whl", hash = "sha256:4efca8f86c54b22348a5467704e3fec767b2db12fc39c6d963168ab1d3fc9135"}, {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:ab3ef638ace319fa26553db0624c4699e31a28bb2a835c5faca8f8acf6a5a902"}, {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:f8ba0e8349a38d3001fae7eadded3f6606f0da5d748ee53cc1dab1d6527b9509"},+ {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c47adbc92fc1bb2b3274c4b3a43ae0e4573d9fbff4f54cd484555edbf030baf1"},+ {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:37205cac2a79194e3750b0af2a5720d95f786a55ce7df90c3af697bfa100eaac"},+ {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:1f2ade76b9903f39aa442b4aadd2177decb66525062db244b35d71d0ee8599b6"}, {file = "MarkupSafe-2.0.1-cp39-cp39-win32.whl", hash = "sha256:10f82115e21dc0dfec9ab5c0223652f7197feb168c940f3ef61563fc2d6beb74"}, {file = "MarkupSafe-2.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:693ce3f9e70a6cf7d2fb9e6c9d8b204b6b39897a2c4a1aa65728d5ac97dcc1d8"}, {file = "MarkupSafe-2.0.1.tar.gz", hash = "sha256:594c67807fb16238b30c44bdf74f36c02cdf22d1c8cda91ef8a0ed8dabf5620a"},@@ -4369,27 +4405,27 @@ prompt-toolkit = [ {file = "prompt_toolkit-2.0.10.tar.gz", hash = "sha256:f15af68f66e664eaa559d4ac8a928111eebd5feda0c11738b5998045224829db"}, ] protobuf = [- {file = "protobuf-3.18.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:9072cb18fca8998b77f969fb74d25a11d7f4a39a8b1ddc3cf76cd5abda8499cb"},- {file = "protobuf-3.18.0-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f589346b5b3f702c1d30e2343c9897e6c35e7bd495c10a0e17d11ecb5ee5bd06"},- {file = "protobuf-3.18.0-cp36-cp36m-win32.whl", hash = "sha256:93c077fd83879cf48f327a2491c24da447a09da6a7ab3cc311a6f5a61fcb5de0"},- {file = "protobuf-3.18.0-cp36-cp36m-win_amd64.whl", hash = "sha256:3b5b81bb665aac548b413480f4e0d8c38a74bc4dea57835f288a3ce74f63dfe9"},- {file = "protobuf-3.18.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:d11465040cadcea8ecf5f0b131af5099a9696f9d0bef6f88148b372bacc1c52d"},- {file = "protobuf-3.18.0-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:f6138462643adce0ed6e49007a63b7fd7dc4fda1ef4e15a70fcebe76c1407a71"},- {file = "protobuf-3.18.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:877664b1b8d1e23553634f625e4e12aae4ff16cbbef473f8118c239d478f422a"},- {file = "protobuf-3.18.0-cp37-cp37m-win32.whl", hash = "sha256:5201333b7aa711965c5769b250f8565a9924e8e27f8b622bbc5e6847aeaab1b1"},- {file = "protobuf-3.18.0-cp37-cp37m-win_amd64.whl", hash = "sha256:1f3ecec3038c2fb4dad952d3d6cb9ca301999903a09e43794fb348da48f7577f"},- {file = "protobuf-3.18.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:17181fc0814655812aac108e755bd5185d71aa8d81bd241cec6e232c84097918"},- {file = "protobuf-3.18.0-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:7646c20605fbee57e77fdbc4a90175538281b152f46ba17019916593f8062c2a"},- {file = "protobuf-3.18.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80b0a5157f3a53043daf8eb7cfa1220b27a5a63dd6655dbd8e1e6f7b5dcd6347"},- {file = "protobuf-3.18.0-cp38-cp38-win32.whl", hash = "sha256:5730de255c95b3403eedd1a568eb28203b913b6192ff5a3fdc3ff30f37107a38"},- {file = "protobuf-3.18.0-cp38-cp38-win_amd64.whl", hash = "sha256:9147565f93e6699d7512747766598afe63205f226ac7b61f47954974c9aab852"},- {file = "protobuf-3.18.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:568c049ff002a7523ed33fb612e6b97da002bf87ffb619a1fc3eadf2257a3b31"},- {file = "protobuf-3.18.0-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:7e791a94db391ae22b3943fc88f6ba0e1f62b6ad58b33db7517df576c7834d23"},- {file = "protobuf-3.18.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:42c04e66ec5a38ad2171639dc9860c2f9594668f709ea3a4a192acf7346853a7"},- {file = "protobuf-3.18.0-cp39-cp39-win32.whl", hash = "sha256:0a59ea8da307118372750e2fdfe0961622e675b8dd35e05c42384d618189a938"},- {file = "protobuf-3.18.0-cp39-cp39-win_amd64.whl", hash = "sha256:f7c8193ec805324ff6024242b00f64a24b94d56b895f62bf28a9d72a228d4fca"},- {file = "protobuf-3.18.0-py2.py3-none-any.whl", hash = "sha256:615099e52e9fbc9fde00177267a94ca820ecf4e80093e390753568b7d8cb3c1a"},- {file = "protobuf-3.18.0.tar.gz", hash = "sha256:18b308946a592e245299391e53c01b5b8efc2794f49986e80f37d7b5e60a270f"},+ {file = "protobuf-3.18.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:fa6d1049d5315566f55c04d0b50c0033415144f96a9d25c820dc542fe2bb7f45"},+ {file = "protobuf-3.18.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0e2790c580070cff2921b93d562539ae027064340151c50db6aaf94c33048cd"},+ {file = "protobuf-3.18.1-cp36-cp36m-win32.whl", hash = "sha256:7e2f0677d68ecdd1cfda2abea65873f5bc7c3f5aae199404a3f5c1d1198c1a63"},+ {file = "protobuf-3.18.1-cp36-cp36m-win_amd64.whl", hash = "sha256:6f714f5de9d40b3bec90ede4a688cce52f637ccdc5403afcda1f67598f4fdcd7"},+ {file = "protobuf-3.18.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:7a7be937c319146cc9f2626f0181e6809062c353e1fe449ecd0df374ba1036b2"},+ {file = "protobuf-3.18.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:10544fc7ace885a882623083c24da5b14148c77563acddc3c58d66f6153c09cd"},+ {file = "protobuf-3.18.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e2ee8b11e3eb2ed38f12137c3c132270a0b1dd509e317228ac47b67f21a583f1"},+ {file = "protobuf-3.18.1-cp37-cp37m-win32.whl", hash = "sha256:c492c217d3f69f4d2d5619571e52ab98538edbf53caf67e53ea92bd0a3b5670f"},+ {file = "protobuf-3.18.1-cp37-cp37m-win_amd64.whl", hash = "sha256:3c1644f8a7f19b45c7a4c32278e2a55ae9e7e2f9e5f02d960a61f04a4890d3e6"},+ {file = "protobuf-3.18.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:e9ac691f7b24e4371dcd3980e4f5d6c840a2010da37986203053fee995786ec5"},+ {file = "protobuf-3.18.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:93bad12895d8b0ebc66b605c2ef1802311595f881aef032d9f13282b7550e6b2"},+ {file = "protobuf-3.18.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0851b5b89191e1976d34fa2e8eb8659829dfb45252053224cf9df857fb5f6a45"},+ {file = "protobuf-3.18.1-cp38-cp38-win32.whl", hash = "sha256:09d9268f6f9da81b7657adcf2fb397524c82f20cdf9e0db3ff4e7567977abd67"},+ {file = "protobuf-3.18.1-cp38-cp38-win_amd64.whl", hash = "sha256:d6d927774c0ec746fed15a4faff5f44aad0b7a3421fadb6f3ae5ca1f2f8ae26e"},+ {file = "protobuf-3.18.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:4d19c9cb805fd2be1d59eee39e152367ee92a30167e77bd06c8819f8f0009a4c"},+ {file = "protobuf-3.18.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:387f621bf7295a331f8c8a6962d097ceddeb85356792888cfa6a5c6bfc6886a4"},+ {file = "protobuf-3.18.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8c1c5d3966c856f60a9d8d62f4455d70c31026422acdd5c228edf22b65b16c38"},+ {file = "protobuf-3.18.1-cp39-cp39-win32.whl", hash = "sha256:f20f803892f2135e8b96dc58c9a0c6a7ad8436794bf8784af229498d939b4c77"},+ {file = "protobuf-3.18.1-cp39-cp39-win_amd64.whl", hash = "sha256:d76201380f41a2d83fb613a4683059d1fcafbe969518b3e409e279a8788fde2f"},+ {file = "protobuf-3.18.1-py2.py3-none-any.whl", hash = "sha256:61ca58e14033ca0dfa484a31d57237c1be3b6013454c7f53876a20fc88dd69b1"},+ {file = "protobuf-3.18.1.tar.gz", hash = "sha256:1c9bb40503751087300dd12ce2e90899d68628977905c76effc48e66d089391e"}, ] psutil = [ {file = "psutil-5.8.0-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:0066a82f7b1b37d334e68697faba68e5ad5e858279fd6351c8ca6024e8d6ba64"},@@ -4535,8 +4571,8 @@ pyflakes = [ {file = "pyflakes-2.3.1.tar.gz", hash = "sha256:f5bc8ecabc05bb9d291eb5203d6810b49040f6ff446a756326104746cc00c1db"}, ] pyjwt = [- {file = "PyJWT-2.1.0-py3-none-any.whl", hash = "sha256:934d73fbba91b0483d3857d1aff50e96b2a892384ee2c17417ed3203f173fca1"},- {file = "PyJWT-2.1.0.tar.gz", hash = "sha256:fba44e7898bbca160a2b2b501f492824fc8382485d3a6f11ba5d0c1937ce6130"},+ {file = "PyJWT-2.2.0-py3-none-any.whl", hash = "sha256:b0ed5824c8ecc5362e540c65dc6247567db130c4226670bf7699aec92fb4dae1"},+ {file = "PyJWT-2.2.0.tar.gz", hash = "sha256:a0b9a3b4e5ca5517cac9f1a6e9cd30bf1aa80be74fcdf4e28eded582ecfcfbae"}, ] pykwalify = [ {file = "pykwalify-1.8.0-py2.py3-none-any.whl", hash = "sha256:731dfa87338cca9f559d1fca2bdea37299116e3139b73f78ca90a543722d6651"},@@ -4713,8 +4749,8 @@ python-socketio = [ {file = "python_socketio-5.4.0-py3-none-any.whl", hash = "sha256:7ed57f6c024abdfeb9b25c74c0c00ffc18da47d903e8d72deecb87584370d1fc"}, ] pytz = [- {file = "pytz-2021.1-py2.py3-none-any.whl", hash = "sha256:eb10ce3e7736052ed3623d49975ce333bcd712c7bb19a58b9e2089d4057d0798"},- {file = "pytz-2021.1.tar.gz", hash = "sha256:83a4a90894bf38e243cf052c8b58f381bfe9a7a483f6a9cab140bc7f702ac4da"},+ {file = "pytz-2021.3-py2.py3-none-any.whl", hash = "sha256:3672058bc3453457b622aab7a1c3bfd5ab0bdae451512f6cf25f64ed37f5b87c"},+ {file = "pytz-2021.3.tar.gz", hash = "sha256:acad2d8b20a1af07d4e4c9d2e9285c5ed9104354062f275f3fcd88dcef4f1326"}, ] pyyaml = [ {file = "PyYAML-5.4.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:3b2b1824fe7112845700f815ff6a489360226a5609b96ec2190a45e62a9fc922"},@@ -4768,6 +4804,10 @@ regex = [ {file = "regex-2021.7.6-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:b85ac458354165405c8a84725de7bbd07b00d9f72c31a60ffbf96bb38d3e25fa"}, {file = "regex-2021.7.6-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:3f5716923d3d0bfb27048242a6e0f14eecdb2e2a7fac47eda1d055288595f222"}, {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e5983c19d0beb6af88cb4d47afb92d96751fb3fa1784d8785b1cdf14c6519407"},+ {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf1d2d183abc7faa101ebe0b8d04fd19cb9138820abc8589083035c9440b8ca6"},+ {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:1947e7de155063e1c495c50590229fb98720d4c383af5031bbcb413db33fa1be"},+ {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:17d8a3f99b18d87ac54a449b836d485cc8c195bb6f5e4379c84c8519045facc9"},+ {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d30895ec80cc80358392841add9dde81ea1d54a4949049269115e6b0555d0498"}, {file = "regex-2021.7.6-cp36-cp36m-win32.whl", hash = "sha256:c92831dac113a6e0ab28bc98f33781383fe294df1a2c3dfd1e850114da35fd5b"}, {file = "regex-2021.7.6-cp36-cp36m-win_amd64.whl", hash = "sha256:791aa1b300e5b6e5d597c37c346fb4d66422178566bbb426dd87eaae475053fb"}, {file = "regex-2021.7.6-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:59506c6e8bd9306cd8a41511e32d16d5d1194110b8cfe5a11d102d8b63cf945d"},@@ -4778,6 +4818,10 @@ regex = [ {file = "regex-2021.7.6-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:173bc44ff95bc1e96398c38f3629d86fa72e539c79900283afa895694229fe6a"}, {file = "regex-2021.7.6-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:15dddb19823f5147e7517bb12635b3c82e6f2a3a6b696cc3e321522e8b9308ad"}, {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2ddeabc7652024803666ea09f32dd1ed40a0579b6fbb2a213eba590683025895"},+ {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8244c681018423a0d1784bc6b9af33bdf55f2ab8acb1f3cd9dd83d90e0813253"},+ {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:8a4c742089faf0e51469c6a1ad7e3d3d21afae54a16a6cead85209dfe0a1ce65"},+ {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:914e626dc8e75fe4fc9b7214763f141d9f40165d00dfe680b104fa1b24063bbf"},+ {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:3fabb19c82ecf39832a3f5060dfea9a7ab270ef156039a1143a29a83a09a62de"}, {file = "regex-2021.7.6-cp37-cp37m-win32.whl", hash = "sha256:f080248b3e029d052bf74a897b9d74cfb7643537fbde97fe8225a6467fb559b5"}, {file = "regex-2021.7.6-cp37-cp37m-win_amd64.whl", hash = "sha256:d8bbce0c96462dbceaa7ac4a7dfbbee92745b801b24bce10a98d2f2b1ea9432f"}, {file = "regex-2021.7.6-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:edd1a68f79b89b0c57339bce297ad5d5ffcc6ae7e1afdb10f1947706ed066c9c"},@@ -4788,6 +4832,10 @@ regex = [ {file = "regex-2021.7.6-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:bc84fb254a875a9f66616ed4538542fb7965db6356f3df571d783f7c8d256edd"}, {file = "regex-2021.7.6-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:598c0a79b4b851b922f504f9f39a863d83ebdfff787261a5ed061c21e67dd761"}, {file = "regex-2021.7.6-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:875c355360d0f8d3d827e462b29ea7682bf52327d500a4f837e934e9e4656068"},+ {file = "regex-2021.7.6-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dfc0957c4a4b91eff5ad036088769e600a25774256cd0e1154378591ce573f08"},+ {file = "regex-2021.7.6-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:efb4af05fa4d2fc29766bf516f1f5098d6b5c3ed846fde980c18bf8646ad3979"},+ {file = "regex-2021.7.6-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7423aca7cc30a6228ccdcf2ea76f12923d652c5c7c6dc1959a0b004e308f39fb"},+ {file = "regex-2021.7.6-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:bb9834c1e77493efd7343b8e38950dee9797d2d6f2d5fd91c008dfaef64684b9"}, {file = "regex-2021.7.6-cp38-cp38-win32.whl", hash = "sha256:e586f448df2bbc37dfadccdb7ccd125c62b4348cb90c10840d695592aa1b29e0"}, {file = "regex-2021.7.6-cp38-cp38-win_amd64.whl", hash = "sha256:2fe5e71e11a54e3355fa272137d521a40aace5d937d08b494bed4529964c19c4"}, {file = "regex-2021.7.6-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6110bab7eab6566492618540c70edd4d2a18f40ca1d51d704f1d81c52d245026"},@@ -4798,6 +4846,10 @@ regex = [ {file = "regex-2021.7.6-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:2bceeb491b38225b1fee4517107b8491ba54fba77cf22a12e996d96a3c55613d"}, {file = "regex-2021.7.6-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:f98dc35ab9a749276f1a4a38ab3e0e2ba1662ce710f6530f5b0a6656f1c32b58"}, {file = "regex-2021.7.6-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:319eb2a8d0888fa6f1d9177705f341bc9455a2c8aca130016e52c7fe8d6c37a3"},+ {file = "regex-2021.7.6-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:598ee917dbe961dcf827217bf2466bb86e4ee5a8559705af57cbabb3489dd37e"},+ {file = "regex-2021.7.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:56fc7045a1999a8d9dd1896715bc5c802dfec5b9b60e883d2cbdecb42adedea4"},+ {file = "regex-2021.7.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e8363ac90ea63c3dd0872dfdb695f38aff3334bfa5712cffb238bd3ffef300e3"},+ {file = "regex-2021.7.6-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:716a6db91b3641f566531ffcc03ceec00b2447f0db9942b3c6ea5d2827ad6be3"}, {file = "regex-2021.7.6-cp39-cp39-win32.whl", hash = "sha256:eaf58b9e30e0e546cdc3ac06cf9165a1ca5b3de8221e9df679416ca667972035"}, {file = "regex-2021.7.6-cp39-cp39-win_amd64.whl", hash = "sha256:4c9c3155fe74269f61e27617529b7f09552fbb12e44b1189cebbdb24294e6e1c"}, {file = "regex-2021.7.6.tar.gz", hash = "sha256:8394e266005f2d8c6f0bc6780001f7afa3ef81a7a2111fa35058ded6fce79e4d"},@@ -5100,6 +5152,10 @@ tabulate = [ {file = "tabulate-0.8.9-py3-none-any.whl", hash = "sha256:d7c013fe7abbc5e491394e10fa845f8f32fe54f8dc60c6622c6cf482d25d47e4"}, {file = "tabulate-0.8.9.tar.gz", hash = "sha256:eb1d13f25760052e8931f2ef80aaf6045a6cceb47514db8beab24cded16f13a7"}, ]+tarsafe = [+ {file = "tarsafe-0.0.3-py3-none-any.whl", hash = "sha256:f8181c5559aea70af2579a0dc0811d2e9e3eabd706dd594555b4dfa52c0be51a"},+ {file = "tarsafe-0.0.3.tar.gz", hash = "sha256:7acf73a11b576fcbb003b52adecf4706d6c3009c6af28a01fd21949235ffd806"},+] tensorboard = [ {file = "tensorboard-2.6.0-py3-none-any.whl", hash = "sha256:f7dac4cdfb52d14c9e3f74585ce2aaf8e6203620a864e51faf84988b09f7bbdb"}, ]@@ -5184,8 +5240,8 @@ thinc = [ {file = "thinc-8.0.10.tar.gz", hash = "sha256:b5e4db8d24e6be8a5f1e4a17854772b79a2b560224519f50a21f3951ca24001f"}, ] threadpoolctl = [- {file = "threadpoolctl-2.2.0-py3-none-any.whl", hash = "sha256:e5a995e3ffae202758fa8a90082e35783b9370699627ae2733cd1c3a73553616"},- {file = "threadpoolctl-2.2.0.tar.gz", hash = "sha256:86d4b6801456d780e94681d155779058759eaef3c3564758b17b6c99db5f81cb"},+ {file = "threadpoolctl-3.0.0-py3-none-any.whl", hash = "sha256:4fade5b3b48ae4b1c30f200b28f39180371104fccc642e039e0f2435ec8cc211"},+ {file = "threadpoolctl-3.0.0.tar.gz", hash = "sha256:d03115321233d0be715f0d3a5ad1d6c065fe425ddc2d671ca8e45e9fd5d7a52a"}, ] tokenizers = [ {file = "tokenizers-0.7.0-cp35-cp35m-macosx_10_10_x86_64.whl", hash = "sha256:c9edc043bc14462faf8b261b528661718e9c4f0b8424fb25be71cae26187432a"},@@ -5258,8 +5314,8 @@ typed-ast = [ {file = "typed_ast-1.4.3.tar.gz", hash = "sha256:fb1bbeac803adea29cedd70781399c99138358c26d05fcbd23c13016b7f5ec65"}, ] typeguard = [- {file = "typeguard-2.12.1-py3-none-any.whl", hash = "sha256:cc15ef2704c9909ef9c80e19c62fb8468c01f75aad12f651922acf4dbe822e02"},- {file = "typeguard-2.12.1.tar.gz", hash = "sha256:c2af8b9bdd7657f4bd27b45336e7930171aead796711bc4cfc99b4731bb9d051"},+ {file = "typeguard-2.13.0-py3-none-any.whl", hash = "sha256:0bc44d1ff865b522eda969627868b0e001c8329296ce50aededbea03febc79ee"},+ {file = "typeguard-2.13.0.tar.gz", hash = "sha256:04e38f92eb59410c9375d3be23df65e0a7643f2e8bcbd421423d808d2f9e99df"}, ] typer = [ {file = "typer-0.4.0-py3-none-any.whl", hash = "sha256:d81169725140423d072df464cad1ff25ee154ef381aaf5b8225352ea187ca338"},@@ -5341,8 +5397,8 @@ ujson = [ {file = "ujson-4.2.0.tar.gz", hash = "sha256:fffe509f556861c7343c6cba57ed05fe7bcf4b48a934a5b946ccb45428cf8883"}, ] uritemplate = [- {file = "uritemplate-3.0.1-py2.py3-none-any.whl", hash = "sha256:07620c3f3f8eed1f12600845892b0e036a2420acf513c53f7de0abd911a5894f"},- {file = "uritemplate-3.0.1.tar.gz", hash = "sha256:5af8ad10cec94f215e3f48112de2022e1d5a37ed427fbd88652fa908f2ab7cae"},+ {file = "uritemplate-4.0.0-py2.py3-none-any.whl", hash = "sha256:9de62e39c3f7f7584982a4159d70e6aafda5a479a91cccc18e89ae865eab4ae4"},+ {file = "uritemplate-4.0.0.tar.gz", hash = "sha256:6f4c5b093c915d269df69f291028a72dfdcaf68c8345b92e180f31daf53c4971"}, ] urllib3 = [ {file = "urllib3-1.26.7-py2.py3-none-any.whl", hash = "sha256:c4fdf4019605b6e5423637e01bc9fe4daef873709a7973e195ceba0a62bbc844"},@@ -5404,8 +5460,8 @@ websockets = [ {file = "websockets-8.0.2.tar.gz", hash = "sha256:882a7266fa867a2ebb2c0baaa0f9159cabf131cf18c1b4270d79ad42f9208dc5"}, ] werkzeug = [- {file = "Werkzeug-2.0.1-py3-none-any.whl", hash = "sha256:6c1ec500dcdba0baa27600f6a22f6333d8b662d22027ff9f6202e3367413caa8"},- {file = "Werkzeug-2.0.1.tar.gz", hash = "sha256:1de1db30d010ff1af14a009224ec49ab2329ad2cde454c8a708130642d579c42"},+ {file = "Werkzeug-2.0.2-py3-none-any.whl", hash = "sha256:63d3dc1cf60e7b7e35e97fa9861f7397283b75d765afcaefd993d6046899de8f"},+ {file = "Werkzeug-2.0.2.tar.gz", hash = "sha256:aa2bb6fc8dee8d6c504c0ac1e7f5f7dc5810a9903e793b6f715a9f015bdadb9a"}, ] wrapt = [ {file = "wrapt-1.12.1.tar.gz", hash = "sha256:b62ffa81fb85f4332a4f609cab4ac40709470da05643a082ec1eb88e6d9b97d7"},@@ -5415,43 +5471,78 @@ xmltodict = [ {file = "xmltodict-0.12.0.tar.gz", hash = "sha256:50d8c638ed7ecb88d90561beedbf720c9b4e851a9fa6c47ebd64e99d166d8a21"}, ] yarl = [- {file = "yarl-1.6.3-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:0355a701b3998dcd832d0dc47cc5dedf3874f966ac7f870e0f3a6788d802d434"},- {file = "yarl-1.6.3-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:bafb450deef6861815ed579c7a6113a879a6ef58aed4c3a4be54400ae8871478"},- {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:547f7665ad50fa8563150ed079f8e805e63dd85def6674c97efd78eed6c224a6"},- {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:63f90b20ca654b3ecc7a8d62c03ffa46999595f0167d6450fa8383bab252987e"},- {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_ppc64le.whl", hash = "sha256:97b5bdc450d63c3ba30a127d018b866ea94e65655efaf889ebeabc20f7d12406"},- {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_s390x.whl", hash = "sha256:d8d07d102f17b68966e2de0e07bfd6e139c7c02ef06d3a0f8d2f0f055e13bb76"},- {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:15263c3b0b47968c1d90daa89f21fcc889bb4b1aac5555580d74565de6836366"},- {file = "yarl-1.6.3-cp36-cp36m-win32.whl", hash = "sha256:b5dfc9a40c198334f4f3f55880ecf910adebdcb2a0b9a9c23c9345faa9185721"},- {file = "yarl-1.6.3-cp36-cp36m-win_amd64.whl", hash = "sha256:b2e9a456c121e26d13c29251f8267541bd75e6a1ccf9e859179701c36a078643"},- {file = "yarl-1.6.3-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:ce3beb46a72d9f2190f9e1027886bfc513702d748047b548b05dab7dfb584d2e"},- {file = "yarl-1.6.3-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:2ce4c621d21326a4a5500c25031e102af589edb50c09b321049e388b3934eec3"},- {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:d26608cf178efb8faa5ff0f2d2e77c208f471c5a3709e577a7b3fd0445703ac8"},- {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:4c5bcfc3ed226bf6419f7a33982fb4b8ec2e45785a0561eb99274ebbf09fdd6a"},- {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_ppc64le.whl", hash = "sha256:4736eaee5626db8d9cda9eb5282028cc834e2aeb194e0d8b50217d707e98bb5c"},- {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_s390x.whl", hash = "sha256:68dc568889b1c13f1e4745c96b931cc94fdd0defe92a72c2b8ce01091b22e35f"},- {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:7356644cbed76119d0b6bd32ffba704d30d747e0c217109d7979a7bc36c4d970"},- {file = "yarl-1.6.3-cp37-cp37m-win32.whl", hash = "sha256:00d7ad91b6583602eb9c1d085a2cf281ada267e9a197e8b7cae487dadbfa293e"},- {file = "yarl-1.6.3-cp37-cp37m-win_amd64.whl", hash = "sha256:69ee97c71fee1f63d04c945f56d5d726483c4762845400a6795a3b75d56b6c50"},- {file = "yarl-1.6.3-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:e46fba844f4895b36f4c398c5af062a9808d1f26b2999c58909517384d5deda2"},- {file = "yarl-1.6.3-cp38-cp38-manylinux1_i686.whl", hash = "sha256:31ede6e8c4329fb81c86706ba8f6bf661a924b53ba191b27aa5fcee5714d18ec"},- {file = "yarl-1.6.3-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:fcbb48a93e8699eae920f8d92f7160c03567b421bc17362a9ffbbd706a816f71"},- {file = "yarl-1.6.3-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:72a660bdd24497e3e84f5519e57a9ee9220b6f3ac4d45056961bf22838ce20cc"},- {file = "yarl-1.6.3-cp38-cp38-manylinux2014_ppc64le.whl", hash = "sha256:324ba3d3c6fee56e2e0b0d09bf5c73824b9f08234339d2b788af65e60040c959"},- {file = "yarl-1.6.3-cp38-cp38-manylinux2014_s390x.whl", hash = "sha256:e6b5460dc5ad42ad2b36cca524491dfcaffbfd9c8df50508bddc354e787b8dc2"},- {file = "yarl-1.6.3-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:6d6283d8e0631b617edf0fd726353cb76630b83a089a40933043894e7f6721e2"},- {file = "yarl-1.6.3-cp38-cp38-win32.whl", hash = "sha256:9ede61b0854e267fd565e7527e2f2eb3ef8858b301319be0604177690e1a3896"},- {file = "yarl-1.6.3-cp38-cp38-win_amd64.whl", hash = "sha256:f0b059678fd549c66b89bed03efcabb009075bd131c248ecdf087bdb6faba24a"},- {file = "yarl-1.6.3-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:329412812ecfc94a57cd37c9d547579510a9e83c516bc069470db5f75684629e"},- {file = "yarl-1.6.3-cp39-cp39-manylinux1_i686.whl", hash = "sha256:c49ff66d479d38ab863c50f7bb27dee97c6627c5fe60697de15529da9c3de724"},- {file = "yarl-1.6.3-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:f040bcc6725c821a4c0665f3aa96a4d0805a7aaf2caf266d256b8ed71b9f041c"},- {file = "yarl-1.6.3-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:d5c32c82990e4ac4d8150fd7652b972216b204de4e83a122546dce571c1bdf25"},- {file = "yarl-1.6.3-cp39-cp39-manylinux2014_ppc64le.whl", hash = "sha256:d597767fcd2c3dc49d6eea360c458b65643d1e4dbed91361cf5e36e53c1f8c96"},- {file = "yarl-1.6.3-cp39-cp39-manylinux2014_s390x.whl", hash = "sha256:8aa3decd5e0e852dc68335abf5478a518b41bf2ab2f330fe44916399efedfae0"},- {file = "yarl-1.6.3-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:73494d5b71099ae8cb8754f1df131c11d433b387efab7b51849e7e1e851f07a4"},- {file = "yarl-1.6.3-cp39-cp39-win32.whl", hash = "sha256:5b883e458058f8d6099e4420f0cc2567989032b5f34b271c0827de9f1079a424"},- {file = "yarl-1.6.3-cp39-cp39-win_amd64.whl", hash = "sha256:4953fb0b4fdb7e08b2f3b3be80a00d28c5c8a2056bb066169de00e6501b986b6"},- {file = "yarl-1.6.3.tar.gz", hash = "sha256:8a9066529240171b68893d60dca86a763eae2139dd42f42106b03cf4b426bf10"},+ {file = "yarl-1.7.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e35d8230e4b08d86ea65c32450533b906a8267a87b873f2954adeaecede85169"},+ {file = "yarl-1.7.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:eb4b3f277880c314e47720b4b6bb2c85114ab3c04c5442c9bc7006b3787904d8"},+ {file = "yarl-1.7.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c7015dcedb91d90a138eebdc7e432aec8966e0147ab2a55f2df27b1904fa7291"},+ {file = "yarl-1.7.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bb3e478175e15e00d659fb0354a6a8db71a7811a2a5052aed98048bc972e5d2b"},+ {file = "yarl-1.7.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8b8c409aa3a7966647e7c1c524846b362a6bcbbe120bf8a176431f940d2b9a2e"},+ {file = "yarl-1.7.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b22ea41c7e98170474a01e3eded1377d46b2dfaef45888a0005c683eaaa49285"},+ {file = "yarl-1.7.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:a7dfc46add4cfe5578013dbc4127893edc69fe19132d2836ff2f6e49edc5ecd6"},+ {file = "yarl-1.7.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:82ff6f85f67500a4f74885d81659cd270eb24dfe692fe44e622b8a2fd57e7279"},+ {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:f3cd2158b2ed0fb25c6811adfdcc47224efe075f2d68a750071dacc03a7a66e4"},+ {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:59c0f13f9592820c51280d1cf811294d753e4a18baf90f0139d1dc93d4b6fc5f"},+ {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:7f7655ad83d1a8afa48435a449bf2f3009293da1604f5dd95b5ddcf5f673bd69"},+ {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:aa9f0d9b62d15182341b3e9816582f46182cab91c1a57b2d308b9a3c4e2c4f78"},+ {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:fdd1b90c225a653b1bd1c0cae8edf1957892b9a09c8bf7ee6321eeb8208eac0f"},+ {file = "yarl-1.7.0-cp310-cp310-win32.whl", hash = "sha256:7c8d0bb76eabc5299db203e952ec55f8f4c53f08e0df4285aac8c92bd9e12675"},+ {file = "yarl-1.7.0-cp310-cp310-win_amd64.whl", hash = "sha256:622a36fa779efb4ff9eff5fe52730ff17521431379851a31e040958fc251670c"},+ {file = "yarl-1.7.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:3d461b7a8e139b9e4b41f62eb417ffa0b98d1c46d4caf14c845e6a3b349c0bb1"},+ {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:81cfacdd1e40bc931b5519499342efa388d24d262c30a3d31187bfa04f4a7001"},+ {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:821b978f2152be7695d4331ef0621d207aedf9bbd591ba23a63412a3efc29a01"},+ {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b64bd24c8c9a487f4a12260dc26732bf41028816dbf0c458f17864fbebdb3131"},+ {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:98c9ddb92b60a83c21be42c776d3d9d5ec632a762a094c41bda37b7dfbd2cd83"},+ {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a532d75ca74431c053a88a802e161fb3d651b8bf5821a3440bc3616e38754583"},+ {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:053e09817eafb892e94e172d05406c1b3a22a93bc68f6eff5198363a3d764459"},+ {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:98c51f02d542945d306c8e934aa2c1e66ba5e9c1c86b5bf37f3a51c8a747067e"},+ {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_ppc64le.whl", hash = "sha256:15ec41a5a5fdb7bace6d7b16701f9440007a82734f69127c0fbf6d87e10f4a1e"},+ {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_s390x.whl", hash = "sha256:a7f08819dba1e1255d6991ed37448a1bf4b1352c004bcd899b9da0c47958513d"},+ {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:8e3ffab21db0542ffd1887f3b9575ddd58961f2cf61429cb6458afc00c4581e0"},+ {file = "yarl-1.7.0-cp36-cp36m-win32.whl", hash = "sha256:50127634f519b2956005891507e3aa4ac345f66a7ea7bbc2d7dcba7401f41898"},+ {file = "yarl-1.7.0-cp36-cp36m-win_amd64.whl", hash = "sha256:36ec44f15193f6d5288d42ebb8e751b967ebdfb72d6830983838d45ab18edb4f"},+ {file = "yarl-1.7.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:ec1b5a25a25c880c976d0bb3d107def085bb08dbb3db7f4442e0a2b980359d24"},+ {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b36f5a63c891f813c6f04ef19675b382efc190fd5ce7e10ab19386d2548bca06"},+ {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:38173b8c3a29945e7ecade9a3f6ff39581eee8201338ee6a2c8882db5df3e806"},+ {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8ba402f32184f0b405fb281b93bd0d8ab7e3257735b57b62a6ed2e94cdf4fe50"},+ {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:be52bc5208d767cdd8308a9e93059b3b36d1e048fecbea0e0346d0d24a76adc0"},+ {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:08c2044a956f4ef30405f2f433ce77f1f57c2c773bf81ae43201917831044d5a"},+ {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:484d61c047c45670ef5967653a1d0783e232c54bf9dd786a7737036828fa8d54"},+ {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:b7de92a4af85cfcaf4081f8aa6165b1d63ee5de150af3ee85f954145f93105a7"},+ {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:376e41775aab79c5575534924a386c8e0f1a5d91db69fc6133fd27a489bcaf10"},+ {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:8a8b10d0e7bac154f959b709fcea593cda527b234119311eb950096653816a86"},+ {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:f46cd4c43e6175030e2a56def8f1d83b64e6706eeb2bb9ab0ef4756f65eab23f"},+ {file = "yarl-1.7.0-cp37-cp37m-win32.whl", hash = "sha256:b28cfb46140efe1a6092b8c5c4994a1fe70dc83c38fbcea4992401e0c6fb9cce"},+ {file = "yarl-1.7.0-cp37-cp37m-win_amd64.whl", hash = "sha256:9624154ec9c02a776802da1086eed7f5034bd1971977f5146233869c2ac80297"},+ {file = "yarl-1.7.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:69945d13e1bbf81784a9bc48824feb9cd66491e6a503d4e83f6cd7c7cc861361"},+ {file = "yarl-1.7.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:46a742ed9e363bd01be64160ce7520e92e11989bd4cb224403cfd31c101cc83d"},+ {file = "yarl-1.7.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:cb4ff1ac7cb4500f43581b3f4cbd627d702143aa6be1fdc1fa3ebffaf4dc1be5"},+ {file = "yarl-1.7.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3ad51e17cd65ea3debb0e10f0120cf8dd987c741fe423ed2285087368090b33d"},+ {file = "yarl-1.7.0-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7e37786ea89a5d3ffbbf318ea9790926f8dfda83858544f128553c347ad143c6"},+ {file = "yarl-1.7.0-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c63c1e208f800daad71715786bfeb1cecdc595d87e2e9b1cd234fd6e597fd71d"},+ {file = "yarl-1.7.0-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:91cbe24300c11835ef186436363352b3257db7af165e0a767f4f17aa25761388"},+ {file = "yarl-1.7.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:e510dbec7c59d32eaa61ffa48173d5e3d7170a67f4a03e8f5e2e9e3971aca622"},+ {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:3def6e681cc02397e5d8141ee97b41d02932b2bcf0fb34532ad62855eab7c60e"},+ {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:263c81b94e6431942b27f6f671fa62f430a0a5c14bb255f2ab69eeb9b2b66ff7"},+ {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:e78c91faefe88d601ddd16e3882918dbde20577a2438e2320f8239c8b7507b8f"},+ {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:22b2430c49713bfb2f0a0dd4a8d7aab218b28476ba86fd1c78ad8899462cbcf2"},+ {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2e7ad9db939082f5d0b9269cfd92c025cb8f2fbbb1f1b9dc5a393c639db5bd92"},+ {file = "yarl-1.7.0-cp38-cp38-win32.whl", hash = "sha256:3a31e4a8dcb1beaf167b7e7af61b88cb961b220db8d3ba1c839723630e57eef7"},+ {file = "yarl-1.7.0-cp38-cp38-win_amd64.whl", hash = "sha256:d579957439933d752358c6a300c93110f84aae67b63dd0c19dde6ecbf4056f6b"},+ {file = "yarl-1.7.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:87721b549505a546eb003252185103b5ec8147de6d3ad3714d148a5a67b6fe53"},+ {file = "yarl-1.7.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a1fa866fa24d9f4108f9e58ea8a2135655419885cdb443e36b39a346e1181532"},+ {file = "yarl-1.7.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:1d3b8449dfedfe94eaff2b77954258b09b24949f6818dfa444b05dbb05ae1b7e"},+ {file = "yarl-1.7.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:db2372e350794ce8b9f810feb094c606b7e0e4aa6807141ac4fadfe5ddd75bb0"},+ {file = "yarl-1.7.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a06d9d0b9a97fa99b84fee71d9dd11e69e21ac8a27229089f07b5e5e50e8d63c"},+ {file = "yarl-1.7.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a3455c2456d6307bcfa80bc1157b8603f7d93573291f5bdc7144489ca0df4628"},+ {file = "yarl-1.7.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:d30d67e3486aea61bb2cbf7cf81385364c2e4f7ce7469a76ed72af76a5cdfe6b"},+ {file = "yarl-1.7.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:c18a4b286e8d780c3a40c31d7b79836aa93b720f71d5743f20c08b7e049ca073"},+ {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:d54c925396e7891666cabc0199366ca55b27d003393465acef63fd29b8b7aa92"},+ {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:64773840952de17851a1c7346ad7f71688c77e74248d1f0bc230e96680f84028"},+ {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:acbf1756d9dc7cd0ae943d883be72e84e04396f6c2ff93a6ddeca929d562039f"},+ {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:2e48f27936aa838939c798f466c851ba4ae79e347e8dfce43b009c64b930df12"},+ {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:1beef4734ca1ad40a9d8c6b20a76ab46e3a2ed09f38561f01e4aa2ea82cafcef"},+ {file = "yarl-1.7.0-cp39-cp39-win32.whl", hash = "sha256:8ee78c9a5f3c642219d4607680a4693b59239c27a3aa608b64ef79ddc9698039"},+ {file = "yarl-1.7.0-cp39-cp39-win_amd64.whl", hash = "sha256:d750503682605088a14d29a4701548c15c510da4f13c8b17409c4097d5b04c52"},+ {file = "yarl-1.7.0.tar.gz", hash = "sha256:8e7ebaf62e19c2feb097ffb7c94deb0f0c9fab52590784c8cd679d30ab009162"}, ] zipp = [ {file = "zipp-3.6.0-py3-none-any.whl", hash = "sha256:9fe5ea21568a0a70e50f273397638d39b03353731e6cbbb3fd8502a33fec40bc"},diff --git a/pyproject.toml b/pyproject.tomlindex 69364c5f6e5..0be486aa0e9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -122,6 +122,7 @@ joblib = ">=0.15.1,<1.1.0" sentry-sdk = ">=0.17.0,<1.3.0" aio-pika = "^6.7.1" pyTelegramBotAPI = "^3.7.3"+tarsafe = "^0.0.3" [tool.poetry.dev-dependencies] pytest-cov = "^2.10.0"diff --git a/rasa/model.py b/rasa/model.pyindex 78be4034060..21ff2b14de0 100644--- a/rasa/model.py+++ b/rasa/model.py@@ -222,13 +222,14 @@ def unpack_model( """ import tarfile+ from tarsafe import TarSafe if working_directory is None: working_directory = tempfile.mkdtemp() # All files are in a subdirectory. try:- with tarfile.open(model_file, mode="r:gz") as tar:+ with TarSafe.open(model_file, mode="r:gz") as tar: tar.extractall(working_directory) logger.debug(f"Extracted model to '{working_directory}'.") except (tarfile.TarError, ValueError) as e:diff --git a/rasa/nlu/persistor.py b/rasa/nlu/persistor.pyindex 9ba50b8e0ed..9f777aeb659 100644--- a/rasa/nlu/persistor.py+++ b/rasa/nlu/persistor.py@@ -2,7 +2,7 @@ import abc import logging import os import shutil-import tarfile+from tarsafe import TarSafe from typing import Optional, Text, Tuple, TYPE_CHECKING import rasa.shared.utils.common@@ -103,7 +103,7 @@ class Persistor(abc.ABC): @staticmethod def _decompress(compressed_path: Text, target_path: Text) -> None: - with tarfile.open(compressed_path, "r:gz") as tar:+ with TarSafe.open(compressed_path, "r:gz") as tar: tar.extractall(target_path) # target dir will be created if it not exists diff --git a/rasa/utils/io.py b/rasa/utils/io.pyindex 65aa2069759..c0831be91d2 100644--- a/rasa/utils/io.py+++ b/rasa/utils/io.py@@ -3,6 +3,7 @@ import logging import os import pickle import tarfile+from tarsafe import TarSafe import tempfile import warnings import zipfile@@ -87,7 +88,7 @@ def unarchive(byte_array: bytes, directory: Text) -> Text: Tries to use tar first to unpack, if that fails, zip will be used.""" try:- tar = tarfile.open(fileobj=IOReader(byte_array))+ tar = TarSafe.open(fileobj=IOReader(byte_array)) tar.extractall(directory) tar.close() return directory123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140# Patch-overlapping Python context after the fix
## `rasa/model.py` — `function:unpack_model` (lines 210-239)
```pythondef unpack_model( model_file: Text, working_directory: Optional[Union[Path, Text]] = None) -> TempDirectoryPath: """Unpack a zipped Rasa model.
Args: model_file: Path to zipped model. working_directory: Location where the model should be unpacked to. If `None` a temporary directory will be created.
Returns: Path to unpacked Rasa model.
""" import tarfile from tarsafe import TarSafe
if working_directory is None: working_directory = tempfile.mkdtemp()
# All files are in a subdirectory. try: with TarSafe.open(model_file, mode="r:gz") as tar: tar.extractall(working_directory) logger.debug(f"Extracted model to '{working_directory}'.") except (tarfile.TarError, ValueError) as e: logger.error(f"Failed to extract model at {model_file}. Error: {e}") raise
return TempDirectoryPath(working_directory)```
## `rasa/nlu/persistor.py` — `class:Persistor` (lines 50-107)
```pythonclass Persistor(abc.ABC): """Store models in cloud and fetch them when needed."""
def persist(self, model_directory: Text, model_name: Text) -> None: """Uploads a model persisted in the `target_dir` to cloud storage.""" if not os.path.isdir(model_directory): raise ValueError(f"Target directory '{model_directory}' not found.")
file_key, tar_path = self._compress(model_directory, model_name) self._persist_tar(file_key, tar_path)
def retrieve(self, model_name: Text, target_path: Text) -> None: """Downloads a model that has been persisted to cloud storage.""" tar_name = model_name
if not model_name.endswith("tar.gz"): # ensure backward compatibility tar_name = self._tar_name(model_name)
self._retrieve_tar(tar_name) self._decompress(os.path.basename(tar_name), target_path)
@abc.abstractmethod def _retrieve_tar(self, filename: Text) -> Text: """Downloads a model previously persisted to cloud storage.""" raise NotImplementedError
@abc.abstractmethod def _persist_tar(self, filekey: Text, tarname: Text) -> None: # noqa: F841 """Uploads a model persisted in the `target_dir` to cloud storage.""" raise NotImplementedError
def _compress(self, model_directory: Text, model_name: Text) -> Tuple[Text, Text]: """Creates a compressed archive and returns key and tar.""" import tempfile
dirpath = tempfile.mkdtemp() base_name = self._tar_name(model_name, include_extension=False) tar_name = shutil.make_archive( os.path.join(dirpath, base_name), "gztar", root_dir=model_directory, base_dir=".", ) file_key = os.path.basename(tar_name) return file_key, tar_name
@staticmethod def _tar_name(model_name: Text, include_extension: bool = True) -> Text:
ext = ".tar.gz" if include_extension else "" return f"{model_name}{ext}"
@staticmethod def _decompress(compressed_path: Text, target_path: Text) -> None:
with TarSafe.open(compressed_path, "r:gz") as tar: tar.extractall(target_path) # target dir will be created if it not exists```
## `rasa/nlu/persistor.py` — `function:Persistor._decompress` (lines 103-107)
```python def _decompress(compressed_path: Text, target_path: Text) -> None:
with TarSafe.open(compressed_path, "r:gz") as tar: tar.extractall(target_path) # target dir will be created if it not exists```
## `rasa/nlu/persistor.py` — `module:<module>@5` (lines 5-5)
```pythonfrom tarsafe import TarSafe```
## `rasa/utils/io.py` — `function:unarchive` (lines 85-99)
```pythondef unarchive(byte_array: bytes, directory: Text) -> Text: """Tries to unpack a byte array interpreting it as an archive.
Tries to use tar first to unpack, if that fails, zip will be used."""
try: tar = TarSafe.open(fileobj=IOReader(byte_array)) tar.extractall(directory) tar.close() return directory except tarfile.TarError: zip_ref = zipfile.ZipFile(IOReader(byte_array)) zip_ref.extractall(directory) zip_ref.close() return directory```
## `rasa/utils/io.py` — `module:<module>@6` (lines 6-6)
```pythonfrom tarsafe import TarSafe```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145# Patch-overlapping Python context before the fix
## `rasa/model.py` — `function:unpack_model` (lines 210-238)
```pythondef unpack_model( model_file: Text, working_directory: Optional[Union[Path, Text]] = None) -> TempDirectoryPath: """Unpack a zipped Rasa model.
Args: model_file: Path to zipped model. working_directory: Location where the model should be unpacked to. If `None` a temporary directory will be created.
Returns: Path to unpacked Rasa model.
""" import tarfile
if working_directory is None: working_directory = tempfile.mkdtemp()
# All files are in a subdirectory. try: with tarfile.open(model_file, mode="r:gz") as tar: tar.extractall(working_directory) logger.debug(f"Extracted model to '{working_directory}'.") except (tarfile.TarError, ValueError) as e: logger.error(f"Failed to extract model at {model_file}. Error: {e}") raise
return TempDirectoryPath(working_directory)```
## `rasa/nlu/persistor.py` — `class:Persistor` (lines 50-107)
```pythonclass Persistor(abc.ABC): """Store models in cloud and fetch them when needed."""
def persist(self, model_directory: Text, model_name: Text) -> None: """Uploads a model persisted in the `target_dir` to cloud storage.""" if not os.path.isdir(model_directory): raise ValueError(f"Target directory '{model_directory}' not found.")
file_key, tar_path = self._compress(model_directory, model_name) self._persist_tar(file_key, tar_path)
def retrieve(self, model_name: Text, target_path: Text) -> None: """Downloads a model that has been persisted to cloud storage.""" tar_name = model_name
if not model_name.endswith("tar.gz"): # ensure backward compatibility tar_name = self._tar_name(model_name)
self._retrieve_tar(tar_name) self._decompress(os.path.basename(tar_name), target_path)
@abc.abstractmethod def _retrieve_tar(self, filename: Text) -> Text: """Downloads a model previously persisted to cloud storage.""" raise NotImplementedError
@abc.abstractmethod def _persist_tar(self, filekey: Text, tarname: Text) -> None: # noqa: F841 """Uploads a model persisted in the `target_dir` to cloud storage.""" raise NotImplementedError
def _compress(self, model_directory: Text, model_name: Text) -> Tuple[Text, Text]: """Creates a compressed archive and returns key and tar.""" import tempfile
dirpath = tempfile.mkdtemp() base_name = self._tar_name(model_name, include_extension=False) tar_name = shutil.make_archive( os.path.join(dirpath, base_name), "gztar", root_dir=model_directory, base_dir=".", ) file_key = os.path.basename(tar_name) return file_key, tar_name
@staticmethod def _tar_name(model_name: Text, include_extension: bool = True) -> Text:
ext = ".tar.gz" if include_extension else "" return f"{model_name}{ext}"
@staticmethod def _decompress(compressed_path: Text, target_path: Text) -> None:
with tarfile.open(compressed_path, "r:gz") as tar: tar.extractall(target_path) # target dir will be created if it not exists```
## `rasa/nlu/persistor.py` — `function:Persistor._decompress` (lines 103-107)
```python def _decompress(compressed_path: Text, target_path: Text) -> None:
with tarfile.open(compressed_path, "r:gz") as tar: tar.extractall(target_path) # target dir will be created if it not exists```
## `rasa/nlu/persistor.py` — `module:<module>@5` (lines 5-5)
```pythonimport tarfile```
## `rasa/nlu/persistor.py` — `module:<module>@6` (lines 6-6)
```pythonfrom typing import Optional, Text, Tuple, TYPE_CHECKING```
## `rasa/utils/io.py` — `function:unarchive` (lines 84-98)
```pythondef unarchive(byte_array: bytes, directory: Text) -> Text: """Tries to unpack a byte array interpreting it as an archive.
Tries to use tar first to unpack, if that fails, zip will be used."""
try: tar = tarfile.open(fileobj=IOReader(byte_array)) tar.extractall(directory) tar.close() return directory except tarfile.TarError: zip_ref = zipfile.ZipFile(IOReader(byte_array)) zip_ref.extractall(directory) zip_ref.close() return directory```
## `rasa/utils/io.py` — `module:<module>@6` (lines 6-6)
```pythonimport tempfile```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657{ "schema_version": "synthesis-task-v1", "task": { "pair_id": "pyvul-3994e3622b21c396ef8a", "dataset_id": "PyVul", "dataset_item_id": "pyvul-3994e3622b21c396ef8a", "project_id": "pyvul__rasahq__rasa", "language": "python", "backend": "codeql" }, "changed_python_files": [ "rasa/model.py", "rasa/nlu/persistor.py", "rasa/utils/io.py" ], "patch_units": { "before": [ "function:unpack_model", "class:Persistor", "function:Persistor._decompress", "module:<module>@5", "module:<module>@6", "function:unarchive", "module:<module>@6" ], "after": [ "function:unpack_model", "class:Persistor", "function:Persistor._decompress", "module:<module>@5", "function:unarchive", "module:<module>@6" ] }, "runtime_assets": { "before": { "database": "assets/c55507b377561f903462ad5cec29b5fc43df8b9f6e8a1eb5bc87da87c5348d2f/database", "cache_key": "c55507b377561f903462ad5cec29b5fc43df8b9f6e8a1eb5bc87da87c5348d2f", "codeql_version": "2.26.4" }, "after": { "database": "assets/9d2daedadeb33c7c140f4863247d20ea58e9e5a26e7947a1305e447ef40f18d3/database", "cache_key": "9d2daedadeb33c7c140f4863247d20ea58e9e5a26e7947a1305e447ef40f18d3", "codeql_version": "2.26.4" }, "refine": { "database": "assets/b7688a4b944f994a4f8cdc0dc46c7126c07a3197c53b14714e52625daac53337/database", "cache_key": "b7688a4b944f994a4f8cdc0dc46c7126c07a3197c53b14714e52625daac53337", "codeql_version": "2.26.4" } }, "benchmark_contract": { "agent_visible": true, "reference_query_location": "references/pyvul-3994e3622b21c396ef8a/query/ (do not mount into agent)", "evaluator_location": "evaluator/pyvul-3994e3622b21c396ef8a/ (do not mount into agent)" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Python CodeQL detector synthesis
You are cc operating in `/work`. Starting only from the supplied patch,before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQLdetector for the vulnerability fixed by the patch. This is one fresh session. You may iterate insidethis session, but no later framework repair or resume will occur.
## Inputs and owned outputs
- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.- Read `references/codeql/convergence_protocol.md` and `references/codeql/api_navigation.md` before experimenting. Read the remaining `references/codeql/` files for the selected mechanism.- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is uncertain. Do not guess predicate names or build a large family of inspection queries.- Complete the design contract in `state.json` and `scope_statement.md` before final validation.- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the fixed offline dependency in `query/qlpack.yml`.- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This task-unique metadata must never be used in a query predicate.- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
## Required reasoning contract
Before coding, record this mapping in `state.json`:
```textvulnerable operation / trigger / patch safety condition → CodeQL-observable evidence → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism → source, sink/report site, guard/barrier and query predicates```
Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches requirereal path/control-flow semantics; provenance-sensitive patches require value flow. Do not replaceeither with source-text matching or with the mere presence of patch-added syntax.
## Mandatory convergence contract
The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query isa failure; an early compilable semantic candidate can be improved. Follow the checkpoints in`references/codeql/convergence_protocol.md`:
1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` immediately. Do not wait until every CodeQL API detail is known.2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled definition with `scripts/search_codeql_api.sh` or simplify the mechanism.3. Obtain a compiling minimal main query before broadening it. Compile the main query after every meaningful mechanism change.4. Move in order from compile → relevant before finding → after elimination → final contract. Do not continue API exploration after the intended before/after differential is established.5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all exploration, preserve the best compiling query, finish the contract files, and exit.
## Semantic and generalization rules
- Report at the vulnerable call, operator, access, or sink.- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary matching condition. Stable library/framework APIs or public project APIs are allowed only when `scope_statement.md` explains why they define the intended vulnerability family.- The safety condition introduced by the patch must be represented by the query.- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it changed in the patch.
## Final validation protocol
1. Compile the final query.2. Run it on before and inspect `raw/before.sarif` for the intended report location.3. Run the identical query on after and inspect `raw/after.sarif`.4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, and absence of patch-local hardcoding.5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
Do not modify the runtime databases, references, patch, context, or validation scripts except fornormal CodeQL-generated database caches produced by the provided run scripts.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980diff --git a/PIL/EpsImagePlugin.py b/PIL/EpsImagePlugin.pyindex a8706b05f..fcfae8a81 100644--- a/PIL/EpsImagePlugin.py+++ b/PIL/EpsImagePlugin.py@@ -67,7 +67,8 @@ def Ghostscript(tile, size, fp, scale=1): import tempfile, os, subprocess - file = tempfile.mktemp()+ out_fd, file = tempfile.mkstemp()+ os.close(out_fd) # Build ghostscript command command = ["gs",diff --git a/PIL/Image.py b/PIL/Image.pyindex 87631d6f7..915f5b1df 100644--- a/PIL/Image.py+++ b/PIL/Image.py@@ -495,14 +495,17 @@ class Image: self.readonly = 0 def _dump(self, file=None, format=None):- import tempfile+ import tempfile, os if not file:- file = tempfile.mktemp()+ f, file = tempfile.mkstemp(format or '')+ os.close(f)+ self.load() if not format or format == "PPM": self.im.save_ppm(file) else:- file = file + "." + format+ if file.endswith(format):+ file = file + "." + format self.save(file, format) return file diff --git a/PIL/IptcImagePlugin.py b/PIL/IptcImagePlugin.pyindex 157b73509..104153002 100644--- a/PIL/IptcImagePlugin.py+++ b/PIL/IptcImagePlugin.py@@ -172,8 +172,8 @@ class IptcImageFile(ImageFile.ImageFile): self.fp.seek(offset) # Copy image data to temporary file- outfile = tempfile.mktemp()- o = open(outfile, "wb")+ o_fd, outfile = tempfile.mkstemp(text=False)+ o = os.fdopen(o_fd) if encoding == "raw": # To simplify access to the extracted file, # prepend a PPM headerdiff --git a/PIL/JpegImagePlugin.py b/PIL/JpegImagePlugin.pyindex 90d3b5194..67dc5ba7d 100644--- a/PIL/JpegImagePlugin.py+++ b/PIL/JpegImagePlugin.py@@ -344,13 +344,17 @@ class JpegImageFile(ImageFile.ImageFile): # ALTERNATIVE: handle JPEGs via the IJG command line utilities import tempfile, os- file = tempfile.mktemp()- os.system("djpeg %s >%s" % (self.filename, file))+ f, path = tempfile.mkstemp()+ os.close(f)+ if os.path.exists(self.filename):+ os.system("djpeg '%s' >'%s'" % (self.filename, path))+ else:+ raise ValueError("Invalid Filename") try:- self.im = Image.core.open_ppm(file)+ self.im = Image.core.open_ppm(path) finally:- try: os.unlink(file)+ try: os.unlink(path) except: pass self.mode = self.im.mode123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683# Patch-overlapping Python context after the fix
## `PIL/EpsImagePlugin.py` — `function:Ghostscript` (lines 53-110)
```pythondef Ghostscript(tile, size, fp, scale=1): """Render an image using Ghostscript"""
# Unpack decoder tile decoder, tile, offset, data = tile[0] length, bbox = data
#Hack to support hi-res rendering scale = int(scale) or 1 orig_size = size orig_bbox = bbox size = (size[0] * scale, size[1] * scale) bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale] #print("Ghostscript", scale, size, orig_size, bbox, orig_bbox)
import tempfile, os, subprocess
out_fd, file = tempfile.mkstemp() os.close(out_fd)
# Build ghostscript command command = ["gs", "-q", # quite mode "-g%dx%d" % size, # set output geometry (pixels) "-r%d" % (72*scale), # set input DPI (dots per inch) "-dNOPAUSE -dSAFER", # don't pause between pages, safe mode "-sDEVICE=ppmraw", # ppm driver "-sOutputFile=%s" % file,# output file ]
if gs_windows_binary is not None: if gs_windows_binary is False: raise WindowsError('Unable to locate Ghostscript on paths') command[0] = gs_windows_binary
# push data through ghostscript try: gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) # adjust for image origin if bbox[0] != 0 or bbox[1] != 0: gs.stdin.write(("%d %d translate\n" % (-bbox[0], -bbox[1])).encode('ascii')) fp.seek(offset) while length > 0: s = fp.read(8192) if not s: break length = length - len(s) gs.stdin.write(s) gs.stdin.close() status = gs.wait() if status: raise IOError("gs failed (status %d)" % status) im = Image.core.open_ppm(file) finally: try: os.unlink(file) except: pass
return im```
## `PIL/Image.py` — `class:Image` (lines 447-1705)
```pythonclass Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly.
* :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None
def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self.size = (0, 0) self.palette = None self.info = {} self.category = NORMAL self.readonly = 0
def _new(self, im): new = Image() new.im = im new.mode = im.mode new.size = im.size new.palette = self.palette if im.mode == "P" and not new.palette: from PIL import ImagePalette new.palette = ImagePalette.ImagePalette() try: new.info = self.info.copy() except AttributeError: # fallback (pre-1.5.2) new.info = {} for k, v in self.info: new.info[k] = v return new
_makeself = _new # compatibility
def _copy(self): self.load() self.im = self.im.copy() self.readonly = 0
def _dump(self, file=None, format=None): import tempfile, os if not file: f, file = tempfile.mkstemp(format or '') os.close(f) self.load() if not format or format == "PPM": self.im.save_ppm(file) else: if file.endswith(format): file = file + "." + format self.save(file, format) return file
def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self) )
def __getattr__(self, name): if name == "__array_interface__": # numpy array interface support new = {} shape, typestr = _conv_type_shape(self) new['shape'] = shape new['typestr'] = typestr new['data'] = self.tobytes() return new raise AttributeError(name)
def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object
:param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. :param args: Extra arguments to the encoder. :rtype: A bytes object. """
# may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
if encoder_name == "raw" and args == (): args = self.mode
self.load()
# unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im)
bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError("encoder error %d in tobytes" % s)
return b"".join(data)
# Declare tostring as alias to tobytes def tostring(self, *args, **kw): warnings.warn( 'tostring() is deprecated. Please call tobytes() instead.', DeprecationWarning, stacklevel=2, ) return self.tobytes(*args, **kw)
def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap.
.. note:: This method only works for mode "1" images.
:param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """
self.load() if self.mode != "1": raise ValueError("not a bitmap") data = self.tobytes("xbm") return b"".join([("#define %s_width %d\n" % (name, self.size[0])).encode('ascii'), ("#define %s_height %d\n"% (name, self.size[1])).encode('ascii'), ("static char %s_bits[] = {\n" % name).encode('ascii'), data, b"};"])
def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object.
This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """
# may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
# default format if decoder_name == "raw" and args == (): args = self.mode
# unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data)
if s[0] >= 0: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data")
def fromstring(self, *args, **kw): """Deprecated alias to frombytes.
.. deprecated:: 2.0 """ warnings.warn('fromstring() is deprecated. Please call frombytes() instead.', DeprecationWarning) return self.frombytes(*args, **kw)
def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time.
:returns: An image access object. """ if self.im and self.palette and self.palette.dirty: # realize palette self.im.putpalette(*self.palette.getdata()) self.palette.dirty = 0 self.palette.mode = "RGB" self.palette.rawmode = None if "transparency" in self.info: if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA"
if self.im: return self.im.pixel_access(self.readonly)
def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass
def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.
The current version supports all possible conversions between "L", "RGB" and "CMYK." The **matrix** argument only supports "L" and "RGB".
When translating a color image to black and white (mode "L"), the library uses the ITU-R 601-2 luma transform::
L = R * 299/1000 + G * 587/1000 + B * 114/1000
The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is NONE, all non-zero values are set to 255 (white). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method.
:param mode: The requested mode. :param matrix: An optional conversion matrix. If given, this should be 4- or 16-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are NONE or FLOYDSTEINBERG (default). :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are WEB or ADAPTIVE. :param colors: Number of colors to use for the ADAPTIVE palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """
if not mode: # determine default mode if self.mode == "P": self.load() if self.palette: mode = self.palette.mode else: mode = "RGB" else: return self.copy()
self.load()
if matrix: # matrix conversion if mode not in ("L", "RGB"): raise ValueError("illegal conversion") im = self.im.convert_matrix(mode, matrix) return self._new(im)
if mode == "P" and palette == ADAPTIVE: im = self.im.quantize(colors) return self._new(im)
# colorspace conversion if dither is None: dither = FLOYDSTEINBERG
# Use transparent conversion to promote from transparent color to an alpha channel. if self.mode in ("L", "RGB") and mode == "RGBA" and "transparency" in self.info: return self._new(self.im.convert_transparent(mode, self.info['transparency'])) try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError: raise ValueError("illegal conversion")
return self._new(im)
def quantize(self, colors=256, method=0, kmeans=0, palette=None):
# methods: # 0 = median cut # 1 = maximum coverage # 2 = fast octree
# NOTE: this functionality will be moved to the extended # quantizer interface in a later version of PIL.
self.load()
if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) im = self.im.convert("P", 1, palette.im) return self._makeself(im)
im = self.im.quantize(colors, method, kmeans) return self._new(im)
def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original.
:rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() im = self.im.copy() return self._new(im)
def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.
This is a lazy operation. Changes to the source image may or may not be reflected in the cropped image. To break the connection, call the :py:meth:`~PIL.Image.Image.load` method on the cropped copy.
:param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """
self.load() if box is None: return self.copy()
# lazy operation return _ImageCrop(self, box)
def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it, or to extract a 128x192 version from a PCD file.
Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect.
:param mode: The requested mode. :param size: The requested size. """ pass
def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0))
def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module.
:param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object. """
self.load()
if isinstance(filter, collections.Callable): filter = filter() if not hasattr(filter, "filter"): raise TypeError("filter argument should be ImageFilter.Filter instance or class")
if self.im.bands == 1: return self._new(filter.filter(self.im)) # fix to handle multiband images since _imaging doesn't ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims)
def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, **getbands** on an RGB image returns ("R", "G", "B").
:returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands
def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image.
:returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. If the image is completely empty, this method returns None.
"""
self.load() return self.im.getbbox()
def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image.
:param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """
self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors)
def getdata(self, band = None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.
Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use **list(im.getdata())**.
:param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """
self.load() if band is not None: return self.im.getband(band) return self.im # could be abused
def getextrema(self): """ Gets the the minimum and maximum pixel values for each band in the image.
:returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """
self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema()
def getim(self): """ Returns a capsule that points to the internal image memory.
:returns: A capsule object. """
self.load() return self.im.ptr
def getpalette(self): """ Returns the image palette as a list.
:returns: A list of color values [r, g, b, ...], or None if the image has no palette. """
self.load() try: if bytes is str: return [i8(c) for c in self.im.getpalette()] else: return list(self.im.getpalette()) except ValueError: return None # no palette
def getpixel(self, xy): """ Returns the pixel value at a given position.
:param xy: The coordinate, given as (x, y). :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """
self.load() return self.im.getpixel(xy)
def getprojection(self): """ Get projection to x and y axes
:returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """
self.load() x, y = self.im.getprojection() return [i8(c) for c in x], [i8(c) for c in y]
def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values).
A bilevel image (mode "1") is treated as a greyscale ("L") image by this method.
If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L").
:param mask: An optional mask. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram()
def offset(self, xoffset, yoffset=None): """ .. deprecated:: 2.0
.. note:: New code should use :py:func:`PIL.ImageChops.offset`.
Returns a copy of the image where the data has been offset by the given distances. Data wraps around the edges. If **yoffset** is omitted, it is assumed to be equal to **xoffset**.
:param xoffset: The horizontal distance. :param yoffset: The vertical distance. If omitted, both distances are set to the same value. :returns: An :py:class:`~PIL.Image.Image` object. """ if warnings: warnings.warn( "'offset' is deprecated; use 'ImageChops.offset' instead", DeprecationWarning, stacklevel=2 ) from PIL import ImageChops return ImageChops.offset(self, xoffset, yoffset)
def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). If a 4-tuple is given, the size of the pasted image must match the size of the region.
If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details).
Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module.
If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values can be used for transparency effects.
Note that if you paste an "RGBA" image, the alpha band is ignored. You can work around this by using the same image as both source image and mask.
:param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner.
If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. :returns: An :py:class:`~PIL.Image.Image` object. """
if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box; box = None
if box is None: # cover all of self box = (0, 0) + self.size
if len(box) == 2: # lower left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? raise ValueError( "cannot determine region size; use 4-item box" ) box = box + (box[0]+size[0], box[1]+size[1])
if isStringType(im): from PIL import ImageColor im = ImageColor.getcolor(im, self.mode)
elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im
self.load() if self.readonly: self._copy()
if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box)
def point(self, lut, mode=None): """ Maps this image through a lookup table or function.
:param lut: A lookup table, containing 256 (or 65336 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """
self.load()
if isinstance(lut, ImagePointHandler): return lut.point(self)
if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands
if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case raise ValueError("point operation not supported for this mode")
return self._new(self.im.point(lut, mode))
def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1".
:param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """
self.load() if self.readonly: self._copy()
if self.mode not in ("LA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError): # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "RGBA"): raise ValueError # sanity check self.im = im self.mode = self.im.mode except (KeyError, ValueError): raise ValueError("illegal image mode")
if self.mode == "LA": band = 1 else: band = 3
if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): raise ValueError("illegal image mode") alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return
self.im.putband(alpha.im, band)
def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data to this image. This method copies data from a sequence object into the image, starting at the upper left corner (0, 0), and continuing until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**.
:param data: A sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """
self.load() if self.readonly: self._copy()
self.im.putdata(data, scale, offset)
def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P" or "L" image, and the palette sequence must contain 768 integer values, where each group of three values represent the red, green, and blue values for the corresponding pixel index. Instead of an integer sequence, you can use an 8-bit string.
:param data: A palette sequence (either a list or a string). """ from PIL import ImagePalette
if self.mode not in ("L", "P"): raise ValueError("illegal image mode") self.load() if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): if bytes is str: data = "".join(chr(x) for x in data) else: data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette
def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images.
Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead.
See:
* :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw`
:param xy: The pixel coordinate, given as (x, y). :param value: The pixel value. """
self.load() if self.readonly: self._copy()
return self.im.putpixel(xy, value)
def resize(self, size, resample=NEAREST): """ Returns a resized copy of this image.
:param size: The requested size in pixels, as a 2-tuple: (width, height). :param filter: An optional resampling filter. This can be one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), :py:attr:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment), or :py:attr:`PIL.Image.ANTIALIAS` (a high-quality downsampling filter). If omitted, or if the image has mode "1" or "P", it is set :py:attr:`PIL.Image.NEAREST`. :returns: An :py:class:`~PIL.Image.Image` object. """
if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS): raise ValueError("unknown resampling filter")
self.load()
if self.mode in ("1", "P"): resample = NEAREST
if self.mode == 'RGBA': return self.convert('RGBa').resize(size, resample).convert('RGBA')
if resample == ANTIALIAS: # requires stretch support (imToolkit & PIL 1.1.3) try: im = self.im.stretch(size, resample) except AttributeError: raise ValueError("unsupported resampling filter") else: im = self.im.resize(size, resample)
return self._new(im)
def rotate(self, angle, resample=NEAREST, expand=0): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre.
:param angle: In degrees counter clockwise. :param filter: An optional resampling filter. This can be one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set :py:attr:`PIL.Image.NEAREST`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. :returns: An :py:class:`~PIL.Image.Image` object. """
if expand: import math angle = -angle * math.pi / 180 matrix = [ math.cos(angle), math.sin(angle), 0.0, -math.sin(angle), math.cos(angle), 0.0 ] def transform(x, y, matrix=matrix): (a, b, c, d, e, f) = matrix return a*x + b*y + c, d*x + e*y + f
# calculate output size w, h = self.size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y) xx.append(x) yy.append(y) w = int(math.ceil(max(xx)) - math.floor(min(xx))) h = int(math.ceil(max(yy)) - math.floor(min(yy)))
# adjust center x, y = transform(w / 2.0, h / 2.0) matrix[2] = self.size[0] / 2.0 - x matrix[5] = self.size[1] / 2.0 - y
return self.transform((w, h), AFFINE, matrix, resample)
if resample not in (NEAREST, BILINEAR, BICUBIC): raise ValueError("unknown resampling filter")
self.load()
if self.mode in ("1", "P"): resample = NEAREST
return self._new(self.im.rotate(angle, resample))
def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible.
Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described later in this handbook.
You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the **seek**, **tell**, and **write** methods, and be opened in binary mode.
:param file: File name or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param options: Extra parameters to the image writer. :returns: None :exception KeyError: If the output format could not be determined from the file name. Use the format option to solve this. :exception IOError: If the file could not be written. The file may have been created, and may contain partial data. """
if isPath(fp): filename = fp else: if hasattr(fp, "name") and isPath(fp.name): filename = fp.name else: filename = ""
# may mutate self! self.load()
self.encoderinfo = params self.encoderconfig = ()
preinit()
ext = os.path.splitext(filename)[1].lower()
if not format: try: format = EXTENSION[ext] except KeyError: init() try: format = EXTENSION[ext] except KeyError: raise KeyError(ext) # unknown extension
try: save_handler = SAVE[format.upper()] except KeyError: init() save_handler = SAVE[format.upper()] # unknown format
if isPath(fp): fp = builtins.open(fp, "wb") close = 1 else: close = 0
try: save_handler(self, fp, filename) finally: # do what we can to clean up if close: fp.close()
def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an **EOFError** exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
See :py:meth:`~PIL.Image.Image.tell`.
:param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """
# overridden by file handlers if frame != 0: raise EOFError
def show(self, title=None, command=None): """ Displays this image. This method is mainly intended for debugging purposes.
On Unix platforms, this method saves the image to a temporary PPM file, and calls the **xv** utility.
On Windows, it saves the image to a temporary BMP file, and uses the standard BMP display utility to show it (usually Paint).
:param title: Optional title to use for the image window, where possible. :param command: command used to show the image """
_show(self, title=title, command=command)
def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue).
:returns: A tuple containing bands. """
self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = [] for i in range(self.im.bands): ims.append(self._new(self.im.getband(i))) return tuple(ims)
def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
:returns: Frame number, starting with 0. """ return 0
def thumbnail(self, size, resample=NEAREST): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image.
Note that the bilinear and bicubic filters in the current version of PIL are not well-suited for thumbnail generation. You should use :py:attr:`PIL.Image.ANTIALIAS` unless speed is much more important than quality.
Also note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image.
:param size: Requested size. :param resample: Optional resampling filter. This can be one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.ANTIALIAS` (best quality). If omitted, it defaults to :py:attr:`PIL.Image.NEAREST` (this will be changed to ANTIALIAS in a future version). :returns: None """
# FIXME: the default resampling filter will be changed # to ANTIALIAS in future versions
# preserve aspect ratio x, y = self.size if x > size[0]: y = int(max(y * size[0] / x, 1)); x = int(size[0]) if y > size[1]: x = int(max(x * size[1] / y, 1)); y = int(size[1]) size = x, y
if size == self.size: return
self.draft(None, size)
self.load()
try: im = self.resize(size, resample) except ValueError: if resample != ANTIALIAS: raise im = self.resize(size, NEAREST) # fallback
self.im = im.im self.mode = im.mode self.size = size
self.readonly = 0
# FIXME: the different tranform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform(self, size, method, data=None, resample=NEAREST, fill=1): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform.
:param size: The output size. :param method: The transformation method. This is one of :py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:attr:`PIL.Image.AFFINE` (affine transform), :py:attr:`PIL.Image.PERSPECTIVE` (perspective transform), :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals in one operation). :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`. :returns: An :py:class:`~PIL.Image.Image` object. """
if self.mode == 'RGBA': return self.convert('RGBa').transform(size, method, data, resample, fill).convert('RGBA')
if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: raise ValueError("missing method data")
im = new(self.mode, size, None) if method == MESH: # list of quads for box, quad in data: im.__transformer(box, self, QUAD, quad, resample, fill) else: im.__transformer((0, 0)+size, self, method, data, resample, fill)
return im
def __transformer(self, box, image, method, data, resample=NEAREST, fill=1):
# FIXME: this should be turned into a lazy operation (?)
w = box[2]-box[0] h = box[3]-box[1]
if method == AFFINE: # change argument order to match implementation data = (data[2], data[0], data[1], data[5], data[3], data[4]) elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = float(x1 - x0) / w ys = float(y1 - y0) / h method = AFFINE data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys) elif method == PERSPECTIVE: # change argument order to match implementation data = (data[2], data[0], data[1], data[5], data[3], data[4], data[6], data[7]) elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8] x0, y0 = nw; As = 1.0 / w; At = 1.0 / h data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At, (se[0]-sw[0]-ne[0]+x0)*As*At, y0, (ne[1]-y0)*As, (sw[1]-y0)*At, (se[1]-sw[1]-ne[1]+y0)*As*At) else: raise ValueError("unknown transformation method")
if resample not in (NEAREST, BILINEAR, BICUBIC): raise ValueError("unknown resampling filter")
image.load()
self.load()
if image.mode in ("1", "P"): resample = NEAREST
self.im.transform2(box, image.im, method, data, resample, fill)
def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps)
:param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`, :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`, :py:attr:`PIL.Image.ROTATE_180`, or :py:attr:`PIL.Image.ROTATE_270`. :returns: Returns a flipped or rotated copy of this image. """
self.load() im = self.im.transpose(method) return self._new(im)```
## `PIL/Image.py` — `function:Image._dump` (lines 497-510)
```python def _dump(self, file=None, format=None): import tempfile, os if not file: f, file = tempfile.mkstemp(format or '') os.close(f) self.load() if not format or format == "PPM": self.im.save_ppm(file) else: if file.endswith(format): file = file + "." + format self.save(file, format) return file```
## `PIL/IptcImagePlugin.py` — `class:IptcImageFile` (lines 53-204)
```pythonclass IptcImageFile(ImageFile.ImageFile):
format = "IPTC" format_description = "IPTC/NAA"
def getint(self, key): return i(self.info[key])
def field(self): # # get a IPTC field header s = self.fp.read(5) if not len(s): return None, 0
tag = i8(s[1]), i8(s[2])
# syntax if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9: raise SyntaxError("invalid IPTC/NAA file")
# field size size = i8(s[3]) if size > 132: raise IOError("illegal field length in IPTC/NAA file") elif size == 128: size = 0 elif size > 128: size = i(self.fp.read(size-128)) else: size = i16(s[3:])
return tag, size
def _is_raw(self, offset, size): # # check if the file can be mapped
# DISABLED: the following only slows things down... return 0
self.fp.seek(offset) t, sz = self.field() if sz != size[0]: return 0 y = 1 while True: self.fp.seek(sz, 1) t, s = self.field() if t != (8, 10): break if s != sz: return 0 y = y + 1 return y == size[1]
def _open(self):
# load descriptive fields while True: offset = self.fp.tell() tag, size = self.field() if not tag or tag == (8,10): break if size: tagdata = self.fp.read(size) else: tagdata = None if tag in list(self.info.keys()): if isinstance(self.info[tag], list): self.info[tag].append(tagdata) else: self.info[tag] = [self.info[tag], tagdata] else: self.info[tag] = tagdata
# print tag, self.info[tag]
# mode layers = i8(self.info[(3,60)][0]) component = i8(self.info[(3,60)][1]) if (3,65) in self.info: id = i8(self.info[(3,65)][0])-1 else: id = 0 if layers == 1 and not component: self.mode = "L" elif layers == 3 and component: self.mode = "RGB"[id] elif layers == 4 and component: self.mode = "CMYK"[id]
# size self.size = self.getint((3,20)), self.getint((3,30))
# compression try: compression = COMPRESSION[self.getint((3,120))] except KeyError: raise IOError("Unknown IPTC image compression")
# tile if tag == (8,10): if compression == "raw" and self._is_raw(offset, self.size): self.tile = [(compression, (offset, size + 5, -1), (0, 0, self.size[0], self.size[1]))] else: self.tile = [("iptc", (compression, offset), (0, 0, self.size[0], self.size[1]))]
def load(self):
if len(self.tile) != 1 or self.tile[0][0] != "iptc": return ImageFile.ImageFile.load(self)
type, tile, box = self.tile[0]
encoding, offset = tile
self.fp.seek(offset)
# Copy image data to temporary file o_fd, outfile = tempfile.mkstemp(text=False) o = os.fdopen(o_fd) if encoding == "raw": # To simplify access to the extracted file, # prepend a PPM header o.write("P5\n%d %d\n255\n" % self.size) while True: type, size = self.field() if type != (8, 10): break while size > 0: s = self.fp.read(min(size, 8192)) if not s: break o.write(s) size = size - len(s) o.close()
try: try: # fast self.im = Image.core.open_ppm(outfile) except: # slightly slower im = Image.open(outfile) im.load() self.im = im.im finally: try: os.unlink(outfile) except: pass```
## `PIL/IptcImagePlugin.py` — `function:IptcImageFile.load` (lines 163-204)
```python def load(self):
if len(self.tile) != 1 or self.tile[0][0] != "iptc": return ImageFile.ImageFile.load(self)
type, tile, box = self.tile[0]
encoding, offset = tile
self.fp.seek(offset)
# Copy image data to temporary file o_fd, outfile = tempfile.mkstemp(text=False) o = os.fdopen(o_fd) if encoding == "raw": # To simplify access to the extracted file, # prepend a PPM header o.write("P5\n%d %d\n255\n" % self.size) while True: type, size = self.field() if type != (8, 10): break while size > 0: s = self.fp.read(min(size, 8192)) if not s: break o.write(s) size = size - len(s) o.close()
try: try: # fast self.im = Image.core.open_ppm(outfile) except: # slightly slower im = Image.open(outfile) im.load() self.im = im.im finally: try: os.unlink(outfile) except: pass```
## `PIL/JpegImagePlugin.py` — `class:JpegImageFile` (lines 267-366)
```pythonclass JpegImageFile(ImageFile.ImageFile):
format = "JPEG" format_description = "JPEG (ISO 10918)"
def _open(self):
s = self.fp.read(1)
if i8(s[0]) != 255: raise SyntaxError("not a JPEG file")
# Create attributes self.bits = self.layers = 0
# JPEG specifics (internal) self.layer = [] self.huffman_dc = {} self.huffman_ac = {} self.quantization = {} self.app = {} # compatibility self.applist = [] self.icclist = []
while True:
s = s + self.fp.read(1)
i = i16(s)
if i in MARKER: name, description, handler = MARKER[i] # print hex(i), name, description if handler is not None: handler(self, i) if i == 0xFFDA: # start of scan rawmode = self.mode if self.mode == "CMYK": rawmode = "CMYK;I" # assume adobe conventions self.tile = [("jpeg", (0,0) + self.size, 0, (rawmode, ""))] # self.__offset = self.fp.tell() break s = self.fp.read(1) elif i == 0 or i == 65535: # padded marker or junk; move on s = "\xff" else: raise SyntaxError("no marker found")
def draft(self, mode, size):
if len(self.tile) != 1: return
d, e, o, a = self.tile[0] scale = 0
if a[0] == "RGB" and mode in ["L", "YCbCr"]: self.mode = mode a = mode, ""
if size: scale = max(self.size[0] // size[0], self.size[1] // size[1]) for s in [8, 4, 2, 1]: if scale >= s: break e = e[0], e[1], (e[2]-e[0]+s-1)//s+e[0], (e[3]-e[1]+s-1)//s+e[1] self.size = ((self.size[0]+s-1)//s, (self.size[1]+s-1)//s) scale = s
self.tile = [(d, e, o, a)] self.decoderconfig = (scale, 1)
return self
def load_djpeg(self):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os f, path = tempfile.mkstemp() os.close(f) if os.path.exists(self.filename): os.system("djpeg '%s' >'%s'" % (self.filename, path)) else: raise ValueError("Invalid Filename")
try: self.im = Image.core.open_ppm(path) finally: try: os.unlink(path) except: pass
self.mode = self.im.mode self.size = self.im.size
self.tile = []
def _getexif(self): return _getexif(self)```
## `PIL/JpegImagePlugin.py` — `function:JpegImageFile.load_djpeg` (lines 342-363)
```python def load_djpeg(self):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os f, path = tempfile.mkstemp() os.close(f) if os.path.exists(self.filename): os.system("djpeg '%s' >'%s'" % (self.filename, path)) else: raise ValueError("Invalid Filename")
try: self.im = Image.core.open_ppm(path) finally: try: os.unlink(path) except: pass
self.mode = self.im.mode self.size = self.im.size
self.tile = []```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668# Patch-overlapping Python context before the fix
## `PIL/EpsImagePlugin.py` — `function:Ghostscript` (lines 53-109)
```pythondef Ghostscript(tile, size, fp, scale=1): """Render an image using Ghostscript"""
# Unpack decoder tile decoder, tile, offset, data = tile[0] length, bbox = data
#Hack to support hi-res rendering scale = int(scale) or 1 orig_size = size orig_bbox = bbox size = (size[0] * scale, size[1] * scale) bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale] #print("Ghostscript", scale, size, orig_size, bbox, orig_bbox)
import tempfile, os, subprocess
file = tempfile.mktemp()
# Build ghostscript command command = ["gs", "-q", # quite mode "-g%dx%d" % size, # set output geometry (pixels) "-r%d" % (72*scale), # set input DPI (dots per inch) "-dNOPAUSE -dSAFER", # don't pause between pages, safe mode "-sDEVICE=ppmraw", # ppm driver "-sOutputFile=%s" % file,# output file ]
if gs_windows_binary is not None: if gs_windows_binary is False: raise WindowsError('Unable to locate Ghostscript on paths') command[0] = gs_windows_binary
# push data through ghostscript try: gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) # adjust for image origin if bbox[0] != 0 or bbox[1] != 0: gs.stdin.write(("%d %d translate\n" % (-bbox[0], -bbox[1])).encode('ascii')) fp.seek(offset) while length > 0: s = fp.read(8192) if not s: break length = length - len(s) gs.stdin.write(s) gs.stdin.close() status = gs.wait() if status: raise IOError("gs failed (status %d)" % status) im = Image.core.open_ppm(file) finally: try: os.unlink(file) except: pass
return im```
## `PIL/Image.py` — `class:Image` (lines 447-1702)
```pythonclass Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly.
* :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None
def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self.size = (0, 0) self.palette = None self.info = {} self.category = NORMAL self.readonly = 0
def _new(self, im): new = Image() new.im = im new.mode = im.mode new.size = im.size new.palette = self.palette if im.mode == "P" and not new.palette: from PIL import ImagePalette new.palette = ImagePalette.ImagePalette() try: new.info = self.info.copy() except AttributeError: # fallback (pre-1.5.2) new.info = {} for k, v in self.info: new.info[k] = v return new
_makeself = _new # compatibility
def _copy(self): self.load() self.im = self.im.copy() self.readonly = 0
def _dump(self, file=None, format=None): import tempfile if not file: file = tempfile.mktemp() self.load() if not format or format == "PPM": self.im.save_ppm(file) else: file = file + "." + format self.save(file, format) return file
def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self) )
def __getattr__(self, name): if name == "__array_interface__": # numpy array interface support new = {} shape, typestr = _conv_type_shape(self) new['shape'] = shape new['typestr'] = typestr new['data'] = self.tobytes() return new raise AttributeError(name)
def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object
:param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. :param args: Extra arguments to the encoder. :rtype: A bytes object. """
# may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
if encoder_name == "raw" and args == (): args = self.mode
self.load()
# unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im)
bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError("encoder error %d in tobytes" % s)
return b"".join(data)
# Declare tostring as alias to tobytes def tostring(self, *args, **kw): warnings.warn( 'tostring() is deprecated. Please call tobytes() instead.', DeprecationWarning, stacklevel=2, ) return self.tobytes(*args, **kw)
def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap.
.. note:: This method only works for mode "1" images.
:param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """
self.load() if self.mode != "1": raise ValueError("not a bitmap") data = self.tobytes("xbm") return b"".join([("#define %s_width %d\n" % (name, self.size[0])).encode('ascii'), ("#define %s_height %d\n"% (name, self.size[1])).encode('ascii'), ("static char %s_bits[] = {\n" % name).encode('ascii'), data, b"};"])
def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object.
This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """
# may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
# default format if decoder_name == "raw" and args == (): args = self.mode
# unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data)
if s[0] >= 0: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data")
def fromstring(self, *args, **kw): """Deprecated alias to frombytes.
.. deprecated:: 2.0 """ warnings.warn('fromstring() is deprecated. Please call frombytes() instead.', DeprecationWarning) return self.frombytes(*args, **kw)
def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time.
:returns: An image access object. """ if self.im and self.palette and self.palette.dirty: # realize palette self.im.putpalette(*self.palette.getdata()) self.palette.dirty = 0 self.palette.mode = "RGB" self.palette.rawmode = None if "transparency" in self.info: if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA"
if self.im: return self.im.pixel_access(self.readonly)
def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass
def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.
The current version supports all possible conversions between "L", "RGB" and "CMYK." The **matrix** argument only supports "L" and "RGB".
When translating a color image to black and white (mode "L"), the library uses the ITU-R 601-2 luma transform::
L = R * 299/1000 + G * 587/1000 + B * 114/1000
The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is NONE, all non-zero values are set to 255 (white). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method.
:param mode: The requested mode. :param matrix: An optional conversion matrix. If given, this should be 4- or 16-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are NONE or FLOYDSTEINBERG (default). :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are WEB or ADAPTIVE. :param colors: Number of colors to use for the ADAPTIVE palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """
if not mode: # determine default mode if self.mode == "P": self.load() if self.palette: mode = self.palette.mode else: mode = "RGB" else: return self.copy()
self.load()
if matrix: # matrix conversion if mode not in ("L", "RGB"): raise ValueError("illegal conversion") im = self.im.convert_matrix(mode, matrix) return self._new(im)
if mode == "P" and palette == ADAPTIVE: im = self.im.quantize(colors) return self._new(im)
# colorspace conversion if dither is None: dither = FLOYDSTEINBERG
# Use transparent conversion to promote from transparent color to an alpha channel. if self.mode in ("L", "RGB") and mode == "RGBA" and "transparency" in self.info: return self._new(self.im.convert_transparent(mode, self.info['transparency'])) try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError: raise ValueError("illegal conversion")
return self._new(im)
def quantize(self, colors=256, method=0, kmeans=0, palette=None):
# methods: # 0 = median cut # 1 = maximum coverage # 2 = fast octree
# NOTE: this functionality will be moved to the extended # quantizer interface in a later version of PIL.
self.load()
if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) im = self.im.convert("P", 1, palette.im) return self._makeself(im)
im = self.im.quantize(colors, method, kmeans) return self._new(im)
def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original.
:rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() im = self.im.copy() return self._new(im)
def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.
This is a lazy operation. Changes to the source image may or may not be reflected in the cropped image. To break the connection, call the :py:meth:`~PIL.Image.Image.load` method on the cropped copy.
:param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """
self.load() if box is None: return self.copy()
# lazy operation return _ImageCrop(self, box)
def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it, or to extract a 128x192 version from a PCD file.
Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect.
:param mode: The requested mode. :param size: The requested size. """ pass
def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0))
def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module.
:param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object. """
self.load()
if isinstance(filter, collections.Callable): filter = filter() if not hasattr(filter, "filter"): raise TypeError("filter argument should be ImageFilter.Filter instance or class")
if self.im.bands == 1: return self._new(filter.filter(self.im)) # fix to handle multiband images since _imaging doesn't ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims)
def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, **getbands** on an RGB image returns ("R", "G", "B").
:returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands
def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image.
:returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. If the image is completely empty, this method returns None.
"""
self.load() return self.im.getbbox()
def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image.
:param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """
self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors)
def getdata(self, band = None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.
Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use **list(im.getdata())**.
:param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """
self.load() if band is not None: return self.im.getband(band) return self.im # could be abused
def getextrema(self): """ Gets the the minimum and maximum pixel values for each band in the image.
:returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """
self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema()
def getim(self): """ Returns a capsule that points to the internal image memory.
:returns: A capsule object. """
self.load() return self.im.ptr
def getpalette(self): """ Returns the image palette as a list.
:returns: A list of color values [r, g, b, ...], or None if the image has no palette. """
self.load() try: if bytes is str: return [i8(c) for c in self.im.getpalette()] else: return list(self.im.getpalette()) except ValueError: return None # no palette
def getpixel(self, xy): """ Returns the pixel value at a given position.
:param xy: The coordinate, given as (x, y). :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """
self.load() return self.im.getpixel(xy)
def getprojection(self): """ Get projection to x and y axes
:returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """
self.load() x, y = self.im.getprojection() return [i8(c) for c in x], [i8(c) for c in y]
def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values).
A bilevel image (mode "1") is treated as a greyscale ("L") image by this method.
If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L").
:param mask: An optional mask. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram()
def offset(self, xoffset, yoffset=None): """ .. deprecated:: 2.0
.. note:: New code should use :py:func:`PIL.ImageChops.offset`.
Returns a copy of the image where the data has been offset by the given distances. Data wraps around the edges. If **yoffset** is omitted, it is assumed to be equal to **xoffset**.
:param xoffset: The horizontal distance. :param yoffset: The vertical distance. If omitted, both distances are set to the same value. :returns: An :py:class:`~PIL.Image.Image` object. """ if warnings: warnings.warn( "'offset' is deprecated; use 'ImageChops.offset' instead", DeprecationWarning, stacklevel=2 ) from PIL import ImageChops return ImageChops.offset(self, xoffset, yoffset)
def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). If a 4-tuple is given, the size of the pasted image must match the size of the region.
If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details).
Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module.
If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values can be used for transparency effects.
Note that if you paste an "RGBA" image, the alpha band is ignored. You can work around this by using the same image as both source image and mask.
:param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner.
If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. :returns: An :py:class:`~PIL.Image.Image` object. """
if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box; box = None
if box is None: # cover all of self box = (0, 0) + self.size
if len(box) == 2: # lower left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? raise ValueError( "cannot determine region size; use 4-item box" ) box = box + (box[0]+size[0], box[1]+size[1])
if isStringType(im): from PIL import ImageColor im = ImageColor.getcolor(im, self.mode)
elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im
self.load() if self.readonly: self._copy()
if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box)
def point(self, lut, mode=None): """ Maps this image through a lookup table or function.
:param lut: A lookup table, containing 256 (or 65336 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """
self.load()
if isinstance(lut, ImagePointHandler): return lut.point(self)
if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands
if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case raise ValueError("point operation not supported for this mode")
return self._new(self.im.point(lut, mode))
def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1".
:param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """
self.load() if self.readonly: self._copy()
if self.mode not in ("LA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError): # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "RGBA"): raise ValueError # sanity check self.im = im self.mode = self.im.mode except (KeyError, ValueError): raise ValueError("illegal image mode")
if self.mode == "LA": band = 1 else: band = 3
if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): raise ValueError("illegal image mode") alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return
self.im.putband(alpha.im, band)
def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data to this image. This method copies data from a sequence object into the image, starting at the upper left corner (0, 0), and continuing until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**.
:param data: A sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """
self.load() if self.readonly: self._copy()
self.im.putdata(data, scale, offset)
def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P" or "L" image, and the palette sequence must contain 768 integer values, where each group of three values represent the red, green, and blue values for the corresponding pixel index. Instead of an integer sequence, you can use an 8-bit string.
:param data: A palette sequence (either a list or a string). """ from PIL import ImagePalette
if self.mode not in ("L", "P"): raise ValueError("illegal image mode") self.load() if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): if bytes is str: data = "".join(chr(x) for x in data) else: data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette
def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images.
Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead.
See:
* :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw`
:param xy: The pixel coordinate, given as (x, y). :param value: The pixel value. """
self.load() if self.readonly: self._copy()
return self.im.putpixel(xy, value)
def resize(self, size, resample=NEAREST): """ Returns a resized copy of this image.
:param size: The requested size in pixels, as a 2-tuple: (width, height). :param filter: An optional resampling filter. This can be one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), :py:attr:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment), or :py:attr:`PIL.Image.ANTIALIAS` (a high-quality downsampling filter). If omitted, or if the image has mode "1" or "P", it is set :py:attr:`PIL.Image.NEAREST`. :returns: An :py:class:`~PIL.Image.Image` object. """
if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS): raise ValueError("unknown resampling filter")
self.load()
if self.mode in ("1", "P"): resample = NEAREST
if self.mode == 'RGBA': return self.convert('RGBa').resize(size, resample).convert('RGBA')
if resample == ANTIALIAS: # requires stretch support (imToolkit & PIL 1.1.3) try: im = self.im.stretch(size, resample) except AttributeError: raise ValueError("unsupported resampling filter") else: im = self.im.resize(size, resample)
return self._new(im)
def rotate(self, angle, resample=NEAREST, expand=0): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre.
:param angle: In degrees counter clockwise. :param filter: An optional resampling filter. This can be one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set :py:attr:`PIL.Image.NEAREST`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. :returns: An :py:class:`~PIL.Image.Image` object. """
if expand: import math angle = -angle * math.pi / 180 matrix = [ math.cos(angle), math.sin(angle), 0.0, -math.sin(angle), math.cos(angle), 0.0 ] def transform(x, y, matrix=matrix): (a, b, c, d, e, f) = matrix return a*x + b*y + c, d*x + e*y + f
# calculate output size w, h = self.size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y) xx.append(x) yy.append(y) w = int(math.ceil(max(xx)) - math.floor(min(xx))) h = int(math.ceil(max(yy)) - math.floor(min(yy)))
# adjust center x, y = transform(w / 2.0, h / 2.0) matrix[2] = self.size[0] / 2.0 - x matrix[5] = self.size[1] / 2.0 - y
return self.transform((w, h), AFFINE, matrix, resample)
if resample not in (NEAREST, BILINEAR, BICUBIC): raise ValueError("unknown resampling filter")
self.load()
if self.mode in ("1", "P"): resample = NEAREST
return self._new(self.im.rotate(angle, resample))
def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible.
Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described later in this handbook.
You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the **seek**, **tell**, and **write** methods, and be opened in binary mode.
:param file: File name or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param options: Extra parameters to the image writer. :returns: None :exception KeyError: If the output format could not be determined from the file name. Use the format option to solve this. :exception IOError: If the file could not be written. The file may have been created, and may contain partial data. """
if isPath(fp): filename = fp else: if hasattr(fp, "name") and isPath(fp.name): filename = fp.name else: filename = ""
# may mutate self! self.load()
self.encoderinfo = params self.encoderconfig = ()
preinit()
ext = os.path.splitext(filename)[1].lower()
if not format: try: format = EXTENSION[ext] except KeyError: init() try: format = EXTENSION[ext] except KeyError: raise KeyError(ext) # unknown extension
try: save_handler = SAVE[format.upper()] except KeyError: init() save_handler = SAVE[format.upper()] # unknown format
if isPath(fp): fp = builtins.open(fp, "wb") close = 1 else: close = 0
try: save_handler(self, fp, filename) finally: # do what we can to clean up if close: fp.close()
def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an **EOFError** exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
See :py:meth:`~PIL.Image.Image.tell`.
:param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """
# overridden by file handlers if frame != 0: raise EOFError
def show(self, title=None, command=None): """ Displays this image. This method is mainly intended for debugging purposes.
On Unix platforms, this method saves the image to a temporary PPM file, and calls the **xv** utility.
On Windows, it saves the image to a temporary BMP file, and uses the standard BMP display utility to show it (usually Paint).
:param title: Optional title to use for the image window, where possible. :param command: command used to show the image """
_show(self, title=title, command=command)
def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue).
:returns: A tuple containing bands. """
self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = [] for i in range(self.im.bands): ims.append(self._new(self.im.getband(i))) return tuple(ims)
def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
:returns: Frame number, starting with 0. """ return 0
def thumbnail(self, size, resample=NEAREST): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image.
Note that the bilinear and bicubic filters in the current version of PIL are not well-suited for thumbnail generation. You should use :py:attr:`PIL.Image.ANTIALIAS` unless speed is much more important than quality.
Also note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image.
:param size: Requested size. :param resample: Optional resampling filter. This can be one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.ANTIALIAS` (best quality). If omitted, it defaults to :py:attr:`PIL.Image.NEAREST` (this will be changed to ANTIALIAS in a future version). :returns: None """
# FIXME: the default resampling filter will be changed # to ANTIALIAS in future versions
# preserve aspect ratio x, y = self.size if x > size[0]: y = int(max(y * size[0] / x, 1)); x = int(size[0]) if y > size[1]: x = int(max(x * size[1] / y, 1)); y = int(size[1]) size = x, y
if size == self.size: return
self.draft(None, size)
self.load()
try: im = self.resize(size, resample) except ValueError: if resample != ANTIALIAS: raise im = self.resize(size, NEAREST) # fallback
self.im = im.im self.mode = im.mode self.size = size
self.readonly = 0
# FIXME: the different tranform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform(self, size, method, data=None, resample=NEAREST, fill=1): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform.
:param size: The output size. :param method: The transformation method. This is one of :py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:attr:`PIL.Image.AFFINE` (affine transform), :py:attr:`PIL.Image.PERSPECTIVE` (perspective transform), :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals in one operation). :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`. :returns: An :py:class:`~PIL.Image.Image` object. """
if self.mode == 'RGBA': return self.convert('RGBa').transform(size, method, data, resample, fill).convert('RGBA')
if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: raise ValueError("missing method data")
im = new(self.mode, size, None) if method == MESH: # list of quads for box, quad in data: im.__transformer(box, self, QUAD, quad, resample, fill) else: im.__transformer((0, 0)+size, self, method, data, resample, fill)
return im
def __transformer(self, box, image, method, data, resample=NEAREST, fill=1):
# FIXME: this should be turned into a lazy operation (?)
w = box[2]-box[0] h = box[3]-box[1]
if method == AFFINE: # change argument order to match implementation data = (data[2], data[0], data[1], data[5], data[3], data[4]) elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = float(x1 - x0) / w ys = float(y1 - y0) / h method = AFFINE data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys) elif method == PERSPECTIVE: # change argument order to match implementation data = (data[2], data[0], data[1], data[5], data[3], data[4], data[6], data[7]) elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8] x0, y0 = nw; As = 1.0 / w; At = 1.0 / h data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At, (se[0]-sw[0]-ne[0]+x0)*As*At, y0, (ne[1]-y0)*As, (sw[1]-y0)*At, (se[1]-sw[1]-ne[1]+y0)*As*At) else: raise ValueError("unknown transformation method")
if resample not in (NEAREST, BILINEAR, BICUBIC): raise ValueError("unknown resampling filter")
image.load()
self.load()
if image.mode in ("1", "P"): resample = NEAREST
self.im.transform2(box, image.im, method, data, resample, fill)
def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps)
:param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`, :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`, :py:attr:`PIL.Image.ROTATE_180`, or :py:attr:`PIL.Image.ROTATE_270`. :returns: Returns a flipped or rotated copy of this image. """
self.load() im = self.im.transpose(method) return self._new(im)```
## `PIL/Image.py` — `function:Image._dump` (lines 497-507)
```python def _dump(self, file=None, format=None): import tempfile if not file: file = tempfile.mktemp() self.load() if not format or format == "PPM": self.im.save_ppm(file) else: file = file + "." + format self.save(file, format) return file```
## `PIL/IptcImagePlugin.py` — `class:IptcImageFile` (lines 53-204)
```pythonclass IptcImageFile(ImageFile.ImageFile):
format = "IPTC" format_description = "IPTC/NAA"
def getint(self, key): return i(self.info[key])
def field(self): # # get a IPTC field header s = self.fp.read(5) if not len(s): return None, 0
tag = i8(s[1]), i8(s[2])
# syntax if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9: raise SyntaxError("invalid IPTC/NAA file")
# field size size = i8(s[3]) if size > 132: raise IOError("illegal field length in IPTC/NAA file") elif size == 128: size = 0 elif size > 128: size = i(self.fp.read(size-128)) else: size = i16(s[3:])
return tag, size
def _is_raw(self, offset, size): # # check if the file can be mapped
# DISABLED: the following only slows things down... return 0
self.fp.seek(offset) t, sz = self.field() if sz != size[0]: return 0 y = 1 while True: self.fp.seek(sz, 1) t, s = self.field() if t != (8, 10): break if s != sz: return 0 y = y + 1 return y == size[1]
def _open(self):
# load descriptive fields while True: offset = self.fp.tell() tag, size = self.field() if not tag or tag == (8,10): break if size: tagdata = self.fp.read(size) else: tagdata = None if tag in list(self.info.keys()): if isinstance(self.info[tag], list): self.info[tag].append(tagdata) else: self.info[tag] = [self.info[tag], tagdata] else: self.info[tag] = tagdata
# print tag, self.info[tag]
# mode layers = i8(self.info[(3,60)][0]) component = i8(self.info[(3,60)][1]) if (3,65) in self.info: id = i8(self.info[(3,65)][0])-1 else: id = 0 if layers == 1 and not component: self.mode = "L" elif layers == 3 and component: self.mode = "RGB"[id] elif layers == 4 and component: self.mode = "CMYK"[id]
# size self.size = self.getint((3,20)), self.getint((3,30))
# compression try: compression = COMPRESSION[self.getint((3,120))] except KeyError: raise IOError("Unknown IPTC image compression")
# tile if tag == (8,10): if compression == "raw" and self._is_raw(offset, self.size): self.tile = [(compression, (offset, size + 5, -1), (0, 0, self.size[0], self.size[1]))] else: self.tile = [("iptc", (compression, offset), (0, 0, self.size[0], self.size[1]))]
def load(self):
if len(self.tile) != 1 or self.tile[0][0] != "iptc": return ImageFile.ImageFile.load(self)
type, tile, box = self.tile[0]
encoding, offset = tile
self.fp.seek(offset)
# Copy image data to temporary file outfile = tempfile.mktemp() o = open(outfile, "wb") if encoding == "raw": # To simplify access to the extracted file, # prepend a PPM header o.write("P5\n%d %d\n255\n" % self.size) while True: type, size = self.field() if type != (8, 10): break while size > 0: s = self.fp.read(min(size, 8192)) if not s: break o.write(s) size = size - len(s) o.close()
try: try: # fast self.im = Image.core.open_ppm(outfile) except: # slightly slower im = Image.open(outfile) im.load() self.im = im.im finally: try: os.unlink(outfile) except: pass```
## `PIL/IptcImagePlugin.py` — `function:IptcImageFile.load` (lines 163-204)
```python def load(self):
if len(self.tile) != 1 or self.tile[0][0] != "iptc": return ImageFile.ImageFile.load(self)
type, tile, box = self.tile[0]
encoding, offset = tile
self.fp.seek(offset)
# Copy image data to temporary file outfile = tempfile.mktemp() o = open(outfile, "wb") if encoding == "raw": # To simplify access to the extracted file, # prepend a PPM header o.write("P5\n%d %d\n255\n" % self.size) while True: type, size = self.field() if type != (8, 10): break while size > 0: s = self.fp.read(min(size, 8192)) if not s: break o.write(s) size = size - len(s) o.close()
try: try: # fast self.im = Image.core.open_ppm(outfile) except: # slightly slower im = Image.open(outfile) im.load() self.im = im.im finally: try: os.unlink(outfile) except: pass```
## `PIL/JpegImagePlugin.py` — `class:JpegImageFile` (lines 267-362)
```pythonclass JpegImageFile(ImageFile.ImageFile):
format = "JPEG" format_description = "JPEG (ISO 10918)"
def _open(self):
s = self.fp.read(1)
if i8(s[0]) != 255: raise SyntaxError("not a JPEG file")
# Create attributes self.bits = self.layers = 0
# JPEG specifics (internal) self.layer = [] self.huffman_dc = {} self.huffman_ac = {} self.quantization = {} self.app = {} # compatibility self.applist = [] self.icclist = []
while True:
s = s + self.fp.read(1)
i = i16(s)
if i in MARKER: name, description, handler = MARKER[i] # print hex(i), name, description if handler is not None: handler(self, i) if i == 0xFFDA: # start of scan rawmode = self.mode if self.mode == "CMYK": rawmode = "CMYK;I" # assume adobe conventions self.tile = [("jpeg", (0,0) + self.size, 0, (rawmode, ""))] # self.__offset = self.fp.tell() break s = self.fp.read(1) elif i == 0 or i == 65535: # padded marker or junk; move on s = "\xff" else: raise SyntaxError("no marker found")
def draft(self, mode, size):
if len(self.tile) != 1: return
d, e, o, a = self.tile[0] scale = 0
if a[0] == "RGB" and mode in ["L", "YCbCr"]: self.mode = mode a = mode, ""
if size: scale = max(self.size[0] // size[0], self.size[1] // size[1]) for s in [8, 4, 2, 1]: if scale >= s: break e = e[0], e[1], (e[2]-e[0]+s-1)//s+e[0], (e[3]-e[1]+s-1)//s+e[1] self.size = ((self.size[0]+s-1)//s, (self.size[1]+s-1)//s) scale = s
self.tile = [(d, e, o, a)] self.decoderconfig = (scale, 1)
return self
def load_djpeg(self):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os file = tempfile.mktemp() os.system("djpeg %s >%s" % (self.filename, file))
try: self.im = Image.core.open_ppm(file) finally: try: os.unlink(file) except: pass
self.mode = self.im.mode self.size = self.im.size
self.tile = []
def _getexif(self): return _getexif(self)```
## `PIL/JpegImagePlugin.py` — `function:JpegImageFile.load_djpeg` (lines 342-359)
```python def load_djpeg(self):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os file = tempfile.mktemp() os.system("djpeg %s >%s" % (self.filename, file))
try: self.im = Image.core.open_ppm(file) finally: try: os.unlink(file) except: pass
self.mode = self.im.mode self.size = self.im.size
self.tile = []```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859{ "schema_version": "synthesis-task-v1", "task": { "pair_id": "pyvul-4954e5890cce23c8b03d", "dataset_id": "PyVul", "dataset_item_id": "pyvul-4954e5890cce23c8b03d", "project_id": "pyvul__python-imaging__pillow", "language": "python", "backend": "codeql" }, "changed_python_files": [ "PIL/EpsImagePlugin.py", "PIL/Image.py", "PIL/IptcImagePlugin.py", "PIL/JpegImagePlugin.py" ], "patch_units": { "before": [ "function:Ghostscript", "class:Image", "function:Image._dump", "class:IptcImageFile", "function:IptcImageFile.load", "class:JpegImageFile", "function:JpegImageFile.load_djpeg" ], "after": [ "function:Ghostscript", "class:Image", "function:Image._dump", "class:IptcImageFile", "function:IptcImageFile.load", "class:JpegImageFile", "function:JpegImageFile.load_djpeg" ] }, "runtime_assets": { "before": { "database": "assets/08f641daaaf70221449c3b5c4a84e91796936219a20b91e4d35203686e7f7f18/database", "cache_key": "08f641daaaf70221449c3b5c4a84e91796936219a20b91e4d35203686e7f7f18", "codeql_version": "2.26.4" }, "after": { "database": "assets/62d7667e51007d1b94a468ba2fb246305f5f01a271bec41480f941757aef828b/database", "cache_key": "62d7667e51007d1b94a468ba2fb246305f5f01a271bec41480f941757aef828b", "codeql_version": "2.26.4" }, "refine": { "database": "assets/25ef67aaf353265855d3a53ef7158ae4fa13015799c0bf4d700c936c6487ed7d/database", "cache_key": "25ef67aaf353265855d3a53ef7158ae4fa13015799c0bf4d700c936c6487ed7d", "codeql_version": "2.26.4" } }, "benchmark_contract": { "agent_visible": true, "reference_query_location": "references/pyvul-4954e5890cce23c8b03d/query/ (do not mount into agent)", "evaluator_location": "evaluator/pyvul-4954e5890cce23c8b03d/ (do not mount into agent)" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Python CodeQL detector synthesis
You are cc operating in `/work`. Starting only from the supplied patch,before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQLdetector for the vulnerability fixed by the patch. This is one fresh session. You may iterate insidethis session, but no later framework repair or resume will occur.
## Inputs and owned outputs
- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.- Read `references/codeql/convergence_protocol.md` and `references/codeql/api_navigation.md` before experimenting. Read the remaining `references/codeql/` files for the selected mechanism.- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is uncertain. Do not guess predicate names or build a large family of inspection queries.- Complete the design contract in `state.json` and `scope_statement.md` before final validation.- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the fixed offline dependency in `query/qlpack.yml`.- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This task-unique metadata must never be used in a query predicate.- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
## Required reasoning contract
Before coding, record this mapping in `state.json`:
```textvulnerable operation / trigger / patch safety condition → CodeQL-observable evidence → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism → source, sink/report site, guard/barrier and query predicates```
Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches requirereal path/control-flow semantics; provenance-sensitive patches require value flow. Do not replaceeither with source-text matching or with the mere presence of patch-added syntax.
## Mandatory convergence contract
The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query isa failure; an early compilable semantic candidate can be improved. Follow the checkpoints in`references/codeql/convergence_protocol.md`:
1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` immediately. Do not wait until every CodeQL API detail is known.2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled definition with `scripts/search_codeql_api.sh` or simplify the mechanism.3. Obtain a compiling minimal main query before broadening it. Compile the main query after every meaningful mechanism change.4. Move in order from compile → relevant before finding → after elimination → final contract. Do not continue API exploration after the intended before/after differential is established.5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all exploration, preserve the best compiling query, finish the contract files, and exit.
## Semantic and generalization rules
- Report at the vulnerable call, operator, access, or sink.- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary matching condition. Stable library/framework APIs or public project APIs are allowed only when `scope_statement.md` explains why they define the intended vulnerability family.- The safety condition introduced by the patch must be represented by the query.- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it changed in the patch.
## Final validation protocol
1. Compile the final query.2. Run it on before and inspect `raw/before.sarif` for the intended report location.3. Run the identical query on after and inspect `raw/after.sarif`.4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, and absence of patch-local hardcoding.5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
Do not modify the runtime databases, references, patch, context, or validation scripts except fornormal CodeQL-generated database caches produced by the provided run scripts.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184diff --git a/nautobot_device_onboarding/jobs.py b/nautobot_device_onboarding/jobs.pyindex cca9e9c..72b843d 100644--- a/nautobot_device_onboarding/jobs.py+++ b/nautobot_device_onboarding/jobs.py@@ -13,12 +13,7 @@ PLUGIN_SETTINGS = settings.PLUGINS_CONFIG["nautobot_device_onboarding"] class OnboardingTask(Job):- class Meta:- """Meta object boilerplate for onboarding."""-- name = "Perform Device Onboarding"- description = "Login to a device and populate Nautobot device object."- has_sensitive_variables = False+ """Nautobot Job for onboarding a new device.""" location = ObjectVar(model=Location, query_params={"": ""}, required=False, description="") ip_address = IPAddressVar(description="", label="")@@ -29,18 +24,32 @@ class OnboardingTask(Job): role = ObjectVar(model=Role, query_params={"": ""}, required=False, description="") device_type = ObjectVar(model=DeviceType, required=False, description="") + class Meta: # pylint: disable=too-few-public-methods+ """Meta object boilerplate for onboarding."""++ name = "Perform Device Onboarding"+ description = "Login to a device and populate Nautobot device object."+ has_sensitive_variables = False++ def __init__(self, *args, **kwargs):+ """Overload init to instantiate class attributes per W0201."""+ self.username = None+ self.password = None+ self.secret = None+ super().__init__(*args, **kwargs)+ def run(self, *args, **data): """Process a single Onboarding Task instance.""" self.logger.info("START: onboard device")- credentials = self._parse_credentials(data["credentials"])+ self._parse_credentials(data["credentials"]) platform = data["platform"] netdev = NetdevKeeper( hostname=data["ip_address"], port=data["port"], timeout=data["timeout"],- username=credentials["username"],- password=credentials["password"],- secret=credentials["secret"],+ username=self.username,+ password=self.password,+ secret=self.secret, napalm_driver=platform.napalm_driver if platform and platform.napalm_driver else None, optional_args=platform.napalm_args if platform and platform.napalm_args else settings.NAPALM_ARGS, )@@ -72,18 +81,16 @@ class OnboardingTask(Job): def _parse_credentials(self, credentials): """Parse and return dictionary of credentials."""- if credentials:- self.username = (credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME),)- self.password = (credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD),)- self.secret = (None,)+ self.username = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME)+ self.password = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD) secret = credentials.secrets.filter(secret_type=SecretsGroupSecretTypeChoices.TYPE_SECRET) if secret.exists(): self.secret = secret.first() else:- self.username = (settings.NAPALM_USERNAME,)- self.password = (settings.NAPALM_PASSWORD,)- self.secret = (settings.NAPALM_ARGS.get("secret", None),)+ self.username = settings.NAPALM_USERNAME+ self.password = settings.NAPALM_PASSWORD+ self.secret = settings.NAPALM_ARGS.get("secret", None) register_jobs(OnboardingTask)diff --git a/nautobot_device_onboarding/tests/test_netdev_keeper.py b/nautobot_device_onboarding/tests/test_netdev_keeper.pydeleted file mode 100644index 91fbde6..0000000--- a/nautobot_device_onboarding/tests/test_netdev_keeper.py+++ /dev/null@@ -1,72 +0,0 @@-"""Unit tests for nautobot_device_onboarding.netdev_keeper module and its classes."""--from socket import gaierror-from unittest import mock--from django.contrib.contenttypes.models import ContentType-from django.test import TestCase--from nautobot.dcim.models import Device, Location, LocationType, Platform-from nautobot.extras.models import Role, Status--from nautobot_device_onboarding.exceptions import OnboardException-from nautobot_device_onboarding.helpers import onboarding_task_fqdn_to_ip-# from nautobot_device_onboarding.models import OnboardingTask---class NetdevKeeperTestCase(TestCase):- """Test the NetdevKeeper Class."""-- def setUp(self):- """Create a superuser and token for API calls."""- role_content_type = ContentType.objects.get_for_model(Device)- status = Status.objects.get(name="Active")- location_type = LocationType.objects.create(name="site")- self.site1 = Location.objects.create(name="USWEST", location_type=location_type, status=status)- self.device_role1 = Role.objects.create(name="Firewall")- self.device_role1.content_types.set([role_content_type])-- self.platform1 = Platform.objects.create(name="JunOS", napalm_driver="junos")- # self.platform2 = Platform.objects.create(name="Cisco NX-OS", slug="cisco-nx-os")-- # self.onboarding_task4 = OnboardingTask.objects.create(- # ip_address="ntc123.local", location=self.site1, role=self.device_role1, platform=self.platform1- # )-- # self.onboarding_task5 = OnboardingTask.objects.create(- # ip_address="bad.local", location=self.site1, role=self.device_role1, platform=self.platform1- # )-- # self.onboarding_task7 = OnboardingTask.objects.create(- # ip_address="192.0.2.1/32", location=self.site1, role=self.device_role1, platform=self.platform1- # )-- # @mock.patch("nautobot_device_onboarding.helpers.socket.gethostbyname")- # def test_check_ip(self, mock_get_hostbyname):- # """Check DNS to IP address."""- # # Look up response value- # mock_get_hostbyname.return_value = "192.0.2.1"-- # # FQDN -> IP- # onboarding_task_fqdn_to_ip(onboarding_task=self.onboarding_task4)-- # # Run the check to change the IP address- # self.assertEqual(self.onboarding_task4.ip_address, "192.0.2.1")-- # @mock.patch("nautobot_device_onboarding.helpers.socket.gethostbyname")- # def test_failed_check_ip(self, mock_get_hostbyname):- # """Check DNS to IP address failing."""- # # Look up a failed response- # mock_get_hostbyname.side_effect = gaierror(8)-- # # Check for bad.local raising an exception- # with self.assertRaises(OnboardException) as exc_info:- # onboarding_task_fqdn_to_ip(onboarding_task=self.onboarding_task5)- # self.assertEqual(exc_info.exception.message, "ERROR failed to complete DNS lookup: bad.local")- # self.assertEqual(exc_info.exception.reason, "fail-dns")-- # # Check for exception with prefix address entered- # with self.assertRaises(OnboardException) as exc_info:- # onboarding_task_fqdn_to_ip(onboarding_task=self.onboarding_task7)- # self.assertEqual(exc_info.exception.reason, "fail-prefix")- # self.assertEqual(exc_info.exception.message, "ERROR appears a prefix was entered: 192.0.2.1/32")diff --git a/nautobot_device_onboarding/tests/test_onboarding.py b/nautobot_device_onboarding/tests/test_onboarding.pyindex d7a938c..f427bba 100644--- a/nautobot_device_onboarding/tests/test_onboarding.py+++ b/nautobot_device_onboarding/tests/test_onboarding.py@@ -1,16 +1,15 @@ """Unit tests for nautobot_device_onboarding.netdev_keeper module and its classes."""-from unittest import mock+# from unittest import mock from django.conf import settings-from django.test import TestCase-from django.contrib.contenttypes.models import ContentType +# from django.test import TestCase+# from django.contrib.contenttypes.models import ContentType -from nautobot.dcim.models import Device, Location, LocationType, Platform-from nautobot.extras.models import Status -# from nautobot_device_onboarding.models import OnboardingTask-# from nautobot_device_onboarding.onboard import OnboardingManager+# from nautobot.dcim.models import Device, Location, LocationType, Platform+# from nautobot.extras.models import Status+ PLUGIN_SETTINGS = settings.PLUGINS_CONFIG["nautobot_device_onboarding"] 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169# Patch-overlapping Python context after the fix
## `nautobot_device_onboarding/jobs.py` — `class:OnboardingTask` (lines 15-93)
```pythonclass OnboardingTask(Job): """Nautobot Job for onboarding a new device."""
location = ObjectVar(model=Location, query_params={"": ""}, required=False, description="") ip_address = IPAddressVar(description="", label="") port = IntegerVar(description="") timeout = IntegerVar(description="") credentials = ObjectVar(model=SecretsGroup, query_params={"": ""}, required=False, description="") platform = ObjectVar(model=Platform, required=False, description="") role = ObjectVar(model=Role, query_params={"": ""}, required=False, description="") device_type = ObjectVar(model=DeviceType, required=False, description="")
class Meta: # pylint: disable=too-few-public-methods """Meta object boilerplate for onboarding."""
name = "Perform Device Onboarding" description = "Login to a device and populate Nautobot device object." has_sensitive_variables = False
def __init__(self, *args, **kwargs): """Overload init to instantiate class attributes per W0201.""" self.username = None self.password = None self.secret = None super().__init__(*args, **kwargs)
def run(self, *args, **data): """Process a single Onboarding Task instance.""" self.logger.info("START: onboard device") self._parse_credentials(data["credentials"]) platform = data["platform"] netdev = NetdevKeeper( hostname=data["ip_address"], port=data["port"], timeout=data["timeout"], username=self.username, password=self.password, secret=self.secret, napalm_driver=platform.napalm_driver if platform and platform.napalm_driver else None, optional_args=platform.napalm_args if platform and platform.napalm_args else settings.NAPALM_ARGS, ) netdev.get_onboarding_facts() netdev_dict = netdev.get_netdev_dict()
onboarding_kwargs = { # Kwargs extracted from OnboardingTask: "netdev_mgmt_ip_address": data["ip_address"], "netdev_nb_location_name": data["location"].name, "netdev_nb_device_type_name": data["device_type"], "netdev_nb_role_name": data["role"].name if data["role"] else PLUGIN_SETTINGS["default_device_role"], "netdev_nb_role_color": PLUGIN_SETTINGS["default_device_role_color"], "netdev_nb_platform_name": data["platform"].name if data["platform"] else None, # Kwargs discovered on the Onboarded Device: "netdev_hostname": netdev_dict["netdev_hostname"], "netdev_vendor": netdev_dict["netdev_vendor"], "netdev_model": netdev_dict["netdev_model"], "netdev_serial_number": netdev_dict["netdev_serial_number"], "netdev_mgmt_ifname": netdev_dict["netdev_mgmt_ifname"], "netdev_mgmt_pflen": netdev_dict["netdev_mgmt_pflen"], "netdev_netmiko_device_type": netdev_dict["netdev_netmiko_device_type"], "onboarding_class": netdev_dict["onboarding_class"], "driver_addon_result": netdev_dict["driver_addon_result"], } onboarding_cls = netdev_dict["onboarding_class"]() onboarding_cls.credentials = {"username": self.username, "password": self.password, "secret": self.secret} onboarding_cls.run(onboarding_kwargs=onboarding_kwargs)
def _parse_credentials(self, credentials): """Parse and return dictionary of credentials.""" if credentials: self.username = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME) self.password = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD) secret = credentials.secrets.filter(secret_type=SecretsGroupSecretTypeChoices.TYPE_SECRET) if secret.exists(): self.secret = secret.first() else: self.username = settings.NAPALM_USERNAME self.password = settings.NAPALM_PASSWORD self.secret = settings.NAPALM_ARGS.get("secret", None)```
## `nautobot_device_onboarding/jobs.py` — `class:OnboardingTask.Meta` (lines 27-32)
```python class Meta: # pylint: disable=too-few-public-methods """Meta object boilerplate for onboarding."""
name = "Perform Device Onboarding" description = "Login to a device and populate Nautobot device object." has_sensitive_variables = False```
## `nautobot_device_onboarding/jobs.py` — `function:OnboardingTask.__init__` (lines 34-39)
```python def __init__(self, *args, **kwargs): """Overload init to instantiate class attributes per W0201.""" self.username = None self.password = None self.secret = None super().__init__(*args, **kwargs)```
## `nautobot_device_onboarding/jobs.py` — `function:OnboardingTask.run` (lines 41-80)
```python def run(self, *args, **data): """Process a single Onboarding Task instance.""" self.logger.info("START: onboard device") self._parse_credentials(data["credentials"]) platform = data["platform"] netdev = NetdevKeeper( hostname=data["ip_address"], port=data["port"], timeout=data["timeout"], username=self.username, password=self.password, secret=self.secret, napalm_driver=platform.napalm_driver if platform and platform.napalm_driver else None, optional_args=platform.napalm_args if platform and platform.napalm_args else settings.NAPALM_ARGS, ) netdev.get_onboarding_facts() netdev_dict = netdev.get_netdev_dict()
onboarding_kwargs = { # Kwargs extracted from OnboardingTask: "netdev_mgmt_ip_address": data["ip_address"], "netdev_nb_location_name": data["location"].name, "netdev_nb_device_type_name": data["device_type"], "netdev_nb_role_name": data["role"].name if data["role"] else PLUGIN_SETTINGS["default_device_role"], "netdev_nb_role_color": PLUGIN_SETTINGS["default_device_role_color"], "netdev_nb_platform_name": data["platform"].name if data["platform"] else None, # Kwargs discovered on the Onboarded Device: "netdev_hostname": netdev_dict["netdev_hostname"], "netdev_vendor": netdev_dict["netdev_vendor"], "netdev_model": netdev_dict["netdev_model"], "netdev_serial_number": netdev_dict["netdev_serial_number"], "netdev_mgmt_ifname": netdev_dict["netdev_mgmt_ifname"], "netdev_mgmt_pflen": netdev_dict["netdev_mgmt_pflen"], "netdev_netmiko_device_type": netdev_dict["netdev_netmiko_device_type"], "onboarding_class": netdev_dict["onboarding_class"], "driver_addon_result": netdev_dict["driver_addon_result"], } onboarding_cls = netdev_dict["onboarding_class"]() onboarding_cls.credentials = {"username": self.username, "password": self.password, "secret": self.secret} onboarding_cls.run(onboarding_kwargs=onboarding_kwargs)```
## `nautobot_device_onboarding/jobs.py` — `function:OnboardingTask._parse_credentials` (lines 82-93)
```python def _parse_credentials(self, credentials): """Parse and return dictionary of credentials.""" if credentials: self.username = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME) self.password = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD) secret = credentials.secrets.filter(secret_type=SecretsGroupSecretTypeChoices.TYPE_SECRET) if secret.exists(): self.secret = secret.first() else: self.username = settings.NAPALM_USERNAME self.password = settings.NAPALM_PASSWORD self.secret = settings.NAPALM_ARGS.get("secret", None)```tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/pre_context.mdAdded+24
tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task.jsonAdded+44
tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task_prompt.mdAdded+82
tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/patch.diffAdded+168
tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/post_context.mdAdded+1823
tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/pre_context.mdAdded+1755
tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task.jsonAdded+71
tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task_prompt.mdAdded+82
tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/patch.diffAdded+60
tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/post_context.mdAdded+64
tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/pre_context.mdAdded+59
tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task.jsonAdded+46
tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task_prompt.mdAdded+82
tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/patch.diffAdded+33
tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/post_context.mdAdded+17
tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/pre_context.mdAdded+23
tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task.jsonAdded+47
tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task_prompt.mdAdded+82
tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/patch.diffAdded+39
tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/post_context.mdAdded+244
tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/pre_context.mdAdded+244
tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task.jsonAdded+49
tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task_prompt.mdAdded+82
tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/patch.diffAdded+39
tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/post_context.mdAdded+40
tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/pre_context.mdAdded+40
tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task.jsonAdded+46
tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task_prompt.mdAdded+82
tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/patch.diffAdded+32
tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/post_context.mdAdded+130
tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/pre_context.mdAdded+128
tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task.jsonAdded+50
tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task_prompt.mdAdded+82
tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/patch.diffAdded+53
tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/post_context.mdAdded+314
tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/pre_context.mdAdded+280
tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task.jsonAdded+51
tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task_prompt.mdAdded+82
tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/patch.diffAdded+912
tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/post_context.mdAdded+140
tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/pre_context.mdAdded+145
tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task.jsonAdded+57
tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task_prompt.mdAdded+82
tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/patch.diffAdded+80
tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/post_context.mdAdded+1683
tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/pre_context.mdAdded+1668
tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task.jsonAdded+59
tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task_prompt.mdAdded+82
tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/patch.diffAdded+184
tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/post_context.mdAdded+169