code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _capture_onecmd(self, line): """ Run one Pdb command, but capture and return stdout. """ stdout = self.stdout lastcmd = self.lastcmd try: self.stdout = StringIO() super().onecmd(line) result = self.stdout.getvalue().rstrip() result = strip_ansi(result) return result finally: self.stdout = stdout self.lastcmd = lastcmd
Run one Pdb command, but capture and return stdout.
_capture_onecmd
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def _getval(self, arg): """ Sandbox for evaluating expressions from the LLM. """ try: if chatdbg_config.unsafe: return super()._getval(arg) else: return sandbox_eval(arg, self.curframe.f_globals, self.curframe_locals) except NameError as e: self.error(f"NameError: {e}") return None except ImportError as e: self.error(f"ImportError: {e}") return None
Sandbox for evaluating expressions from the LLM.
_getval
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def _getval_except(self, arg, frame=None): """ Sandbox in case an LLM ever tries to use the display features... """ try: if frame is None: return sandbox_eval(arg, self.curframe.f_globals, self.curframe_locals) else: return sandbox_eval(arg, frame.f_globals, frame.f_locals) except: exc_info = sys.exc_info()[:2] err = traceback.format_exception_only(*exc_info)[-1].strip() return "** raised %s **" % err
Sandbox in case an LLM ever tries to use the display features...
_getval_except
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_pydoc(self, arg): """pydoc name Print the pydoc string for a name. """ try: obj = self._getval(arg) if obj.__doc__ != None: pydoc.doc(obj, output=self.stdout) else: self.message(f"No documentation is available.") except NameError: # message already printed in _getval pass
pydoc name Print the pydoc string for a name.
do_pydoc
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_info(self, arg): """info name Print the pydoc string (and source code, if available) for a name. """ try: # try both given and unqualified form incase LLM biffs args_to_try = [arg, arg.split(".")[-1]] obj = None for x in args_to_try: try: obj = eval(x, self.curframe.f_globals, self.curframe_locals) break # found something so we're good except: # fail silently, try the next name pass if obj == None: # try again, using pydoc's logic... obj = pydoc.locate(arg) # didn't find anything if obj == None: self.message(f"No name `{arg}` is visible in the current frame.") elif isinstance(obj, types.BuiltinFunctionType) or isinstance( obj, types.BuiltinMethodType ): self.message(f"`{arg}` is a built-in.") elif self._is_user_file(inspect.getfile(obj)): self.message(f"Source from file {inspect.getfile(obj)}:") self.do_source(x) else: self.do_pydoc(x) self.message( f"You MUST assume that `{x}` is specified and implemented correctly." ) except OSError: raise except NameError: # alread handled pass except Exception: self.do_pydoc(x) self.message( f"You MUST assume that `{x}` is specified and implemented correctly." )
info name Print the pydoc string (and source code, if available) for a name.
do_info
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_slice(self, arg): """ slice Print the backwards slice for a variable used in the current cell but defined in an earlier cell. [interactive IPython / Jupyter only] """ if not self._supports_flow: self.message("*** `slice` is only supported in Jupyter notebooks") return try: from ipyflow import cells, singletons from ipyflow.models import statements index = self.curindex _x = None cell = None while index > 0: # print(index) pos, _ = singletons.flow().get_position(self.stack[index][0]) if pos >= 0: cell = cells().at_counter(pos) # print(cell.used_symbols) _x = next((x for x in cell.used_symbols if x.name == arg), None) if _x != None: break index -= 1 if _x != None: time_stamps = _x._get_timestamps_for_version(version=-1) time_stamps = [ts for ts in time_stamps if ts.cell_num > -1] result = str( statements().format_multi_slice( time_stamps, blacken=True, format_type=None ) ).rstrip() else: used_symbols = ( set() if cell == None else set([str(x) for x in cell.used_symbols]) ) defined = ( f", only for these symbols: {', '.join(used_symbols)}" if len(used_symbols) > 0 else "" ) result = f"*** No information avaiable for {arg}{defined}. Run the command `p {arg}` to see its value." except OSError: raise except Exception as e: # traceback.print_exc() result = f"*** Bad frame for call to slice ({type(e).__name__}: {e})" self.message(result)
slice Print the backwards slice for a variable used in the current cell but defined in an earlier cell. [interactive IPython / Jupyter only]
do_slice
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_test_prompt(self, arg): """test_prompt [For debugging] Prints the prompts to be sent to the assistant. """ self.message("Instructions:") self.message(self._initial_prompt_instructions()) self.message("-" * 80) self.message("Prompt:") self.message(self._build_prompt(arg, False))
test_prompt [For debugging] Prints the prompts to be sent to the assistant.
do_test_prompt
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def _hidden_predicate(self, frame): """ Given a frame return whether it it should be hidden or not by IPython. """ if self._predicates["readonly"]: fname = frame.f_code.co_filename # we need to check for file existence and interactively define # function would otherwise appear as RO. if os.path.isfile(fname) and not os.access(fname, os.W_OK): return True if self._predicates["tbhide"]: if frame in (self.curframe, getattr(self, "initial_frame", None)): return False fname = frame.f_code.co_filename # Hack because the locals for this frame are shared with # the first user frame, so we can't rely on the flag # in frame_locals to be set properly. if fname == "<string>": return True frame_locals = self._get_frame_locals(frame) if "__tracebackhide__" not in frame_locals: return False return frame_locals["__tracebackhide__"] return False
Given a frame return whether it it should be hidden or not by IPython.
_hidden_predicate
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_renew(self, arg): """renew End the current chat dialog and prepare to start a new one. """ if self._assistant != None: self._assistant.close() self._assistant = None self.was_chat_or_renew = True self.message(f"Ready to start a new dialog.")
renew End the current chat dialog and prepare to start a new one.
do_renew
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_config(self, arg): """ config Print out the ChatDBG config options. """ args = arg.split() message = chatdbg_config.parse_only_user_flags(args) self.message(message)
config Print out the ChatDBG config options.
do_config
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def info(self, value): """ { "name": "info", "description": "Call the `info` function to get the documentation and source code for any variable, function, package, class, method reference, field reference, or dotted reference visible in the current frame. Examples include: n, e.n where e is an expression, and t.n where t is a type. Unless it is from a common, widely-used library, you MUST call `info` exactly once on any symbol that is referenced in code leading up to the error.", "parameters": { "type": "object", "properties": { "value": { "type": "string", "description": "The reference to get the information for." } }, "required": [ "value" ] } } """ command = f"info {value}" result = self._capture_onecmd(command) return command, truncate_proportionally(result, top_proportion=1)
{ "name": "info", "description": "Call the `info` function to get the documentation and source code for any variable, function, package, class, method reference, field reference, or dotted reference visible in the current frame. Examples include: n, e.n where e is an expression, and t.n where t is a type. Unless it is from a common, widely-used library, you MUST call `info` exactly once on any symbol that is referenced in code leading up to the error.", "parameters": { "type": "object", "properties": { "value": { "type": "string", "description": "The reference to get the information for." } }, "required": [ "value" ] } }
info
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def debug(self, command): """ { "name": "debug", "description": "Call the `debug` function to run Pdb debugger commands on the stopped program. You may call the `pdb` function to run the following commands: `bt`, `up`, `down`, `p expression`, `list`. Call `debug` to print any variable value or expression that you believe may contribute to the error.", "parameters": { "type": "object", "properties": { "command": { "type": "string", "description": "The pdb command to run." } }, "required": [ "command" ] } } """ cmd = command if command != "list" else "ll" # old_curframe = self.curframe result = self._capture_onecmd(cmd) # help the LLM know where it is... # if old_curframe != self.curframe: # result += strip_color(self._stack_prompt()) return command, truncate_proportionally(result, maxlen=8000, top_proportion=0.9)
{ "name": "debug", "description": "Call the `debug` function to run Pdb debugger commands on the stopped program. You may call the `pdb` function to run the following commands: `bt`, `up`, `down`, `p expression`, `list`. Call `debug` to print any variable value or expression that you believe may contribute to the error.", "parameters": { "type": "object", "properties": { "command": { "type": "string", "description": "The pdb command to run." } }, "required": [ "command" ] } }
debug
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def slice(self, name): """ { "name": "slice", "description": "Call the `slice` function to get the code used to produce the value currently stored a variable. You MUST call `slice` exactly once on any variable used but not defined in the current frame's code.", "parameters": { "type": "object", "properties": { "name": { "type": "string", "description": "The variable to look at." } }, "required": [ "name" ] } } """ command = f"slice {name}" result = self._capture_onecmd(command) return command, truncate_proportionally(result, top_proportion=0.5)
{ "name": "slice", "description": "Call the `slice` function to get the code used to produce the value currently stored a variable. You MUST call `slice` exactly once on any variable used but not defined in the current frame's code.", "parameters": { "type": "object", "properties": { "name": { "type": "string", "description": "The variable to look at." } }, "required": [ "name" ] } }
slice
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def query(self, prompt: str, user_text): """ Send a query to the LLM. - prompt is the prompt to send. - user_text is what the user typed (which may or not be the same as prompt) Returns a dictionary containing: - "completed": True of the query ran to completion. - "cost": Cost of query, or 0 if not completed. Other fields only if completed is True - "time": completion time in seconds - "model": the model used. - "tokens": total tokens - "prompt_tokens": our prompts - "completion_tokens": the LLM completions part """ stats = {"completed": False, "cost": 0} start = time.time() self._broadcast("on_begin_query", prompt, user_text) try: stats = self._streamed_query(prompt, user_text) elapsed = time.time() - start stats["time"] = elapsed stats["model"] = self._model stats["completed"] = True stats["message"] = f"\n[Cost: ~${stats['cost']:.2f} USD]" except openai.OpenAIError as e: self._warn_about_exception(e, f"Unexpected OpenAI Error. Retry the query.") stats["message"] = f"[Exception: {e}]" except KeyboardInterrupt: # user action -- just ignore stats["message"] = "[Chat Interrupted]" except Exception as e: self._warn_about_exception(e, f"Unexpected Exception.") stats["message"] = f"[Exception: {e}]" self._broadcast("on_end_query", stats) return stats
Send a query to the LLM. - prompt is the prompt to send. - user_text is what the user typed (which may or not be the same as prompt) Returns a dictionary containing: - "completed": True of the query ran to completion. - "cost": Cost of query, or 0 if not completed. Other fields only if completed is True - "time": completion time in seconds - "model": the model used. - "tokens": total tokens - "prompt_tokens": our prompts - "completion_tokens": the LLM completions part
query
python
plasma-umass/ChatDBG
src/chatdbg/assistant/assistant.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/assistant/assistant.py
Apache-2.0
def _add_function(self, function): """ Add a new function to the list of function tools. The function should have the necessary json spec as its docstring """ schema = json.loads(function.__doc__) assert "name" in schema, "Bad JSON in docstring for function tool." self._functions[schema["name"]] = {"function": function, "schema": schema}
Add a new function to the list of function tools. The function should have the necessary json spec as its docstring
_add_function
python
plasma-umass/ChatDBG
src/chatdbg/assistant/assistant.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/assistant/assistant.py
Apache-2.0
def make_arrow(pad): """generate the leading arrow in front of traceback or debugger""" if pad >= 2: return "-" * (pad - 2) + "> " elif pad == 1: return ">" return ""
generate the leading arrow in front of traceback or debugger
make_arrow
python
plasma-umass/ChatDBG
src/chatdbg/custom_pdb/text.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/custom_pdb/text.py
Apache-2.0
def llm_get_code_surrounding(self, filename: str, line_number: int) -> str: """ { "name": "get_code_surrounding", "description": "The `get_code_surrounding` function returns the source code in the given file surrounding and including the provided line number.", "parameters": { "type": "object", "properties": { "filename": { "type": "string", "description": "The filename to read from." }, "line_number": { "type": "integer", "description": "The line number to focus on. Some context before and after that line will be provided." } }, "required": [ "filename", "line_number" ] } } """ return f"code {filename}:{line_number}", self._run_one_command( f"code {filename}:{line_number}" )
{ "name": "get_code_surrounding", "description": "The `get_code_surrounding` function returns the source code in the given file surrounding and including the provided line number.", "parameters": { "type": "object", "properties": { "filename": { "type": "string", "description": "The filename to read from." }, "line_number": { "type": "integer", "description": "The line number to focus on. Some context before and after that line will be provided." } }, "required": [ "filename", "line_number" ] } }
llm_get_code_surrounding
python
plasma-umass/ChatDBG
src/chatdbg/native_util/dbg_dialog.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/native_util/dbg_dialog.py
Apache-2.0
def llm_find_definition(self, filename: str, line_number: int, symbol: str) -> str: """ { "name": "find_definition", "description": "The `find_definition` function returns the source code for the definition for the given symbol at the given source line number. Call `find_definition` on every symbol that could be linked to the issue.", "parameters": { "type": "object", "properties": { "filename": { "type": "string", "description": "The filename the symbol is from." }, "line_number": { "type": "integer", "description": "The line number where the symbol is present." }, "symbol": { "type": "string", "description": "The symbol to lookup." } }, "required": [ "filename", "line_number", "symbol" ] } } """ return f"definition {filename}:{line_number} {symbol}", self._run_one_command( f"definition {filename}:{line_number} {symbol}" )
{ "name": "find_definition", "description": "The `find_definition` function returns the source code for the definition for the given symbol at the given source line number. Call `find_definition` on every symbol that could be linked to the issue.", "parameters": { "type": "object", "properties": { "filename": { "type": "string", "description": "The filename the symbol is from." }, "line_number": { "type": "integer", "description": "The line number where the symbol is present." }, "symbol": { "type": "string", "description": "The symbol to lookup." } }, "required": [ "filename", "line_number", "symbol" ] } }
llm_find_definition
python
plasma-umass/ChatDBG
src/chatdbg/native_util/dbg_dialog.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/native_util/dbg_dialog.py
Apache-2.0
def _sandboxed_call(func, *args, **kwargs): """ Check if the function is in the module whitelist before calling it. """ allowed_modules = chatdbg_config.get_module_whitelist() # Get the module name of the function. # If the module name is None, use the __name__ attribute of the globals dictionary. module_name = func.__module__ if module_name is None: module_name = func.__globals__.get("__name__", None) # Check if the function is in the module whitelist. If it is, call the function. # Otherwise, raise an ImportError. if any( re.fullmatch(allowed, f"{module_name}.{func.__name__}") for allowed in allowed_modules ): return func(*args, **kwargs) else: raise ImportError( f"Calling function {func.__name__} from module {module_name} is not allowed." )
Check if the function is in the module whitelist before calling it.
_sandboxed_call
python
plasma-umass/ChatDBG
src/chatdbg/pdb_util/sandbox.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/pdb_util/sandbox.py
Apache-2.0
def sandbox_eval(expression, globals, locals): """ Wrap all function calls in the expression with a call to _sandboxed_call. This function will raise an ImportError if the function is not in the module whitelist. """ tree = ast.parse(expression, mode="eval") tree = SandboxTransformer().visit(tree) ast.fix_missing_locations(tree) code = compile(tree, filename="<ast>", mode="eval") globals = globals.copy() globals["_sandboxed_call"] = _sandboxed_call return eval(code, globals, locals)
Wrap all function calls in the expression with a call to _sandboxed_call. This function will raise an ImportError if the function is not in the module whitelist.
sandbox_eval
python
plasma-umass/ChatDBG
src/chatdbg/pdb_util/sandbox.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/pdb_util/sandbox.py
Apache-2.0
def to_json(self) -> dict[str, Union[int, str, bool]]: """Serialize the object to a JSON string.""" return { "model": self.model, "log": self.log, "tag": self.tag, "rc_lines": self.rc_lines, "context": self.context, "show_locals": self.show_locals, "show_libs": self.show_libs, "show_slices": self.show_slices, "take_the_wheel": self.take_the_wheel, "format": self.format, "instructions": self.instructions, "module_whitelist": self.module_whitelist, }
Serialize the object to a JSON string.
to_json
python
plasma-umass/ChatDBG
src/chatdbg/util/config.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/util/config.py
Apache-2.0
def make_arrow(pad): """generate the leading arrow in front of traceback or debugger""" if pad >= 2: return "-" * (pad - 2) + "> " elif pad == 1: return ">" return ""
generate the leading arrow in front of traceback or debugger
make_arrow
python
plasma-umass/ChatDBG
src/chatdbg/util/text.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/util/text.py
Apache-2.0
def word_wrap_except_code_blocks(text: str, width: int = 80) -> str: """ Wraps text except for code blocks for nice terminal formatting. Splits the text into paragraphs and wraps each paragraph, except for paragraphs that are inside of code blocks denoted by ` ``` `. Returns the updated text. Args: text (str): The text to wrap. width (int): The width of the lines to wrap at, passed to `textwrap.fill`. Returns: The wrapped text. """ blocks = text.split("```") for i in range(0, len(blocks), 2): paras = blocks[i].split("\n") wrapped = [textwrap.fill(para, width=width) for para in paras] blocks[i] = "\n".join(wrapped) return "```".join(blocks)
Wraps text except for code blocks for nice terminal formatting. Splits the text into paragraphs and wraps each paragraph, except for paragraphs that are inside of code blocks denoted by ` ``` `. Returns the updated text. Args: text (str): The text to wrap. width (int): The width of the lines to wrap at, passed to `textwrap.fill`. Returns: The wrapped text.
word_wrap_except_code_blocks
python
plasma-umass/ChatDBG
src/chatdbg/util/wrap.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/util/wrap.py
Apache-2.0
async def generate_code_and_time( image_url: str, stack: Stack, model: Llm, original_input_filename: str, attempt_idx: int, ) -> Tuple[str, int, Optional[str], Optional[float], Optional[Exception]]: """ Generates code for an image, measures the time taken, and returns identifiers along with success/failure status. Returns a tuple: (original_input_filename, attempt_idx, content, duration, error_object) content and duration are None if an error occurs during generation. """ start_time = time.perf_counter() try: content = await generate_code_for_image( image_url=image_url, stack=stack, model=model ) end_time = time.perf_counter() duration = end_time - start_time return original_input_filename, attempt_idx, content, duration, None except Exception as e: print( f"Error during code generation for {original_input_filename} (attempt {attempt_idx}): {e}" ) return original_input_filename, attempt_idx, None, None, e
Generates code for an image, measures the time taken, and returns identifiers along with success/failure status. Returns a tuple: (original_input_filename, attempt_idx, content, duration, error_object) content and duration are None if an error occurs during generation.
generate_code_and_time
python
abi/screenshot-to-code
backend/evals/runner.py
https://github.com/abi/screenshot-to-code/blob/master/backend/evals/runner.py
MIT
def convert_openai_messages_to_claude( messages: List[ChatCompletionMessageParam], ) -> Tuple[str, List[Dict[str, Any]]]: """ Convert OpenAI format messages to Claude format, handling image content properly. Args: messages: List of messages in OpenAI format Returns: Tuple of (system_prompt, claude_messages) """ # Deep copy messages to avoid modifying the original list cloned_messages = copy.deepcopy(messages) system_prompt = cast(str, cloned_messages[0].get("content")) claude_messages = [dict(message) for message in cloned_messages[1:]] for message in claude_messages: if not isinstance(message["content"], list): continue for content in message["content"]: # type: ignore if content["type"] == "image_url": content["type"] = "image" # Extract base64 data and media type from data URL # Example base64 data URL: data:image/png;base64,iVBOR... image_data_url = cast(str, content["image_url"]["url"]) # Process image and split media type and data # so it works with Claude (under 5mb in base64 encoding) (media_type, base64_data) = process_image(image_data_url) # Remove OpenAI parameter del content["image_url"] content["source"] = { "type": "base64", "media_type": media_type, "data": base64_data, } return system_prompt, claude_messages
Convert OpenAI format messages to Claude format, handling image content properly. Args: messages: List of messages in OpenAI format Returns: Tuple of (system_prompt, claude_messages)
convert_openai_messages_to_claude
python
abi/screenshot-to-code
backend/models/claude.py
https://github.com/abi/screenshot-to-code/blob/master/backend/models/claude.py
MIT
def extract_image_from_messages( messages: List[ChatCompletionMessageParam], ) -> Dict[str, str]: """ Extracts image data from OpenAI-style chat completion messages. Args: messages: List of ChatCompletionMessageParam containing message content Returns: Dictionary with mime_type and data keys for the first image found """ for content_part in messages[-1]["content"]: # type: ignore if content_part["type"] == "image_url": # type: ignore image_url = content_part["image_url"]["url"] # type: ignore if image_url.startswith("data:"): # type: ignore # Extract base64 data and mime type for data URLs mime_type = image_url.split(";")[0].split(":")[1] # type: ignore base64_data = image_url.split(",")[1] # type: ignore return {"mime_type": mime_type, "data": base64_data} else: # Handle regular URLs - would need to download and convert to base64 # For now, just return the URI return {"uri": image_url} # type: ignore # No image found raise ValueError("No image found in messages")
Extracts image data from OpenAI-style chat completion messages. Args: messages: List of ChatCompletionMessageParam containing message content Returns: Dictionary with mime_type and data keys for the first image found
extract_image_from_messages
python
abi/screenshot-to-code
backend/models/gemini.py
https://github.com/abi/screenshot-to-code/blob/master/backend/models/gemini.py
MIT
async def get_eval_input_files(): """Get a list of all input files available for evaluations""" input_dir = os.path.join(EVALS_DIR, "inputs") try: files: list[InputFile] = [] for filename in os.listdir(input_dir): if filename.endswith(".png"): file_path = os.path.join(input_dir, filename) files.append(InputFile(name=filename, path=file_path)) return sorted(files, key=lambda x: x.name) except Exception as e: raise HTTPException( status_code=500, detail=f"Error reading input files: {str(e)}" )
Get a list of all input files available for evaluations
get_eval_input_files
python
abi/screenshot-to-code
backend/routes/evals.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/evals.py
MIT
async def run_evals(request: RunEvalsRequest) -> List[str]: """Run evaluations on selected images in the inputs directory for multiple models""" all_output_files: List[str] = [] for model in request.models: output_files = await run_image_evals( model=model, stack=request.stack, input_files=request.files ) all_output_files.extend(output_files) return all_output_files
Run evaluations on selected images in the inputs directory for multiple models
run_evals
python
abi/screenshot-to-code
backend/routes/evals.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/evals.py
MIT
async def get_output_folders(): """Get a list of all output folders available for evaluations, sorted by recently modified""" output_dir = os.path.join(EVALS_DIR, "results") try: folders: list[OutputFolder] = [] for folder_name in os.listdir(output_dir): folder_path = os.path.join(output_dir, folder_name) if os.path.isdir(folder_path) and not folder_name.startswith("."): # Get modification time modified_time = os.path.getmtime(folder_path) folders.append( OutputFolder( name=folder_name, path=folder_path, modified_time=modified_time ) ) # Sort by modified time, most recent first return sorted(folders, key=lambda x: x.modified_time, reverse=True) except Exception as e: raise HTTPException( status_code=500, detail=f"Error reading output folders: {str(e)}" )
Get a list of all output folders available for evaluations, sorted by recently modified
get_output_folders
python
abi/screenshot-to-code
backend/routes/evals.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/evals.py
MIT
async def process( self, context: PipelineContext, next_func: Callable[[], Awaitable[None]] ) -> None: """Process the context and call the next middleware""" pass
Process the context and call the next middleware
process
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def execute(self, websocket: WebSocket) -> None: """Execute the pipeline with the given WebSocket""" context = PipelineContext(websocket=websocket) # Build the middleware chain async def start(ctx: PipelineContext): pass # End of pipeline chain = start for middleware in reversed(self.middlewares): chain = self._wrap_middleware(middleware, chain) await chain(context)
Execute the pipeline with the given WebSocket
execute
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
def _wrap_middleware( self, middleware: Middleware, next_func: Callable[[PipelineContext], Awaitable[None]], ) -> Callable[[PipelineContext], Awaitable[None]]: """Wrap a middleware with its next function""" async def wrapped(context: PipelineContext) -> None: await middleware.process(context, lambda: next_func(context)) return wrapped
Wrap a middleware with its next function
_wrap_middleware
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def send_message( self, type: MessageType, value: str, variantIndex: int, ) -> None: """Send a message to the client with debug logging""" # Print for debugging on the backend if type == "error": print(f"Error (variant {variantIndex}): {value}") elif type == "status": print(f"Status (variant {variantIndex}): {value}") elif type == "variantComplete": print(f"Variant {variantIndex} complete") elif type == "variantError": print(f"Variant {variantIndex} error: {value}") await self.websocket.send_json( {"type": type, "value": value, "variantIndex": variantIndex} )
Send a message to the client with debug logging
send_message
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def throw_error(self, message: str) -> None: """Send an error message and close the connection""" print(message) if not self.is_closed: await self.websocket.send_json({"type": "error", "value": message}) await self.websocket.close(APP_ERROR_WEB_SOCKET_CODE) self.is_closed = True
Send an error message and close the connection
throw_error
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def extract_and_validate(self, params: Dict[str, str]) -> ExtractedParams: """Extract and validate all parameters from the request""" # Read the code config settings (stack) from the request. generated_code_config = params.get("generatedCodeConfig", "") if generated_code_config not in get_args(Stack): await self.throw_error( f"Invalid generated code config: {generated_code_config}" ) raise ValueError(f"Invalid generated code config: {generated_code_config}") validated_stack = cast(Stack, generated_code_config) # Validate the input mode input_mode = params.get("inputMode") if input_mode not in get_args(InputMode): await self.throw_error(f"Invalid input mode: {input_mode}") raise ValueError(f"Invalid input mode: {input_mode}") validated_input_mode = cast(InputMode, input_mode) openai_api_key = self._get_from_settings_dialog_or_env( params, "openAiApiKey", OPENAI_API_KEY ) # If neither is provided, we throw an error later only if Claude is used. anthropic_api_key = self._get_from_settings_dialog_or_env( params, "anthropicApiKey", ANTHROPIC_API_KEY ) # Base URL for OpenAI API openai_base_url: str | None = None # Disable user-specified OpenAI Base URL in prod if not IS_PROD: openai_base_url = self._get_from_settings_dialog_or_env( params, "openAiBaseURL", OPENAI_BASE_URL ) if not openai_base_url: print("Using official OpenAI URL") # Get the image generation flag from the request. Fall back to True if not provided. should_generate_images = bool(params.get("isImageGenerationEnabled", True)) # Extract and validate generation type generation_type = params.get("generationType", "create") if generation_type not in ["create", "update"]: await self.throw_error(f"Invalid generation type: {generation_type}") raise ValueError(f"Invalid generation type: {generation_type}") generation_type = cast(Literal["create", "update"], generation_type) return ExtractedParams( stack=validated_stack, input_mode=validated_input_mode, should_generate_images=should_generate_images, openai_api_key=openai_api_key, anthropic_api_key=anthropic_api_key, openai_base_url=openai_base_url, generation_type=generation_type, )
Extract and validate all parameters from the request
extract_and_validate
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
def _get_from_settings_dialog_or_env( self, params: dict[str, str], key: str, env_var: str | None ) -> str | None: """Get value from client settings or environment variable""" value = params.get(key) if value: print(f"Using {key} from client-side settings dialog") return value if env_var: print(f"Using {key} from environment variable") return env_var return None
Get value from client settings or environment variable
_get_from_settings_dialog_or_env
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def select_models( self, generation_type: Literal["create", "update"], input_mode: InputMode, openai_api_key: str | None, anthropic_api_key: str | None, gemini_api_key: str | None = None, ) -> List[Llm]: """Select appropriate models based on available API keys""" try: variant_models = self._get_variant_models( generation_type, input_mode, NUM_VARIANTS, openai_api_key, anthropic_api_key, gemini_api_key, ) # Print the variant models (one per line) print("Variant models:") for index, model in enumerate(variant_models): print(f"Variant {index}: {model.value}") return variant_models except Exception: await self.throw_error( "No OpenAI or Anthropic API key found. Please add the environment variable " "OPENAI_API_KEY or ANTHROPIC_API_KEY to backend/.env or in the settings dialog. " "If you add it to .env, make sure to restart the backend server." ) raise Exception("No OpenAI or Anthropic key")
Select appropriate models based on available API keys
select_models
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
def _get_variant_models( self, generation_type: Literal["create", "update"], input_mode: InputMode, num_variants: int, openai_api_key: str | None, anthropic_api_key: str | None, gemini_api_key: str | None, ) -> List[Llm]: """Simple model cycling that scales with num_variants""" # Determine primary Claude model based on generation type if generation_type == "create": claude_model = Llm.CLAUDE_3_7_SONNET_2025_02_19 else: claude_model = Llm.CLAUDE_3_5_SONNET_2024_06_20 # For text input mode, use Claude 4 Sonnet as third option # For other input modes (image/video), use Gemini as third option if input_mode == "text": third_model = Llm.CLAUDE_4_SONNET_2025_05_14 else: # Gemini only works for create right now if generation_type == "create": third_model = Llm.GEMINI_2_0_FLASH else: third_model = Llm.CLAUDE_3_7_SONNET_2025_02_19 # Define models based on available API keys if openai_api_key and anthropic_api_key and (gemini_api_key or input_mode == "text"): models = [ Llm.GPT_4_1_2025_04_14, claude_model, third_model, ] elif openai_api_key and anthropic_api_key: models = [claude_model, Llm.GPT_4_1_2025_04_14] elif anthropic_api_key: models = [claude_model, Llm.CLAUDE_3_5_SONNET_2024_06_20] elif openai_api_key: models = [Llm.GPT_4_1_2025_04_14, Llm.GPT_4O_2024_11_20] else: raise Exception("No OpenAI or Anthropic key") # Cycle through models: [A, B] with num=5 becomes [A, B, A, B, A] selected_models: List[Llm] = [] for i in range(num_variants): selected_models.append(models[i % len(models)]) return selected_models
Simple model cycling that scales with num_variants
_get_variant_models
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def create_prompt( self, params: Dict[str, str], stack: Stack, input_mode: InputMode, ) -> tuple[List[ChatCompletionMessageParam], Dict[str, str]]: """Create prompt messages and return image cache""" try: prompt_messages, image_cache = await create_prompt( params, stack, input_mode ) return prompt_messages, image_cache except Exception: await self.throw_error( "Error assembling prompt. Contact support at [email protected]" ) raise
Create prompt messages and return image cache
create_prompt
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def generate_video_code( self, prompt_messages: List[ChatCompletionMessageParam], anthropic_api_key: str | None, ) -> List[str]: """Generate code for video input mode""" if not anthropic_api_key: await self.throw_error( "Video only works with Anthropic models. No Anthropic API key found. " "Please add the environment variable ANTHROPIC_API_KEY to backend/.env " "or in the settings dialog" ) raise Exception("No Anthropic key") async def process_chunk(content: str, variantIndex: int): await self.send_message("chunk", content, variantIndex) completion_results = [ await stream_claude_response_native( system_prompt=VIDEO_PROMPT, messages=prompt_messages, # type: ignore api_key=anthropic_api_key, callback=lambda x: process_chunk(x, 0), model_name=Llm.CLAUDE_3_OPUS.value, include_thinking=True, ) ] completions = [result["code"] for result in completion_results] # Send the complete variant back to the client await self.send_message("setCode", completions[0], 0) await self.send_message("variantComplete", "Variant generation complete", 0) return completions
Generate code for video input mode
generate_video_code
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def process_variants( self, variant_models: List[Llm], prompt_messages: List[ChatCompletionMessageParam], image_cache: Dict[str, str], params: Dict[str, str], ) -> Dict[int, str]: """Process all variants in parallel and return completions""" tasks = self._create_generation_tasks(variant_models, prompt_messages, params) # Dictionary to track variant tasks and their status variant_tasks: Dict[int, asyncio.Task[Completion]] = {} variant_completions: Dict[int, str] = {} # Create tasks for each variant for index, task in enumerate(tasks): variant_task = asyncio.create_task(task) variant_tasks[index] = variant_task # Process each variant independently variant_processors = [ self._process_variant_completion( index, task, variant_models[index], image_cache, variant_completions ) for index, task in variant_tasks.items() ] # Wait for all variants to complete await asyncio.gather(*variant_processors, return_exceptions=True) return variant_completions
Process all variants in parallel and return completions
process_variants
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
def _create_generation_tasks( self, variant_models: List[Llm], prompt_messages: List[ChatCompletionMessageParam], params: Dict[str, str], ) -> List[Coroutine[Any, Any, Completion]]: """Create generation tasks for each variant model""" tasks: List[Coroutine[Any, Any, Completion]] = [] for index, model in enumerate(variant_models): if ( model == Llm.GPT_4O_2024_11_20 or model == Llm.O1_2024_12_17 or model == Llm.O4_MINI_2025_04_16 or model == Llm.O3_2025_04_16 or model == Llm.GPT_4_1_2025_04_14 or model == Llm.GPT_4_1_MINI_2025_04_14 or model == Llm.GPT_4_1_NANO_2025_04_14 ): if self.openai_api_key is None: raise Exception("OpenAI API key is missing.") tasks.append( self._stream_openai_with_error_handling( prompt_messages, model_name=model.value, index=index, ) ) elif GEMINI_API_KEY and ( model == Llm.GEMINI_2_0_PRO_EXP or model == Llm.GEMINI_2_0_FLASH_EXP or model == Llm.GEMINI_2_0_FLASH or model == Llm.GEMINI_2_5_FLASH_PREVIEW_05_20 or model == Llm.GEMINI_2_5_PRO_PREVIEW_05_06 ): tasks.append( stream_gemini_response( prompt_messages, api_key=GEMINI_API_KEY, callback=lambda x, i=index: self._process_chunk(x, i), model_name=model.value, ) ) elif ( model == Llm.CLAUDE_3_5_SONNET_2024_06_20 or model == Llm.CLAUDE_3_5_SONNET_2024_10_22 or model == Llm.CLAUDE_3_7_SONNET_2025_02_19 or model == Llm.CLAUDE_4_SONNET_2025_05_14 or model == Llm.CLAUDE_4_OPUS_2025_05_14 ): if self.anthropic_api_key is None: raise Exception("Anthropic API key is missing.") # For creation, use Claude Sonnet 3.7 # For updates, we use Claude Sonnet 3.5 until we have tested Claude Sonnet 3.7 if params["generationType"] == "create": claude_model = Llm.CLAUDE_3_7_SONNET_2025_02_19 else: claude_model = Llm.CLAUDE_3_5_SONNET_2024_06_20 tasks.append( stream_claude_response( prompt_messages, api_key=self.anthropic_api_key, callback=lambda x, i=index: self._process_chunk(x, i), model_name=claude_model.value, ) ) return tasks
Create generation tasks for each variant model
_create_generation_tasks
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def _stream_openai_with_error_handling( self, prompt_messages: List[ChatCompletionMessageParam], model_name: str, index: int, ) -> Completion: """Wrap OpenAI streaming with specific error handling""" try: assert self.openai_api_key is not None return await stream_openai_response( prompt_messages, api_key=self.openai_api_key, base_url=self.openai_base_url, callback=lambda x: self._process_chunk(x, index), model_name=model_name, ) except openai.AuthenticationError as e: print(f"[VARIANT {index}] OpenAI Authentication failed", e) error_message = ( "Incorrect OpenAI key. Please make sure your OpenAI API key is correct, " "or create a new OpenAI API key on your OpenAI dashboard." + ( " Alternatively, you can purchase code generation credits directly on this website." if IS_PROD else "" ) ) await self.send_message("variantError", error_message, index) raise VariantErrorAlreadySent(e) except openai.NotFoundError as e: print(f"[VARIANT {index}] OpenAI Model not found", e) error_message = ( e.message + ". Please make sure you have followed the instructions correctly to obtain " "an OpenAI key with GPT vision access: " "https://github.com/abi/screenshot-to-code/blob/main/Troubleshooting.md" + ( " Alternatively, you can purchase code generation credits directly on this website." if IS_PROD else "" ) ) await self.send_message("variantError", error_message, index) raise VariantErrorAlreadySent(e) except openai.RateLimitError as e: print(f"[VARIANT {index}] OpenAI Rate limit exceeded", e) error_message = ( "OpenAI error - 'You exceeded your current quota, please check your plan and billing details.'" + ( " Alternatively, you can purchase code generation credits directly on this website." if IS_PROD else "" ) ) await self.send_message("variantError", error_message, index) raise VariantErrorAlreadySent(e)
Wrap OpenAI streaming with specific error handling
_stream_openai_with_error_handling
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def _perform_image_generation( self, completion: str, image_cache: dict[str, str], ): """Generate images for the completion if needed""" if not self.should_generate_images: return completion replicate_api_key = REPLICATE_API_KEY if replicate_api_key: image_generation_model = "flux" api_key = replicate_api_key else: if not self.openai_api_key: print( "No OpenAI API key and Replicate key found. Skipping image generation." ) return completion image_generation_model = "dalle3" api_key = self.openai_api_key print("Generating images with model: ", image_generation_model) return await generate_images( completion, api_key=api_key, base_url=self.openai_base_url, image_cache=image_cache, model=image_generation_model, )
Generate images for the completion if needed
_perform_image_generation
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def _process_variant_completion( self, index: int, task: asyncio.Task[Completion], model: Llm, image_cache: Dict[str, str], variant_completions: Dict[int, str], ): """Process a single variant completion including image generation""" try: completion = await task print(f"{model.value} completion took {completion['duration']:.2f} seconds") variant_completions[index] = completion["code"] try: # Process images for this variant processed_html = await self._perform_image_generation( completion["code"], image_cache, ) # Extract HTML content processed_html = extract_html_content(processed_html) # Send the complete variant back to the client await self.send_message("setCode", processed_html, index) await self.send_message( "variantComplete", "Variant generation complete", index, ) except Exception as inner_e: # If websocket is closed or other error during post-processing print(f"Post-processing error for variant {index}: {inner_e}") # We still keep the completion in variant_completions except Exception as e: # Handle any errors that occurred during generation print(f"Error in variant {index}: {e}") traceback.print_exception(type(e), e, e.__traceback__) # Only send error message if it hasn't been sent already if not isinstance(e, VariantErrorAlreadySent): await self.send_message("variantError", str(e), index)
Process a single variant completion including image generation
_process_variant_completion
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def stream_code(websocket: WebSocket): """Handle WebSocket code generation requests using a pipeline pattern""" pipeline = Pipeline() # Configure the pipeline pipeline.use(WebSocketSetupMiddleware()) pipeline.use(ParameterExtractionMiddleware()) pipeline.use(StatusBroadcastMiddleware()) pipeline.use(PromptCreationMiddleware()) pipeline.use(CodeGenerationMiddleware()) pipeline.use(PostProcessingMiddleware()) # Execute the pipeline await pipeline.execute(websocket)
Handle WebSocket code generation requests using a pipeline pattern
stream_code
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
def normalize_url(url: str) -> str: """ Normalize URL to ensure it has a proper protocol. If no protocol is specified, default to https:// """ url = url.strip() # Parse the URL parsed = urlparse(url) # Check if we have a scheme if not parsed.scheme: # No scheme, add https:// url = f"https://{url}" elif parsed.scheme in ['http', 'https']: # Valid scheme, keep as is pass else: # Check if this might be a domain with port (like example.com:8080) # urlparse treats this as scheme:netloc, but we want to handle it as domain:port if ':' in url and not url.startswith(('http://', 'https://', 'ftp://', 'file://')): # Likely a domain:port without protocol url = f"https://{url}" else: # Invalid protocol raise ValueError(f"Unsupported protocol: {parsed.scheme}") return url
Normalize URL to ensure it has a proper protocol. If no protocol is specified, default to https://
normalize_url
python
abi/screenshot-to-code
backend/routes/screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/screenshot.py
MIT
def test_url_without_protocol(self): """Test that URLs without protocol get https:// added.""" assert normalize_url("example.com") == "https://example.com" assert normalize_url("www.example.com") == "https://www.example.com" assert normalize_url("subdomain.example.com") == "https://subdomain.example.com"
Test that URLs without protocol get https:// added.
test_url_without_protocol
python
abi/screenshot-to-code
backend/tests/test_screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/tests/test_screenshot.py
MIT
def test_url_with_http_protocol(self): """Test that existing http protocol is preserved.""" assert normalize_url("http://example.com") == "http://example.com" assert normalize_url("http://www.example.com") == "http://www.example.com"
Test that existing http protocol is preserved.
test_url_with_http_protocol
python
abi/screenshot-to-code
backend/tests/test_screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/tests/test_screenshot.py
MIT
def test_url_with_https_protocol(self): """Test that existing https protocol is preserved.""" assert normalize_url("https://example.com") == "https://example.com" assert normalize_url("https://www.example.com") == "https://www.example.com"
Test that existing https protocol is preserved.
test_url_with_https_protocol
python
abi/screenshot-to-code
backend/tests/test_screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/tests/test_screenshot.py
MIT
def test_url_with_path_and_params(self): """Test URLs with paths and query parameters.""" assert normalize_url("example.com/path") == "https://example.com/path" assert normalize_url("example.com/path?param=value") == "https://example.com/path?param=value" assert normalize_url("example.com:8080/path") == "https://example.com:8080/path"
Test URLs with paths and query parameters.
test_url_with_path_and_params
python
abi/screenshot-to-code
backend/tests/test_screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/tests/test_screenshot.py
MIT
def test_invalid_protocols(self): """Test that unsupported protocols raise ValueError.""" with pytest.raises(ValueError, match="Unsupported protocol: ftp"): normalize_url("ftp://example.com") with pytest.raises(ValueError, match="Unsupported protocol: file"): normalize_url("file:///path/to/file")
Test that unsupported protocols raise ValueError.
test_invalid_protocols
python
abi/screenshot-to-code
backend/tests/test_screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/tests/test_screenshot.py
MIT
def extract_tag_content(tag: str, text: str) -> str: """ Extracts content for a given tag from the provided text. :param tag: The tag to search for. :param text: The text to search within. :return: The content found within the tag, if any. """ tag_start = f"<{tag}>" tag_end = f"</{tag}>" start_idx = text.find(tag_start) end_idx = text.find(tag_end, start_idx) if start_idx != -1 and end_idx != -1: return text[start_idx : end_idx + len(tag_end)] return ""
Extracts content for a given tag from the provided text. :param tag: The tag to search for. :param text: The text to search within. :return: The content found within the tag, if any.
extract_tag_content
python
abi/screenshot-to-code
backend/video/utils.py
https://github.com/abi/screenshot-to-code/blob/master/backend/video/utils.py
MIT
def count(start: int = 0, step: int = 1): """Local implementation of `itertools.count()` to allow v2.6 compatibility.""" n = start while True: yield n n += step
Local implementation of `itertools.count()` to allow v2.6 compatibility.
count
python
scanny/python-pptx
features/steps/helpers.py
https://github.com/scanny/python-pptx/blob/master/features/steps/helpers.py
MIT
def then_the_size_of_the_text_is_10pt(context): """Size depends on Pillow version, probably algorithm isn't quite right either.""" text_frame = context.text_frame for paragraph in text_frame.paragraphs: for run in paragraph.runs: assert run.font.size in (Pt(10.0), Pt(11.0)), "got %s" % run.font.size.pt
Size depends on Pillow version, probably algorithm isn't quite right either.
then_the_size_of_the_text_is_10pt
python
scanny/python-pptx
features/steps/text_frame.py
https://github.com/scanny/python-pptx/blob/master/features/steps/text_frame.py
MIT
def _child(element, child_tagname): """ Return direct child of *element* having *child_tagname* or :class:`None` if no such child element is present. """ xpath = './%s' % child_tagname matching_children = element.xpath(xpath, namespaces=nsmap) return matching_children[0] if len(matching_children) else None
Return direct child of *element* having *child_tagname* or :class:`None` if no such child element is present.
_child
python
scanny/python-pptx
lab/cust-elm-classes/main.py
https://github.com/scanny/python-pptx/blob/master/lab/cust-elm-classes/main.py
MIT
def _child_list(element, child_tagname): """ Return list containing the direct children of *element* having *child_tagname*. """ xpath = './%s' % child_tagname return element.xpath(xpath, namespaces=nsmap)
Return list containing the direct children of *element* having *child_tagname*.
_child_list
python
scanny/python-pptx
lab/cust-elm-classes/main.py
https://github.com/scanny/python-pptx/blob/master/lab/cust-elm-classes/main.py
MIT
def _nsmap(*prefixes): """ Return a dict containing the subset namespace prefix mappings specified by *prefixes*. Any number of namespace prefixes can be supplied, e.g. namespaces('a', 'r', 'p'). """ namespaces = {} for prefix in prefixes: namespaces[prefix] = nsmap[prefix] return namespaces
Return a dict containing the subset namespace prefix mappings specified by *prefixes*. Any number of namespace prefixes can be supplied, e.g. namespaces('a', 'r', 'p').
_nsmap
python
scanny/python-pptx
lab/cust-elm-classes/main.py
https://github.com/scanny/python-pptx/blob/master/lab/cust-elm-classes/main.py
MIT
def pfxdtag(tag): """ Return short-form prefixed tag from fully qualified (Clark notation) tagname. """ uri, tagroot = tag[1:].split('}') prefix = reverse_nsmap[uri] return '%s:%s' % (prefix, tagroot)
Return short-form prefixed tag from fully qualified (Clark notation) tagname.
pfxdtag
python
scanny/python-pptx
lab/parse_xsd/objectify_lab.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/objectify_lab.py
MIT
def qn(tag): """ qn is short for *qualified name*. Return fully qualified (Clark notation) tagname corresponding to short-form prefixed tagname *tag*. """ prefix, tagroot = tag.split(':') uri = nsmap[prefix] return '{%s}%s' % (uri, tagroot)
qn is short for *qualified name*. Return fully qualified (Clark notation) tagname corresponding to short-form prefixed tagname *tag*.
qn
python
scanny/python-pptx
lab/parse_xsd/objectify_lab.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/objectify_lab.py
MIT
def pfxdtag(tag): """ Return short-form prefixed tag from fully qualified (Clark notation) tagname. """ uri, tagroot = tag[1:].split('}') prefix = reverse_nsmap[uri] return '%s:%s' % (prefix, tagroot)
Return short-form prefixed tag from fully qualified (Clark notation) tagname.
pfxdtag
python
scanny/python-pptx
lab/parse_xsd/parse_xsd.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/parse_xsd.py
MIT
def qtag(tag): """ Return fully qualified (Clark notation) tagname corresponding to short-form prefixed tagname *tag*. """ prefix, tagroot = tag.split(':') uri = nsmap[prefix] return '{%s}%s' % (uri, tagroot)
Return fully qualified (Clark notation) tagname corresponding to short-form prefixed tagname *tag*.
qtag
python
scanny/python-pptx
lab/parse_xsd/parse_xsd.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/parse_xsd.py
MIT
def get_complexType(self, typename): """Return complex type element with name *typename*""" if typename.startswith('a:'): typename = typename[2:] xpath = "./xsd:complexType[@name='%s']" % typename for xsd in self.__xsd_trees: elms = xsd.xpath(xpath) if len(elms): return elms[0], xsd.nsprefix raise KeyError("no complexType named '%s' found" % typename)
Return complex type element with name *typename*
get_complexType
python
scanny/python-pptx
lab/parse_xsd/parse_xsd.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/parse_xsd.py
MIT
def getdef(self, defname, tag='*'): """Return definition element with name *defname*""" if defname.startswith('a:'): defname = defname[2:] for xsd in self.__xsd_trees: xpath = "./%s[@name='%s']" % (tag, defname) elements = xsd.xpath(xpath) if elements: return elements[0] raise KeyError("no definition named '%s' found" % defname)
Return definition element with name *defname*
getdef
python
scanny/python-pptx
lab/parse_xsd/parse_xsd.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/parse_xsd.py
MIT
def element_def(self): """ blipFill = ElementDef('p:blipFill', 'CT_BlipFillProperties') blipFill.add_child('a:blip', cardinality='?') blipFill.add_attributes('dpi', 'rotWithShape') """ s = ("%s = ElementDef('%s', '%s')\n" % (self.name, self.name, self.name)) for element in self.elements: s += ("%s.add_child('%s', cardinality='%s')\n" % (self.name, element.name, element.cardinality)) # for attribute in self.attributes: # s += '\n %s' % attribute return s
blipFill = ElementDef('p:blipFill', 'CT_BlipFillProperties') blipFill.add_child('a:blip', cardinality='?') blipFill.add_attributes('dpi', 'rotWithShape')
element_def
python
scanny/python-pptx
lab/parse_xsd/parse_xsd.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/parse_xsd.py
MIT
def load_adjustment_values(self, c): """load adjustment values for auto shape types in self""" # retrieve auto shape types in const_name order -------- for mast in self: # retriev adj vals for this auto shape type -------- c.execute( ' SELECT name, val\n' ' FROM adjustment_values\n' ' WHERE prst = ?\n' 'ORDER BY seq_nmbr', (mast.prst,) ) for name, val in c: mast.adj_vals.append(AdjustmentValue(name, val))
load adjustment values for auto shape types in self
load_adjustment_values
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def create_tables(c): """create (or recreate) the auto shape type tables""" # auto_shape_types --------------------- c.execute( 'DROP TABLE IF EXISTS auto_shape_types' ) c.execute( 'CREATE TABLE auto_shape_types (\n' ' id integer,\n' ' prst text,\n' ' const_name text,\n' ' base_name text,\n' ' ms_name text,\n' ' desc text\n' ')\n' ) c.execute( 'DROP TABLE IF EXISTS adjustment_values' ) c.execute( 'CREATE TABLE adjustment_values (\n' ' prst text,\n' ' seq_nmbr integer,\n' ' name text,\n' ' val integer\n' ')\n' )
create (or recreate) the auto shape type tables
create_tables
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def insert_adjustment_values(c): """insert adjustment values into their table""" adjustment_values = load_adjustment_values() # insert into table ------------------------------------ q_insert = ( 'INSERT INTO adjustment_values\n' ' (prst, seq_nmbr, name, val)\n' ' VALUES (?, ?, ?, ?)\n' ) c.executemany(q_insert, adjustment_values)
insert adjustment values into their table
insert_adjustment_values
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def load_adjustment_values(): """load adjustment values and their default values from XML""" # parse XML -------------------------------------------- thisdir = os.path.split(__file__)[0] prst_defs_relpath = ( 'ISO-IEC-29500-1/schemas/dml-geometries/OfficeOpenXML-DrawingMLGeomet' 'ries/presetShapeDefinitions.xml' ) prst_defs_path = os.path.join(thisdir, prst_defs_relpath) presetShapeDefinitions = objectify.parse(prst_defs_path).getroot() # load individual records into tuples to return -------- ns = 'http://schemas.openxmlformats.org/drawingml/2006/main' avLst_qn = '{%s}avLst' % ns adjustment_values = [] for shapedef in presetShapeDefinitions.iterchildren(): prst = shapedef.tag try: avLst = shapedef[avLst_qn] except AttributeError: continue for idx, gd in enumerate(avLst.gd): name = gd.get('name') val = int(gd.get('fmla')[4:]) # strip off leading 'val ' record = (prst, idx+1, name, val) adjustment_values.append(record) return adjustment_values
load adjustment values and their default values from XML
load_adjustment_values
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def print_mso_auto_shape_type_constants(): """print symbolic constant definitions for msoAutoShapeType""" auto_shape_types = MsoAutoShapeTypeCollection.load(sort='const_name') out = render_mso_auto_shape_type_constants(auto_shape_types) print out
print symbolic constant definitions for msoAutoShapeType
print_mso_auto_shape_type_constants
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def print_mso_auto_shape_type_enum(): """print symbolic constant definitions for msoAutoShapeType""" auto_shape_types = MsoAutoShapeTypeCollection.load(sort='const_name') out = render_mso_auto_shape_type_enum(auto_shape_types) print out
print symbolic constant definitions for msoAutoShapeType
print_mso_auto_shape_type_enum
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def render_desc(desc): """calculate desc string, wrapped if too long""" desc = desc + '.' desc_lines = split_len(desc, 54) if len(desc_lines) > 1: join_str = "'\n%s'" % (' '*21) lines_str = join_str.join(desc_lines) out = "('%s')" % lines_str else: out = "'%s'" % desc_lines[0] return out
calculate desc string, wrapped if too long
render_desc
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def to_mixed_case(s): """ convert upper snake case string to mixed case, e.g. MIXED_CASE becomes MixedCase """ out = '' last_c = '' for c in s: if c == '_': pass elif last_c in ('', '_'): out += c.upper() else: out += c.lower() last_c = c return out
convert upper snake case string to mixed case, e.g. MIXED_CASE becomes MixedCase
to_mixed_case
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def parse_args(spectypes): """ Return arguments object formed by parsing the command line used to launch the program. """ arg_parser = argparse.ArgumentParser() arg_parser.add_argument( "-c", "--constants", help="emit constants instead of spec dict", action="store_true" ) arg_parser.add_argument( "spectype", help="specifies the spec type to be generated", choices=spectypes ) return arg_parser.parse_args()
Return arguments object formed by parsing the command line used to launch the program.
parse_args
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def msdn_msoAutoShapeTypes(): """ Return sequence of tuples representing the msoAutoShapeType enumeration as defined in the MS Office API. Access with:: for ms_name, id_, desc in msdn_msoAutoShapeTypes(): ... This is structured as a function simply so code folding will work on it. """ return ( ('msoShape10PointStar', 149, '10-Point Star'), ('msoShape12PointStar', 150, '12-Point Star'), ('msoShape16pointStar', 94, '16-point star.'), ('msoShape24pointStar', 95, '24-point star.'), ('msoShape32pointStar', 96, '32-point star.'), ('msoShape4pointStar', 91, '4-point star.'), ('msoShape5pointStar', 92, '5-point star.'), ('msoShape6PointStar', 147, '6-Point Star'), ('msoShape7PointStar', 148, '7-Point Star'), ('msoShape8pointStar', 93, '8-point star.'), ('msoShapeActionButtonBackorPrevious', 129, 'Back or Previous button. Supports mouse-click and mouse-over actio' 'ns.'), ('msoShapeActionButtonBeginning', 131, 'Beginning button. Supports mouse-click and mouse-over actions.'), ('msoShapeActionButtonCustom', 125, 'Button with no default picture or text. Supports mouse-click and m' 'ouse-over actions.'), ('msoShapeActionButtonDocument', 134, 'Document button. Supports mouse-click and mouse-over actions.'), ('msoShapeActionButtonEnd', 132, 'End button. Supports mouse-click and mouse-over actions.'), ('msoShapeActionButtonForwardorNext', 130, 'Forward or Next button. Supports mouse-click and mouse-over action' 's.'), ('msoShapeActionButtonHelp', 127, 'Help button. Supports mouse-click and mouse-over actions.'), ('msoShapeActionButtonHome', 126, 'Home button. Supports mouse-click and mouse-over actions.'), ('msoShapeActionButtonInformation', 128, 'Information button. Supports mouse-click and mouse-over actions.'), ('msoShapeActionButtonMovie', 136, 'Movie button. Supports mouse-click and mouse-over actions.'), ('msoShapeActionButtonReturn', 133, 'Return button. Supports mouse-click and mouse-over actions.'), ('msoShapeActionButtonSound', 135, 'Sound button. Supports mouse-click and mouse-over actions.'), ('msoShapeArc', 25, 'Arc.'), ('msoShapeBalloon', 137, 'Balloon.'), ('msoShapeBentArrow', 41, 'Block arrow that follows a curved 90-degree angle.'), ('msoShapeBentUpArrow', 44, 'Block arrow that follows a sharp 90-degree angle. Points up by def' 'ault.'), ('msoShapeBevel', 15, 'Bevel.'), ('msoShapeBlockArc', 20, 'Block arc.'), ('msoShapeCan', 13, 'Can.'), ('msoShapeChartPlus', 182, 'Chart Plus'), ('msoShapeChartStar', 181, 'Chart Star'), ('msoShapeChartX', 180, 'Chart X'), ('msoShapeChevron', 52, 'Chevron.'), ('msoShapeChord', 161, 'Geometric chord shape'), ('msoShapeCircularArrow', 60, 'Block arrow that follows a curved 180-degree angle.'), ('msoShapeCloud', 179, 'Cloud'), ('msoShapeCloudCallout', 108, 'Cloud callout.'), ('msoShapeCorner', 162, 'Corner'), ('msoShapeCornerTabs', 169, 'Corner Tabs'), ('msoShapeCross', 11, 'Cross.'), ('msoShapeCube', 14, 'Cube.'), ('msoShapeCurvedDownArrow', 48, 'Block arrow that curves down.'), ('msoShapeCurvedDownRibbon', 100, 'Ribbon banner that curves down.'), ('msoShapeCurvedLeftArrow', 46, 'Block arrow that curves left.'), ('msoShapeCurvedRightArrow', 45, 'Block arrow that curves right.'), ('msoShapeCurvedUpArrow', 47, 'Block arrow that curves up.'), ('msoShapeCurvedUpRibbon', 99, 'Ribbon banner that curves up.'), ('msoShapeDecagon', 144, 'Decagon'), ('msoShapeDiagonalStripe', 141, 'Diagonal Stripe'), ('msoShapeDiamond', 4, 'Diamond'), ('msoShapeDodecagon', 146, 'Dodecagon'), ('msoShapeDonut', 18, 'Donut.'), ('msoShapeDoubleBrace', 27, 'Double brace.'), ('msoShapeDoubleBracket', 26, 'Double bracket.'), ('msoShapeDoubleWave', 104, 'Double wave.'), ('msoShapeDownArrow', 36, 'Block arrow that points down.'), ('msoShapeDownArrowCallout', 56, 'Callout with arrow that points down.'), ('msoShapeDownRibbon', 98, 'Ribbon banner with center area below ribbon ends.'), ('msoShapeExplosion1', 89, 'Explosion.'), ('msoShapeExplosion2', 90, 'Explosion.'), ('msoShapeFlowchartAlternateProcess', 62, 'Alternate process flowchart symbol.'), ('msoShapeFlowchartCard', 75, 'Card flowchart symbol.'), ('msoShapeFlowchartCollate', 79, 'Collate flowchart symbol.'), ('msoShapeFlowchartConnector', 73, 'Connector flowchart symbol.'), ('msoShapeFlowchartData', 64, 'Data flowchart symbol.'), ('msoShapeFlowchartDecision', 63, 'Decision flowchart symbol.'), ('msoShapeFlowchartDelay', 84, 'Delay flowchart symbol.'), ('msoShapeFlowchartDirectAccessStorage', 87, 'Direct access storage flowchart symbol.'), ('msoShapeFlowchartDisplay', 88, 'Display flowchart symbol.'), ('msoShapeFlowchartDocument', 67, 'Document flowchart symbol.'), ('msoShapeFlowchartExtract', 81, 'Extract flowchart symbol.'), ('msoShapeFlowchartInternalStorage', 66, 'Internal storage flowchart symbol.'), ('msoShapeFlowchartMagneticDisk', 86, 'Magnetic disk flowchart symbol.'), ('msoShapeFlowchartManualInput', 71, 'Manual input flowchart symbol.'), ('msoShapeFlowchartManualOperation', 72, 'Manual operation flowchart symbol.'), ('msoShapeFlowchartMerge', 82, 'Merge flowchart symbol.'), ('msoShapeFlowchartMultidocument', 68, 'Multi-document flowchart symbol.'), ('msoShapeFlowchartOfflineStorage', 139, 'Offline Storage'), ('msoShapeFlowchartOffpageConnector', 74, 'Off-page connector flowchart symbol.'), ('msoShapeFlowchartOr', 78, '"Or" flowchart symbol.'), ('msoShapeFlowchartPredefinedProcess', 65, 'Predefined process flowchart symbol.'), ('msoShapeFlowchartPreparation', 70, 'Preparation flowchart symbol.'), ('msoShapeFlowchartProcess', 61, 'Process flowchart symbol.'), ('msoShapeFlowchartPunchedTape', 76, 'Punched tape flowchart symbol.'), ('msoShapeFlowchartSequentialAccessStorage', 85, 'Sequential access storage flowchart symbol.'), ('msoShapeFlowchartSort', 80, 'Sort flowchart symbol.'), ('msoShapeFlowchartStoredData', 83, 'Stored data flowchart symbol.'), ('msoShapeFlowchartSummingJunction', 77, 'Summing junction flowchart symbol.'), ('msoShapeFlowchartTerminator', 69, 'Terminator flowchart symbol.'), ('msoShapeFoldedCorner', 16, 'Folded corner.'), ('msoShapeFrame', 158, 'Frame'), ('msoShapeFunnel', 174, 'Funnel'), ('msoShapeGear6', 172, 'Gear 6'), ('msoShapeGear9', 173, 'Gear 9'), ('msoShapeHalfFrame', 159, 'Half Frame'), ('msoShapeHeart', 21, 'Heart.'), ('msoShapeHeptagon', 145, 'Heptagon'), ('msoShapeHexagon', 10, 'Hexagon.'), ('msoShapeHorizontalScroll', 102, 'Horizontal scroll.'), ('msoShapeIsoscelesTriangle', 7, 'Isosceles triangle.'), ('msoShapeLeftArrow', 34, 'Block arrow that points left.'), ('msoShapeLeftArrowCallout', 54, 'Callout with arrow that points left.'), ('msoShapeLeftBrace', 31, 'Left brace.'), ('msoShapeLeftBracket', 29, 'Left bracket.'), ('msoShapeLeftCircularArrow', 176, 'Left Circular Arrow'), ('msoShapeLeftRightArrow', 37, 'Block arrow with arrowheads that point both left and right.'), ('msoShapeLeftRightArrowCallout', 57, 'Callout with arrowheads that point both left and right.'), ('msoShapeLeftRightCircularArrow', 177, 'Left Right Circular Arrow'), ('msoShapeLeftRightRibbon', 140, 'Left Right Ribbon'), ('msoShapeLeftRightUpArrow', 40, 'Block arrow with arrowheads that point left, right, and up.'), ('msoShapeLeftUpArrow', 43, 'Block arrow with arrowheads that point left and up.'), ('msoShapeLightningBolt', 22, 'Lightning bolt.'), ('msoShapeLineCallout1', 109, 'Callout with border and horizontal callout line.'), ('msoShapeLineCallout1AccentBar', 113, 'Callout with horizontal accent bar.'), ('msoShapeLineCallout1BorderandAccentBar', 121, 'Callout with border and horizontal accent bar.'), ('msoShapeLineCallout1NoBorder', 117, 'Callout with horizontal line.'), ('msoShapeLineCallout2', 110, 'Callout with diagonal straight line.'), ('msoShapeLineCallout2AccentBar', 114, 'Callout with diagonal callout line and accent bar.'), ('msoShapeLineCallout2BorderandAccentBar', 122, 'Callout with border, diagonal straight line, and accent bar.'), ('msoShapeLineCallout2NoBorder', 118, 'Callout with no border and diagonal callout line.'), ('msoShapeLineCallout3', 111, 'Callout with angled line.'), ('msoShapeLineCallout3AccentBar', 115, 'Callout with angled callout line and accent bar.'), ('msoShapeLineCallout3BorderandAccentBar', 123, 'Callout with border, angled callout line, and accent bar.'), ('msoShapeLineCallout3NoBorder', 119, 'Callout with no border and angled callout line.'), ('msoShapeLineCallout4', 112, 'Callout with callout line segments forming a U-shape.'), ('msoShapeLineCallout4AccentBar', 116, 'Callout with accent bar and callout line segments forming a U-shap' 'e.'), ('msoShapeLineCallout4BorderandAccentBar', 124, 'Callout with border, accent bar, and callout line segments forming' 'a U-shape.'), ('msoShapeLineCallout4NoBorder', 120, 'Callout with no border and callout line segments forming a U-shape' '.'), ('msoShapeLineInverse', 183, 'Straight Connector'), ('msoShapeMathDivide', 166, 'Division'), ('msoShapeMathEqual', 167, 'Equal'), ('msoShapeMathMinus', 164, 'Minus'), ('msoShapeMathMultiply', 165, 'Multiply'), ('msoShapeMathNotEqual', 168, 'Not Equal'), ('msoShapeMathPlus', 163, 'Plus'), ('msoShapeMoon', 24, 'Moon.'), ('msoShapeNoSymbol', 19, '"No" symbol.'), ('msoShapeNonIsoscelesTrapezoid', 143, 'Non-isosceles Trapezoid'), ('msoShapeNotPrimitive', 138, 'Not supported.'), ('msoShapeNotchedRightArrow', 50, 'Notched block arrow that points right.'), ('msoShapeOctagon', 6, 'Octagon'), ('msoShapeOval', 9, 'Oval'), ('msoShapeOvalCallout', 107, 'Oval-shaped callout.'), ('msoShapeParallelogram', 2, 'Parallelogram'), ('msoShapePentagon', 51, 'Pentagon.'), ('msoShapePie', 142, 'Pie'), ('msoShapePieWedge', 175, 'Pie'), ('msoShapePlaque', 28, 'Plaque.'), ('msoShapePlaqueTabs', 171, 'Plaque Tabs'), ('msoShapeQuadArrow', 39, 'Block arrows that point up, down, left, and right.'), ('msoShapeQuadArrowCallout', 59, 'Callout with arrows that point up, down, left, and right.'), ('msoShapeRectangle', 1, 'Rectangle'), ('msoShapeRectangularCallout', 105, 'Rectangular callout.'), ('msoShapeRegularPentagon', 12, 'Pentagon.'), ('msoShapeRightArrow', 33, 'Block arrow that points right.'), ('msoShapeRightArrowCallout', 53, 'Callout with arrow that points right.'), ('msoShapeRightBrace', 32, 'Right brace.'), ('msoShapeRightBracket', 30, 'Right bracket.'), ('msoShapeRightTriangle', 8, 'Right triangle.'), ('msoShapeRound1Rectangle', 151, 'Round Single Corner Rectangle'), ('msoShapeRound2DiagRectangle', 153, 'Round Diagonal Corner Rectangle'), ('msoShapeRound2SameRectangle', 152, 'Round Same Side Corner Rectangle'), ('msoShapeRoundedRectangle', 5, 'Rounded rectangle.'), ('msoShapeRoundedRectangularCallout', 106, 'Rounded rectangle-shaped callout.'), ('msoShapeSmileyFace', 17, 'Smiley face.'), ('msoShapeSnip1Rectangle', 155, 'Snip Single Corner Rectangle'), ('msoShapeSnip2DiagRectangle', 157, 'Snip Diagonal Corner Rectangle'), ('msoShapeSnip2SameRectangle', 156, 'Snip Same Side Corner Rectangle'), ('msoShapeSnipRoundRectangle', 154, 'Snip and Round Single Corner Rectangle'), ('msoShapeSquareTabs', 170, 'Square Tabs'), ('msoShapeStripedRightArrow', 49, 'Block arrow that points right with stripes at the tail.'), ('msoShapeSun', 23, 'Sun.'), ('msoShapeSwooshArrow', 178, 'Swoosh Arrow'), ('msoShapeTear', 160, 'Teardrop'), ('msoShapeTrapezoid', 3, 'Trapezoid'), ('msoShapeUTurnArrow', 42, 'Block arrow forming a U shape.'), ('msoShapeUpArrow', 35, 'Block arrow that points up.'), ('msoShapeUpArrowCallout', 55, 'Callout with arrow that points up.'), ('msoShapeUpDownArrow', 38, 'Block arrow that points up and down.'), ('msoShapeUpDownArrowCallout', 58, 'Callout with arrows that point up and down.'), ('msoShapeUpRibbon', 97, 'Ribbon banner with center area above ribbon ends.'), ('msoShapeVerticalScroll', 101, 'Vertical scroll.'), ('msoShapeWave', 103, 'Wave.') )
Return sequence of tuples representing the msoAutoShapeType enumeration as defined in the MS Office API. Access with:: for ms_name, id_, desc in msdn_msoAutoShapeTypes(): ... This is structured as a function simply so code folding will work on it.
msdn_msoAutoShapeTypes
python
scanny/python-pptx
spec/gen_spec/src_data/msoAutoShapeType.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/src_data/msoAutoShapeType.py
MIT
def prst_map(): """ Sequence of tuples representing the mapping of names in the msoAutoShapeType enumeration to the 'prst' and 'name' values used in the XML to specify and identify that auto shape type. These were discovered using the VBA editor in PowerPoint for Windows. Access with:: for ms_name, prst, base_name in prst_map(): ... """ return ( ('msoShape10PointStar', 'star10', '10-Point Star'), ('msoShape12PointStar', 'star12', '12-Point Star'), ('msoShape16pointStar', 'star16', '16-Point Star'), ('msoShape24pointStar', 'star24', '24-Point Star'), ('msoShape32pointStar', 'star32', '32-Point Star'), ('msoShape4pointStar', 'star4', '4-Point Star'), ('msoShape5pointStar', 'star5', '5-Point Star'), ('msoShape6PointStar', 'star6', '6-Point Star'), ('msoShape7PointStar', 'star7', '7-Point Star'), ('msoShape8pointStar', 'star8', '8-Point Star'), ('msoShapeActionButtonBackorPrevious', 'actionButtonBackPrevious', 'Action Button: Back or Previous'), ('msoShapeActionButtonBeginning', 'actionButtonBeginning', 'Action Button: Beginning'), ('msoShapeActionButtonCustom', 'actionButtonBlank', 'Action Button: Custom'), ('msoShapeActionButtonDocument', 'actionButtonDocument', 'Action Button: Document'), ('msoShapeActionButtonEnd', 'actionButtonEnd', 'Action Button: End'), ('msoShapeActionButtonForwardorNext', 'actionButtonForwardNext', 'Action Button: Forward or Next'), ('msoShapeActionButtonHelp', 'actionButtonHelp', 'Action Button: Help'), ('msoShapeActionButtonHome', 'actionButtonHome', 'Action Button: Home'), ('msoShapeActionButtonInformation', 'actionButtonInformation', 'Action Button: Information'), ('msoShapeActionButtonMovie', 'actionButtonMovie', 'Action Button: Movie'), ('msoShapeActionButtonReturn', 'actionButtonReturn', 'Action Button: Return'), ('msoShapeActionButtonSound', 'actionButtonSound', 'Action Button: Sound'), ('msoShapeArc', 'arc', 'Arc'), ('msoShapeBalloon', 'wedgeRoundRectCallout', 'Rounded Rectangular Callout'), ('msoShapeBentArrow', 'bentArrow', 'Bent Arrow'), ('msoShapeBentUpArrow', 'bentUpArrow', 'Bent-Up Arrow'), ('msoShapeBevel', 'bevel', 'Bevel'), ('msoShapeBlockArc', 'blockArc', 'Block Arc'), ('msoShapeCan', 'can', 'Can'), ('msoShapeChartPlus', 'chartPlus', 'Chart Plus'), ('msoShapeChartStar', 'chartStar', 'Chart Star'), ('msoShapeChartX', 'chartX', 'Chart X'), ('msoShapeChevron', 'chevron', 'Chevron'), ('msoShapeChord', 'chord', 'Chord'), ('msoShapeCircularArrow', 'circularArrow', 'Circular Arrow'), ('msoShapeCloud', 'cloud', 'Cloud'), ('msoShapeCloudCallout', 'cloudCallout', 'Cloud Callout'), ('msoShapeCorner', 'corner', 'Corner'), ('msoShapeCornerTabs', 'cornerTabs', 'Corner Tabs'), ('msoShapeCross', 'plus', 'Cross'), ('msoShapeCube', 'cube', 'Cube'), ('msoShapeCurvedDownArrow', 'curvedDownArrow', 'Curved Down Arrow'), ('msoShapeCurvedDownRibbon', 'ellipseRibbon', 'Curved Down Ribbon'), ('msoShapeCurvedLeftArrow', 'curvedLeftArrow', 'Curved Left Arrow'), ('msoShapeCurvedRightArrow', 'curvedRightArrow', 'Curved Right Arrow'), ('msoShapeCurvedUpArrow', 'curvedUpArrow', 'Curved Up Arrow'), ('msoShapeCurvedUpRibbon', 'ellipseRibbon2', 'Curved Up Ribbon'), ('msoShapeDecagon', 'decagon', 'Decagon'), ('msoShapeDiagonalStripe', 'diagStripe', 'Diagonal Stripe'), ('msoShapeDiamond', 'diamond', 'Diamond'), ('msoShapeDodecagon', 'dodecagon', 'Dodecagon'), ('msoShapeDonut', 'donut', 'Donut'), ('msoShapeDoubleBrace', 'bracePair', 'Double Brace'), ('msoShapeDoubleBracket', 'bracketPair', 'Double Bracket'), ('msoShapeDoubleWave', 'doubleWave', 'Double Wave'), ('msoShapeDownArrow', 'downArrow', 'Down Arrow'), ('msoShapeDownArrowCallout', 'downArrowCallout', 'Down Arrow Callout'), ('msoShapeDownRibbon', 'ribbon', 'Down Ribbon'), ('msoShapeExplosion1', 'irregularSeal1', 'Explosion'), ('msoShapeExplosion2', 'irregularSeal2', 'Explosion'), ('msoShapeFlowchartAlternateProcess', 'flowChartAlternateProcess', 'Alternate process'), ('msoShapeFlowchartCard', 'flowChartPunchedCard', 'Card'), ('msoShapeFlowchartCollate', 'flowChartCollate', 'Collate'), ('msoShapeFlowchartConnector', 'flowChartConnector', 'Connector'), ('msoShapeFlowchartData', 'flowChartInputOutput', 'Data'), ('msoShapeFlowchartDecision', 'flowChartDecision', 'Decision'), ('msoShapeFlowchartDelay', 'flowChartDelay', 'Delay'), ('msoShapeFlowchartDirectAccessStorage', 'flowChartMagneticDrum', 'Direct Access Storage'), ('msoShapeFlowchartDisplay', 'flowChartDisplay', 'Display'), ('msoShapeFlowchartDocument', 'flowChartDocument', 'Document'), ('msoShapeFlowchartExtract', 'flowChartExtract', 'Extract'), ('msoShapeFlowchartInternalStorage', 'flowChartInternalStorage', 'Internal Storage'), ('msoShapeFlowchartMagneticDisk', 'flowChartMagneticDisk', 'Magnetic Disk'), ('msoShapeFlowchartManualInput', 'flowChartManualInput', 'Manual Input'), ('msoShapeFlowchartManualOperation', 'flowChartManualOperation', 'Manual Operation'), ('msoShapeFlowchartMerge', 'flowChartMerge', 'Merge'), ('msoShapeFlowchartMultidocument', 'flowChartMultidocument', 'Multidocument'), ('msoShapeFlowchartOfflineStorage', 'flowChartOfflineStorage', 'Offline Storage'), ('msoShapeFlowchartOffpageConnector', 'flowChartOffpageConnector', 'Off-page Connector'), ('msoShapeFlowchartOr', 'flowChartOr', 'Or'), ('msoShapeFlowchartPredefinedProcess', 'flowChartPredefinedProcess', 'Predefined Process'), ('msoShapeFlowchartPreparation', 'flowChartPreparation', 'Preparation'), ('msoShapeFlowchartProcess', 'flowChartProcess', 'Process'), ('msoShapeFlowchartPunchedTape', 'flowChartPunchedTape', 'Punched Tape'), ('msoShapeFlowchartSequentialAccessStorage', 'flowChartMagneticTape', 'Sequential Access Storage'), ('msoShapeFlowchartSort', 'flowChartSort', 'Sort'), ('msoShapeFlowchartStoredData', 'flowChartOnlineStorage', 'Stored Data'), ('msoShapeFlowchartSummingJunction', 'flowChartSummingJunction', 'Summing Junction'), ('msoShapeFlowchartTerminator', 'flowChartTerminator', 'Terminator'), ('msoShapeFoldedCorner', 'folderCorner', 'Folded Corner'), ('msoShapeFrame', 'frame', 'Frame'), ('msoShapeFunnel', 'funnel', 'Funnel'), ('msoShapeGear6', 'gear6', 'Gear 6'), ('msoShapeGear9', 'gear9', 'Gear 9'), ('msoShapeHalfFrame', 'halfFrame', 'Half Frame'), ('msoShapeHeart', 'heart', 'Heart'), ('msoShapeHeptagon', 'heptagon', 'Heptagon'), ('msoShapeHexagon', 'hexagon', 'Hexagon'), ('msoShapeHorizontalScroll', 'horizontalScroll', 'Horizontal Scroll'), ('msoShapeIsoscelesTriangle', 'triangle', 'Isosceles Triangle'), ('msoShapeLeftArrow', 'leftArrow', 'Left Arrow'), ('msoShapeLeftArrowCallout', 'leftArrowCallout', 'Left Arrow Callout'), ('msoShapeLeftBrace', 'leftBrace', 'Left Brace'), ('msoShapeLeftBracket', 'leftBracket', 'Left Bracket'), ('msoShapeLeftCircularArrow', 'leftCircularArrow', 'Left Circular Arrow'), ('msoShapeLeftRightArrow', 'leftRightArrow', 'Left-Right Arrow'), ('msoShapeLeftRightArrowCallout', 'leftRightArrowCallout', 'Left-Right Arrow Callout'), ('msoShapeLeftRightCircularArrow', 'leftRightCircularArrow', 'Left Right Circular Arrow'), ('msoShapeLeftRightRibbon', 'leftRightRibbon', 'Left Right Ribbon'), ('msoShapeLeftRightUpArrow', 'leftRightUpArrow', 'Left-Right-Up Arrow'), ('msoShapeLeftUpArrow', 'leftUpArrow', 'Left-Up Arrow'), ('msoShapeLightningBolt', 'lightningBolt', 'Lightning Bolt'), ('msoShapeLineCallout1', 'borderCallout1', 'Line Callout 1'), ('msoShapeLineCallout1AccentBar', 'accentCallout1', 'Line Callout 1 (Accent Bar)'), ('msoShapeLineCallout1BorderandAccentBar', 'accentBorderCallout1', 'Line Callout 1 (Border and Accent Bar)'), ('msoShapeLineCallout1NoBorder', 'callout1', 'Line Callout 1 (No Border)'), ('msoShapeLineCallout2', 'borderCallout2', 'Line Callout 2'), ('msoShapeLineCallout2AccentBar', 'accentCallout2', 'Line Callout 2 (Accent Bar)'), ('msoShapeLineCallout2BorderandAccentBar', 'accentBorderCallout2', 'Line Callout 2 (Border and Accent Bar)'), ('msoShapeLineCallout2NoBorder', 'callout2', 'Line Callout 2 (No Border)'), ('msoShapeLineCallout3', 'borderCallout3', 'Line Callout 3'), ('msoShapeLineCallout3AccentBar', 'accentCallout3', 'Line Callout 3 (Accent Bar)'), ('msoShapeLineCallout3BorderandAccentBar', 'accentBorderCallout3', 'Line Callout 3 (Border and Accent Bar)'), ('msoShapeLineCallout3NoBorder', 'callout3', 'Line Callout 3 (No Border)'), ('msoShapeLineCallout4', 'borderCallout3', 'Line Callout 3'), ('msoShapeLineCallout4AccentBar', 'accentCallout3', 'Line Callout 3 (Accent Bar)'), ('msoShapeLineCallout4BorderandAccentBar', 'accentBorderCallout3', 'Line Callout 3 (Border and Accent Bar)'), ('msoShapeLineCallout4NoBorder', 'callout3', 'Line Callout 3 (No Border)'), ('msoShapeLineInverse', 'lineInv', 'Straight Connector'), ('msoShapeMathDivide', 'mathDivide', 'Division'), ('msoShapeMathEqual', 'mathEqual', 'Equal'), ('msoShapeMathMinus', 'mathMinus', 'Minus'), ('msoShapeMathMultiply', 'mathMultiply', 'Multiply'), ('msoShapeMathNotEqual', 'mathNotEqual', 'Not Equal'), ('msoShapeMathPlus', 'mathPlus', 'Plus'), ('msoShapeMoon', 'moon', 'Moon'), ('msoShapeNoSymbol', 'noSmoking', '"No" symbol'), ('msoShapeNonIsoscelesTrapezoid', 'nonIsoscelesTrapezoid', 'Non-isosceles Trapezoid'), ('msoShapeNotchedRightArrow', 'notchedRightArrow', 'Notched Right Arrow'), ('msoShapeOctagon', 'octagon', 'Octagon'), ('msoShapeOval', 'ellipse', 'Oval'), ('msoShapeOvalCallout', 'wedgeEllipseCallout', 'Oval Callout'), ('msoShapeParallelogram', 'parallelogram', 'Parallelogram'), ('msoShapePentagon', 'homePlate', 'Pentagon'), ('msoShapePie', 'pie', 'Pie'), ('msoShapePieWedge', 'pieWedge', 'Pie'), ('msoShapePlaque', 'plaque', 'Plaque'), ('msoShapePlaqueTabs', 'plaqueTabs', 'Plaque Tabs'), ('msoShapeQuadArrow', 'quadArrow', 'Quad Arrow'), ('msoShapeQuadArrowCallout', 'quadArrowCallout', 'Quad Arrow Callout'), ('msoShapeRectangle', 'rect', 'Rectangle'), ('msoShapeRectangularCallout', 'wedgeRectCallout', 'Rectangular Callout'), ('msoShapeRegularPentagon', 'pentagon', 'Regular Pentagon'), ('msoShapeRightArrow', 'rightArrow', 'Right Arrow'), ('msoShapeRightArrowCallout', 'rightArrowCallout', 'Right Arrow Callout'), ('msoShapeRightBrace', 'rightBrace', 'Right Brace'), ('msoShapeRightBracket', 'rightBracket', 'Right Bracket'), ('msoShapeRightTriangle', 'rtTriangle', 'Right Triangle'), ('msoShapeRound1Rectangle', 'round1Rect', 'Round Single Corner Rectangle'), ('msoShapeRound2DiagRectangle', 'round2DiagRect', 'Round Diagonal Corner Rectangle'), ('msoShapeRound2SameRectangle', 'round2SameRect', 'Round Same Side Corner Rectangle'), ('msoShapeRoundedRectangle', 'roundRect', 'Rounded Rectangle'), ('msoShapeRoundedRectangularCallout', 'wedgeRoundRectCallout', 'Rounded Rectangular Callout'), ('msoShapeSmileyFace', 'smileyFace', 'Smiley Face'), ('msoShapeSnip1Rectangle', 'snip1Rect', 'Snip Single Corner Rectangle'), ('msoShapeSnip2DiagRectangle', 'snip2DiagRect', 'Snip Diagonal Corner Rectangle'), ('msoShapeSnip2SameRectangle', 'snip2SameRect', 'Snip Same Side Corner Rectangle'), ('msoShapeSnipRoundRectangle', 'snipRoundRect', 'Snip and Round Single Corner Rectangle'), ('msoShapeSquareTabs', 'squareTabs', 'Square Tabs'), ('msoShapeStripedRightArrow', 'stripedRightArrow', 'Striped Right Arrow'), ('msoShapeSun', 'sun', 'Sun'), ('msoShapeSwooshArrow', 'swooshArrow', 'Swoosh Arrow'), ('msoShapeTear', 'teardrop', 'Teardrop'), ('msoShapeTrapezoid', 'trapezoid', 'Trapezoid'), ('msoShapeUTurnArrow', 'uturnArrow', 'U-Turn Arrow'), ('msoShapeUpArrow', 'upArrow', 'Up Arrow'), ('msoShapeUpArrowCallout', 'upArrowCallout', 'Up Arrow Callout'), ('msoShapeUpDownArrow', 'upDownArrow', 'Up-Down Arrow'), ('msoShapeUpDownArrowCallout', 'upDownArrowCallout', 'Up-Down Arrow Callout'), ('msoShapeUpRibbon', 'ribbon2', 'Up Ribbon'), ('msoShapeVerticalScroll', 'verticalScroll', 'Vertical Scroll'), ('msoShapeWave', 'wave', 'Wave') )
Sequence of tuples representing the mapping of names in the msoAutoShapeType enumeration to the 'prst' and 'name' values used in the XML to specify and identify that auto shape type. These were discovered using the VBA editor in PowerPoint for Windows. Access with:: for ms_name, prst, base_name in prst_map(): ...
prst_map
python
scanny/python-pptx
spec/gen_spec/src_data/msoAutoShapeType.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/src_data/msoAutoShapeType.py
MIT
def const_name_map(): """ Sequence of tuples representing the mapping of msoAutoShapeType enumeration names to the constant names used in python-pptx to identify an auto shape type. The mapping is largely coercing the camel case to upper snake case, but some names produced by that transformation require transformation to be suitable. Access with:: for ms_name, const_name in const_name_map(): ... """ return ( ('msoShape10PointStar', 'STAR_10_POINT'), ('msoShape12PointStar', 'STAR_12_POINT'), ('msoShape16pointStar', 'STAR_16_POINT'), ('msoShape24pointStar', 'STAR_24_POINT'), ('msoShape32pointStar', 'STAR_32_POINT'), ('msoShape4pointStar', 'STAR_4_POINT'), ('msoShape5pointStar', 'STAR_5_POINT'), ('msoShape6PointStar', 'STAR_6_POINT'), ('msoShape7PointStar', 'STAR_7_POINT'), ('msoShape8pointStar', 'STAR_8_POINT'), ('msoShapeActionButtonBackorPrevious', 'ACTION_BUTTON_BACK_OR_PREVIOUS'), ('msoShapeActionButtonBeginning', 'ACTION_BUTTON_BEGINNING'), ('msoShapeActionButtonCustom', 'ACTION_BUTTON_CUSTOM'), ('msoShapeActionButtonDocument', 'ACTION_BUTTON_DOCUMENT'), ('msoShapeActionButtonEnd', 'ACTION_BUTTON_END'), ('msoShapeActionButtonForwardorNext', 'ACTION_BUTTON_FORWARD_OR_NEXT'), ('msoShapeActionButtonHelp', 'ACTION_BUTTON_HELP'), ('msoShapeActionButtonHome', 'ACTION_BUTTON_HOME'), ('msoShapeActionButtonInformation', 'ACTION_BUTTON_INFORMATION'), ('msoShapeActionButtonMovie', 'ACTION_BUTTON_MOVIE'), ('msoShapeActionButtonReturn', 'ACTION_BUTTON_RETURN'), ('msoShapeActionButtonSound', 'ACTION_BUTTON_SOUND'), ('msoShapeArc', 'ARC'), ('msoShapeBalloon', 'BALLOON'), ('msoShapeBentArrow', 'BENT_ARROW'), ('msoShapeBentUpArrow', 'BENT_UP_ARROW'), ('msoShapeBevel', 'BEVEL'), ('msoShapeBlockArc', 'BLOCK_ARC'), ('msoShapeCan', 'CAN'), ('msoShapeChartPlus', 'CHART_PLUS'), ('msoShapeChartStar', 'CHART_STAR'), ('msoShapeChartX', 'CHART_X'), ('msoShapeChevron', 'CHEVRON'), ('msoShapeChord', 'CHORD'), ('msoShapeCircularArrow', 'CIRCULAR_ARROW'), ('msoShapeCloud', 'CLOUD'), ('msoShapeCloudCallout', 'CLOUD_CALLOUT'), ('msoShapeCorner', 'CORNER'), ('msoShapeCornerTabs', 'CORNER_TABS'), ('msoShapeCross', 'CROSS'), ('msoShapeCube', 'CUBE'), ('msoShapeCurvedDownArrow', 'CURVED_DOWN_ARROW'), ('msoShapeCurvedDownRibbon', 'CURVED_DOWN_RIBBON'), ('msoShapeCurvedLeftArrow', 'CURVED_LEFT_ARROW'), ('msoShapeCurvedRightArrow', 'CURVED_RIGHT_ARROW'), ('msoShapeCurvedUpArrow', 'CURVED_UP_ARROW'), ('msoShapeCurvedUpRibbon', 'CURVED_UP_RIBBON'), ('msoShapeDecagon', 'DECAGON'), ('msoShapeDiagonalStripe', 'DIAGONAL_STRIPE'), ('msoShapeDiamond', 'DIAMOND'), ('msoShapeDodecagon', 'DODECAGON'), ('msoShapeDonut', 'DONUT'), ('msoShapeDoubleBrace', 'DOUBLE_BRACE'), ('msoShapeDoubleBracket', 'DOUBLE_BRACKET'), ('msoShapeDoubleWave', 'DOUBLE_WAVE'), ('msoShapeDownArrow', 'DOWN_ARROW'), ('msoShapeDownArrowCallout', 'DOWN_ARROW_CALLOUT'), ('msoShapeDownRibbon', 'DOWN_RIBBON'), ('msoShapeExplosion1', 'EXPLOSION1'), ('msoShapeExplosion2', 'EXPLOSION2'), ('msoShapeFlowchartAlternateProcess', 'FLOWCHART_ALTERNATE_PROCESS'), ('msoShapeFlowchartCard', 'FLOWCHART_CARD'), ('msoShapeFlowchartCollate', 'FLOWCHART_COLLATE'), ('msoShapeFlowchartConnector', 'FLOWCHART_CONNECTOR'), ('msoShapeFlowchartData', 'FLOWCHART_DATA'), ('msoShapeFlowchartDecision', 'FLOWCHART_DECISION'), ('msoShapeFlowchartDelay', 'FLOWCHART_DELAY'), ('msoShapeFlowchartDirectAccessStorage', 'FLOWCHART_DIRECT_ACCESS_STORAGE'), ('msoShapeFlowchartDisplay', 'FLOWCHART_DISPLAY'), ('msoShapeFlowchartDocument', 'FLOWCHART_DOCUMENT'), ('msoShapeFlowchartExtract', 'FLOWCHART_EXTRACT'), ('msoShapeFlowchartInternalStorage', 'FLOWCHART_INTERNAL_STORAGE'), ('msoShapeFlowchartMagneticDisk', 'FLOWCHART_MAGNETIC_DISK'), ('msoShapeFlowchartManualInput', 'FLOWCHART_MANUAL_INPUT'), ('msoShapeFlowchartManualOperation', 'FLOWCHART_MANUAL_OPERATION'), ('msoShapeFlowchartMerge', 'FLOWCHART_MERGE'), ('msoShapeFlowchartMultidocument', 'FLOWCHART_MULTIDOCUMENT'), ('msoShapeFlowchartOfflineStorage', 'FLOWCHART_OFFLINE_STORAGE'), ('msoShapeFlowchartOffpageConnector', 'FLOWCHART_OFFPAGE_CONNECTOR'), ('msoShapeFlowchartOr', 'FLOWCHART_OR'), ('msoShapeFlowchartPredefinedProcess', 'FLOWCHART_PREDEFINED_PROCESS'), ('msoShapeFlowchartPreparation', 'FLOWCHART_PREPARATION'), ('msoShapeFlowchartProcess', 'FLOWCHART_PROCESS'), ('msoShapeFlowchartPunchedTape', 'FLOWCHART_PUNCHED_TAPE'), ('msoShapeFlowchartSequentialAccessStorage', 'FLOWCHART_SEQUENTIAL_ACCESS_STORAGE'), ('msoShapeFlowchartSort', 'FLOWCHART_SORT'), ('msoShapeFlowchartStoredData', 'FLOWCHART_STORED_DATA'), ('msoShapeFlowchartSummingJunction', 'FLOWCHART_SUMMING_JUNCTION'), ('msoShapeFlowchartTerminator', 'FLOWCHART_TERMINATOR'), ('msoShapeFoldedCorner', 'FOLDED_CORNER'), ('msoShapeFrame', 'FRAME'), ('msoShapeFunnel', 'FUNNEL'), ('msoShapeGear6', 'GEAR_6'), ('msoShapeGear9', 'GEAR_9'), ('msoShapeHalfFrame', 'HALF_FRAME'), ('msoShapeHeart', 'HEART'), ('msoShapeHeptagon', 'HEPTAGON'), ('msoShapeHexagon', 'HEXAGON'), ('msoShapeHorizontalScroll', 'HORIZONTAL_SCROLL'), ('msoShapeIsoscelesTriangle', 'ISOSCELES_TRIANGLE'), ('msoShapeLeftArrow', 'LEFT_ARROW'), ('msoShapeLeftArrowCallout', 'LEFT_ARROW_CALLOUT'), ('msoShapeLeftBrace', 'LEFT_BRACE'), ('msoShapeLeftBracket', 'LEFT_BRACKET'), ('msoShapeLeftCircularArrow', 'LEFT_CIRCULAR_ARROW'), ('msoShapeLeftRightArrow', 'LEFT_RIGHT_ARROW'), ('msoShapeLeftRightArrowCallout', 'LEFT_RIGHT_ARROW_CALLOUT'), ('msoShapeLeftRightCircularArrow', 'LEFT_RIGHT_CIRCULAR_ARROW'), ('msoShapeLeftRightRibbon', 'LEFT_RIGHT_RIBBON'), ('msoShapeLeftRightUpArrow', 'LEFT_RIGHT_UP_ARROW'), ('msoShapeLeftUpArrow', 'LEFT_UP_ARROW'), ('msoShapeLightningBolt', 'LIGHTNING_BOLT'), ('msoShapeLineCallout1', 'LINE_CALLOUT_1'), ('msoShapeLineCallout1AccentBar', 'LINE_CALLOUT_1_ACCENT_BAR'), ('msoShapeLineCallout1BorderandAccentBar', 'LINE_CALLOUT_1_BORDER_AND_ACCENT_BAR'), ('msoShapeLineCallout1NoBorder', 'LINE_CALLOUT_1_NO_BORDER'), ('msoShapeLineCallout2', 'LINE_CALLOUT_2'), ('msoShapeLineCallout2AccentBar', 'LINE_CALLOUT_2_ACCENT_BAR'), ('msoShapeLineCallout2BorderandAccentBar', 'LINE_CALLOUT_2_BORDER_AND_ACCENT_BAR'), ('msoShapeLineCallout2NoBorder', 'LINE_CALLOUT_2_NO_BORDER'), ('msoShapeLineCallout3', 'LINE_CALLOUT_3'), ('msoShapeLineCallout3AccentBar', 'LINE_CALLOUT_3_ACCENT_BAR'), ('msoShapeLineCallout3BorderandAccentBar', 'LINE_CALLOUT_3_BORDER_AND_ACCENT_BAR'), ('msoShapeLineCallout3NoBorder', 'LINE_CALLOUT_3_NO_BORDER'), ('msoShapeLineCallout4', 'LINE_CALLOUT_4'), ('msoShapeLineCallout4AccentBar', 'LINE_CALLOUT_4_ACCENT_BAR'), ('msoShapeLineCallout4BorderandAccentBar', 'LINE_CALLOUT_4_BORDER_AND_ACCENT_BAR'), ('msoShapeLineCallout4NoBorder', 'LINE_CALLOUT_4_NO_BORDER'), ('msoShapeLineInverse', 'LINE_INVERSE'), ('msoShapeMathDivide', 'MATH_DIVIDE'), ('msoShapeMathEqual', 'MATH_EQUAL'), ('msoShapeMathMinus', 'MATH_MINUS'), ('msoShapeMathMultiply', 'MATH_MULTIPLY'), ('msoShapeMathNotEqual', 'MATH_NOT_EQUAL'), ('msoShapeMathPlus', 'MATH_PLUS'), ('msoShapeMoon', 'MOON'), ('msoShapeNoSymbol', 'NO_SYMBOL'), ('msoShapeNonIsoscelesTrapezoid', 'NON_ISOSCELES_TRAPEZOID'), ('msoShapeNotchedRightArrow', 'NOTCHED_RIGHT_ARROW'), ('msoShapeOctagon', 'OCTAGON'), ('msoShapeOval', 'OVAL'), ('msoShapeOvalCallout', 'OVAL_CALLOUT'), ('msoShapeParallelogram', 'PARALLELOGRAM'), ('msoShapePentagon', 'PENTAGON'), ('msoShapePie', 'PIE'), ('msoShapePieWedge', 'PIE_WEDGE'), ('msoShapePlaque', 'PLAQUE'), ('msoShapePlaqueTabs', 'PLAQUE_TABS'), ('msoShapeQuadArrow', 'QUAD_ARROW'), ('msoShapeQuadArrowCallout', 'QUAD_ARROW_CALLOUT'), ('msoShapeRectangle', 'RECTANGLE'), ('msoShapeRectangularCallout', 'RECTANGULAR_CALLOUT'), ('msoShapeRegularPentagon', 'REGULAR_PENTAGON'), ('msoShapeRightArrow', 'RIGHT_ARROW'), ('msoShapeRightArrowCallout', 'RIGHT_ARROW_CALLOUT'), ('msoShapeRightBrace', 'RIGHT_BRACE'), ('msoShapeRightBracket', 'RIGHT_BRACKET'), ('msoShapeRightTriangle', 'RIGHT_TRIANGLE'), ('msoShapeRound1Rectangle', 'ROUND_1_RECTANGLE'), ('msoShapeRound2DiagRectangle', 'ROUND_2_DIAG_RECTANGLE'), ('msoShapeRound2SameRectangle', 'ROUND_2_SAME_RECTANGLE'), ('msoShapeRoundedRectangle', 'ROUNDED_RECTANGLE'), ('msoShapeRoundedRectangularCallout', 'ROUNDED_RECTANGULAR_CALLOUT'), ('msoShapeSmileyFace', 'SMILEY_FACE'), ('msoShapeSnip1Rectangle', 'SNIP_1_RECTANGLE'), ('msoShapeSnip2DiagRectangle', 'SNIP_2_DIAG_RECTANGLE'), ('msoShapeSnip2SameRectangle', 'SNIP_2_SAME_RECTANGLE'), ('msoShapeSnipRoundRectangle', 'SNIP_ROUND_RECTANGLE'), ('msoShapeSquareTabs', 'SQUARE_TABS'), ('msoShapeStripedRightArrow', 'STRIPED_RIGHT_ARROW'), ('msoShapeSun', 'SUN'), ('msoShapeSwooshArrow', 'SWOOSH_ARROW'), ('msoShapeTear', 'TEAR'), ('msoShapeTrapezoid', 'TRAPEZOID'), ('msoShapeUTurnArrow', 'U_TURN_ARROW'), ('msoShapeUpArrow', 'UP_ARROW'), ('msoShapeUpArrowCallout', 'UP_ARROW_CALLOUT'), ('msoShapeUpDownArrow', 'UP_DOWN_ARROW'), ('msoShapeUpDownArrowCallout', 'UP_DOWN_ARROW_CALLOUT'), ('msoShapeUpRibbon', 'UP_RIBBON'), ('msoShapeVerticalScroll', 'VERTICAL_SCROLL'), ('msoShapeWave', 'WAVE') )
Sequence of tuples representing the mapping of msoAutoShapeType enumeration names to the constant names used in python-pptx to identify an auto shape type. The mapping is largely coercing the camel case to upper snake case, but some names produced by that transformation require transformation to be suitable. Access with:: for ms_name, const_name in const_name_map(): ...
const_name_map
python
scanny/python-pptx
spec/gen_spec/src_data/msoAutoShapeType.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/src_data/msoAutoShapeType.py
MIT
def action(self): """Member of :ref:`PpActionType` enumeration, such as `PP_ACTION.HYPERLINK`. The returned member indicates the type of action that will result when the specified shape or text is clicked or the mouse pointer is positioned over the shape during a slide show. If there is no click-action or the click-action value is not recognized (is not one of the official `MsoPpAction` values) then `PP_ACTION.NONE` is returned. """ hlink = self._hlink if hlink is None: return PP_ACTION.NONE action_verb = hlink.action_verb if action_verb == "hlinkshowjump": relative_target = hlink.action_fields["jump"] return { "firstslide": PP_ACTION.FIRST_SLIDE, "lastslide": PP_ACTION.LAST_SLIDE, "lastslideviewed": PP_ACTION.LAST_SLIDE_VIEWED, "nextslide": PP_ACTION.NEXT_SLIDE, "previousslide": PP_ACTION.PREVIOUS_SLIDE, "endshow": PP_ACTION.END_SHOW, }[relative_target] return { None: PP_ACTION.HYPERLINK, "hlinksldjump": PP_ACTION.NAMED_SLIDE, "hlinkpres": PP_ACTION.PLAY, "hlinkfile": PP_ACTION.OPEN_FILE, "customshow": PP_ACTION.NAMED_SLIDE_SHOW, "ole": PP_ACTION.OLE_VERB, "macro": PP_ACTION.RUN_MACRO, "program": PP_ACTION.RUN_PROGRAM, }.get(action_verb, PP_ACTION.NONE)
Member of :ref:`PpActionType` enumeration, such as `PP_ACTION.HYPERLINK`. The returned member indicates the type of action that will result when the specified shape or text is clicked or the mouse pointer is positioned over the shape during a slide show. If there is no click-action or the click-action value is not recognized (is not one of the official `MsoPpAction` values) then `PP_ACTION.NONE` is returned.
action
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def target_slide(self) -> Slide | None: """ A reference to the slide in this presentation that is the target of the slide jump action in this shape. Slide jump actions include `PP_ACTION.FIRST_SLIDE`, `LAST_SLIDE`, `NEXT_SLIDE`, `PREVIOUS_SLIDE`, and `NAMED_SLIDE`. Returns |None| for all other actions. In particular, the `LAST_SLIDE_VIEWED` action and the `PLAY` (start other presentation) actions are not supported. A slide object may be assigned to this property, which makes the shape an "internal hyperlink" to the assigened slide:: slide, target_slide = prs.slides[0], prs.slides[1] shape = slide.shapes[0] shape.target_slide = target_slide Assigning |None| removes any slide jump action. Note that this is accomplished by removing any action present (such as a hyperlink), without first checking that it is a slide jump action. """ slide_jump_actions = ( PP_ACTION.FIRST_SLIDE, PP_ACTION.LAST_SLIDE, PP_ACTION.NEXT_SLIDE, PP_ACTION.PREVIOUS_SLIDE, PP_ACTION.NAMED_SLIDE, ) if self.action not in slide_jump_actions: return None if self.action == PP_ACTION.FIRST_SLIDE: return self._slides[0] elif self.action == PP_ACTION.LAST_SLIDE: return self._slides[-1] elif self.action == PP_ACTION.NEXT_SLIDE: next_slide_idx = self._slide_index + 1 if next_slide_idx >= len(self._slides): raise ValueError("no next slide") return self._slides[next_slide_idx] elif self.action == PP_ACTION.PREVIOUS_SLIDE: prev_slide_idx = self._slide_index - 1 if prev_slide_idx < 0: raise ValueError("no previous slide") return self._slides[prev_slide_idx] elif self.action == PP_ACTION.NAMED_SLIDE: assert self._hlink is not None rId = self._hlink.rId slide_part = cast("SlidePart", self.part.related_part(rId)) return slide_part.slide
A reference to the slide in this presentation that is the target of the slide jump action in this shape. Slide jump actions include `PP_ACTION.FIRST_SLIDE`, `LAST_SLIDE`, `NEXT_SLIDE`, `PREVIOUS_SLIDE`, and `NAMED_SLIDE`. Returns |None| for all other actions. In particular, the `LAST_SLIDE_VIEWED` action and the `PLAY` (start other presentation) actions are not supported. A slide object may be assigned to this property, which makes the shape an "internal hyperlink" to the assigened slide:: slide, target_slide = prs.slides[0], prs.slides[1] shape = slide.shapes[0] shape.target_slide = target_slide Assigning |None| removes any slide jump action. Note that this is accomplished by removing any action present (such as a hyperlink), without first checking that it is a slide jump action.
target_slide
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def _hlink(self) -> CT_Hyperlink | None: """ Reference to the `a:hlinkClick` or `a:hlinkHover` element for this click action. Returns |None| if the element is not present. """ if self._hover: assert isinstance(self._element, CT_NonVisualDrawingProps) return self._element.hlinkHover return self._element.hlinkClick
Reference to the `a:hlinkClick` or `a:hlinkHover` element for this click action. Returns |None| if the element is not present.
_hlink
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def address(self) -> str | None: """Read/write. The URL of the hyperlink. URL can be on http, https, mailto, or file scheme; others may work. Returns |None| if no hyperlink is defined, including when another action such as `RUN_MACRO` is defined on the object. Assigning |None| removes any action defined on the object, whether it is a hyperlink action or not. """ hlink = self._hlink # there's no URL if there's no click action if hlink is None: return None # a click action without a relationship has no URL rId = hlink.rId if not rId: return None return self.part.target_ref(rId)
Read/write. The URL of the hyperlink. URL can be on http, https, mailto, or file scheme; others may work. Returns |None| if no hyperlink is defined, including when another action such as `RUN_MACRO` is defined on the object. Assigning |None| removes any action defined on the object, whether it is a hyperlink action or not.
address
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def _get_or_add_hlink(self) -> CT_Hyperlink: """Get the `a:hlinkClick` or `a:hlinkHover` element for the Hyperlink object. The actual element depends on the value of `self._hover`. Create the element if not present. """ if self._hover: return cast("CT_NonVisualDrawingProps", self._element).get_or_add_hlinkHover() return self._element.get_or_add_hlinkClick()
Get the `a:hlinkClick` or `a:hlinkHover` element for the Hyperlink object. The actual element depends on the value of `self._hover`. Create the element if not present.
_get_or_add_hlink
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def _hlink(self) -> CT_Hyperlink | None: """Reference to the `a:hlinkClick` or `h:hlinkHover` element for this click action. Returns |None| if the element is not present. """ if self._hover: return cast("CT_NonVisualDrawingProps", self._element).hlinkHover return self._element.hlinkClick
Reference to the `a:hlinkClick` or `h:hlinkHover` element for this click action. Returns |None| if the element is not present.
_hlink
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def _remove_hlink(self): """Remove the a:hlinkClick or a:hlinkHover element. Also drops any relationship it might have. """ hlink = self._hlink if hlink is None: return rId = hlink.rId if rId: self.part.drop_rel(rId) self._element.remove(hlink)
Remove the a:hlinkClick or a:hlinkHover element. Also drops any relationship it might have.
_remove_hlink
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def Presentation(pptx: str | IO[bytes] | None = None) -> presentation.Presentation: """ Return a |Presentation| object loaded from *pptx*, where *pptx* can be either a path to a ``.pptx`` file (a string) or a file-like object. If *pptx* is missing or ``None``, the built-in default presentation "template" is loaded. """ if pptx is None: pptx = _default_pptx_path() presentation_part = Package.open(pptx).main_document_part if not _is_pptx_package(presentation_part): tmpl = "file '%s' is not a PowerPoint file, content type is '%s'" raise ValueError(tmpl % (pptx, presentation_part.content_type)) return presentation_part.presentation
Return a |Presentation| object loaded from *pptx*, where *pptx* can be either a path to a ``.pptx`` file (a string) or a file-like object. If *pptx* is missing or ``None``, the built-in default presentation "template" is loaded.
Presentation
python
scanny/python-pptx
src/pptx/api.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/api.py
MIT
def _default_pptx_path() -> str: """Return the path to the built-in default .pptx package.""" _thisdir = os.path.split(__file__)[0] return os.path.join(_thisdir, "templates", "default.pptx")
Return the path to the built-in default .pptx package.
_default_pptx_path
python
scanny/python-pptx
src/pptx/api.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/api.py
MIT
def _is_pptx_package(prs_part: PresentationPart): """Return |True| if *prs_part* is a valid main document part, |False| otherwise.""" valid_content_types = (CT.PML_PRESENTATION_MAIN, CT.PML_PRES_MACRO_MAIN) return prs_part.content_type in valid_content_types
Return |True| if *prs_part* is a valid main document part, |False| otherwise.
_is_pptx_package
python
scanny/python-pptx
src/pptx/api.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/api.py
MIT
def from_path_or_file_like(cls, movie_file: str | IO[bytes], mime_type: str | None) -> Video: """Return a new |Video| object containing video in *movie_file*. *movie_file* can be either a path (string) or a file-like (e.g. StringIO) object. """ if isinstance(movie_file, str): # treat movie_file as a path with open(movie_file, "rb") as f: blob = f.read() filename = os.path.basename(movie_file) else: # assume movie_file is a file-like object blob = movie_file.read() filename = None return cls.from_blob(blob, mime_type, filename)
Return a new |Video| object containing video in *movie_file*. *movie_file* can be either a path (string) or a file-like (e.g. StringIO) object.
from_path_or_file_like
python
scanny/python-pptx
src/pptx/media.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/media.py
MIT
def ext(self): """Return the file extension for this video, e.g. 'mp4'. The extension is that from the actual filename if known. Otherwise it is the lowercase canonical extension for the video's MIME type. 'vid' is used if the MIME type is 'video/unknown'. """ if self._filename: return os.path.splitext(self._filename)[1].lstrip(".") return { CT.ASF: "asf", CT.AVI: "avi", CT.MOV: "mov", CT.MP4: "mp4", CT.MPG: "mpg", CT.MS_VIDEO: "avi", CT.SWF: "swf", CT.WMV: "wmv", CT.X_MS_VIDEO: "avi", }.get(self._mime_type, "vid")
Return the file extension for this video, e.g. 'mp4'. The extension is that from the actual filename if known. Otherwise it is the lowercase canonical extension for the video's MIME type. 'vid' is used if the MIME type is 'video/unknown'.
ext
python
scanny/python-pptx
src/pptx/media.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/media.py
MIT
def filename(self) -> str: """Return a filename.ext string appropriate to this video. The base filename from the original path is used if this image was loaded from the filesystem. If no filename is available, such as when the video object is created from an in-memory stream, the string 'movie.{ext}' is used where 'ext' is suitable to the video format, such as 'mp4'. """ if self._filename is not None: return self._filename return "movie.%s" % self.ext
Return a filename.ext string appropriate to this video. The base filename from the original path is used if this image was loaded from the filesystem. If no filename is available, such as when the video object is created from an in-memory stream, the string 'movie.{ext}' is used where 'ext' is suitable to the video format, such as 'mp4'.
filename
python
scanny/python-pptx
src/pptx/media.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/media.py
MIT
def core_properties(self) -> CorePropertiesPart: """Instance of |CoreProperties| holding read/write Dublin Core doc properties. Creates a default core properties part if one is not present (not common). """ try: return self.part_related_by(RT.CORE_PROPERTIES) except KeyError: core_props = CorePropertiesPart.default(self) self.relate_to(core_props, RT.CORE_PROPERTIES) return core_props
Instance of |CoreProperties| holding read/write Dublin Core doc properties. Creates a default core properties part if one is not present (not common).
core_properties
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def next_image_partname(self, ext: str) -> PackURI: """Return a |PackURI| instance representing the next available image partname. Partname uses the next available sequence number. *ext* is used as the extention on the returned partname. """ def first_available_image_idx(): image_idxs = sorted( [ part.partname.idx for part in self.iter_parts() if ( part.partname.startswith("/ppt/media/image") and part.partname.idx is not None ) ] ) for i, image_idx in enumerate(image_idxs): idx = i + 1 if idx < image_idx: return idx return len(image_idxs) + 1 idx = first_available_image_idx() return PackURI("/ppt/media/image%d.%s" % (idx, ext))
Return a |PackURI| instance representing the next available image partname. Partname uses the next available sequence number. *ext* is used as the extention on the returned partname.
next_image_partname
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def next_media_partname(self, ext): """Return |PackURI| instance for next available media partname. Partname is first available, starting at sequence number 1. Empty sequence numbers are reused. *ext* is used as the extension on the returned partname. """ def first_available_media_idx(): media_idxs = sorted( [ part.partname.idx for part in self.iter_parts() if part.partname.startswith("/ppt/media/media") ] ) for i, media_idx in enumerate(media_idxs): idx = i + 1 if idx < media_idx: return idx return len(media_idxs) + 1 idx = first_available_media_idx() return PackURI("/ppt/media/media%d.%s" % (idx, ext))
Return |PackURI| instance for next available media partname. Partname is first available, starting at sequence number 1. Empty sequence numbers are reused. *ext* is used as the extension on the returned partname.
next_media_partname
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def __iter__(self) -> Iterator[ImagePart]: """Generate a reference to each |ImagePart| object in the package.""" image_parts = [] for rel in self._package.iter_rels(): if rel.is_external: continue if rel.reltype != RT.IMAGE: continue image_part = rel.target_part if image_part in image_parts: continue image_parts.append(image_part) yield image_part
Generate a reference to each |ImagePart| object in the package.
__iter__
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def get_or_add_image_part(self, image_file: str | IO[bytes]) -> ImagePart: """Return |ImagePart| object containing the image in `image_file`. `image_file` can be either a path to an image file or a file-like object containing an image. If an image part containing this same image already exists, that instance is returned, otherwise a new image part is created. """ image = Image.from_file(image_file) image_part = self._find_by_sha1(image.sha1) return image_part if image_part else ImagePart.new(self._package, image)
Return |ImagePart| object containing the image in `image_file`. `image_file` can be either a path to an image file or a file-like object containing an image. If an image part containing this same image already exists, that instance is returned, otherwise a new image part is created.
get_or_add_image_part
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def _find_by_sha1(self, sha1: str) -> ImagePart | None: """ Return an |ImagePart| object belonging to this package or |None| if no matching image part is found. The image part is identified by the SHA1 hash digest of the image binary it contains. """ for image_part in self: # ---skip unknown/unsupported image types, like SVG--- if not hasattr(image_part, "sha1"): continue if image_part.sha1 == sha1: return image_part return None
Return an |ImagePart| object belonging to this package or |None| if no matching image part is found. The image part is identified by the SHA1 hash digest of the image binary it contains.
_find_by_sha1
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def __iter__(self): """Generate a reference to each |MediaPart| object in the package.""" # A media part can appear in more than one relationship (and commonly # does in the case of video). Use media_parts to keep track of those # that have been "yielded"; they can be skipped if they occur again. media_parts = [] for rel in self._package.iter_rels(): if rel.is_external: continue if rel.reltype not in (RT.MEDIA, RT.VIDEO): continue media_part = rel.target_part if media_part in media_parts: continue media_parts.append(media_part) yield media_part
Generate a reference to each |MediaPart| object in the package.
__iter__
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def get_or_add_media_part(self, media): """Return a |MediaPart| object containing the media in *media*. If this package already contains a media part for the same bytestream, that instance is returned, otherwise a new media part is created. """ media_part = self._find_by_sha1(media.sha1) if media_part is None: media_part = MediaPart.new(self._package, media) return media_part
Return a |MediaPart| object containing the media in *media*. If this package already contains a media part for the same bytestream, that instance is returned, otherwise a new media part is created.
get_or_add_media_part
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def _find_by_sha1(self, sha1): """Return |MediaPart| object having *sha1* hash or None if not found. All media parts belonging to this package are considered. A media part is identified by the SHA1 hash digest of its bytestream ("file"). """ for media_part in self: if media_part.sha1 == sha1: return media_part return None
Return |MediaPart| object having *sha1* hash or None if not found. All media parts belonging to this package are considered. A media part is identified by the SHA1 hash digest of its bytestream ("file").
_find_by_sha1
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def slide_height(self) -> Length | None: """Height of slides in this presentation, in English Metric Units (EMU). Returns |None| if no slide width is defined. Read/write. """ sldSz = self._element.sldSz if sldSz is None: return None return sldSz.cy
Height of slides in this presentation, in English Metric Units (EMU). Returns |None| if no slide width is defined. Read/write.
slide_height
python
scanny/python-pptx
src/pptx/presentation.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/presentation.py
MIT