id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,288,500 | fnparser.py | zimolab_PyGUIAdapter/pyguiadapter/parser/fnparser.py | import dataclasses
import inspect
import warnings
from collections import OrderedDict
from typing import Callable, Literal, List, Tuple, Set, Dict, Any, Type, Union, Optional
import tomli
from .docstring import FnDocstring
from .typenames import get_typename, get_type_args
from .. import utils
from ..fn import FnInfo, ParameterInfo
from ..utils import IconType
PARAM_WIDGET_METADATA_START = ("@widgets", "@parameters", "@params")
PARAM_WIDGET_METADATA_END = "@end"
class _Unset(object):
pass
UNSET = _Unset
@dataclasses.dataclass
class WidgetMeta(object):
widget_class: Union[str, None, UNSET] = UNSET
default_value: Union[Any, UNSET] = UNSET
label: Union[str, None, UNSET] = UNSET
description: Union[str, None, UNSET] = UNSET
default_value_description: Union[str, None, UNSET] = UNSET
stylesheet: Union[str, None, UNSET] = UNSET
custom_configs: Union[Dict[str, Any], UNSET] = UNSET
def to_config_dict(self) -> Dict[str, Any]:
config_dict = dataclasses.asdict(self)
custom_configs = config_dict.pop("custom_configs", None)
if not isinstance(custom_configs, dict):
custom_configs = OrderedDict()
config_dict.update(**custom_configs)
config_dict = {k: v for k, v in config_dict.items() if v is not UNSET}
return config_dict
class FnParser(object):
def __init__(
self,
widget_metadata_start: Union[
str, List[str], Tuple[str], Set[str]
] = PARAM_WIDGET_METADATA_START,
widget_metadata_end: Union[
str, List[str], Tuple[str], Set[str]
] = PARAM_WIDGET_METADATA_END,
):
self._widget_metadata_start: Union[str, List[str], Tuple[str], Set[str]] = (
widget_metadata_start
)
self._widget_metadata_end: Union[str, List[str], Tuple[str], Set[str]] = (
widget_metadata_end
)
def parse_fn_info(
self,
fn: Callable,
display_name: Optional[str] = None,
document: Optional[str] = None,
document_format: Literal["markdown", "html", "plaintext"] = "markdown",
icon: IconType = None,
group: Optional[str] = None,
ignore_self_param: bool = True,
) -> FnInfo:
if not inspect.ismethod(fn) and not inspect.isfunction(fn):
raise ValueError("fn must be a function or method")
doc = fn.__doc__ or ""
fn_docstring_text = utils.remove_text_block(
doc, self._widget_metadata_start, self._widget_metadata_end
)
fn_docstring = FnDocstring(fn_docstring_text)
if not display_name:
display_name = fn.__name__
if not document:
# desc = fn_docstring.get_short_description() or ""
# desc += "\n\n" + (fn_docstring.get_long_description() or "")
short_desc = fn_docstring.get_short_description() or ""
long_desc = fn_docstring.get_long_description() or ""
document = (short_desc + "\n\n" + long_desc).strip() or fn_docstring_text
return FnInfo(
fn=fn,
display_name=display_name,
document=document,
document_format=document_format,
icon=icon,
group=group,
parameters=self._parse_fn_params(fn, fn_docstring, ignore_self_param),
)
def parse_widget_configs(
self, fn_info: FnInfo
) -> Dict[str, Tuple[Optional[str], dict]]:
# this method returns a dict of "parameter_name" -> (widget_class_name| None, widget_config)
configs = OrderedDict()
metas = self._parse_widget_meta(fn_info)
for param_name, param_info in fn_info.parameters.items():
widget_config = OrderedDict(
{
"default_value": param_info.default_value,
# "group": None,
"label": param_name,
"description": param_info.description,
# "default_value_description": None,
# "stylesheet": None,
}
)
if widget_config["default_value"] is UNSET:
widget_config.pop("default_value")
widget_class = None
meta = metas.get(param_name, None)
if meta is not None:
meta_config_dict = meta.to_config_dict()
widget_class = meta_config_dict.pop("widget_class", None)
widget_config.update(**meta_config_dict)
configs[param_name] = (widget_class, widget_config)
return configs
def _parse_widget_meta(self, fn_info: FnInfo) -> Dict[str, WidgetMeta]:
fn = fn_info.fn
meta_text = utils.extract_text_block(
fn.__doc__ or "", self._widget_metadata_start, self._widget_metadata_end
)
if meta_text is None:
return OrderedDict()
meta_text = meta_text.strip()
try:
metadata = tomli.loads(meta_text)
if not isinstance(metadata, dict):
raise ValueError("invalid widget configs text")
except Exception as e:
warnings.warn(f"failed to parse widget configs in docstring: {e}")
return OrderedDict()
meta = OrderedDict()
for param_name, widget_configs in metadata.items():
if not isinstance(widget_configs, dict):
continue
param_info: Optional[ParameterInfo] = fn_info.parameters.get(
param_name, None
)
widget_config_meta = WidgetMeta()
key_widget_class = "widget_class"
conf_widget_class = widget_configs.pop(key_widget_class, None)
if conf_widget_class:
widget_config_meta.widget_class = conf_widget_class
else:
widget_config_meta.widget_class = UNSET
key_default_value = "default_value"
conf_default_value = widget_configs.pop(key_default_value, None)
if conf_default_value is not None:
widget_config_meta.default_value = conf_default_value
elif param_info is not None:
widget_config_meta.default_value = param_info.default_value
else:
widget_config_meta.default_value = UNSET
key_label = "label"
conf_label = widget_configs.pop(key_label, None)
if conf_label is not None:
widget_config_meta.label = str(conf_label)
elif param_info is not None:
widget_config_meta.label = param_name
else:
widget_config_meta.label = UNSET
key_description = "description"
conf_description = widget_configs.pop(key_description, None)
if conf_description is not None:
widget_config_meta.description = str(conf_description)
elif param_info is not None:
widget_config_meta.description = str(param_info.description or "")
else:
widget_config_meta.description = UNSET
key_default_value_description = "default_value_description"
conf_default_value_description = widget_configs.pop(
key_default_value_description, None
)
if conf_default_value_description is not None:
widget_config_meta.default_value_description = str(
conf_default_value_description
)
else:
widget_config_meta.default_value_description = UNSET
key_stylesheet = "stylesheet"
conf_stylesheet = widget_configs.pop(key_stylesheet, None)
if conf_stylesheet is not None:
widget_config_meta.stylesheet = str(conf_stylesheet)
else:
widget_config_meta.stylesheet = UNSET
if len(widget_configs) > 0:
widget_config_meta.custom_configs = {**widget_configs}
meta[param_name] = widget_config_meta
return meta
def _parse_fn_params(
self, fn: Callable, fn_docstring: FnDocstring, ignore_self_param: bool
) -> Dict[str, ParameterInfo]:
params = OrderedDict()
fn_signature = inspect.signature(fn)
for param_name, param in fn_signature.parameters.items():
if param_name in params:
raise ValueError(f"duplicate parameter name: {param_name}")
if ignore_self_param and param_name == "self":
continue
default_value = self._get_param_default_value(param, fn_docstring)
typ, typename, type_args = self._get_param_type_info(
param, default_value, fn_docstring
)
description = fn_docstring.get_parameter_description(param.name) or ""
params[param_name] = ParameterInfo(
type=typ,
typename=typename,
type_args=type_args,
default_value=default_value,
description=description,
)
return params
def _get_param_type_info(
self, param: inspect.Parameter, default_value: Any, fn_docstring: FnDocstring
) -> (Type, str, List[Any]):
param_typename = None
param_type_args = None
if param.kind == inspect.Parameter.POSITIONAL_ONLY:
raise RuntimeError(
f"positional only parameters are not supported: {param.name}"
)
elif param.kind == inspect.Parameter.VAR_POSITIONAL:
param_type = list
param_type_args = []
elif param.kind == inspect.Parameter.VAR_KEYWORD:
param_type = dict
param_type_args = []
elif self._has_type_annotation(param):
param_type = param.annotation
else:
_param_type_in_docstring = fn_docstring.get_parameter_typename(param.name)
if _param_type_in_docstring is not None:
param_typename = _param_type_in_docstring
param_type = None
else:
param_type = self._guess_param_type(default_value)
param_type_args = []
if param_typename is None:
param_typename = get_typename(param_type)
if param_type_args is None:
param_type_args = get_type_args(param_type)
return param_type, param_typename, param_type_args
@staticmethod
def _get_param_default_value(
param: inspect.Parameter, fn_docstring: FnDocstring
) -> Any:
if param.default is UNSET:
return UNSET
if param.default is not inspect.Parameter.empty:
return param.default
default_value = fn_docstring.get_parameter_default_value(param.name)
if default_value is not None:
return default_value
return UNSET
@staticmethod
def _guess_param_type(default_value: Any) -> Type:
if default_value is None or default_value is UNSET:
return Any
if isinstance(default_value, type):
return default_value
return type(default_value)
@staticmethod
def _has_type_annotation(param: inspect.Parameter) -> bool:
if (
param.annotation is not None
and param.annotation is not inspect.Parameter.empty
):
return True
return False
| 11,439 | Python | .py | 263 | 32.292776 | 100 | 0.594876 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,501 | docstring.py | zimolab_PyGUIAdapter/pyguiadapter/parser/docstring.py | from typing import Optional
import docstring_parser
class FnDocstring(object):
def __init__(self, fn_docstring: str):
self._fn_docstring: str = fn_docstring
try:
self._docstring = docstring_parser.parse(fn_docstring)
except docstring_parser.ParseError:
self._docstring = None
def has_parameter(self, parameter_name: str) -> bool:
if self._docstring is None:
return False
return self._find_parameter(parameter_name) is not None
def get_short_description(self) -> Optional[str]:
if self._docstring is None:
return None
return self._docstring.short_description
def get_long_description(self) -> Optional[str]:
if self._docstring is None:
return None
return self._docstring.long_description
def get_parameter_description(self, parameter_name: str) -> Optional[str]:
docstring_param = self._find_parameter(parameter_name)
if docstring_param is None:
return None
return docstring_param.description.strip()
def get_parameter_default_value(self, parameter_name: str) -> Optional[str]:
docstring_param = self._find_parameter(parameter_name)
if docstring_param is None:
return None
return docstring_param.default
def get_parameter_typename(self, parameter_name: str) -> Optional[str]:
docstring_param = self._find_parameter(parameter_name)
if docstring_param is None:
return None
return docstring_param.type_name
def _find_parameter(
self, parameter_name: str
) -> Optional[docstring_parser.DocstringParam]:
if self._docstring is None:
return None
for param in self._docstring.params:
if param.arg_name == parameter_name:
return param
return None
| 1,897 | Python | .py | 45 | 33.155556 | 80 | 0.654891 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,502 | io.py | zimolab_PyGUIAdapter/pyguiadapter/utils/io.py | """
@Time : 2024.10.20
@File : io.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 读写文件相关的工具函数
"""
def read_text_file(text_file: str, encoding: str = "utf-8") -> str:
"""
读取文本文件内容。
Args:
text_file: 文件路径
encoding: 文件编码,默认utf-8
Returns:
返回文件内容。
"""
with open(text_file, "r", encoding=encoding) as f:
return f.read()
def write_text_file(text_file: str, content: str, encoding: str = "utf-8") -> None:
"""
写入文本文件内容。
Args:
text_file: 文件路径
content: 文件内容
encoding: 文件编码,默认utf-8
Returns:
无返回值
"""
with open(text_file, "w", encoding=encoding) as f:
f.write(content)
def read_file(file_path: str) -> bytes:
"""
读取文件内容(以字节的方式)
Args:
file_path: 文件路径
Returns:
返回文件内容(以字节的方式)
"""
with open(file_path, "rb") as f:
return f.read()
def write_file(file_path: str, content: bytes) -> None:
"""
写入文件内容(以字节的方式)
Args:
file_path: 文件路径
content: 文件内容
Returns:
无返回值
"""
with open(file_path, "wb") as f:
f.write(content)
| 1,398 | Python | .py | 51 | 16.862745 | 83 | 0.563653 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,503 | dialog.py | zimolab_PyGUIAdapter/pyguiadapter/utils/dialog.py | """
@Time : 2024.10.20
@File : dialog.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 定义了自定义对话框基类。
"""
from abc import abstractmethod
from typing import Optional, Any
from qtpy.QtWidgets import QDialog, QWidget
class BaseCustomDialog(QDialog):
"""
自定义对话框基类,可用于实现自定义消息对话框、自定义输入对话框等。
"""
def __init__(self, parent: Optional[QWidget], **kwargs):
super().__init__(parent)
@abstractmethod
def get_result(self) -> Any:
"""
获取对话框的结果。
Returns:
对话框的结果。
"""
pass
@classmethod
def new_instance(cls, parent: QWidget, **kwargs) -> "BaseCustomDialog":
return cls(parent, **kwargs)
@classmethod
def show_and_get_result(cls, parent: Optional[QWidget], **kwargs) -> Any:
"""
显示对话框并获取结果。
Args:
parent: 父窗口
**kwargs: 构造函数参数
Returns:
结果元组,第一个元素为返回码,第二个元素为对话框的结果。
"""
dialog = cls.new_instance(parent, **kwargs)
ret_code = dialog.exec_()
result = None
if ret_code == QDialog.Accepted:
result = dialog.get_result()
dialog.deleteLater()
return result
| 1,416 | Python | .py | 44 | 20.431818 | 77 | 0.593176 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,504 | messagebox.py | zimolab_PyGUIAdapter/pyguiadapter/utils/messagebox.py | """
@Time : 2024/10/20
@Author : zimolab
@File : messagebox.py
@Project : PyGUIAdapter
@Desc : 消息对话框相关的工具函数
"""
import dataclasses
from typing import Any, Literal, Tuple, Type, Optional, Union
from qtpy.QtCore import Qt
from qtpy.QtGui import QIcon, QPixmap
from qtpy.QtWidgets import (
QWidget,
QDialogButtonBox,
QTextBrowser,
QVBoxLayout,
QMessageBox,
)
from ._core import get_traceback
from .dialog import BaseCustomDialog
from ._ui import IconType, get_icon
from .io import read_text_file
StandardButton: Type[QMessageBox.StandardButton] = QMessageBox.StandardButton
TextFormat = Qt.TextFormat
Yes = StandardButton.Yes
No = StandardButton.No
Ok = StandardButton.Ok
Cancel = StandardButton.Cancel
NoButton = QMessageBox.NoButton
DialogButton: Type[QDialogButtonBox.StandardButton] = QDialogButtonBox.StandardButton
DialogButtons = Union[DialogButton, int]
DialogButtonYes = DialogButton.Yes
DialogButtonNo = DialogButton.No
DialogButtonCancel = DialogButton.Cancel
DialogButtonOk = DialogButton.Ok
DialogNoButton = QDialogButtonBox.NoButton
MessageBoxIcon: Type[QMessageBox.Icon] = QMessageBox.Icon
InformationIcon = MessageBoxIcon.Information
WarningIcon = MessageBoxIcon.Warning
CriticalIcon = MessageBoxIcon.Critical
QuestionIcon = MessageBoxIcon.Question
NoIcon = MessageBoxIcon.NoIcon
#########Standard MessageBox#################
def show_warning_message(
parent: QWidget,
message: str,
title: str = "Warning",
) -> Union[int, StandardButton]:
"""
显示警告消息对话框。
Args:
parent: 父窗口
message: 消息内容
title: 对话框标题
Returns:
返回用户点击的按钮的按键值
"""
return QMessageBox.warning(parent, title, message)
def show_critical_message(
parent: QWidget,
message: str,
title: str = "Critical",
) -> Union[int, StandardButton]:
"""
显示严重错误消息对话框。
Args:
parent: 父窗口
message: 消息内容
title: 对话框标题
Returns:
返回用户点击的按钮的按键值
"""
return QMessageBox.critical(parent, title, message)
def show_info_message(
parent: QWidget,
message: str,
title: str = "Information",
) -> Union[int, StandardButton]:
"""
显示一般信息消息对话框。
Args:
parent: 父窗口
message: 消息内容
title: 对话框标题
Returns:
返回用户点击的按钮的按键值。
"""
return QMessageBox.information(parent, title, message)
def show_question_message(
parent: QWidget,
message: str,
title: str = "Question",
buttons: Union[int, StandardButton, None] = Yes | No,
) -> Union[int, StandardButton]:
"""
显示询问消息对话框。
Args:
parent: 父窗口
message: 消息内容
title: 对话框标题
buttons: 对话框标准按钮
Returns:
返回用户点击的按钮的按键值
"""
if buttons is None:
return QMessageBox.question(parent, title, message)
return QMessageBox.question(parent, title, message, buttons)
###########Custom MessageBox#############
@dataclasses.dataclass
class MessageBoxConfig(object):
"""
自定义消息框配置类。
"""
text: str = ""
"""消息内容"""
title: Optional[str] = None
"""对话框标题"""
icon: Union[int, QPixmap, None] = None
"""对话框图标"""
detailed_text: Optional[str] = None
"""详细消息内容"""
informative_text: Optional[str] = None
"""提示性消息内容"""
text_format: Optional[TextFormat] = None
"""消息内容格式"""
buttons: Union[StandardButton, int, None] = None
"""对话框标准按钮"""
default_button: Union[StandardButton, int, None] = None
"""默认按钮"""
escape_button: Union[StandardButton, int, None] = None
"""取消按钮"""
def create_messagebox(self, parent: Optional[QWidget]) -> QMessageBox:
# noinspection SpellCheckingInspection,PyArgumentList
msgbox = QMessageBox(parent)
msgbox.setText(self.text)
if self.title:
msgbox.setWindowTitle(self.title)
if self.icon is not None:
msgbox.setIcon(self.icon)
if isinstance(self.icon, QPixmap):
msgbox.setIconPixmap(self.icon)
if self.informative_text:
msgbox.setInformativeText(self.informative_text)
if self.detailed_text:
msgbox.setDetailedText(self.detailed_text)
if self.text_format is not None:
msgbox.setTextFormat(self.text_format)
if self.buttons is not None:
msgbox.setStandardButtons(self.buttons)
if self.default_button is not None:
msgbox.setDefaultButton(self.default_button)
if self.escape_button is not None:
msgbox.setEscapeButton(self.escape_button)
return msgbox
def show_messagebox(parent: Optional[QWidget], **kwargs) -> Union[int, StandardButton]:
"""
显示自定义消息框, 并返回用户点击的按钮的按键值。
Args:
parent: 父窗口
**kwargs: 消息框配置参数,具体参数见MessageBoxConfig类。
Returns:
返回用户点击的按钮的按键值。
"""
config = MessageBoxConfig(**kwargs)
msg_box = config.create_messagebox(parent)
ret_code = msg_box.exec_()
msg_box.deleteLater()
return ret_code
def show_exception_messagebox(
parent: Optional[QWidget],
exception: Exception,
message: str = "",
title: str = "Error",
detail: bool = True,
show_error_type: bool = True,
**kwargs,
) -> Union[int, StandardButton]:
"""
显示异常消息对话框。
Args:
parent: 父窗口
exception: 异常对象
message: 错误消息内容
title: 对话框标题
detail: 是否显示详细信息
show_error_type: 是否显示异常类型
**kwargs: 消息框其他配置参数,具体参数见MessageBoxConfig类。
Returns:
返回用户点击的按钮的按键值。
"""
if not detail:
detail_msg = None
else:
detail_msg = get_traceback(exception)
if show_error_type:
error_msg = f"{type(exception).__name__}: {exception}"
else:
error_msg = str(exception)
if message:
error_msg = f"{message}{error_msg}"
return show_messagebox(
parent,
text=error_msg,
title=title,
icon=QMessageBox.Critical,
detailed_text=detail_msg,
**kwargs,
)
############Text Dialogs##############
class TextBrowserMessageBox(BaseCustomDialog):
"""
文本浏览器消息框,用于展示长文本内容。
"""
DEFAULT_SIZE = (585, 523)
def __init__(
self,
parent: Optional[QWidget],
text_content: str,
text_format: Literal["markdown", "plaintext", "html"] = "markdown",
size: Optional[Tuple[int, int]] = None,
title: Optional[str] = None,
icon: IconType = None,
buttons: Optional[DialogButtons] = DialogButtonYes,
resizeable: bool = True,
**kwargs,
):
"""
构造函数。
Args:
parent: 父窗口
text_content: 文本内容
text_format: 文本格式
size: 对话框大小
title: 对话框标题
icon: 对话框图标
buttons: 对话框按钮
resizeable: 是否可调整大小
**kwargs: 其他参数
"""
super().__init__(parent, **kwargs)
self._text_content = text_content
self._text_format = text_format
self._size = size or self.DEFAULT_SIZE
self._title = title
self._icon = icon
self._buttons = buttons
self._resizeable = resizeable
# noinspection PyArgumentList
self._button_box = QDialogButtonBox(self)
# noinspection SpellCheckingInspection
self._textbrowser = QTextBrowser(self)
# noinspection PyArgumentList
self._layout = QVBoxLayout()
self.setLayout(self._layout)
self._setup_ui()
def get_result(self) -> Any:
return None
# noinspection PyUnresolvedReferences
def _setup_ui(self):
if self._title is not None:
self.setWindowTitle(self._title)
if self._icon:
icon = get_icon(self._icon) or QIcon()
self.setWindowIcon(icon)
if self._size:
self.resize(*self._size)
if not self._resizeable:
self.setFixedSize(*self._size)
if self._buttons is not None:
self._button_box.setStandardButtons(self._buttons)
self._button_box.accepted.connect(self.accept)
self._button_box.rejected.connect(self.reject)
else:
self._button_box.hide()
if self._text_content:
self._textbrowser.setOpenLinks(True)
self._textbrowser.setOpenExternalLinks(True)
if self._text_format == "markdown":
self._textbrowser.setMarkdown(self._text_content)
elif self._text_format == "html":
self._textbrowser.setHtml(self._text_content)
elif self._text_format == "plaintext":
self._textbrowser.setPlainText(self._text_content)
else:
self._textbrowser.setText(self._text_content)
self._layout.addWidget(self._textbrowser)
self._layout.addWidget(self._button_box)
def show_text_content(
parent: Optional[QWidget],
text_content: str,
text_format: Literal["markdown", "plaintext", "html"] = "markdown",
size: Optional[Tuple[int, int]] = None,
title: Optional[str] = None,
icon: IconType = None,
buttons: Optional[DialogButtons] = DialogButtonOk,
resizeable: bool = True,
) -> None:
"""
显示文本内容对话框。
Args:
parent: 父窗口
text_content: 文本内容
text_format: 文本格式
size: 对话框大小
title: 对话框标题
icon: 对话框图标
buttons: 对话框按钮
resizeable: 是否可调整大小
Returns:
无返回值
"""
TextBrowserMessageBox.show_and_get_result(
parent,
text_content=text_content,
text_format=text_format,
size=size,
title=title,
icon=icon,
buttons=buttons,
resizeable=resizeable,
)
def show_text_file(
parent: Optional[QWidget],
text_file: str,
text_format: Literal["markdown", "plaintext", "html"] = "markdown",
size: Tuple[int, int] = None,
title: Optional[str] = "",
icon: IconType = None,
buttons: Optional[DialogButtons] = DialogButtonOk,
resizeable: bool = True,
) -> None:
"""
显示文本文件内容对话框。
Args:
parent: 父窗口
text_file: 文本文件路径
text_format: 文本格式
size: 对话框大小
title: 对话框标题
icon: 对话框图标
buttons: 对话框按钮
resizeable: 是否可调整大小
Returns:
无返回值
"""
text_content = read_text_file(text_file)
show_text_content(
parent,
text_content=text_content,
text_format=text_format,
size=size,
title=title,
icon=icon,
buttons=buttons,
resizeable=resizeable,
)
| 11,632 | Python | .py | 356 | 22.823034 | 87 | 0.630853 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,505 | inputdialog.py | zimolab_PyGUIAdapter/pyguiadapter/utils/inputdialog.py | """
@Time : 2024.10.20
@File : inputdialog.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 输入对话框相关的工具函数
"""
import ast
import json
from abc import abstractmethod
from typing import Optional, Any, Tuple
from typing import (
Union,
List,
Literal,
Sequence,
cast,
Type,
)
from pyqcodeeditor.QCodeEditor import QCodeEditor
from pyqcodeeditor.highlighters import QJSONHighlighter, QPythonHighlighter
from qtpy.QtCore import Qt
from qtpy.QtGui import QColor, QFont
from qtpy.QtWidgets import (
QLineEdit,
QInputDialog,
QColorDialog,
QTextEdit,
)
from qtpy.QtWidgets import QWidget, QPushButton, QVBoxLayout, QHBoxLayout
from ._core import PyLiteralType
from ._ui import get_icon
from ._ui import to_qcolor, convert_color, IconType
from .dialog import BaseCustomDialog
from .messagebox import show_critical_message
# 输入控件的回显模式
# 常量别名,方便开发者直接导入使用
EchoMode = QLineEdit.EchoMode
PasswordEchoMode = EchoMode.Password
PasswordEchoOnEdit = EchoMode.PasswordEchoOnEdit
NormalEchoMode = EchoMode.Normal
NoEcho = EchoMode.NoEcho
def input_integer(
parent: Optional[QWidget],
title: str = "Input Integer",
label: str = "",
value: int = 0,
min_value: int = -2147483647,
max_value: int = 2147483647,
step: int = 1,
) -> Optional[int]:
"""
弹出一个整数输入对话框,并返回输入的整数值。
Args:
parent: 父窗口
title: 对话框标题
label: 提示标签
value: 初始值
min_value: 最大值
max_value: 最小值
step: 单次增加的步长
Returns:
输入的整数值,如果用户取消输入则返回 None。
"""
ret_val, ok = QInputDialog.getInt(
parent, title, label, value, min_value, max_value, step
)
if not ok:
return None
return ret_val
def input_float(
parent: Optional[QWidget],
title: str = "Input Float",
label: str = "",
value: float = 0.0,
min_value: float = -2147483647.0,
max_value: float = 2147483647.0,
decimals: int = 3,
step: float = 1.0,
) -> Optional[float]:
"""
弹出一个浮点数输入对话框,并返回输入的浮点数值。
Args:
parent: 父窗口
title: 对话框标题
label: 提示标签
value: 初始值
min_value: 最小值
max_value: 最大值
decimals: 小数位数
step: 单次增加的步长
Returns:
输入的浮点数值,如果用户取消输入则返回 None。
"""
value = float(value)
min_value = float(min_value)
max_value = float(max_value)
ret_val, ok = QInputDialog.getDouble(
parent,
title,
label,
value,
min_value,
max_value,
decimals,
Qt.WindowFlags(),
step,
)
if not ok:
return None
return ret_val
def input_text(
parent: Optional[QWidget],
title: str = "Input Text",
label: str = "",
text: str = "",
):
"""
弹出一个多行文本输入对话框,并返回输入的文本。
Args:
parent: 父窗口
title: 对话框标题
label: 提示标签
text: 初始文本
Returns:
输入的文本,如果用户取消输入则返回 None。
"""
text, ok = QInputDialog.getMultiLineText(parent, title, label, text)
if not ok:
return None
return text
def input_string(
parent: Optional[QWidget],
title: str = "Input Text",
label: str = "",
echo: Optional[EchoMode] = None,
text: str = "",
) -> Optional[str]:
"""
弹出一个单行文本输入对话框,并返回输入的文本。
Args:
parent: 父窗口
title: 对话框标题
label: 提示标签
echo: 回显模式,默认为 None,即使用 QLineEdit.Normal 回显模式
text: 初始文本
Returns:
输入的文本,如果用户取消输入则返回 None。
"""
if echo is None:
echo = EchoMode.Normal
text, ok = QInputDialog.getText(parent, title, label, echo, text)
if ok:
return text
return None
def select_item(
parent: Optional[QWidget],
items: List[str],
title: str = "Select Item",
label: str = "",
current: int = 0,
editable: bool = False,
) -> Optional[str]:
"""
弹出一个选项列表对话框,并返回用户选择的选项。
Args:
parent: 父窗口
items: 选项列表
title: 对话框标题
label: 提示标签
current: 当前选择的选项索引
editable: 是否允许编辑
Returns:
用户选择的选项,如果用户取消输入则返回 None。
"""
ret_val, ok = QInputDialog.getItem(
parent, title, label, items, current, editable=editable
)
if not ok:
return None
return ret_val
def input_color(
parent: Optional[QWidget],
initial: Union[QColor, str, tuple] = "white",
title: str = "",
alpha_channel: bool = True,
return_type: Literal["tuple", "str", "QColor"] = "str",
) -> Union[Tuple[int, int, int], Tuple[int, int, int], str, QColor, None]:
initial = to_qcolor(initial)
"""
弹出一个颜色选择对话框,并返回用户选择的颜色。
Args:
parent: 父窗口
initial: 初始颜色,可以是 QColor 对象,也可以是字符串表示的颜色值,也可以是元组表示的颜色值
title: 对话框标题
alpha_channel: 是否显示 alpha 通道
return_type: 返回值类型,可以是 "tuple","str","QColor" 之一
Returns:
用户选择的颜色,如果用户取消输入则返回 None。
"""
if alpha_channel:
ret_val = QColorDialog.getColor(
initial, parent, title, options=QColorDialog.ShowAlphaChannel
)
else:
ret_val = QColorDialog.getColor(initial, parent, title)
if ret_val.isValid():
return convert_color(ret_val, return_type, alpha_channel)
return None
LineWrapMode = QTextEdit.LineWrapMode
class UniversalInputDialog(BaseCustomDialog):
"""
通用输入对话框基类,用于实现自定义输入对话框。
"""
def __init__(
self,
parent: Optional[QWidget],
title: str = "",
icon: IconType = None,
size: Tuple[int, int] = (400, 300),
ok_button_text: str = "Ok",
cancel_button_text: Optional[str] = "Cancel",
**kwargs,
):
"""
构造函数,创建自定义输入对话框。
Args:
parent: 父窗口
title: 对话框标题
icon: 对话框图标
size: 对话框大小
ok_button_text: 确定按钮文本
cancel_button_text: 取消按钮文本
**kwargs: 其他参数
"""
super().__init__(parent, **kwargs)
self._title = title or ""
self._icon = icon
self._size = size
self._ok_button_text: str = ok_button_text
self._cancel_button_text: Optional[str] = cancel_button_text
self._layout: QVBoxLayout = QVBoxLayout()
self._main_widget: Optional[QWidget] = None
self._ok_button: QPushButton = QPushButton(self)
self._cancel_button: Optional[QPushButton] = None
self.setLayout(self._layout)
self._setup_ui()
def _setup_ui(self):
self.setWindowTitle(self._title)
icon = get_icon(self._icon)
if icon:
self.setWindowIcon(icon)
if self._size:
self.resize(*self._size)
if self._main_widget is None:
main_widget = self.create_main_widget()
main_widget.setParent(self)
self._main_widget = main_widget
self._layout.addWidget(self._main_widget)
self._setup_buttons()
@abstractmethod
def create_main_widget(self) -> QWidget:
"""
创建主部件,子类必须实现。
Returns:
主部件
"""
pass
def _setup_buttons(self):
self._ok_button.setText(self._ok_button_text)
# noinspection PyUnresolvedReferences
self._ok_button.clicked.connect(self.on_accept)
if self._cancel_button_text:
self._cancel_button = QPushButton(self)
self._cancel_button.setText(self._cancel_button_text)
# noinspection PyUnresolvedReferences
self._cancel_button.clicked.connect(self.on_reject)
button_layout = QHBoxLayout()
button_layout.addStretch()
button_layout.addWidget(self._ok_button)
if self._cancel_button_text:
button_layout.addWidget(self._cancel_button)
self._layout.addLayout(button_layout)
def on_accept(self):
self.accept()
def on_reject(self):
self.reject()
@abstractmethod
def get_result(self) -> Any:
"""
获取输入结果,子类必须实现。
Returns:
输入结果
"""
pass
@classmethod
def new_instance(cls, parent: QWidget, **kwargs) -> "UniversalInputDialog":
"""
创建新的实例。
Args:
parent: 父窗口
**kwargs: 构造函数参数
Returns:
新的实例
"""
return super().new_instance(parent, **kwargs)
class CodeEditDialog(UniversalInputDialog):
"""
代码编辑器输入对话框。
"""
def __init__(
self,
parent: Optional[QWidget],
title: str = "",
icon: IconType = None,
size: Tuple[int, int] = (600, 400),
ok_button_text: str = "Ok",
cancel_button_text: Optional[str] = "Cancel",
initial_text: str = "",
auto_indent: bool = True,
indent_size: int = 4,
auto_parentheses: bool = True,
line_wrap_mode: LineWrapMode = LineWrapMode.WidgetWidth,
line_wrap_width: int = 88,
font_family: Union[str, Sequence[str], None] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
构造函数。
Args:
parent: 父窗口
title: 对话框标题
icon: 对话框图标
size: 对话框大小
ok_button_text: 确定按钮文本
cancel_button_text: 取消按钮文本
initial_text: 初始文本
auto_indent: 自动缩进
indent_size: 缩进大小
auto_parentheses: 自动括号匹配
line_wrap_mode: 换行模式
line_wrap_width: 换行宽度
font_family: 字体
font_size: 字体大小
**kwargs: 其他参数
"""
self._initial_text = initial_text
self._auto_indent = auto_indent
self._indent_size = indent_size
self._auto_parentheses = auto_parentheses
self._line_wrap_mode = line_wrap_mode
self._line_wrap_width = line_wrap_width
self._font_family = font_family
self._font_size = font_size
super().__init__(
parent, title, icon, size, ok_button_text, cancel_button_text, **kwargs
)
def create_main_widget(self) -> QCodeEditor:
main_widget = QCodeEditor(self)
main_widget.setTabReplace(True)
main_widget.setTabReplaceSize(self._indent_size)
main_widget.setAutoIndentation(self._auto_indent)
main_widget.setAutoParentheses(self._auto_parentheses)
main_widget.setLineWrapMode(self._line_wrap_mode)
if self._line_wrap_mode in (
LineWrapMode.FixedPixelWidth,
LineWrapMode.FixedColumnWidth,
):
main_widget.setLineWrapColumnOrWidth(self._line_wrap_width)
if self._initial_text:
main_widget.setPlainText(self._initial_text)
if self._font_family:
font_size = main_widget.fontSize()
font: QFont = main_widget.font()
if isinstance(self._font_family, str):
font.setFamily(self._font_family)
else:
font.setFamilies(self._font_family)
main_widget.setFont(font)
main_widget.setFontSize(font_size)
if self._font_size and self._font_size > 0:
main_widget.setFontSize(self._font_size)
return main_widget
def get_result(self) -> str:
return self._main_widget.toPlainText()
class ObjectInputDialog(CodeEditDialog):
"""
对象输入对话框基类。
"""
def __init__(
self,
parent: Optional[QWidget],
title: str = "",
icon: IconType = None,
size: Tuple[int, int] = (600, 400),
ok_button_text: str = "Ok",
cancel_button_text: Optional[str] = "Cancel",
initial_text: str = "",
auto_indent: bool = True,
indent_size: int = 4,
auto_parentheses: bool = True,
line_wrap_mode: LineWrapMode = LineWrapMode.WidgetWidth,
line_wrap_width: int = 88,
font_family: Union[str, Sequence[str], None] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
构造函数。
Args:
parent: 父窗口
title: 对话框标题
icon: 对话框图标
size: 对话框大小
ok_button_text: 确定按钮文本
cancel_button_text: 取消按钮文本
initial_text: 初始文本
auto_indent: 自动缩进
indent_size: 缩进大小
auto_parentheses: 自动括号匹配
line_wrap_mode: 换行模式
line_wrap_width: 换行宽度
font_family: 字体
font_size: 字体大小
**kwargs: 其他参数
"""
super().__init__(
parent,
title,
icon,
size,
ok_button_text,
cancel_button_text,
initial_text,
auto_indent,
indent_size,
auto_parentheses,
line_wrap_mode,
line_wrap_width,
font_family,
font_size,
**kwargs,
)
self._current_value: Any = None
@abstractmethod
def get_object(self) -> Any:
"""
获取输入的对象。子类必须实现。
Returns:
输入的对象。
"""
pass
def on_accept(self):
try:
current_value = self.get_object()
except Exception as e:
show_critical_message(self, f"{type(e).__name__}: {e}", title="Error")
else:
self._current_value = current_value
self.accept()
def get_result(self) -> Any:
return self._current_value
class JsonInputDialog(ObjectInputDialog):
"""
JSON 输入对话框,从用户输入的 JSON 文本获得 Python 对象。
"""
def create_main_widget(self) -> QCodeEditor:
editor = super().create_main_widget()
highlighter = QJSONHighlighter(editor)
editor.setHighlighter(highlighter)
return editor
def get_object(self) -> Any:
"""
获取输入的 JSON 对象。
Returns:
输入的 JSON 对象。
Raises:
Exception: 输入的文本不是合法的 JSON 文本时抛出异常。
"""
editor = cast(QCodeEditor, self._main_widget)
text = editor.toPlainText()
if text.strip() == "":
self._current_value = None
self.accept()
return
return json.loads(text)
class PyLiteralInputDialog(ObjectInputDialog):
"""
Python 字面量输入对话框,从用户输入的python字面量代码获得 Python 对象(使用ast.literal_eval())。
"""
def create_main_widget(self) -> QCodeEditor:
editor = super().create_main_widget()
highlighter = QPythonHighlighter(editor)
editor.setHighlighter(highlighter)
return editor
def get_object(self) -> Any:
"""
获取输入的 Python 字面量对象。
Returns:
输入的 Python 字面量对象。
Raises:
Exception: 输入的文本不是合法的python字面量代码时抛出异常。
"""
editor = cast(QCodeEditor, self._main_widget)
text = editor.toPlainText()
if text.strip() == "":
self._current_value = None
self.accept()
return
return ast.literal_eval(text)
def input_json_object(
parent: Optional[QWidget],
title: str = "Input Json",
icon: IconType = None,
size: Tuple[int, int] = (600, 400),
ok_button_text: str = "Ok",
cancel_button_text: Optional[str] = "Cancel",
initial_text: str = "",
auto_indent: bool = True,
indent_size: int = 4,
auto_parentheses: bool = True,
line_wrap_mode: LineWrapMode = LineWrapMode.WidgetWidth,
line_wrap_width: int = 88,
font_family: Union[str, Sequence[str], None] = None,
font_size: Optional[int] = None,
**kwargs,
) -> Any:
"""
弹出一个 JSON 输入对话框,并返回用户输入的 JSON 对象。
Args:
parent: 父窗口
title: 对话框标题
icon: 对话框图标
size: 对话框大小
ok_button_text: 确定按钮文本
cancel_button_text: 取消按钮文本
initial_text: 初始文本
auto_indent: 自动缩进
indent_size: 缩进大小
auto_parentheses: 自动括号匹配
line_wrap_mode: 换行模式
line_wrap_width: 换行宽度
font_family: 字体
font_size: 字体大小
**kwargs: 其他参数
Returns:
用户输入的 JSON 对象,如果用户取消输入则返回 None。
Raises:
Exception: 输入的文本不是合法的 JSON 文本时抛出异常。
"""
return JsonInputDialog.show_and_get_result(
parent,
title=title,
icon=icon,
size=size,
ok_button_text=ok_button_text,
cancel_button_text=cancel_button_text,
initial_text=initial_text,
auto_indent=auto_indent,
indent_size=indent_size,
auto_parentheses=auto_parentheses,
line_wrap_mode=line_wrap_mode,
line_wrap_width=line_wrap_width,
font_family=font_family,
font_size=font_size,
**kwargs,
)
def input_py_literal(
parent: Optional[QWidget],
title: str = "Input Python Literal",
icon: IconType = None,
size: Tuple[int, int] = (600, 400),
ok_button_text: str = "Ok",
cancel_button_text: Optional[str] = "Cancel",
initial_text: str = "",
auto_indent: bool = True,
indent_size: int = 4,
auto_parentheses: bool = True,
line_wrap_mode: LineWrapMode = LineWrapMode.WidgetWidth,
line_wrap_width: int = 88,
font_family: Union[str, Sequence[str], None] = None,
font_size: Optional[int] = None,
**kwargs,
) -> PyLiteralType:
"""
弹出一个 Python 字面量输入对话框,并返回用户输入的 Python 字面量对象。
Args:
parent: 父窗口
title: 对话框标题
icon: 对话框图标
size: 对话框大小
ok_button_text: 确定按钮文本
cancel_button_text: 取消按钮文本
initial_text: 初始文本
auto_indent: 自动缩进
indent_size: 缩进大小
auto_parentheses: 自动括号匹配
line_wrap_mode: 换行模式
line_wrap_width: 换行宽度
font_family: 字体
font_size: 字体大小
**kwargs: 其他参数
Returns:
用户输入的 Python 字面量对象,如果用户取消输入则返回 None。
Raises:
Exception: 输入的文本不是合法的python字面量代码时抛出异常。
"""
return PyLiteralInputDialog.show_and_get_result(
parent,
title=title,
icon=icon,
size=size,
ok_button_text=ok_button_text,
cancel_button_text=cancel_button_text,
initial_text=initial_text,
auto_indent=auto_indent,
indent_size=indent_size,
auto_parentheses=auto_parentheses,
line_wrap_mode=line_wrap_mode,
line_wrap_width=line_wrap_width,
font_family=font_family,
font_size=font_size,
**kwargs,
)
def get_custom_input(
parent: QWidget, input_dialog_class: Type[UniversalInputDialog], **input_dialog_args
) -> Any:
"""
弹出一个自定义输入对话框,并返回用户输入的对象。
Args:
parent: 父窗口
input_dialog_class: 自定义输入对话框类
**input_dialog_args: 自定义输入对话框构造函数参数
Returns:
用户输入的对象,如果用户取消输入则返回 None。
"""
return input_dialog_class.show_and_get_result(parent, **input_dialog_args)
| 21,190 | Python | .py | 638 | 21.437304 | 88 | 0.589346 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,506 | __init__.py | zimolab_PyGUIAdapter/pyguiadapter/utils/__init__.py | from ._core import *
from ._ui import *
from .io import *
from .dialog import BaseCustomDialog
from .messagebox import *
from .filedialog import *
from .inputdialog import *
| 174 | Python | .py | 7 | 23.857143 | 36 | 0.784431 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,507 | filedialog.py | zimolab_PyGUIAdapter/pyguiadapter/utils/filedialog.py | """
@Time : 2024.10.20
@File : filedialog.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 提供文件选择对话框的相关工具函数
"""
from typing import List, Optional
from qtpy import compat
from qtpy.QtCore import QUrl
from qtpy.QtWidgets import QWidget, QFileDialog
def get_existing_directory(
parent: Optional[QWidget] = None,
title: str = "Open Directory",
start_dir: str = "",
) -> Optional[str]:
"""
弹出选择目录对话框,获取已存在的目录路径
Args:
parent: 父窗口
title: 对话框标题
start_dir: 起始目录
Returns:
用户选择的目录路径,如果用户取消选择,则返回None。
"""
return compat.getexistingdirectory(parent, title, start_dir) or None
def get_existing_directory_url(
parent: Optional[QWidget] = None,
title: str = "Open Directory URL",
start_dir: Optional[QUrl] = None,
supported_schemes: Optional[List[str]] = None,
) -> Optional[QUrl]:
"""
弹出选择目录URL对话框,获取已存在的目录URL
Args:
parent: 父窗口
title: 对话框标题
start_dir: 起始目录
supported_schemes: 支持的URL协议
Returns:
用户选择的目录URL,如果用户取消选择,则返回None
"""
if start_dir is None:
start_dir = QUrl()
if not supported_schemes:
url = QFileDialog.getExistingDirectoryUrl(
parent,
title,
start_dir,
QFileDialog.ShowDirsOnly,
)
else:
url = QFileDialog.getExistingDirectoryUrl(
parent,
title,
start_dir,
QFileDialog.ShowDirsOnly,
supportedSchemes=supported_schemes,
)
return url
def get_open_file(
parent: Optional[QWidget] = None,
title: str = "Open File",
start_dir: str = "",
filters: str = "",
) -> Optional[str]:
"""
弹出选择文件对话框,获取已存在的文件路径。
Args:
parent: 父窗口
title: 对话框标题
start_dir: 起始目录
filters: 文件过滤器
Returns:
用户选择的文件路径,如果用户取消选择,则返回None。
"""
filename, _ = compat.getopenfilename(parent, title, start_dir, filters)
return filename or None
def get_open_files(
parent: Optional[QWidget] = None,
title: str = "Open Files",
start_dir: str = "",
filters: str = "",
) -> Optional[List[str]]:
"""
弹出选择多个文件对话框,获取已存在的文件路径。
Args:
parent: 父窗口
title: 对话框标题
start_dir: 起始目录
filters: 文件过滤器
Returns:
用户选择的文件路径列表,如果用户取消选择,则返回None。
"""
filenames, _ = compat.getopenfilenames(parent, title, start_dir, filters)
return filenames or None
def get_save_file(
parent: Optional[QWidget] = None,
title: str = "Save File",
start_dir: str = "",
filters: str = "",
) -> Optional[str]:
"""
弹出保存文件对话框,获取保存文件的路径。
Args:
parent: 父窗口
title: 对话框标题
start_dir: 起始目录
filters: 文件过滤器
Returns:
用户选择的保存文件路径,如果用户取消选择,则返回None。
"""
filename, _ = compat.getsavefilename(parent, title, start_dir, filters)
return filename or None
| 3,565 | Python | .py | 114 | 19.649123 | 77 | 0.6175 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,508 | _core.py | zimolab_PyGUIAdapter/pyguiadapter/utils/_core.py | """
@Time : 2024.10.20
@File : _core.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 一些重要的工具函数和类型定义
"""
import ast
import base64
import hashlib
import inspect
import re
import traceback
import warnings
from io import StringIO
from typing import List, Set, Tuple, Any, Union, Optional, Type
PyLiteralType = Union[bool, int, float, bytes, str, list, tuple, dict, set, type(None)]
def _marks(marks: Union[str, List[str], Tuple[str], Set[str]]) -> Set[str]:
if not isinstance(marks, (list, tuple, set, str)):
raise TypeError(f"unsupported types for marks: {type(marks)}")
if isinstance(marks, str):
if marks.strip() == "":
raise ValueError("marks must be a non-empty string")
return {marks}
if len(marks) <= 0:
raise ValueError("at least one mark must be provided")
tmp = set()
for mark in marks:
if not isinstance(mark, str):
raise TypeError(f"a mark must be a string: {type(mark)}")
if mark.strip() == "":
raise ValueError("an empty-string mark found")
tmp.add(mark)
return tmp
def _block_pattern(
start_marks: Union[str, List[str], Tuple[str], Set[str]],
end_marks: Union[str, List[str], Tuple[str], Set[str]],
) -> str:
start_marks = _marks(start_marks)
end_marks = _marks(end_marks)
start_mark_choices = "|".join(start_marks)
end_mark_choices = "|".join(end_marks)
pattern = (
rf"^(\s*(?:{start_mark_choices})\s*(.*\n.+)^\s*(?:{end_mark_choices})\s*\n)"
)
return pattern
def extract_text_block(
text: str,
start_marks: Union[str, List[str], Tuple[str], Set[str]],
end_marks: Union[str, List[str], Tuple[str], Set[str]],
) -> Optional[str]:
pattern = _block_pattern(start_marks, end_marks)
result = re.search(pattern, text, re.MULTILINE | re.DOTALL | re.UNICODE)
if result:
return result.group(2)
return None
def remove_text_block(
text: str,
start_marks: Union[str, List[str], Tuple[str], Set[str]],
end_marks: Union[str, List[str], Tuple[str], Set[str]],
) -> str:
pattern = _block_pattern(start_marks, end_marks)
result = re.search(pattern, text, re.MULTILINE | re.DOTALL | re.UNICODE)
if not result:
return text
return re.sub(
pattern, repl="", string=text, flags=re.MULTILINE | re.DOTALL | re.UNICODE
)
def hashable(obj: Any) -> bool:
try:
hash(obj)
return True
except TypeError:
return False
def unique_list(origin: List[Any]) -> List[Any]:
added = set()
bool_true_added = False
bool_false_added = False
ret = []
for item in origin:
if item is True:
if not bool_true_added:
ret.append(item)
bool_true_added = True
elif item is False:
if not bool_false_added:
ret.append(item)
bool_false_added = True
else:
if item not in added:
added.add(item)
ret.append(item)
return ret
def fingerprint(text: str) -> Optional[str]:
if not text:
return None
md5 = hashlib.md5()
md5.update(text.encode("utf-8"))
return md5.hexdigest()
def get_object_filename(obj: Any) -> Optional[str]:
return inspect.getsourcefile(obj)
def get_object_sourcecode(obj: Any) -> Optional[str]:
return inspect.getsource(obj)
def get_type_args(raw: str) -> list:
raw = raw.strip()
if raw.startswith("[") and raw.endswith("]"):
content = raw[1:-1].strip()
elif raw.startswith("(") and raw.endswith(")"):
content = raw[1:-1].strip()
else:
content = None
if content is None:
return raw.split(",")
content = "[" + content + "]"
try:
args = ast.literal_eval(content)
except Exception as e:
warnings.warn(f"unable to parse type args '{raw}': {e}")
return []
return args
def is_subclass_of(cls: Any, base_cls: Any):
if not inspect.isclass(cls) or not inspect.isclass(base_cls):
return False
return issubclass(cls, base_cls)
def get_traceback(
error: Exception, limit: Optional[int] = None, complete_msg: bool = True
) -> str:
assert isinstance(error, Exception)
buffer = StringIO()
if complete_msg:
buffer.write("Traceback (most recent call last):\n")
traceback.print_tb(error.__traceback__, limit=limit, file=buffer)
if complete_msg:
buffer.write(f"{type(error).__name__}: {error}")
msg = buffer.getvalue()
buffer.close()
return msg
def type_check(value: Any, allowed_types: Tuple[Type[Any], ...], allow_none: bool):
if allow_none and value is None:
return
if not isinstance(value, allowed_types):
raise TypeError(f"invalid type: {type(value)}")
def to_base64(data: Union[bytes, str]) -> str:
return base64.b64encode(data).decode()
| 4,948 | Python | .py | 144 | 28.229167 | 87 | 0.626872 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,509 | _ui.py | zimolab_PyGUIAdapter/pyguiadapter/utils/_ui.py | """
@Time : 2024.10.20
@File : _ui.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 一些UI相关的工具函数
"""
import os.path
import warnings
from typing import Literal, Tuple, Union, Optional
import qtawesome as qta
from qtpy.QtCore import QSize
from qtpy.QtGui import QColor
from qtpy.QtGui import QIcon, QPixmap, QTextCursor
from qtpy.QtWidgets import QTextBrowser, QWidget, QFrame, QApplication
IconType = Union[str, Tuple[str, Union[list, dict]], QIcon, QPixmap, type(None)]
SIZE_FLAG_DESKTOP = -1
POSITION_FLAG_DESKTOP_CENTER = -1
# noinspection PyArgumentList
def get_icon(src: IconType, *args, **kwargs) -> Optional[QIcon]:
if src is None:
return None
if isinstance(src, QIcon):
return src
if isinstance(src, QPixmap):
return QIcon(src)
if isinstance(src, str):
if os.path.isfile(src) or src.startswith(":/"):
return QIcon(src)
return qta.icon(src, *args, **kwargs)
if isinstance(src, tuple):
assert len(src) >= 2
assert isinstance(src[0], str) and isinstance(src[1], (dict, list))
if isinstance(src[1], dict):
return qta.icon(src[0], **src[1])
else:
return qta.icon(src[0], *src[1])
else:
raise ValueError(f"invalid icon type: {type(src)}")
def qta_icon(icon_name: str, **kwargs) -> Union[str, Tuple[str, dict]]:
if not kwargs:
return icon_name
return icon_name, kwargs
# noinspection SpellCheckingInspection
def set_textbrowser_content(
textbrowser: QTextBrowser,
content: str,
content_format: Literal["markdown", "html", "plaintext"] = "markdown",
):
content_format = content_format.lower()
if content_format == "markdown":
textbrowser.setMarkdown(content)
elif content_format == "html":
textbrowser.setHtml(content)
elif content_format == "plaintext":
textbrowser.setPlainText("")
textbrowser.append(content)
else:
raise ValueError(f"invalid content format: {content_format}")
cursor = textbrowser.textCursor()
cursor.movePosition(
QTextCursor.MoveOperation.Start, QTextCursor.MoveMode.MoveAnchor
)
textbrowser.setTextCursor(cursor)
# noinspection SpellCheckingInspection
def hline(parent: QWidget) -> QFrame:
line = QFrame(parent)
line.setFrameShape(QFrame.Shape.HLine)
line.setFrameShadow(QFrame.Shadow.Sunken)
return line
def get_inverted_color(color: QColor) -> QColor:
return QColor(255 - color.red(), 255 - color.green(), 255 - color.blue())
def get_size(size: Union[int, Tuple[int, int], QSize, None]) -> Optional[QSize]:
if size is None:
return None
if isinstance(size, int):
if size <= 0:
warnings.warn(f"invalid size: {size}")
return None
return QSize(size, size)
if isinstance(size, tuple):
if len(size) < 2:
warnings.warn(f"invalid size: {size}")
return None
return QSize(size[0], size[1])
if isinstance(size, QSize):
return size
warnings.warn(f"invalid size type: {type(size)}")
return None
def convert_color(
c: QColor,
return_type: Literal["tuple", "str", "QColor"],
alpha_channel: bool = True,
) -> Union[Tuple[int, int, int, int], Tuple[int, int, int], str, QColor]:
assert isinstance(c, QColor)
if return_type == "QColor":
return c
if return_type == "tuple":
if alpha_channel:
return c.red(), c.green(), c.blue(), c.alpha()
else:
return c.red(), c.green(), c.blue()
if return_type == "str":
if alpha_channel:
return f"#{c.red():02x}{c.green():02x}{c.blue():02x}{c.alpha():02x}"
else:
return f"#{c.red():02x}{c.green():02x}{c.blue():02x}"
raise ValueError(f"invalid return_type: {return_type}")
# noinspection SpellCheckingInspection
def to_qcolor(color: Union[str, tuple, list, QColor]) -> QColor:
if isinstance(color, QColor):
return color
if isinstance(color, (list, tuple)):
if len(color) < 3:
raise ValueError(f"invalid color tuple: {color}")
c = QColor()
c.setRgb(*color)
return c
if isinstance(color, str):
alpha = None
if len(color) >= 9:
try:
print(color[7:9], int(color[7:9], 16))
alpha = int(color[7:9], 16)
except ValueError:
raise ValueError(
f"unable to parse alpha channel from color string: {color}"
)
color = color[:7]
c = QColor(color)
if alpha is not None:
c.setAlpha(alpha)
return c
raise ValueError(f"invalid color type: {type(color)}")
def move_window(
window: QWidget, x: Union[int, float, None], y: Union[int, float, None]
) -> None:
desktop = QApplication.primaryScreen()
screen_size = desktop.size()
window_size = window.geometry().size()
if isinstance(x, float):
x = min(max(0.0, x), 1.0)
x = int((screen_size.width() - window_size.width()) * x)
elif isinstance(x, int):
x = max(0, x)
else:
pass
if isinstance(y, float):
y = min(max(0.0, y), 1.0)
y = int((screen_size.height() - window_size.height()) * y)
elif isinstance(y, int):
y = max(0, y)
else:
pass
window.move(x, y)
| 5,441 | Python | .py | 155 | 28.245161 | 80 | 0.621802 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,510 | uclipboard.py | zimolab_PyGUIAdapter/pyguiadapter/adapter/uclipboard.py | """
@Time : 2024.10.20
@File : uclipboard.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 提供了访问系统剪贴板的相关接口
"""
from concurrent.futures import Future
from typing import Optional
from ..window import (
CLIPBOARD_GET_TEXT,
CLIPBOARD_SET_TEXT,
CLIPBOARD_GET_SELECTION_TEXT,
CLIPBOARD_SET_SELECTION_TEXT,
CLIPBOARD_SUPPORTS_SELECTION,
CLIPBOARD_OWNS_CLIPBOARD,
CLIPBOARD_OWNS_SELECTION,
)
from .ucontext import _context
def get_text() -> Optional[str]:
"""
获取系统剪贴板中的文本内容。
Returns:
系统剪贴板中当前文本,如果剪贴板为空则返回None。
"""
future = Future()
_context.sig_clipboard_operation.emit(future, CLIPBOARD_GET_TEXT, None)
return future.result()
def set_text(text: str) -> None:
"""
设置系统剪贴板中当前文本。
Args:
text: 要设置的文本
Returns:
无返回值
"""
future = Future()
_context.sig_clipboard_operation.emit(future, CLIPBOARD_SET_TEXT, text)
return future.result()
def supports_selection() -> bool:
future = Future()
_context.sig_clipboard_operation.emit(future, CLIPBOARD_SUPPORTS_SELECTION, None)
return future.result()
def get_selection_text() -> Optional[str]:
future = Future()
_context.sig_clipboard_operation.emit(future, CLIPBOARD_GET_SELECTION_TEXT, None)
return future.result()
def set_selection_text(text: str):
future = Future()
_context.sig_clipboard_operation.emit(future, CLIPBOARD_SET_SELECTION_TEXT, text)
return future.result()
def owns_clipboard() -> bool:
future = Future()
_context.sig_clipboard_operation.emit(future, CLIPBOARD_OWNS_CLIPBOARD, None)
return future.result()
def owns_selection() -> bool:
future = Future()
_context.sig_clipboard_operation.emit(future, CLIPBOARD_OWNS_SELECTION, None)
return future.result()
| 1,953 | Python | .py | 59 | 26.355932 | 85 | 0.71106 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,511 | udialog.py | zimolab_PyGUIAdapter/pyguiadapter/adapter/udialog.py | """
@Time : 2024.10.20
@File : udialog.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 提供对话框相关的功能
"""
from concurrent.futures import Future
from typing import Any, Literal, Tuple, Type, Optional, Union
from qtpy.QtGui import QPixmap
from .ucontext import _context
from ..utils import IconType, InformationIcon, WarningIcon, CriticalIcon, QuestionIcon
from ..utils import io
from ..utils.dialog import BaseCustomDialog
from ..utils.messagebox import (
TextBrowserMessageBox,
StandardButton,
Ok,
Yes,
No,
NoButton,
DialogButtons,
DialogButtonOk,
MessageBoxIcon,
)
def show_custom_dialog(dialog_class: Type[BaseCustomDialog], **kwargs) -> Any:
"""
弹出自定义对话框。
Args:
dialog_class: 自定义对话框类
**kwargs: 自定义对话框初始化参数
Returns:
返回自定义对话框`show_and_get_result()`函数的返回值。
"""
result_future = Future()
# noinspection PyUnresolvedReferences
_context.sig_show_custom_dialog.emit(result_future, dialog_class, kwargs)
return result_future.result()
def _show_messagebox(
text: str,
icon: Union[MessageBoxIcon, int, QPixmap],
title: str = "Information",
buttons: Union[StandardButton, int] = Ok,
default_button: Union[StandardButton, int] = NoButton,
**kwargs,
) -> Union[int, StandardButton]:
result_future = Future()
# noinspection PyUnresolvedReferences
args = dict(
text=text,
title=title,
icon=icon,
buttons=buttons,
default_button=default_button,
**kwargs,
)
_context.sig_show_messagebox.emit(result_future, args)
return result_future.result()
def show_info_messagebox(
text: str,
title: str = "Information",
buttons: Union[StandardButton, int] = Ok,
default_button: Union[StandardButton, int] = Ok,
**kwargs,
) -> Union[int, StandardButton]:
"""
弹出Information消息对话框。
Args:
text: 消息文本
title: 对话框标题
buttons: 对话框的按钮
default_button: 默认按钮
**kwargs: 其他参数
Returns:
返回用户按下的按钮。
"""
return _show_messagebox(
text=text,
icon=InformationIcon,
title=title,
buttons=buttons,
default_button=default_button,
**kwargs,
)
def show_warning_messagebox(
text: str,
title: str = "Warning",
buttons: Union[StandardButton, int] = Ok,
default_button: Union[StandardButton, int] = Ok,
**kwargs,
) -> Union[int, StandardButton]:
"""
弹出Warning消息对话框。
Args:
text: 消息文本
title: 对话框标题
buttons: 对话框的按钮
default_button: 默认按钮
**kwargs: 其他参数
Returns:
返回用户按下的按钮。
"""
return _show_messagebox(
text=text,
icon=WarningIcon,
title=title,
buttons=buttons,
default_button=default_button,
**kwargs,
)
def show_critical_messagebox(
text: str,
title: str = "Critical",
buttons: Union[StandardButton, int] = Ok,
default_button: Union[StandardButton, int] = NoButton,
**kwargs,
) -> Union[int, StandardButton]:
"""
弹出Critical消息对话框。
Args:
text: 消息文本
title: 对话框标题
buttons: 对话框的按钮
default_button: 默认按钮
**kwargs: 其他参数
Returns:
返回用户按下的按钮。
"""
return _show_messagebox(
text=text,
icon=CriticalIcon,
title=title,
buttons=buttons,
default_button=default_button,
**kwargs,
)
def show_question_messagebox(
text: str,
title: str = "Question",
buttons: Union[StandardButton, int] = Yes | No,
default_button: Union[StandardButton, int] = NoButton,
**kwargs,
) -> Union[int, StandardButton]:
"""
弹出Question消息对话框。
Args:
text: 消息文本
title: 对话框标题
buttons: 对话框的按钮
default_button: 默认按钮
**kwargs: 其他参数
Returns:
返回用户按下的按钮。
"""
return _show_messagebox(
text=text,
icon=QuestionIcon,
title=title,
buttons=buttons,
default_button=default_button,
**kwargs,
)
def show_text_content(
text_content: str,
text_format: Literal["markdown", "plaintext", "html"] = "markdown",
size: Tuple[int, int] = None,
title: Optional[str] = "",
icon: IconType = None,
buttons: Optional[DialogButtons] = DialogButtonOk,
resizeable: bool = True,
) -> None:
"""
显示多行文本内容。
Args:
text_content: 文本内容
text_format: 文本格式
size: 对话框尺寸
title: 对话框标题
icon: 对话框图标
buttons: 对话框按钮
resizeable: 对话框是否可调整大小
Returns:
无返回值
"""
return show_custom_dialog(
TextBrowserMessageBox,
text_content=text_content,
text_format=text_format,
size=size,
title=title,
icon=icon,
buttons=buttons,
resizeable=resizeable,
)
def show_text_file(
text_file: str,
text_format: Literal["markdown", "plaintext", "html"] = "markdown",
size: Tuple[int, int] = None,
title: Optional[str] = "",
icon: IconType = None,
buttons: Optional[DialogButtons] = DialogButtonOk,
resizeable: bool = True,
) -> None:
"""
展示文本文件内容。
Args:
text_file: 文本文件路径
text_format: 文本文件格式
size: 对话框尺寸
title: 对话框标题
icon: 对话框图标
buttons: 对话框按钮
resizeable: 对话框是否可调整大小
Returns:
无返回值
"""
text_content = io.read_text_file(text_file)
return show_text_content(
text_content=text_content,
text_format=text_format,
size=size,
title=title,
icon=icon,
buttons=buttons,
resizeable=resizeable,
)
| 6,322 | Python | .py | 226 | 18.969027 | 86 | 0.622255 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,512 | __init__.py | zimolab_PyGUIAdapter/pyguiadapter/adapter/__init__.py | from .adapter import GUIAdapter
from . import uoutput
from .udialog import BaseCustomDialog
# noinspection SpellCheckingInspection
__all__ = [
"GUIAdapter",
"BaseCustomDialog",
"uoutput",
]
| 203 | Python | .py | 9 | 20.111111 | 38 | 0.766839 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,513 | ucontext.py | zimolab_PyGUIAdapter/pyguiadapter/adapter/ucontext.py | """
@Time : 2024.10.20
@File : ucontext.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 维护全局上下文信息,提供一些核心功能
"""
import warnings
from concurrent.futures import Future
from typing import Any, Type, Optional, Callable, Dict
from qtpy.QtCore import QObject, Signal, QMutex
from ..utils import BaseCustomDialog
from ..utils.messagebox import show_messagebox
# noinspection PyProtectedMember
from ..windows.fnexec._base import BaseFnExecuteWindow
# noinspection PyMethodMayBeStatic,SpellCheckingInspection
class _Context(QObject):
sig_current_window_created = Signal(BaseFnExecuteWindow)
sig_current_window_destroyed = Signal()
# noinspection SpellCheckingInspection
sig_uprint = Signal(str, bool, bool)
# noinspection SpellCheckingInspection
sig_clear_output = Signal()
sig_show_messagebox = Signal(Future, dict)
sig_show_custom_dialog = Signal(Future, object, dict)
sig_get_input = Signal(Future, object)
sig_show_progressbar = Signal(dict)
sig_hide_progressbar = Signal()
sig_update_progressbar = Signal(int, str)
sig_clipboard_operation = Signal(Future, int, object)
sig_show_toast = Signal(str, int, object, bool)
sig_clear_toasts = Signal()
def __init__(self, parent):
super().__init__(parent)
self._lock = QMutex()
self._current_window: Optional[BaseFnExecuteWindow] = None
# noinspection PyUnresolvedReferences
self.sig_current_window_created.connect(self._on_current_window_created)
# noinspection PyUnresolvedReferences
self.sig_current_window_destroyed.connect(self._on_current_window_destroyed)
# noinspection PyUnresolvedReferences
self.sig_uprint.connect(self._on_uprint)
# noinspection PyUnresolvedReferences
self.sig_clear_output.connect(self._on_clear_output)
# noinspection PyUnresolvedReferences
self.sig_show_messagebox.connect(self._on_show_messagebox)
# noinspection PyUnresolvedReferences
self.sig_show_custom_dialog.connect(self._on_show_custom_dialog)
# noinspection PyUnresolvedReferences
self.sig_get_input.connect(self._on_get_input)
# noinspection PyUnresolvedReferences
self.sig_show_progressbar.connect(self._on_show_progressbar)
# noinspection PyUnresolvedReferences
self.sig_hide_progressbar.connect(self._on_hide_progressbar)
# noinspection PyUnresolvedReferences
self.sig_update_progressbar.connect(self._on_update_progressbar)
# noinspection PyUnresolvedReferences
self.sig_clipboard_operation.connect(self._on_clipboard_operation)
@property
def current_window(self) -> Optional[BaseFnExecuteWindow]:
return self._current_window
def is_function_cancelled(self) -> bool:
self._lock.lock()
if not isinstance(self._current_window, BaseFnExecuteWindow):
self._lock.unlock()
return False
cancelled = (
self._current_window.executor.is_executing
and self._current_window.executor.is_cancelled
)
self._lock.unlock()
return cancelled
def reset(self):
self._try_cleanup_old_window()
def _try_cleanup_old_window(self):
if self._current_window is not None:
try:
self._current_window.close()
self._current_window.deleteLater()
except Exception as e:
warnings.warn(f"error while closing window: {e}")
finally:
self._current_window = None
def _on_current_window_created(self, window: BaseFnExecuteWindow):
if not isinstance(window, BaseFnExecuteWindow):
raise TypeError(f"FnExecuteWindow expected, got {type(window)}")
self._try_cleanup_old_window()
self._current_window = window
def _on_current_window_destroyed(self):
self._current_window.deleteLater()
self._current_window = None
def _on_uprint(self, msg: str, html: bool, scroll_to_bottom: bool):
win = self.current_window
if not isinstance(win, BaseFnExecuteWindow):
warnings.warn("current_window is None")
print(msg)
return
win.append_output(msg, html, scroll_to_bottom)
def _on_clear_output(self):
wind = self.current_window
if not isinstance(wind, BaseFnExecuteWindow):
warnings.warn("current_window is None")
return
wind.clear_output()
def _on_show_messagebox(self, future: Future, kwargs: Dict[str, Any]):
win = self.current_window
if not isinstance(win, BaseFnExecuteWindow):
warnings.warn("current_window is None")
win = None
ret = show_messagebox(win, **kwargs)
future.set_result(ret)
def _on_show_custom_dialog(
self,
future: Future,
dialog_class: Type[BaseCustomDialog],
kwargs: Dict[str, Any],
):
win = self.current_window
if not isinstance(win, BaseFnExecuteWindow):
warnings.warn("current_window is None")
win = None
# dialog = dialog_class.new_instance(win, **kwargs)
# ret_code = dialog.exec_()
# result = dialog.get_result()
# dialog.deleteLater()
# future.set_result((ret_code, result))
result = dialog_class.show_and_get_result(win, **kwargs)
future.set_result(result)
def _on_get_input(
self, future: Future, get_input_impl: Callable[[BaseFnExecuteWindow], Any]
):
win = self.current_window
if not isinstance(win, BaseFnExecuteWindow):
warnings.warn("current_window is None")
win = None
result = get_input_impl(win)
future.set_result(result)
def _on_show_progressbar(self, config: dict):
win = self.current_window
if not isinstance(win, BaseFnExecuteWindow):
warnings.warn("current_window is None")
win = None
win.update_progressbar_config(config)
win.show_progressbar()
def _on_hide_progressbar(self):
win = self.current_window
if not isinstance(win, BaseFnExecuteWindow):
warnings.warn("current_window is None")
win = None
win.update_progressbar_config({})
win.hide_progressbar()
def _on_update_progressbar(self, progress: int, msg: str):
win = self.current_window
if not isinstance(win, BaseFnExecuteWindow):
warnings.warn("current_window is None")
win = None
win.update_progress(progress, msg)
def _on_clipboard_operation(self, future: Future, operation: int, data: object):
win = self.current_window
if not isinstance(win, BaseFnExecuteWindow):
warnings.warn("current_window is None")
return
win.on_clipboard_operation(future, operation, data)
_context = _Context(None)
################################################################################################
# Functions below with a leading '_' are for internal use only. DO NOT USE THEM IN USER'S CODE.#
# Other functions are free to use in user's function code. #
################################################################################################
def _reset():
global _context
_context.reset()
# noinspection PyUnresolvedReferences
def _current_window_created(window: BaseFnExecuteWindow):
global _context
_context.sig_current_window_created.emit(window)
# noinspection PyUnresolvedReferences
def _current_window_destroyed():
global _context
_context.sig_current_window_destroyed.emit()
def get_current_window() -> Optional[BaseFnExecuteWindow]:
global _context
return _context.current_window
def is_function_cancelled() -> bool:
"""检测函数是否被用户取消。
Returns:
检测到用户发出取消函数执行的请求时返回`True`,否则返回`False`
"""
global _context
return _context.is_function_cancelled()
| 8,152 | Python | .py | 189 | 34.835979 | 96 | 0.654683 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,514 | uoutput.py | zimolab_PyGUIAdapter/pyguiadapter/adapter/uoutput.py | """
@Time : 2024.10.20
@File : uoutput.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 提供信息打印相关的功能
"""
import dataclasses
import os.path
from typing import Optional, Union, Dict, Any
from ..constants.color import (
COLOR_INFO,
COLOR_DEBUG,
COLOR_WARNING,
COLOR_FATAL,
COLOR_CRITICAL,
)
from ..utils import io, to_base64
from . import ucontext
_MSG_TMPL = "<p><pre style='color:{color}'>{msg}</pre></p>"
# noinspection SpellCheckingInspection
def uprint(
*args: Any,
sep: str = " ",
end: str = "\n",
html: bool = False,
scroll_to_bottom: bool = True,
) -> None:
"""打印信息到输出浏览器
Args:
*args: 要打印的信息
sep: 每条信息之间的分隔字符串
end: 添加到最后一条信息后面的字符串
html: 要打印的信息是否为`html`格式
scroll_to_bottom: 打印信息后是否将`输出浏览器`滚动到最底部
Returns:
无返回值
"""
text = sep.join([str(arg) for arg in args]) + end
# noinspection PyUnresolvedReferences,PyProtectedMember
ucontext._context.sig_uprint.emit(text, html, scroll_to_bottom)
def clear_output() -> None:
"""清除`输出浏览器`中所有内容
Returns:
无返回值
"""
# noinspection PyUnresolvedReferences,PyProtectedMember
ucontext._context.sig_clear_output.emit()
@dataclasses.dataclass
class LoggerConfig(object):
"""
`Logger`的配置类,用于配置`Logger`的颜色等属性。
"""
info_color: str = COLOR_INFO
"""`info`级别消息的颜色值"""
debug_color: str = COLOR_DEBUG
"""`debug`级别消息的颜色值"""
warning_color: str = COLOR_WARNING
"""`warning`级别消息的颜色值"""
critical_color: str = COLOR_CRITICAL
"""`critical`级别消息的颜色值"""
fatal_color: str = COLOR_FATAL
"""`fatal`级别消息的颜色值"""
class Logger(object):
"""
该类用于向函数执行窗口的`输出浏览器`区域打印日志消息。不同级别的日志消息,主要以颜色进行区分。可以使用`LoggerConfig`实例指定各消息级别的颜色值。
示例:
```python
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import Logger, LoggerConfig
logger = Logger(
config=LoggerConfig(
info_color="green",
debug_color="blue",
warning_color="yellow",
critical_color="red",
fatal_color="magenta",
)
)
def output_log_msg(
info_msg: str = "info message",
debug_msg: str = "debug message",
warning_msg: str = "warning message",
critical_msg: str = "critical message",
fatal_msg: str = "fatal message",
):
logger.info(info_msg)
logger.debug(debug_msg)
logger.warning(warning_msg)
logger.critical(critical_msg)
logger.fatal(fatal_msg)
if __name__ == "__main__":
adapter = GUIAdapter()
adapter.add(output_log_msg)
adapter.run()
```
结果:

"""
def __init__(self, config: Optional[LoggerConfig] = None):
self._config = config or LoggerConfig()
@property
def config(self) -> LoggerConfig:
return self._config
def info(self, msg: str) -> None:
"""打印`info`级别的消息。
Args:
msg: 要打印的消息
Returns:
无返回值
"""
uprint(self._message(self._config.info_color, msg), html=True)
def debug(self, msg: str) -> None:
"""打印`debug`级别的消息。
Args:
msg: 要打印的消息
Returns:
无返回值
"""
uprint(self._message(self._config.debug_color, msg), html=True)
def warning(self, msg: str) -> None:
"""打印`warning`级别的消息。
Args:
msg: 要打印的消息
Returns:
无返回值
"""
uprint(self._message(self._config.warning_color, msg), html=True)
def critical(self, msg: str) -> None:
"""打印`critical`级别的消息。
Args:
msg: 要打印的消息
Returns:
无返回值
"""
uprint(self._message(self._config.critical_color, msg), html=True)
def fatal(self, msg: str) -> None:
"""打印`fatal`级别的消息。
Args:
msg: 要打印的消息
Returns:
无返回值
"""
uprint(self._message(self._config.fatal_color, msg), html=True)
@staticmethod
def _message(color: str, msg: str):
return _MSG_TMPL.format(color=color, msg=msg)
_global_logger = Logger()
def info(msg: str) -> None:
"""模块级函数。打印`info`级别的消息。`info`消息颜色值默认为:<b>`#00FF00`</b>。
Args:
msg: 要打印的消息
Returns:
无返回值
"""
_global_logger.info(msg)
def debug(msg: str) -> None:
"""模块级函数。打印`debug`级别的消息。`debug`消息颜色值默认为:<b>`#909399`</b>。
Args:
msg: 要打印的消息
Returns:
无返回值
"""
_global_logger.debug(msg)
def warning(msg: str) -> None:
"""模块级函数。打印`warning`级别的消息。`warning`消息颜色值默认为:<b>`#FFFF00`</b>。
Args:
msg: 要打印的消息
Returns:
无返回值
"""
_global_logger.warning(msg)
def critical(msg: str) -> None:
"""模块级函数。打印`critical`级别的消息。`critical`消息颜色值默认为:<b>`#A61C00`</b>。
Args:
msg: 要打印的消息
Returns:
无返回值
"""
_global_logger.critical(msg)
def fatal(msg: str) -> None:
"""模块级函数。打印`fatal`级别的消息。`fatal`消息颜色值默认为:<b>`#FF0000`</b>。
Args:
msg: 要打印的消息
Returns:
无返回值
"""
_global_logger.fatal(msg)
def _join_props(props: Dict[str, Any]):
return " ".join([f'{k}="{v}"' for k, v in props.items() if v is not None])
def _make_img_url(img: str, props: Dict[str, Any]) -> str:
return f'<img src="{os.path.abspath(img)}" {_join_props(props)} />'
def _make_embed_img_url(img: bytes, img_type: str, props: Dict[str, Any]) -> str:
return f'<img src="data:image/{img_type};base64,{to_base64(img)}" {_join_props(props)} />'
def print_image(
img: Union[str, bytes],
img_type: str = "jpeg",
embed_base64: bool = False,
width: Optional[int] = None,
height: Optional[int] = None,
centered: bool = True,
) -> None:
"""
模块级函数。打印图片。
Args:
img: 待打印的图片。可以为图片文件的路径(`str`)或图片的二进制数据(`bytes`)
img_type: 图片类型。
embed_base64: 是否使用`data url`(`base64格式`)嵌入图片。传入二进制图片数据时,将忽略此参数。
width: 图片的宽度。若未指定,则显示图片的原始宽度。
height: 图片的高度。若未指定,则显示图片的原始高度。
centered: 是否将图片居中显示。
Returns:
无返回值。
"""
props = {
"width": width,
"height": height,
}
uprint("print image...")
uprint("<p>some text</p>", html=True)
if isinstance(img, str):
if not embed_base64:
url = _make_img_url(img, props)
else:
url = _make_embed_img_url(io.read_file(img), img_type, props)
else:
url = _make_embed_img_url(img, img_type, props)
if centered:
url = f'<br /><div style="text-align:center;">{url}</div><br />'
else:
url = f"<br /><div>{url}</div><br />"
uprint(url, html=True)
del url
| 7,993 | Python | .py | 233 | 22.317597 | 95 | 0.591884 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,515 | utoast.py | zimolab_PyGUIAdapter/pyguiadapter/adapter/utoast.py | """
@Time : 2024.10.20
@File : utoast.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 提供toast消息弹窗相关的功能
"""
from typing import Optional
from .ucontext import _context
from ..toast import ToastConfig
# noinspection PyProtectedMember
from ..windows.fnexec._base import BaseFnExecuteWindow
def _on_show_toast(
message: str, duration: int, config: Optional[ToastConfig], clear: bool
) -> None:
wind = _context.current_window
if not isinstance(wind, BaseFnExecuteWindow):
return
wind.show_toast(message, duration, config, clear)
wind = None
def _on_clear_toasts() -> None:
wind = _context.current_window
if not isinstance(wind, BaseFnExecuteWindow):
return
wind.clear_toasts()
wind = None
_context.sig_show_toast.connect(_on_show_toast)
_context.sig_clear_toasts.connect(_on_clear_toasts)
def show_toast(
message: str,
duration: int = 3000,
config: Optional[ToastConfig] = None,
clear: bool = False,
) -> None:
"""
展示toast消息。
Args:
message: toast消息内容
duration: toast显示时间,单位为毫秒
config: toast配置
clear: 是否清除之前的toast消息
Returns:
无返回值
"""
_context.sig_show_toast.emit(message, duration, config, clear)
def clear_toasts() -> None:
"""
清除所有toast消息。
Returns:
无返回值
"""
_context.sig_clear_output.emit()
| 1,489 | Python | .py | 52 | 22.096154 | 75 | 0.683728 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,516 | adapter.py | zimolab_PyGUIAdapter/pyguiadapter/adapter/adapter.py | """
@Time : 2024.10.20
@File : adapter.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 定义了GUI适配器类GUIAdapter,负责管理函数和启动GUI应用。
"""
import sys
import warnings
from collections import OrderedDict
from typing import (
Literal,
Dict,
Type,
Tuple,
List,
Union,
Optional,
Callable,
Sequence,
)
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QApplication
from . import ucontext
from ..action import Separator
from ..bundle import FnBundle
from ..exceptions import NotRegisteredError
from ..fn import ParameterInfo
from ..menu import Menu
from ..paramwidget import (
BaseParameterWidget,
BaseParameterWidgetConfig,
is_parameter_widget_class,
)
from ..parser import FnParser
from ..toolbar import ToolBar
from ..utils import IconType
from ..widgets import ParameterWidgetFactory
from ..window import BaseWindowEventListener
from ..windows.fnexec import FnExecuteWindow, FnExecuteWindowConfig
from ..windows.fnselect import FnSelectWindow, FnSelectWindowConfig
class GUIAdapter(object):
"""
GUI适配器类,负责管理函数和启动GUI应用。
"""
def __init__(
self,
*,
hdpi_mode: bool = True,
global_stylesheet: Union[str, Callable[[], str], None] = None,
on_app_start: Optional[Callable[[QApplication], None]] = None,
on_app_shutdown: Optional[Callable] = None,
):
"""
`GUIAdapter`构造函数。用于创建`GUIAdapter`实例。
Args:
hdpi_mode: 启用高DPI模式。某些Qt版本上,该参数不生效。
global_stylesheet: 应用全局样式。可以为样式表字符串,也可以为一个返回全局样式表字符串的函数。
on_app_start: 应用启动回调函数。在应用启动时调用。
on_app_shutdown: 应用停止回调函数。在应用停止时调用。
Examples:
```python
from pyguiadapter.adapter import GUIAdapter
def foo(a: int, b: int, c: str):
pass
adapter = GUIAdapter()
adapter.add(foo)
adapter.run()
```
"""
self._hdpi_mode: bool = hdpi_mode
self._global_stylesheet: Optional[str] = global_stylesheet
self._on_app_start: Optional[Callable[[QApplication], None]] = on_app_start
self._on_app_shutdown: Optional[Callable] = on_app_shutdown
self._bundles: Dict[Callable, FnBundle] = OrderedDict()
self._fn_parser = FnParser()
self._application: Optional[QApplication] = None
self._select_window: Optional[FnSelectWindow] = None
self._execute_window: Optional[FnExecuteWindow] = None
def add(
self,
fn: Callable,
display_name: Optional[str] = None,
group: Optional[str] = None,
icon: IconType = None,
document: Optional[str] = None,
document_format: Literal["markdown", "html", "plaintext"] = "markdown",
cancelable: bool = False,
*,
widget_configs: Optional[
Dict[str, Union[BaseParameterWidgetConfig, dict]]
] = None,
window_config: Optional[FnExecuteWindowConfig] = None,
window_listener: Optional[BaseWindowEventListener] = None,
window_toolbar: Optional[ToolBar] = None,
window_menus: Optional[List[Union[Menu, Separator]]] = None,
) -> None:
"""
添加一个函数。
Args:
fn: 待添加的函数。
display_name: 函数的显示名称。如果不指定,则使用函数的名称。
group: 函数所属的分组。如果不指定,则将函数添加到默认分组。
icon: 函数的图标。可以为文件路径,也可使用QtAwesome支持的图标名称。
document: 函数的说明文档。若不指定,则尝试提取函数的docstring作为文档。
document_format: 函数说明文档的格式。可以为"markdown"、"html"或"plaintext"。
cancelable: 函数是否可取消。
widget_configs: 函数参数控件配置。键为参数名,值为参数控件配置。
window_config: 窗口配置。
window_listener: 窗口事件监听器。
window_toolbar: 窗口的工具栏。
window_menus: 窗口菜单列表。
Returns:
无返回值
"""
# create the FnInfo from the function and given arguments
fn_info = self._fn_parser.parse_fn_info(
fn,
display_name=display_name,
group=group,
icon=icon,
document=document,
document_format=document_format,
)
fn_info.cancelable = cancelable
# configs for parameter widget can be from various sources
# for example, from the function signature or function docstring, those are automatically parsed by FnParser
# user can override those auto-parsed configs with 'widget_configs' of this method
# That means the user's 'widget_configs' has a higher priority than the auto-parsed widget configs
user_widget_configs = widget_configs or {}
parsed_widget_configs = self._fn_parser.parse_widget_configs(fn_info)
widget_configs: Dict[
str, Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig]
] = self._merge_widget_configs(
parameters=fn_info.parameters,
parsed_configs=parsed_widget_configs,
user_configs=user_widget_configs,
)
window_config = window_config or FnExecuteWindowConfig()
bundle = FnBundle(
fn_info,
widget_configs=widget_configs,
window_config=window_config,
window_listener=window_listener,
window_toolbar=window_toolbar,
window_menus=window_menus,
)
self._bundles[fn] = bundle
def remove(self, fn: Callable) -> None:
"""
移除一个已添加的函数。
Args:
fn: 待移除的函数。
Returns:
无返回值
"""
if fn in self._bundles:
del self._bundles[fn]
def exists(self, fn: Callable) -> bool:
"""
判断函数是否已添加。
Args:
fn: 目标函数
Returns:
函数是否已添加
"""
return fn in self._bundles
# def get_bundle(self, fn: Callable) -> Optional[FnBundle]:
# return self._bundles.get(fn, None)
#
# def clear_bundles(self):
# self._bundles.clear()
def run(
self,
argv: Optional[Sequence[str]] = None,
*,
show_select_window: bool = False,
select_window_config: Optional[FnSelectWindowConfig] = None,
select_window_listener: Optional[BaseWindowEventListener] = None,
select_window_toolbar: Optional[ToolBar] = None,
select_window_menus: Optional[List[Union[Menu, Separator]]] = None,
) -> None:
"""
启动GUI应用。
Args:
argv: 传递给QApplication的命令行参数。
show_select_window: 是否强制显示函数选择窗口,当添加的函数数量大于1时,默认显示。
select_window_config: 函数选择窗口配置。
select_window_listener: 函数选择窗口事件监听器。
select_window_toolbar: 函数选择窗口的工具栏。
select_window_menus: 函数选择窗口菜单列表。
Returns:
无返回值
"""
if self._application is None:
self._start_application(argv)
# noinspection PyProtectedMember
ucontext._reset()
count = len(self._bundles)
if count == 0:
self._shutdown_application()
raise RuntimeError("no functions has been added")
try:
if count == 1 and not show_select_window:
fn_bundle = next(iter(self._bundles.values()))
self._show_execute_window(fn_bundle)
else:
self._show_select_window(
list(self._bundles.values()),
config=select_window_config or FnSelectWindowConfig(),
listener=select_window_listener,
toolbar=select_window_toolbar,
menus=select_window_menus,
)
self._application.exec()
except Exception as e:
raise e
finally:
self._shutdown_application()
def is_application_started(self) -> bool:
return self._application is not None
@property
def application(self) -> Optional[QApplication]:
return self._application
def _start_application(self, argv: Optional[Sequence[str]]):
if argv is None:
argv = sys.argv
if self._application is not None:
warnings.warn("application already started")
return
if self._hdpi_mode and hasattr(Qt, "AA_EnableHighDpiScaling"):
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
self._application = QApplication(argv)
if self._global_stylesheet:
if isinstance(self._global_stylesheet, str):
self._application.setStyleSheet(self._global_stylesheet)
if callable(self._global_stylesheet):
self._application.setStyleSheet(self._global_stylesheet())
if self._on_app_start:
self._on_app_start(self._application)
def _shutdown_application(self):
if self._application is None:
warnings.warn("application not started yet")
return
# noinspection PyProtectedMember
ucontext._reset()
self._application.closeAllWindows()
self._application.quit()
self._application = None
if self._on_app_shutdown:
self._on_app_shutdown()
def _show_select_window(
self,
bundles: List[FnBundle],
config: FnSelectWindowConfig,
listener: Optional[BaseWindowEventListener],
toolbar: Optional[ToolBar],
menus: Optional[List[Union[Menu, Separator]]],
):
if self._select_window is not None:
return
self._select_window = FnSelectWindow(
parent=None,
bundles=bundles,
config=config,
listener=listener,
toolbar=toolbar,
menus=menus,
)
self._select_window.setAttribute(Qt.WA_DeleteOnClose, True)
# noinspection PyUnresolvedReferences
self._select_window.destroyed.connect(self._on_select_window_destroyed)
self._select_window.start()
def _on_select_window_destroyed(self):
self._select_window = None
# noinspection PyUnresolvedReferences
def _show_execute_window(self, bundle: FnBundle):
if self._execute_window is not None:
return
self._execute_window = FnExecuteWindow(None, bundle=bundle)
self._execute_window.setAttribute(Qt.WA_DeleteOnClose, True)
self._execute_window.setWindowModality(Qt.ApplicationModal)
self._execute_window.destroyed.connect(self._on_execute_window_destroyed)
self._execute_window.show()
def _on_execute_window_destroyed(self):
self._execute_window = None
def _merge_widget_configs(
self,
parameters: Dict[str, ParameterInfo],
parsed_configs: Dict[str, Tuple[Optional[str], dict]],
user_configs: Dict[str, Union[BaseParameterWidgetConfig, dict]],
) -> Dict[str, Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig]]:
final_configs: Dict[
str, Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig]
] = OrderedDict()
for param_name, (
p_widget_class_name,
p_widget_config,
) in parsed_configs.items():
assert isinstance(p_widget_class_name, (str, type(None)))
assert isinstance(p_widget_config, dict)
param_info = parameters.get(param_name, None)
assert param_info is not None
p_widget_class = self._get_widget_class(p_widget_class_name, param_info)
user_config = user_configs.get(param_name, None)
if user_config is None:
widget_class = p_widget_class
if not is_parameter_widget_class(widget_class):
raise NotRegisteredError(
f"unknown widget class name for: {param_info.type}"
)
widget_config = widget_class.ConfigClass.new(**p_widget_config)
final_configs[param_name] = (widget_class, widget_config)
continue
assert isinstance(user_config, (dict, BaseParameterWidgetConfig))
if isinstance(user_config, dict):
widget_class = p_widget_class
if not is_parameter_widget_class(widget_class):
raise NotRegisteredError(
f"unknown widget class name: {p_widget_class_name}"
)
# override parsed config with user config
tmp = {**p_widget_config, **user_config}
widget_config = widget_class.ConfigClass.new(**tmp)
final_configs[param_name] = (widget_class, widget_config)
continue
# when user_config is a BaseParameterWidgetConfig instance
widget_class = user_config.target_widget_class()
widget_config = user_config
final_configs[param_name] = (widget_class, widget_config)
return final_configs
@staticmethod
def _get_widget_class(
widget_class_name: Optional[str], param_info: ParameterInfo
) -> Optional[Type[BaseParameterWidget]]:
if widget_class_name is not None:
widget_class_name = widget_class_name.strip()
if widget_class_name:
return ParameterWidgetFactory.find_by_widget_class_name(widget_class_name)
widget_class = ParameterWidgetFactory.find_by_typename(param_info.typename)
if is_parameter_widget_class(widget_class):
return widget_class
return ParameterWidgetFactory.find_by_rule(param_info)
| 14,435 | Python | .py | 343 | 29.419825 | 116 | 0.618026 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,517 | uprogress.py | zimolab_PyGUIAdapter/pyguiadapter/adapter/uprogress.py | """
@Time : 2024.10.20
@File : uprogress.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 提供进度条相关的功能
"""
from typing import Literal, Optional
from .ucontext import _context
def show_progressbar(
min_value: int = 0,
max_value: int = 100,
inverted_appearance: bool = False,
*,
message_visible: bool = False,
message_format: str = "%p%",
message_centered: str = True,
info_visible: bool = True,
info_centered: bool = True,
info_text_format: Literal[
"richtext", "markdown", "plaintext", "autotext"
] = "autotext",
initial_info: str = "",
) -> None:
"""
显示进度条。默认情况下,进度条处于隐藏状态,开发者必须手动调用此函数来显示进度条,此函数除了用于显示进度条,还可以对进度条进行配置。
Args:
min_value: 最小进度值,默认为`0`
max_value: 最大进度值,默认为`100`
inverted_appearance: 是否改变进度条的显示方式,使其以反方向显示进度
message_visible: 是否显示message信息
message_format: message信息的格式,支持:`%p%`(显示完成的百分比,这是默认显示方式)、`%v`(显示当前的进度值)和`%m`(显示总的步进值)
message_centered: message信息是否居中显示
info_visible: 是否显示info区域
info_centered: info信息是否居中显示
info_text_format: info信息的文本格式,支持`"richtext"` 、` "markdown"` 、`"plaintext"` 、`"autotext"`
initial_info: info信息的初始值
Returns:
无返回值
"""
config = {
"min_value": min_value,
"max_value": max_value,
"inverted_appearance": inverted_appearance,
"message_visible": message_visible,
"message_format": message_format,
"message_centered": message_centered,
"show_info_label": info_visible,
"info_text_centered": info_centered,
"info_text_format": info_text_format,
"initial_info": initial_info,
}
_context.sig_show_progressbar.emit(config)
def hide_progressbar() -> None:
"""
隐藏进度条
Returns:
无返回值
"""
_context.sig_hide_progressbar.emit()
def update_progress(value: int, info: Optional[str] = None) -> None:
"""
更新进度信息
Args:
value: 当前进度值
info: 当前info文本
Returns:
无返回值
"""
_context.sig_update_progressbar.emit(value, info)
| 2,577 | Python | .py | 70 | 23.885714 | 96 | 0.633733 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,518 | ubeep.py | zimolab_PyGUIAdapter/pyguiadapter/adapter/ubeep.py | """
@Time : 2024.10.20
@File : ubeep.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 提供了发出蜂鸣声的功能
"""
from qtpy.QtWidgets import QApplication
def beep() -> None:
"""
发出蜂鸣声。
Returns:
无返回值
"""
QApplication.beep()
| 299 | Python | .py | 15 | 14 | 39 | 0.621849 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,519 | uinput.py | zimolab_PyGUIAdapter/pyguiadapter/adapter/uinput.py | """
@Time : 2024.10.20
@File : uinput.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 提供输入框相关的功能
"""
from concurrent.futures import Future
from typing import (
List,
Tuple,
Literal,
Callable,
Any,
Optional,
Union,
Sequence,
Type,
)
from qtpy.QtCore import QUrl
from qtpy.QtGui import QColor
from .ucontext import _context
from ..utils import EchoMode, inputdialog, filedialog, IconType, PyLiteralType
from ..utils.inputdialog import LineWrapMode, UniversalInputDialog
from ..windows.fnexec import FnExecuteWindow
def _get_input(get_input_impl: Callable[[FnExecuteWindow], Any]) -> Any:
result_future = Future()
# noinspection PyUnresolvedReferences
_context.sig_get_input.emit(result_future, get_input_impl)
return result_future.result()
def get_string(
title: str = "Input Text",
label: str = "",
echo: Optional[EchoMode] = None,
text: str = "",
) -> Optional[str]:
"""
弹出单行文本输入框,返回用户输入的字符串。
Args:
title: 对话框标题
label: 提示标签
echo: 回显模式
text: 初始文本
Returns:
用户输入的字符串,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Optional[str]:
return inputdialog.input_string(wind, title, label, echo, text)
return _get_input(_impl)
def get_text(
title: str = "Input Text", label: str = "", text: str = ""
) -> Optional[str]:
"""
弹出多行文本输入框,返回用户输入的字符串。
Args:
title: 对话框标题
label: 提示标签
text: 初始文本
Returns:
用户输入的字符串,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Optional[str]:
return inputdialog.input_text(wind, title, label, text)
return _get_input(_impl)
def get_int(
title: str = "Input Integer",
label: str = "",
value: int = 0,
min_value: int = -2147483647,
max_value: int = 2147483647,
step: int = 1,
) -> Optional[int]:
"""
弹出整数输入框,返回用户输入的整数。
Args:
title: 对话框标题
label: 提示标签
value: 初始值
min_value: 最小值
max_value: 最大值
step: 步长
Returns:
用户输入的整数,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Optional[int]:
return inputdialog.input_integer(
wind, title, label, value, min_value, max_value, step
)
return _get_input(_impl)
def get_float(
title: str = "Input Float",
label: str = "",
value: float = 0.0,
min_value: float = -2147483647.0,
max_value: float = 2147483647.0,
decimals: int = 3,
step: float = 1.0,
) -> Optional[float]:
"""
弹出浮点数输入框,返回用户输入的浮点数。
Args:
title: 对话框标题
label: 提示标签
value: 初始值
min_value: 最小值
max_value: 最大值
decimals: 小数位数
step: 步长
Returns:
用户输入的浮点数,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Optional[float]:
return inputdialog.input_float(
wind, title, label, value, min_value, max_value, decimals, step
)
return _get_input(_impl)
def get_selected_item(
items: List[str],
title: str = "Select Item",
label: str = "",
current: int = 0,
editable: bool = False,
) -> Optional[str]:
"""
弹出选项列表,返回用户选择的项目。
Args:
items: 项目列表
title: 对话框标题
label: 提示标签
current: 当前选择项索引
editable: 是否可编辑
Returns:
用户选择的项目,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]):
return inputdialog.select_item(wind, items, title, label, current, editable)
return _get_input(_impl)
def get_color(
initial: Union[QColor, str, tuple] = "white",
title: str = "",
alpha_channel: bool = True,
return_type: Literal["tuple", "str", "QColor"] = "str",
) -> Union[Tuple[int, int, int], Tuple[int, int, int], str, QColor, None]:
"""
弹出颜色选择框,返回用户选择的颜色。
Args:
initial: 初始颜色
title: 对话框标题
alpha_channel: 是否显示Alpha通道
return_type: 返回类型,可以是tuple、str、QColor
Returns:
用户选择的颜色,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Optional[QColor]:
return inputdialog.input_color(wind, initial, title, alpha_channel, return_type)
return _get_input(_impl)
def get_json_object(
title: str = "Input Json",
icon: IconType = None,
size: Tuple[int, int] = (600, 400),
ok_button_text: str = "Ok",
cancel_button_text: Optional[str] = "Cancel",
initial_text: str = "",
auto_indent: bool = True,
indent_size: int = 4,
auto_parentheses: bool = True,
line_wrap_mode: LineWrapMode = LineWrapMode.WidgetWidth,
line_wrap_width: int = 88,
font_family: Union[str, Sequence[str], None] = None,
font_size: Optional[int] = None,
**kwargs,
) -> Any:
"""
弹出Json输入框,返回用户输入的Json对象。
Args:
title: 对话框标题
icon: 窗口图标
size: 窗口大小
ok_button_text: 确定按钮文本
cancel_button_text: 取消按钮文本
initial_text: 初始文本
auto_indent: 是否自动缩进
indent_size: 缩进大小
auto_parentheses: 是否自动匹配括号
line_wrap_mode: 换行模式
line_wrap_width: 换行宽度
font_family: 字体
font_size: 字体大小
**kwargs: 其他参数
Returns:
用户输入的Json对象,如果用户取消输入则返回None。
Raises:
Exception: 如果输入了非法的Json文本,则会抛出异常。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Any:
return inputdialog.input_json_object(
wind,
title=title,
icon=icon,
size=size,
ok_button_text=ok_button_text,
cancel_button_text=cancel_button_text,
initial_text=initial_text,
auto_indent=auto_indent,
indent_size=indent_size,
auto_parentheses=auto_parentheses,
line_wrap_mode=line_wrap_mode,
line_wrap_width=line_wrap_width,
font_family=font_family,
font_size=font_size,
**kwargs,
)
return _get_input(_impl)
def get_py_literal(
title: str = "Input Python Literal",
icon: IconType = None,
size: Tuple[int, int] = (600, 400),
ok_button_text: str = "Ok",
cancel_button_text: Optional[str] = "Cancel",
initial_text: str = "",
auto_indent: bool = True,
indent_size: int = 4,
auto_parentheses: bool = True,
line_wrap_mode: LineWrapMode = LineWrapMode.WidgetWidth,
line_wrap_width: int = 88,
font_family: Union[str, Sequence[str], None] = None,
font_size: Optional[int] = None,
**kwargs,
) -> PyLiteralType:
"""
弹出Python字面量输入框,返回用户输入的Python字面量。
Args:
title: 对话框标题
icon: 窗口图标
size: 窗口大小
ok_button_text: 确定按钮文本
cancel_button_text: 取消按钮文本
initial_text: 初始文本
auto_indent: 是否自动缩进
indent_size: 缩进大小
auto_parentheses: 是否自动匹配括号
line_wrap_mode: 换行模式
line_wrap_width: 换行宽度
font_family: 字体
font_size: 字体大小
**kwargs: 其他参数
Returns:
用户输入的Python字面量,如果用户取消输入则返回None。
Raises:
Exception: 如果输入了非法的Python字面量(即ast.literal_eval()无法解析的内容),则会抛出异常。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Any:
return inputdialog.input_py_literal(
wind,
title=title,
icon=icon,
size=size,
ok_button_text=ok_button_text,
cancel_button_text=cancel_button_text,
initial_text=initial_text,
auto_indent=auto_indent,
indent_size=indent_size,
auto_parentheses=auto_parentheses,
line_wrap_mode=line_wrap_mode,
line_wrap_width=line_wrap_width,
font_family=font_family,
font_size=font_size,
**kwargs,
)
return _get_input(_impl)
def get_custom_input(
input_dialog_class: Type[UniversalInputDialog],
**input_dialog_args,
) -> Any:
"""
弹出自定义输入框,返回用户输入的内容。
Args:
input_dialog_class: 自定义输入框类
**input_dialog_args: 自定义输入框参数
Returns:
用户输入的内容,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Any:
return inputdialog.get_custom_input(
wind, input_dialog_class, **input_dialog_args
)
return _get_input(_impl)
def get_existing_directory(
title: str = "",
start_dir: str = "",
) -> Optional[str]:
"""
弹出选择文件夹对话框,返回用户选择的目录。
Args:
title: 对话框标题
start_dir: 起始目录
Returns:
用户选择的目录,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Optional[str]:
return filedialog.get_existing_directory(wind, title, start_dir)
return _get_input(_impl)
def get_existing_directory_url(
title: str = "",
start_dir: Optional[QUrl] = None,
supported_schemes: Optional[List[str]] = None,
) -> Optional[QUrl]:
"""
弹出选择文件夹对话框,返回用户选择的目录的URL。
Args:
title: 对话框标题
start_dir: 起始目录
supported_schemes: 支持的协议
Returns:
用户选择的目录的URL,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> QUrl:
return filedialog.get_existing_directory_url(
wind, title, start_dir, supported_schemes
)
return _get_input(_impl)
def get_open_file(
title: str = "",
start_dir: str = "",
filters: str = "",
) -> Optional[str]:
"""
弹出打开文件对话框,返回用户选择的文件。
Args:
title: 对话框标题
start_dir: 起始目录
filters: 文件过滤器
Returns:
用户选择的文件路径,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Optional[str]:
return filedialog.get_open_file(wind, title, start_dir, filters)
return _get_input(_impl)
def get_open_files(
title: str = "",
start_dir: str = "",
filters: str = "",
) -> Optional[List[str]]:
"""
弹出打开文件对话框,返回用户选择的多个文件。
Args:
title: 对话框标题
start_dir: 起始目录
filters: 文件过滤器
Returns:
用户选择的文件路径列表,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Optional[List[str]]:
return filedialog.get_open_files(wind, title, start_dir, filters)
return _get_input(_impl)
def get_save_file(
title: str = "",
start_dir: str = "",
filters: str = "",
) -> Optional[str]:
"""
弹出保存文件对话框,返回用户输入或选择的文件路径。
Args:
title: 对话框标题
start_dir: 起始目录
filters: 文件过滤器
Returns:
用户输入或选择的文件路径,如果用户取消输入则返回None。
"""
def _impl(wind: Optional[FnExecuteWindow]) -> Optional[str]:
return filedialog.get_save_file(wind, title, start_dir, filters)
return _get_input(_impl)
| 12,540 | Python | .py | 372 | 21.846774 | 88 | 0.612245 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,520 | constants.py | zimolab_PyGUIAdapter/pyguiadapter/codeeditor/constants.py | DEFAULT_WINDOW_TITLE = "Code Editor"
DEFAULT_UNTITLED_FILENAME = "Untitled"
DEFAULT_TAB_SIZE = 4
DEFAULT_ICON_SIZE = (24, 24)
DEFAULT_LINE_WRAP_WIDTH = 88
QUIT_DIALOG_TITLE = "Quit"
CONFIRM_DIALOG_TITLE = "Confirm"
ERROR_DIALOG_TITLE = "Error"
UNSAVED_WARNING_MSG = "Unsaved changes will be lost. Continue?"
OPEN_FILE_DIALOG_TITLE = "Open"
SAVE_FILE_DIALOG_TITLE = "Save"
SAVE_AS_DIALOG_TITLE = "Save As"
SAVE_FAILED_MSG = "Failed to save file {}"
OPEN_FAILED_MSG = "Failed to open file {}"
FORMAT_FAILED_MSG = "Failed to format code"
MENU_FILE = "File"
MENU_EDIT = "Edit"
ACTION_OPEN = "Open"
ACTION_SAVE = "Save"
ACTION_SAVE_AS = "Save as"
ACTION_QUIT = "Quit"
ACTION_UNDO = "Undo"
ACTION_REDO = "Redo"
ACTION_CUT = "Cut"
ACTION_COPY = "Copy"
ACTION_PASTE = "Paste"
ACTION_SELECT_ALL = "Select all"
ACTION_FORMAT_CODE = "Format code"
| 839 | Python | .py | 28 | 28.857143 | 63 | 0.733911 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,521 | _example.py | zimolab_PyGUIAdapter/pyguiadapter/codeeditor/_example.py | from pyqcodeeditor.highlighters import QPythonHighlighter
from qtpy.QtWidgets import QApplication
from pyguiadapter.codeeditor import (
CodeEditorWindow,
CodeEditorConfig,
PythonFormatter,
)
app = QApplication([])
config = CodeEditorConfig(
highlighter=QPythonHighlighter,
formatter=PythonFormatter(),
file_filters="python(*.py)",
use_default_menus=True,
# exclude_default_menus=["Edit", "File"],
# exclude_default_menu_actions=(
# ("File", "Save"),
# ("File", "Save as"),
# ("Edit", "Select all"),
# ),
# exclude_default_toolbar_actions=("Save",),
)
window = CodeEditorWindow(None, config)
window.show()
app.exec_()
| 687 | Python | .py | 24 | 25.208333 | 57 | 0.694402 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,522 | __init__.py | zimolab_PyGUIAdapter/pyguiadapter/codeeditor/__init__.py | from .base import (
LineWrapMode,
WordWrapMode,
BaseCodeEditorWindow,
BaseCodeFormatter,
create_highlighter,
)
from .editor import CodeEditorWindow, CodeEditorConfig
from .formatters import JsonFormatter, PythonFormatter
__all__ = [
"LineWrapMode",
"WordWrapMode",
"BaseCodeEditorWindow",
"CodeEditorWindow",
"CodeEditorConfig",
"BaseCodeFormatter",
"JsonFormatter",
"PythonFormatter",
"create_highlighter",
]
| 467 | Python | .py | 20 | 19.5 | 54 | 0.737668 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,523 | editor.py | zimolab_PyGUIAdapter/pyguiadapter/codeeditor/editor.py | import dataclasses
from typing import Optional, List, Union
from pyqcodeeditor.QStyleSyntaxHighlighter import QStyleSyntaxHighlighter
from qtpy.QtWidgets import QWidget
from .actions import DEFAULT_MENUS, DEFAULT_TOOLBAR
from .base import BaseCodeEditorWindow, CodeEditorConfig
from .. import utils
from ..action import Separator
from ..toolbar import ToolBar
from ..window import BaseWindowEventListener
class CodeEditorWindow(BaseCodeEditorWindow):
def __init__(
self,
parent: Optional[QWidget],
config: Optional[CodeEditorConfig] = None,
listener: Optional[BaseWindowEventListener] = None,
toolbar: Optional[ToolBar] = None,
menus: Optional[List[Union[ToolBar, Separator]]] = None,
):
config = config or CodeEditorConfig()
if config.use_default_menus and not menus:
exclude_menus = config.excluded_menus
_menus = {
menu.title: dataclasses.replace(menu)
for menu in DEFAULT_MENUS
if menu.title not in exclude_menus
}
exclude_menu_actions = config.excluded_menu_actions
for menu_title, exclude_action in exclude_menu_actions:
menu = _menus.get(menu_title, None)
if not menu:
continue
menu.remove_action(exclude_action)
menus = list(_menus.values())
if config.use_default_toolbar and not toolbar:
toolbar = DEFAULT_TOOLBAR
exclude_toolbar_actions = config.excluded_toolbar_actions
for exclude_action in exclude_toolbar_actions:
toolbar.remove_action(exclude_action)
self.__current_file: Optional[str] = None
self.__fingerprint: Optional[str] = utils.fingerprint(config.initial_text)
self.__highlighter: Optional[QStyleSyntaxHighlighter] = None
super().__init__(parent, config, listener, toolbar, menus)
def _current_highlighter(self) -> Optional[QStyleSyntaxHighlighter]:
return self.__highlighter
def _update_current_highlighter(
self, highlighter: Optional[QStyleSyntaxHighlighter]
):
self.__highlighter = highlighter
def _current_fingerprint(self) -> Optional[str]:
return self.__fingerprint
def _update_fingerprint(self):
self.__fingerprint = utils.fingerprint(self.get_text())
def _current_file(self) -> Optional[str]:
self._config: CodeEditorConfig
if self._config.no_file_mode:
return None
return self.__current_file
def _update_current_file(self, file: str):
self._config: CodeEditorConfig
if self._config.no_file_mode:
return
self.__current_file = file
| 2,769 | Python | .py | 63 | 34.904762 | 82 | 0.665923 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,524 | base.py | zimolab_PyGUIAdapter/pyguiadapter/codeeditor/base.py | import dataclasses
import inspect
import os
from abc import abstractmethod
from typing import Type, Callable, Tuple, Optional, Union, List
from pyqcodeeditor.QCodeEditor import QCodeEditor
from pyqcodeeditor.QStyleSyntaxHighlighter import QStyleSyntaxHighlighter
from qtpy.QtGui import QTextOption
from qtpy.QtWidgets import QWidget, QCompleter, QVBoxLayout, QTextEdit
from .constants import (
DEFAULT_TAB_SIZE,
DEFAULT_LINE_WRAP_WIDTH,
UNSAVED_WARNING_MSG,
CONFIRM_DIALOG_TITLE,
DEFAULT_WINDOW_TITLE,
DEFAULT_UNTITLED_FILENAME,
OPEN_FILE_DIALOG_TITLE,
ERROR_DIALOG_TITLE,
OPEN_FAILED_MSG,
SAVE_FAILED_MSG,
SAVE_AS_DIALOG_TITLE,
FORMAT_FAILED_MSG,
QUIT_DIALOG_TITLE,
)
from .. import utils
from ..action import Separator
from ..toolbar import ToolBar
from ..window import BaseWindow, BaseWindowConfig, BaseWindowEventListener
class BaseCodeFormatter(object):
@abstractmethod
def format_code(self, text: str) -> Optional[str]:
pass
LineWrapMode = QTextEdit.LineWrapMode
WordWrapMode = QTextOption.WrapMode
@dataclasses.dataclass(frozen=True)
class CodeEditorConfig(BaseWindowConfig):
title: Optional[str] = None
untitled_filename: Optional[str] = None
highlighter: Optional[Type[QStyleSyntaxHighlighter]] = None
highlighter_args: Union[dict, list, tuple, None] = None
completer: Optional[QCompleter] = None
auto_indent: bool = True
auto_parentheses: bool = True
text_font_size: Optional[int] = None
text_font_family: Optional[str] = None
tab_size: int = DEFAULT_TAB_SIZE
tab_replace: bool = True
initial_text: str = ""
formatter: Union[BaseCodeFormatter, Callable[[str], str], None] = None
file_filters: Optional[str] = None
start_dir: Optional[str] = None
check_unsaved_changes: bool = True
show_filename_in_title: bool = True
line_wrap_mode: LineWrapMode = LineWrapMode.NoWrap
line_wrap_width: int = DEFAULT_LINE_WRAP_WIDTH
word_wrap_mode: WordWrapMode = WordWrapMode.NoWrap
file_encoding: str = "utf-8"
quit_dialog_title: Optional[str] = None
confirm_dialog_title: Optional[str] = None
error_dialog_title: Optional[str] = None
open_file_dialog_title: Optional[str] = None
save_file_dialog_title: Optional[str] = None
save_as_dialog_title: Optional[str] = None
unsaved_warning_message: Optional[str] = None
open_failed_message: Optional[str] = None
save_failed_message: Optional[str] = None
format_failed_message: Optional[str] = None
use_default_menus: bool = True
excluded_menus: Tuple[str] = ()
excluded_menu_actions: Tuple[Tuple[str, str], ...] = ()
use_default_toolbar: bool = True
excluded_toolbar_actions: Tuple[str, ...] = ()
no_file_mode: bool = False
class BaseCodeEditorWindow(BaseWindow):
def __init__(
self,
parent: Optional[QWidget],
config: Optional[CodeEditorConfig] = None,
listener: Optional[BaseWindowEventListener] = None,
toolbar: Optional[ToolBar] = None,
menus: Optional[List[Union[ToolBar, Separator]]] = None,
):
config = config or CodeEditorConfig()
self._editor: Optional[QCodeEditor] = None
super().__init__(parent, config, listener, toolbar, menus)
def apply_configs(self):
super().apply_configs()
self._config: CodeEditorConfig
self.set_highlighter(self._config.highlighter)
self.set_completer(self._config.completer)
self.set_auto_indent_enabled(self._config.auto_indent)
self.set_auto_parentheses_enabled(self._config.auto_parentheses)
self.set_tab_replace(self._config.tab_size, self._config.tab_replace)
self.set_text_font_size(self._config.text_font_size)
self.set_text_font_family(self._config.text_font_family)
self.set_line_wrap_mode(self._config.line_wrap_mode)
self.set_line_wrap_width(self._config.line_wrap_width)
self.set_word_wrap_mode(self._config.word_wrap_mode)
def _create_ui(self):
self._config: CodeEditorConfig
center_widget = QWidget(self)
self._editor = QCodeEditor(center_widget)
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self._editor)
self.setCentralWidget(center_widget)
center_widget.setLayout(layout)
self.set_text(self._config.initial_text)
self._update_fingerprint()
self._update_title()
def _on_close(self) -> bool:
self._config: CodeEditorConfig
if not self.check_modification():
return super()._on_close()
# noinspection PyUnresolvedReferences
msgbox = utils.MessageBoxConfig(
title=self._config.quit_dialog_title or QUIT_DIALOG_TITLE,
text=self._config.unsaved_warning_message or UNSAVED_WARNING_MSG,
buttons=utils.StandardButton.Yes | utils.StandardButton.No,
).create_messagebox(self)
if msgbox.exec_() == utils.StandardButton.Yes:
return super()._on_close()
else:
return False
@abstractmethod
def _current_highlighter(self) -> Optional[QStyleSyntaxHighlighter]:
pass
@abstractmethod
def _update_current_highlighter(
self, highlighter: Optional[QStyleSyntaxHighlighter]
):
pass
@abstractmethod
def _current_fingerprint(self) -> Optional[str]:
pass
@abstractmethod
def _update_fingerprint(self):
pass
@abstractmethod
def _current_file(self) -> Optional[str]:
pass
@abstractmethod
def _update_current_file(self, file: str):
pass
def _update_title(self):
self._config: CodeEditorConfig
if self._config.title is None:
win_title = DEFAULT_WINDOW_TITLE
else:
win_title = self._config.title.strip()
if self._config.untitled_filename is None:
untitled_filename = DEFAULT_UNTITLED_FILENAME
else:
untitled_filename = self._config.untitled_filename
current_file = (self._current_file() or "").strip()
if self._config.show_filename_in_title:
if not current_file:
filename = untitled_filename
else:
filename = os.path.basename(current_file)
win_title = f"{win_title} - {filename}".strip()
self.setWindowTitle(win_title)
def get_text(self) -> str:
return self._editor.toPlainText()
def set_text(self, text: Optional[str]):
self._editor.setPlainText(text or "")
def set_highlighter(
self,
highlighter: Optional[Type[QStyleSyntaxHighlighter]],
args: Union[list, tuple, dict, None] = None,
):
current_highlighter = self._current_highlighter()
if current_highlighter is not None:
current_highlighter.setDocument(None)
current_highlighter.deleteLater()
self._update_current_highlighter(None)
current_highlighter = create_highlighter(highlighter, args)
if current_highlighter is not None:
current_highlighter.setParent(self)
self._editor.setHighlighter(current_highlighter)
def set_completer(self, completer: Optional[QCompleter]):
self._editor.setCompleter(completer)
def set_tab_replace(self, size: int = DEFAULT_TAB_SIZE, tab_replace: bool = True):
self._editor.setTabReplace(tab_replace)
self._editor.setTabReplaceSize(size)
def is_tab_replace_enabled(self) -> bool:
return self._editor.tabReplace()
def get_tab_replace_size(self) -> int:
return self._editor.tabReplaceSize()
def set_auto_indent_enabled(self, enable: bool = True):
self._editor.setAutoIndentation(enable)
def is_auto_indent_enabled(self) -> bool:
return self._editor.autoIndentation()
def set_auto_parentheses_enabled(self, enable: bool):
self._editor.setAutoParentheses(enable)
def is_auto_parentheses_enabled(self) -> bool:
return self._editor.autoParentheses()
def set_text_font_size(self, size: Optional[int]):
if size is None:
return
if size <= 0:
raise ValueError(f"invalid size: {size}")
self._editor.setFontPointSize(size)
def set_text_font_family(self, family: Optional[str]):
if family is None or family.strip() == "":
return
self._editor.setFontFamily(family)
def get_text_font_size(self) -> Optional[int]:
return self._editor.fontSize()
def set_word_wrap_mode(self, mode: WordWrapMode):
if mode is not None:
self._editor.setWordWrapMode(mode)
def get_word_wrap_mode(self) -> WordWrapMode:
return self._editor.wordWrapMode()
def set_line_wrap_mode(self, mode: LineWrapMode):
if mode is not None:
self._editor.setLineWrapMode(mode)
def get_line_wrap_mode(self) -> LineWrapMode:
return self._editor.lineWrapMode()
def set_line_wrap_width(self, width: Optional[int]):
if width is None:
return
if width <= 0:
raise ValueError(f"invalid width: {width}")
self._editor.setLineWrapColumnOrWidth(width)
def get_line_wrap_width(self) -> int:
return self._editor.lineWrapColumnOrWidth()
def is_modified(self) -> bool:
text = self.get_text()
current_fingerprint = utils.fingerprint(text)
return current_fingerprint != self._current_fingerprint()
def check_modification(self) -> bool:
self._config: CodeEditorConfig
if not self._config.check_unsaved_changes:
return False
return self.is_modified()
def open_file(self):
self._config: CodeEditorConfig
if self.check_modification():
# noinspection PyUnresolvedReferences
ret = utils.show_question_message(
self,
message=self._config.unsaved_warning_message or UNSAVED_WARNING_MSG,
title=self._config.confirm_dialog_title or CONFIRM_DIALOG_TITLE,
buttons=utils.StandardButton.No | utils.StandardButton.Yes,
)
if ret != utils.StandardButton.Yes:
return
filepath = utils.get_open_file(
self,
title=self._config.open_file_dialog_title or OPEN_FILE_DIALOG_TITLE,
start_dir=self._config.start_dir,
filters=self._config.file_filters,
)
if not filepath:
return
try:
new_text = utils.read_text_file(
filepath, encoding=self._config.file_encoding
)
except Exception as e:
msg = self._config.open_failed_message or OPEN_FAILED_MSG
msg = msg.format(filepath)
utils.show_exception_messagebox(
self,
exception=e,
title=self._config.error_dialog_title or ERROR_DIALOG_TITLE,
message=f"{msg}:{e}",
detail=True,
)
return
self.set_text(new_text)
if not self._config.no_file_mode:
self._update_current_file(os.path.normpath(os.path.abspath(filepath)))
self._update_fingerprint()
self._update_title()
def save_file(self):
self._config: CodeEditorConfig
if self._config.no_file_mode:
return
current_file = self._current_file()
if not current_file:
return self.save_as_file()
if not self.check_modification():
return
try:
utils.write_text_file(
current_file, self.get_text(), encoding=self._config.file_encoding
)
except Exception as e:
msg = self._config.save_failed_message or SAVE_FAILED_MSG
msg = msg.format(current_file)
utils.show_exception_messagebox(
self,
exception=e,
title=self._config.error_dialog_title or ERROR_DIALOG_TITLE,
message=f"{msg}: {e}",
)
else:
self._update_fingerprint()
def save_as_file(self):
self._config: CodeEditorConfig
if self._config.no_file_mode:
return
filepath = utils.get_save_file(
self,
title=self._config.save_as_dialog_title or SAVE_AS_DIALOG_TITLE,
start_dir=self._config.start_dir,
filters=self._config.file_filters,
)
if not filepath:
return
try:
utils.write_text_file(
filepath, self.get_text(), encoding=self._config.file_encoding
)
except Exception as e:
msg = self._config.save_failed_message or SAVE_FAILED_MSG
msg = msg.format(filepath)
utils.show_exception_messagebox(
self,
exception=e,
title=self._config.error_dialog_title or ERROR_DIALOG_TITLE,
message=f"{msg}: {e}",
)
else:
self._update_current_file(os.path.normpath(os.path.abspath(filepath)))
self._update_fingerprint()
self._update_title()
def format_code(self):
self._config: CodeEditorConfig
if not self._config.formatter:
return
try:
if isinstance(self._config.formatter, BaseCodeFormatter):
formatted = self._config.formatter.format_code(self.get_text())
else:
formatted = self._config.formatter(self.get_text())
except Exception as e:
msg = self._config.format_failed_message or FORMAT_FAILED_MSG
utils.show_exception_messagebox(
self,
exception=e,
title=self._config.error_dialog_title or ERROR_DIALOG_TITLE,
message=f"{msg}: {e}",
)
return
if isinstance(formatted, str):
self.set_text(formatted)
def redo(self):
self._editor.redo()
def undo(self):
self._editor.undo()
def cut(self):
self._editor.cut()
def copy(self):
self._editor.copy()
def paste(self):
self._editor.paste()
def select_all(self):
self._editor.selectAll()
def create_highlighter(
highlighter_class: Optional[Type[QStyleSyntaxHighlighter]],
args: Union[dict, list, tuple, None],
) -> Optional[QStyleSyntaxHighlighter]:
assert highlighter_class is None or (
inspect.isclass(highlighter_class)
and issubclass(highlighter_class, QStyleSyntaxHighlighter)
)
assert args is None or isinstance(args, (dict, list, tuple))
if highlighter_class is None:
return None
if not args:
instance = highlighter_class(None)
elif isinstance(args, dict):
instance = highlighter_class(**args)
elif isinstance(args, (list, tuple)):
instance = highlighter_class(*args)
else:
raise TypeError(f"invalid type of args: {type(args)}")
return instance
| 15,193 | Python | .py | 381 | 30.973753 | 86 | 0.639403 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,525 | actions.py | zimolab_PyGUIAdapter/pyguiadapter/codeeditor/actions.py | from typing import List
from .base import BaseCodeEditorWindow
from .constants import (
DEFAULT_ICON_SIZE,
ACTION_OPEN,
ACTION_SAVE,
ACTION_SAVE_AS,
ACTION_QUIT,
ACTION_UNDO,
ACTION_REDO,
ACTION_CUT,
ACTION_COPY,
ACTION_PASTE,
ACTION_FORMAT_CODE,
ACTION_SELECT_ALL,
MENU_FILE,
MENU_EDIT,
)
from ..action import Action, Separator
from ..menu import Menu
from ..toolbar import ToolBar
def _on_open_file(ctx: BaseCodeEditorWindow, _: Action):
ctx.open_file()
def _on_save_file(ctx: BaseCodeEditorWindow, _: Action):
ctx.save_file()
def _on_save_file_as(ctx: BaseCodeEditorWindow, _: Action):
ctx.save_as_file()
def _on_quit(ctx: BaseCodeEditorWindow, _: Action):
ctx.close()
def _on_undo(ctx: BaseCodeEditorWindow, _: Action):
ctx.undo()
def _on_redo(ctx: BaseCodeEditorWindow, _: Action):
ctx.redo()
def _on_cut(ctx: BaseCodeEditorWindow, _: Action):
ctx.cut()
def _on_copy(ctx: BaseCodeEditorWindow, _: Action):
ctx.copy()
def _on_paste(ctx: BaseCodeEditorWindow, _: Action):
ctx.paste()
def _on_format_code(ctx: BaseCodeEditorWindow, _: Action):
ctx.format_code()
def _on_select_all(ctx: BaseCodeEditorWindow, _: Action):
ctx.select_all()
DEFAULT_ACTION_OPEN = Action(
text=ACTION_OPEN,
icon="fa.folder-open-o",
shortcut="Ctrl+O",
on_triggered=_on_open_file,
)
DEFAULT_ACTION_SAVE = Action(
text=ACTION_SAVE,
icon="fa.save",
shortcut="Ctrl+S",
on_triggered=_on_save_file,
)
DEFAULT_ACTION_SAVE_AS = Action(
text=ACTION_SAVE_AS,
icon="mdi.content-save-edit-outline",
shortcut="Ctrl+Shift+S",
on_triggered=_on_save_file_as,
)
DEFAULT_ACTION_QUIT = Action(
text=ACTION_QUIT,
icon="fa.window-close-o",
shortcut="Ctrl+Q",
on_triggered=_on_quit,
)
DEFAULT_ACTION_UNDO = Action(
text=ACTION_UNDO,
icon="fa.undo",
shortcut="Ctrl+Z",
on_triggered=_on_undo,
)
DEFAULT_ACTION_REDO = Action(
text=ACTION_REDO,
icon="fa.repeat",
shortcut="Ctrl+Y",
on_triggered=_on_redo,
)
DEFAULT_ACTION_CUT = Action(
text=ACTION_CUT,
icon="fa.cut",
shortcut="Ctrl+X",
on_triggered=_on_cut,
)
DEFAULT_ACTION_COPY = Action(
text=ACTION_COPY,
icon="fa.copy",
shortcut="Ctrl+C",
on_triggered=_on_copy,
)
DEFAULT_ACTION_PASTE = Action(
text=ACTION_PASTE,
icon="fa.paste",
shortcut="Ctrl+V",
on_triggered=_on_paste,
)
DEFAULT_ACTION_FORMAT_CODE = Action(
text=ACTION_FORMAT_CODE,
icon="fa.indent",
shortcut="Ctrl+Alt+L",
on_triggered=_on_format_code,
)
DEFAULT_ACTION_SELECT_ALL = Action(
text=ACTION_SELECT_ALL,
icon="fa.object-group",
shortcut="Ctrl+A",
on_triggered=_on_select_all,
)
DEFAULT_FILE_MENU = Menu(
title=MENU_FILE,
actions=[
DEFAULT_ACTION_OPEN,
DEFAULT_ACTION_SAVE,
DEFAULT_ACTION_SAVE_AS,
Separator(),
DEFAULT_ACTION_QUIT,
],
)
DEFAULT_EDIT_MENU = Menu(
title=MENU_EDIT,
actions=[
DEFAULT_ACTION_UNDO,
DEFAULT_ACTION_REDO,
Separator(),
DEFAULT_ACTION_CUT,
DEFAULT_ACTION_COPY,
DEFAULT_ACTION_PASTE,
Separator(),
DEFAULT_ACTION_FORMAT_CODE,
Separator(),
DEFAULT_ACTION_SELECT_ALL,
],
)
DEFAULT_MENUS: List[Menu] = [DEFAULT_FILE_MENU, DEFAULT_EDIT_MENU]
DEFAULT_TOOLBAR = ToolBar(
actions=[
DEFAULT_ACTION_OPEN,
DEFAULT_ACTION_SAVE,
Separator(),
DEFAULT_ACTION_UNDO,
DEFAULT_ACTION_REDO,
Separator(),
DEFAULT_ACTION_CUT,
DEFAULT_ACTION_COPY,
DEFAULT_ACTION_PASTE,
Separator(),
DEFAULT_ACTION_FORMAT_CODE,
Separator(),
DEFAULT_ACTION_SELECT_ALL,
],
moveable=True,
icon_size=DEFAULT_ICON_SIZE,
)
| 3,854 | Python | .py | 154 | 20.266234 | 66 | 0.662114 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,526 | _json.py | zimolab_PyGUIAdapter/pyguiadapter/codeeditor/formatters/_json.py | import json
import warnings
from typing import Optional
from ..base import BaseCodeFormatter
class JsonFormatter(BaseCodeFormatter):
def __init__(self, indent: int = 4):
self._indent = indent
@property
def indent(self) -> int:
return self._indent
@indent.setter
def indent(self, value: int):
if value < 0:
warnings.warn(f"indent must be greater than or equals to 0, got: {value}")
return
self._indent = value
def format_code(self, text: str) -> Optional[str]:
try:
return json.dumps(json.loads(text), indent=self._indent, ensure_ascii=False)
except Exception as e:
warnings.warn(f"failed to format code: {e}")
return None
| 761 | Python | .py | 22 | 27.272727 | 88 | 0.636612 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,527 | __init__.py | zimolab_PyGUIAdapter/pyguiadapter/codeeditor/formatters/__init__.py | from ._json import JsonFormatter
from ._python import PythonFormatter
__all__ = [
"JsonFormatter",
"PythonFormatter",
]
| 129 | Python | .py | 6 | 19 | 36 | 0.729508 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,528 | _python.py | zimolab_PyGUIAdapter/pyguiadapter/codeeditor/formatters/_python.py | import warnings
from typing import Optional
from yapf.yapflib.yapf_api import FormatCode
from ..base import BaseCodeFormatter
class PythonFormatter(BaseCodeFormatter):
def format_code(self, text: str) -> Optional[str]:
try:
formatted, changed = FormatCode(text)
except Exception as e:
warnings.warn(f"failed to format code: {e}")
return None
else:
if changed:
return formatted
return None
| 497 | Python | .py | 15 | 24.933333 | 56 | 0.648536 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,529 | font.py | zimolab_PyGUIAdapter/pyguiadapter/constants/font.py | FONT_FAMILY = "Consolas, monospace, Monaco, Source Code Pro, Inter, Arial, sans-serif;"
FONT_EXTRA_SMALL = 12
FONT_SMALL = 13
FONT_BASE = 14
FONT_MEDIUM = 16
FONT_LARGE = 18
FONT_EXTRA_LARGE = 20
FONT_HUGE = 26
FONT_EXTRA_HUGE = 30
| 232 | Python | .py | 9 | 24.777778 | 87 | 0.744395 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,530 | color.py | zimolab_PyGUIAdapter/pyguiadapter/constants/color.py | COLOR_SUCCESS = "#67C23A"
COLOR_WARNING = "#FFFF00"
COLOR_FATAL = "#FF0000"
COLOR_INFO = "#00FF00"
COLOR_CRITICAL = "#A61C00"
COLOR_DEBUG = "#909399"
COLOR_BASE_TEXT = "#000000"
COLOR_PRIMARY_TEXT = "#303133"
COLOR_REGULAR_TEXT = "#606266"
COLOR_SECONDARY_TEXT = "#A8ABB2"
COLOR_DISABLED_TEXT = "#C0C4CC"
COLOR_BASE_BACKGROUND = "#FFFFFF"
COLOR_PAGE_BACKGROUND = "#F2F3F5"
COLOR_TERMINAL_BACKGROUND_CLASSIC = "#380C2A"
COLOR_TERMINAL_TEXT_CLASSIC = "#FFFFFF"
COLOR_TOAST_BACKGROUND_CLASSIC = "#222222"
COLOR_TOAST_TEXT_CLASSIC = "#FEFEFE"
| 542 | Python | .py | 17 | 30.705882 | 45 | 0.743295 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,531 | clipboard.py | zimolab_PyGUIAdapter/pyguiadapter/constants/clipboard.py | CLIPBOARD_SET_TEXT = 0
CLIPBOARD_GET_TEXT = 1
CLIPBOARD_SUPPORTS_SELECTION = 2
CLIPBOARD_GET_SELECTION_TEXT = 3
CLIPBOARD_SET_SELECTION_TEXT = 4
CLIPBOARD_OWNS_SELECTION = 5
CLIPBOARD_OWNS_CLIPBOARD = 6
| 203 | Python | .py | 7 | 28 | 32 | 0.811224 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,532 | document_browser.py | zimolab_PyGUIAdapter/pyguiadapter/windows/document_browser.py | """
@Time : 2024.10.20
@File : document_browser.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 文档浏览器类的实现
"""
import dataclasses
import re
from typing import Optional
from urllib.parse import unquote
from qtpy.QtCore import QUrl, Signal
from qtpy.QtWidgets import QWidget
from ..constants.color import COLOR_PAGE_BACKGROUND, COLOR_PRIMARY_TEXT
from ..textbrowser import TextBrowserConfig, TextBrowser, LineWrapMode
@dataclasses.dataclass
class DocumentBrowserConfig(TextBrowserConfig):
"""文档浏览器配置类。"""
text_color: str = COLOR_PRIMARY_TEXT
background_color: str = COLOR_PAGE_BACKGROUND
line_wrap_mode: LineWrapMode = LineWrapMode.WidgetWidth
parameter_anchor: bool = False
"""是否启用参数锚点。当启用时,用户点击文档中的参数锚点,会自动跳转到对应的参数控件处。"""
parameter_anchor_pattern: str = r"^#\s*param\s*=\s*([\w]+)\s*$"
"""参数锚点的格式。默认格式为:#param=参数名。"""
group_anchor: bool = False
"""是否启用参数分组锚点。当启用时,用户点击文档中的参数分组锚点,会自动展开对应的参数分组。"""
group_anchor_pattern: str = r"^#\s*group\s*=\s*([\w\W\s]*)\s*$"
"""参数分组锚点的格式。默认格式为:#group=分组名。"""
class DocumentBrowser(TextBrowser):
"""文档浏览器类。"""
sig_parameter_anchor_clicked = Signal(str)
sig_group_anchor_clicked = Signal(str)
def __init__(
self, parent: Optional[QWidget], config: Optional[DocumentBrowserConfig]
):
config = config or DocumentBrowserConfig()
super().__init__(parent, config)
def on_url_clicked(self, url: QUrl):
self._config: DocumentBrowserConfig
if not url or url.isEmpty() or (not url.isValid()) or (not url.isRelative()):
super().on_url_clicked(url)
return
processed = False
url_str = unquote(url.toString())
if self._config.parameter_anchor:
processed = self._process_parameter_anchor(url_str)
if processed:
return
if self._config.group_anchor:
processed = self._process_group_anchor(url_str)
if processed:
return
super().on_url_clicked(url)
def _process_parameter_anchor(self, url: str) -> bool:
self._config: DocumentBrowserConfig
param_pattern = self._config.parameter_anchor_pattern
if not param_pattern:
return False
match = re.match(param_pattern, url)
if not match:
return False
param_name = match.group(1).strip()
self.sig_parameter_anchor_clicked.emit(param_name)
return True
def _process_group_anchor(self, url: str) -> bool:
self._config: DocumentBrowserConfig
group_pattern = self._config.group_anchor_pattern
if not group_pattern:
return False
match = re.match(group_pattern, url)
if not match:
return False
group_name = match.group(1)
if group_name.strip() == "":
group_name = ""
self.sig_group_anchor_clicked.emit(group_name)
return True
| 3,252 | Python | .py | 78 | 30.910256 | 85 | 0.656392 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,533 | _window.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnselect/_window.py | import dataclasses
from typing import Tuple, Dict, Literal, List, Union, Optional
from qtpy.QtCore import QSize, Qt
from qtpy.QtGui import QIcon
from qtpy.QtWidgets import (
QSplitter,
QToolBox,
QVBoxLayout,
QPushButton,
QWidget,
)
from ._group import FnGroupPage
from ..document_browser import DocumentBrowserConfig, DocumentBrowser
from ..fnexec import FnExecuteWindow
from ...utils import IconType, get_icon, set_textbrowser_content, messagebox
from ...action import Separator
from ...menu import Menu
from ...toolbar import ToolBar
from ...bundle import FnBundle
from ...window import BaseWindow, BaseWindowConfig, BaseWindowEventListener
DEFAULT_FN_ICON_SIZE = (48, 48)
WARNING_MSG_NO_FN_SELECTED = "No Selected Function!"
@dataclasses.dataclass(frozen=True)
class FnSelectWindowConfig(BaseWindowConfig):
title: str = "Select Function"
"""窗口标题"""
size: Union[Tuple[int, int], QSize] = (800, 600)
"""窗口尺寸"""
select_button_text: str = "Select"
"""选择按钮文字"""
icon_mode: bool = False
"""函数列表是否启用图标模式"""
icon_size: Union[Tuple[int, int], int, QSize, None] = DEFAULT_FN_ICON_SIZE
"""函数图标大小"""
default_fn_group_name: str = "Main Functions"
"""默认函数分组名称"""
default_fn_group_icon: IconType = None
"""默认函数分组图标"""
fn_group_icons: Dict[str, IconType] = dataclasses.field(default_factory=dict)
"""其他函数分组图标"""
document_browser_config: Optional[DocumentBrowserConfig] = None
"""文档浏览器配置"""
document_browser_width: int = 490
"""文档浏览器宽度"""
class FnSelectWindow(BaseWindow):
# noinspection SpellCheckingInspection
def __init__(
self,
parent: Optional[QWidget],
bundles: List[FnBundle],
config: Optional[FnSelectWindowConfig],
listener: Optional[BaseWindowEventListener] = None,
toolbar: Optional[ToolBar] = None,
menus: Optional[List[Union[Menu, Separator]]] = None,
):
self._initial_bundles = bundles.copy()
self._group_pages: Dict[str, FnGroupPage] = {}
self._current_exec_window: Optional[FnSelectWindow] = None
self._fn_group_toolbox: Optional[QToolBox] = None
self._document_browser: Optional[DocumentBrowser] = None
self._select_button: Optional[QPushButton] = None
self._splitter: Optional[QSplitter] = None
super().__init__(parent, config, listener, toolbar, menus)
def _create_ui(self):
self._config: FnSelectWindowConfig
central_widget: QWidget = QWidget(self)
# noinspection PyArgumentList
layout_main = QVBoxLayout(central_widget)
self.setCentralWidget(central_widget)
# noinspection PyArgumentList
splitter = QSplitter(central_widget)
splitter.setOrientation(Qt.Horizontal)
layout_main.addWidget(splitter)
self._fn_group_toolbox: QToolBox = QToolBox(splitter)
# noinspection PyUnresolvedReferences
self._fn_group_toolbox.currentChanged.connect(self._on_current_group_change)
splitter.addWidget(self._fn_group_toolbox)
right_area = QWidget(splitter)
# noinspection PyArgumentList
layout_right_area = QVBoxLayout()
layout_right_area.setContentsMargins(0, 0, 0, 0)
self._document_browser = DocumentBrowser(
right_area, self._config.document_browser_config
)
layout_right_area.addWidget(self._document_browser)
self._select_button = QPushButton(right_area)
layout_right_area.addWidget(self._select_button)
right_area.setLayout(layout_right_area)
# noinspection PyUnresolvedReferences
self._select_button.clicked.connect(self._on_button_select_click)
self._splitter = splitter
def apply_configs(self):
super().apply_configs()
self._config: FnSelectWindowConfig
self.set_select_button_text(self._config.select_button_text)
self.set_document_browser_width(self._config.document_browser_width)
def set_select_button_text(self, text: str) -> None:
"""
设置选择按钮文字。
Args:
text: 带设置的文字
Returns:
无返回值
"""
self._select_button.setText(text)
def get_select_button_text(self) -> str:
"""
获取选择按钮文字。
Returns:
返回当前选择按钮上的文字。
"""
return self._select_button.text()
def set_document_browser_width(self, width: int) -> None:
"""
设置文档浏览器宽度。
Args:
width: 目标宽度
Returns:
无返回值
"""
if width <= 0:
raise ValueError(f"invalid width: {width}")
left_width = self.width() - width
self._splitter.setSizes([left_width, width])
def get_group_names(self) -> List[str]:
"""
获取所有函数分组名称。
Returns:
返回函数分组名称列表。
"""
return list(self._group_pages.keys())
def remove_group(self, group_name: Optional[str]) -> None:
"""
移除指定函数分组。
Args:
group_name: 待移除的函数分组名称。
Returns:
无返回值
Raises:
ValueError: 当指定函数分组名称不存在时,将抛出`ValueError`。
"""
group_name = self._group_name(group_name)
group_page = self._group_pages.get(group_name, None)
if group_page is None:
raise ValueError(f"group not found: {group_name}")
group_page.clear_bundles()
group_page_index = self._fn_group_toolbox.indexOf(group_page)
if group_page_index < 0:
return
self._fn_group_toolbox.removeItem(group_page_index)
group_page.deleteLater()
def start(self):
for bundle in self._initial_bundles:
self._add_bundle(bundle)
del self._initial_bundles
self._fn_group_toolbox.setCurrentIndex(0)
self.show()
def _add_bundle(self, bundle: FnBundle):
fn = bundle.fn_info
page = self._get_group_page(self._group_name(fn.group))
page.add_bundle(bundle)
def _get_bundles_of(self, group_name: Optional[str]) -> Tuple[FnBundle, ...]:
group_name = self._group_name(group_name)
group_page = self._group_pages.get(group_name, None)
return group_page.bundles() if group_page is not None else ()
def _get_all_bundles(self) -> List[FnBundle]:
bundles = []
for page in self._group_pages.values():
bs = page.bundles()
if bs:
bundles.extend(bs)
return bundles
def _remove_bundle(self, bundle: FnBundle) -> None:
group_name = self._group_name(bundle.fn_info.group)
group_page = self._group_pages.get(group_name, None)
if group_page is not None:
group_page.remove_bundle(bundle)
def _start_exec_window(self, bundle: FnBundle):
assert isinstance(bundle, FnBundle)
self._current_exec_window = FnExecuteWindow(self, bundle)
self._current_exec_window.setWindowModality(Qt.ApplicationModal)
self._current_exec_window.setAttribute(Qt.WA_DeleteOnClose, True)
# noinspection PyUnresolvedReferences
self._current_exec_window.destroyed.connect(
self._on_current_exec_window_destroyed
)
self._current_exec_window.show()
def _on_current_exec_window_destroyed(self):
self._current_exec_window = None
def _on_button_select_click(self):
bundle = self._current_bundle()
if bundle is None:
messagebox.show_warning_message(self, WARNING_MSG_NO_FN_SELECTED)
return
self._start_exec_window(bundle)
# noinspection PyUnusedLocal
def _on_current_bundle_change(self, bundle: FnBundle, page: FnGroupPage):
doc = ""
doc_format = "plaintext"
if bundle is not None:
doc = bundle.fn_info.document
doc_format = bundle.fn_info.document_format
# noinspection PyTypeChecker
self._update_document(doc, doc_format)
# noinspection PyUnusedLocal
def _on_item_double_click(self, bundle: FnBundle, page: FnGroupPage):
self._start_exec_window(bundle)
def _on_current_group_change(self, index: int):
current_page = self._fn_group_toolbox.widget(index)
if not isinstance(current_page, FnGroupPage):
return
bundle = current_page.current_bundle()
if bundle is None:
current_page.set_current_index(0)
return
self._on_current_bundle_change(bundle, current_page)
def _get_group_page(self, group_name: Optional[str]) -> FnGroupPage:
self._config: FnSelectWindowConfig
group_name = self._group_name(group_name)
# return existing page
if group_name in self._group_pages:
page = self._group_pages[group_name]
self._fn_group_toolbox.setCurrentWidget(page)
return page
# if no existing page, create a new one
icon_size = self._config.icon_size or DEFAULT_FN_ICON_SIZE
page = FnGroupPage(self._fn_group_toolbox, self._config.icon_mode, icon_size)
# noinspection PyUnresolvedReferences
page.sig_current_bundle_changed.connect(self._on_current_bundle_change)
# noinspection PyUnresolvedReferences
page.sig_item_double_clicked.connect(self._on_item_double_click)
group_icon = self._group_icon(group_name)
self._fn_group_toolbox.addItem(page, group_icon, group_name)
self._fn_group_toolbox.setCurrentWidget(page)
self._group_pages[group_name] = page
return page
def _group_icon(self, group_name: Optional[str]):
self._config: FnSelectWindowConfig
if group_name is None or group_name == self._config.default_fn_group_name:
return get_icon(self._config.default_fn_group_icon) or QIcon()
icon_src = self._config.fn_group_icons.get(group_name, None)
if icon_src is None:
return QIcon()
return get_icon(icon_src) or QIcon()
def _update_document(
self, document: str, document_format: Literal["markdown", "html", "plaintext"]
):
set_textbrowser_content(self._document_browser, document, document_format)
def _current_bundle(self) -> Optional[FnBundle]:
current_page = self._fn_group_toolbox.currentWidget()
if not isinstance(current_page, FnGroupPage):
return None
return current_page.current_bundle()
def _on_cleanup(self):
super()._on_cleanup()
for group_page in self._group_pages.values():
group_page.clear_bundles()
group_page.deleteLater()
self._group_pages.clear()
def _group_name(self, group_name: Optional[str]):
self._config: FnSelectWindowConfig
if group_name is None:
return self._config.default_fn_group_name
return group_name
| 11,272 | Python | .py | 264 | 32.901515 | 86 | 0.650066 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,534 | _group.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnselect/_group.py | from typing import Tuple, List, Union, Optional
import qtawesome as qta
from qtpy.QtCore import QSize, Qt, Signal, QModelIndex
from qtpy.QtWidgets import (
QVBoxLayout,
QListWidget,
QListWidgetItem,
QWidget,
)
from ...bundle import FnBundle
from ...utils import get_icon, get_size
DEFAULT_FN_ICON = "fa5s.cubes"
class FnGroupPage(QWidget):
sig_current_bundle_changed = Signal(FnBundle, object)
sig_item_double_clicked = Signal(FnBundle, object)
def __init__(
self,
parent: QWidget,
icon_mode: bool,
icon_size: Union[Tuple[int, int], int, QSize, None],
):
super().__init__(parent)
self._bundles: List[FnBundle] = []
# noinspection PyArgumentList
self._layout = QVBoxLayout()
self._layout.setContentsMargins(0, 0, 0, 0)
self._fn_list_widget = QListWidget(self)
self.set_icon_mode(icon_mode)
self.set_icon_size(icon_size)
self._layout.addWidget(self._fn_list_widget)
# noinspection PyUnresolvedReferences
self._fn_list_widget.currentItemChanged.connect(self._on_current_item_change)
# noinspection PyUnresolvedReferences
self._fn_list_widget.doubleClicked.connect(self._on_double_clicked)
self.setLayout(self._layout)
def set_icon_size(self, size: Union[int, Tuple[int, int], QSize]):
if size is None:
return
size = get_size(size)
if not size:
raise ValueError(f"invalid icon size: {size}")
self._fn_list_widget.setIconSize(size)
def get_icon_size(self) -> Tuple[int, int]:
size = self._fn_list_widget.iconSize()
return size.width(), size.height()
def set_icon_mode(self, enable: bool):
if enable:
self._fn_list_widget.setViewMode(QListWidget.IconMode)
else:
self._fn_list_widget.setViewMode(QListWidget.ListMode)
def is_icon_mode(self) -> bool:
return self._fn_list_widget.viewMode() == QListWidget.IconMode
def add_bundle(self, bundle: FnBundle):
if bundle in self._bundles:
return
item = self._create_bundle_item(bundle)
self._bundles.append(bundle)
self._fn_list_widget.addItem(item)
if not self.current_bundle():
self.set_current_index(0)
def bundles(self) -> Tuple[FnBundle, ...]:
return tuple(self._bundles)
def bundles_count(self):
return self._fn_list_widget.count()
def bundle_at(self, index: int) -> Optional[FnBundle]:
item = self._fn_list_widget.item(index)
if item is None:
return None
bundle = item.data(Qt.UserRole)
if isinstance(bundle, FnBundle):
return bundle
return None
def bundle_index(self, bundle: FnBundle) -> int:
for i in range(self._fn_list_widget.count()):
item = self._fn_list_widget.item(i)
if item is None:
continue
if item.data(Qt.UserRole) == bundle:
return i
return -1
def current_bundle(self) -> Optional[FnBundle]:
current_item = self._fn_list_widget.currentItem()
if current_item is None:
return None
return current_item.data(Qt.UserRole)
def set_current_index(self, index: int):
self._fn_list_widget.setCurrentRow(index)
def remove_bundle(self, bundle: FnBundle):
idx = self.bundle_index(bundle)
if idx >= 0:
item = self._fn_list_widget.takeItem(idx)
self._delete_item(item)
if bundle in self._bundles:
self._bundles.remove(bundle)
def remove_bundle_at(self, index: int):
bundle = self.bundle_at(index)
if bundle is not None:
item = self._fn_list_widget.takeItem(index)
self._delete_item(item)
if bundle in self._bundles:
self._bundles.remove(bundle)
def clear_bundles(self):
for i in range(self._fn_list_widget.count()):
item = self._fn_list_widget.takeItem(i)
self._delete_item(item)
self._bundles.clear()
@staticmethod
def _delete_item(item: Optional[QListWidgetItem]):
if item is None:
return
item_widget = item.listWidget()
if item_widget is not None:
item_widget.deleteLater()
def _on_current_item_change(self, current_item: QListWidgetItem):
if current_item is None:
return
bundle = current_item.data(Qt.UserRole)
if bundle is None:
return
# noinspection PyUnresolvedReferences
self.sig_current_bundle_changed.emit(bundle, self)
def _on_double_clicked(self, index: QModelIndex):
item = self._fn_list_widget.item(index.row())
if item is None:
return
bundle = item.data(Qt.UserRole)
if not isinstance(bundle, FnBundle):
return
# noinspection PyUnresolvedReferences
self.sig_item_double_clicked.emit(bundle, self)
def _create_bundle_item(self, bundle: FnBundle) -> QListWidgetItem:
fn = bundle.fn_info
icon = get_icon(fn.icon) or qta.icon(DEFAULT_FN_ICON)
item = QListWidgetItem(icon, fn.display_name, self._fn_list_widget)
item.setData(Qt.UserRole, bundle)
return item
| 5,367 | Python | .py | 136 | 30.691176 | 85 | 0.628797 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,535 | __init__.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnselect/__init__.py | from ._window import FnSelectWindow, FnSelectWindowConfig
__all__ = [
"FnSelectWindow",
"FnSelectWindowConfig",
]
| 123 | Python | .py | 5 | 21.8 | 57 | 0.74359 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,536 | _window.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_window.py | from typing import Tuple, Literal, Dict, Union, Type, Any, List, Optional
from qtpy.QtCore import Qt
from qtpy.QtWidgets import (
QWidget,
QVBoxLayout,
QDockWidget,
)
from ._base import (
BaseFnExecuteWindow,
DEFAULT_EXECUTOR_CLASS,
FnExecuteWindowConfig,
FnExecuteWindowEventListener,
DockWidgetArea,
DockWidgetAreas,
)
from ._document_area import DocumentArea
from ._operation_area import OperationArea
from ._output_area import OutputArea, ProgressBarConfig
from ._parameter_area import ParameterArea
from ...adapter import ucontext
from ...adapter import uoutput
from ...bundle import FnBundle
from ...exceptions import (
ParameterError,
FunctionNotCancellableError,
FunctionNotExecutingError,
)
from ...executor import BaseFunctionExecutor
from ...fn import FnInfo
from ...paramwidget import (
BaseParameterWidget,
BaseParameterWidgetConfig,
)
from ...utils import messagebox, get_traceback
class FnExecuteWindow(BaseFnExecuteWindow):
def __init__(self, parent: Optional[QWidget], bundle: FnBundle):
self._bundle: FnBundle = bundle
self._center_widget: Optional[QWidget] = None
self._operation_area: Optional[OperationArea] = None
self._parameter_area: Optional[ParameterArea] = None
self._document_area: Optional[DocumentArea] = None
self._output_area: Optional[OutputArea] = None
self._document_dock: Optional[QDockWidget] = None
self._output_dock: Optional[QDockWidget] = None
super().__init__(
parent,
bundle.window_config,
bundle.window_listener,
bundle.window_toolbar,
bundle.window_menus,
)
executor_class = self._bundle.fn_info.executor or DEFAULT_EXECUTOR_CLASS
# noinspection PyTypeChecker
self._executor = executor_class(self, self)
try:
self.add_parameters(self._bundle.widget_configs)
except Exception as e:
messagebox.show_exception_messagebox(
self,
exception=e,
message="failed to create parameter widget: ",
detail=True,
)
exit(-1)
# noinspection PyProtectedMember
ucontext._current_window_created(self)
@property
def executor(self) -> BaseFunctionExecutor:
return self._executor
def _create_ui(self):
self._config: FnExecuteWindowConfig
super()._create_ui()
self._center_widget = QWidget(self)
# noinspection PyArgumentList
layout_main = QVBoxLayout()
self._center_widget.setLayout(layout_main)
self.setCentralWidget(self._center_widget)
parameter_area_layout = QVBoxLayout()
layout_main.addLayout(parameter_area_layout)
self._parameter_area = ParameterArea(
self._center_widget, self._config, self._bundle
)
parameter_area_layout.addWidget(self._parameter_area)
self._operation_area = OperationArea(self._center_widget, self._config)
self._operation_area.set_cancel_button_visible(self._bundle.fn_info.cancelable)
self._operation_area.sig_execute_requested.connect(
self._on_execute_button_clicked
)
self._operation_area.sig_clear_requested.connect(self._on_clear_button_clicked)
self._operation_area.sig_cancel_requested.connect(
self._on_cancel_button_clicked
)
parameter_area_layout.addWidget(self._operation_area)
self._document_dock = QDockWidget(self)
self._document_area = DocumentArea(
self._document_dock, self._config.document_browser_config
)
self._document_dock.setWidget(self._document_area)
self._output_dock = QDockWidget(self)
self._output_area = OutputArea(
self._output_dock, self._config.output_browser_config
)
self._output_dock.setWidget(self._output_area)
# noinspection PyUnresolvedReferences
def apply_configs(self):
super().apply_configs()
self._config: FnExecuteWindowConfig
if self._config.title is None:
title = self._bundle.fn_info.display_name or ""
else:
title = self._config.title
self.set_title(title)
icon = self._config.icon or self._bundle.fn_info.icon
self.set_icon(icon)
self._operation_area.set_cancel_button_visible(self._bundle.fn_info.cancelable)
self._operation_area.set_cancel_button_enabled(False)
self.set_document_dock_property(
title=self._config.document_dock_title,
visible=self._config.document_dock_visible,
floating=self._config.document_dock_floating,
area=self._config.document_dock_initial_area,
)
self.set_document(
self._bundle.fn_info.document, self._bundle.fn_info.document_format
)
self._document_area.on_parameter_anchor_clicked(self.scroll_to_parameter)
self._document_area.on_group_anchor_clicked(self.activate_parameter_group)
self.set_output_dock_property(
title=self._config.output_dock_title,
visible=self._config.output_dock_visible,
floating=self._config.output_dock_floating,
area=self._config.output_dock_initial_area,
)
if self._config.initial_docks_state == "tabified":
self.tabify_docks()
self.resize_document_dock(self._config.document_dock_initial_size)
self.resize_output_dock(self._config.output_dock_initial_size)
self.set_statusbar_visible(self._config.statusbar_visible)
def update_progressbar_config(
self, config: Union[ProgressBarConfig, dict, None]
) -> None:
"""
更新进度条配置
Args:
config: 进度条配置
Returns:
无返回值
"""
if isinstance(config, dict):
config = ProgressBarConfig(**config)
self._output_area.update_progressbar_config(config)
def show_progressbar(self) -> None:
"""
显示进度条
Returns:
无返回值
"""
self._output_area.show_progressbar()
def hide_progressbar(self) -> None:
"""
隐藏进度条
Returns:
无返回值
"""
self._output_area.hide_progressbar()
self._output_area.scroll_to_bottom()
def update_progress(
self, current_value: int, message: Optional[str] = None
) -> None:
"""
更新进度条进度
Args:
current_value: 当前进度
message: 额外信息
Returns:
"""
self._output_area.update_progress(current_value, message)
def append_output(
self, text: str, html: bool = False, scroll_to_bottom: bool = True
) -> None:
"""
把文本追加到输出浏览器中
Args:
text: 带输出的文本
html: 是否为html格式
scroll_to_bottom: 完成后是否将输出浏览器滚动到底部
Returns:
无返回值
"""
self._output_area.append_output(text, html)
if scroll_to_bottom:
self._output_area.scroll_to_bottom()
def clear_output(self) -> None:
"""
清除输出浏览器内容
Returns:
无返回值
"""
self._output_area.clear_output()
def set_document(
self, document: str, document_format: Literal["markdown", "html", "plaintext"]
) -> None:
"""
设置函数说明文档
Args:
document: 文档内容
document_format: 文档格式
Returns:
无返回值
"""
self._document_area.set_document(document, document_format)
def add_parameter(
self,
parameter_name: str,
config: Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig],
) -> None:
"""
添加一个新的函数参数
Args:
parameter_name: 要增加的函数参数名称
config: 函数参数配置,格式为: (参数控件类, 参数控件配置类实例)
Returns:
无返回值
Raises:
ParameterError: 当参数为空、参数名称重复时将引发此异常
"""
self._parameter_area.add_parameter(parameter_name, config)
def add_parameters(
self,
configs: Dict[str, Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig]],
) -> None:
"""
增加一组新的函数参数
Args:
configs: 要增加的函数参数名称及其配置
Returns:
无返回值
Raises:
ParameterError: 当参数为空、参数名称重复时将引发此异常
"""
self._parameter_area.add_parameters(configs)
def remove_parameter(
self, parameter_name: str, ignore_unknown_parameter: bool = True
) -> None:
"""
移除指定参数控件
Args:
parameter_name: 要移除的指定参数名称
ignore_unknown_parameter: 是否忽略未知参数
Returns:
无返回值
Raises:
ParameterNotFoundError: 当参数`parameter_name`不存在且`ignore_unknown_parameter`为`False`时,将引发此异常
"""
self._parameter_area.remove_parameter(
parameter_name, ignore_unknown_parameter=ignore_unknown_parameter
)
def has_parameter(self, parameter_name: str) -> bool:
"""
判断是否存在指定参数名称
Args:
parameter_name: 带判断的参数名称
Returns:
存在指定参数时返回`True`,否则返回`False`
"""
return self._parameter_area.has_parameter(parameter_name)
def clear_parameters(self) -> None:
"""
清除所有参数
Returns:
无返回值
"""
self._parameter_area.clear_parameters()
def get_parameter_value(self, parameter_name: str) -> Any:
"""
获取指定参数当前值
Args:
parameter_name: 参数名称
Returns:
返回当前值
Raises:
ParameterNotFoundError: 指定参数不存在时,将引发此异常
ParameterError: 无法从对应控件获取当前值时,将引发此异常
"""
return self._parameter_area.get_parameter_value(parameter_name)
def get_parameter_values(self) -> Dict[str, Any]:
"""
获取所有参数的当前值
Returns:
以字典形式返回当前所有参数的值
Raises:
ParameterError: 无法从对应控件获取某个参数的当前值时,将引发此异常
"""
return self._parameter_area.get_parameter_values()
def get_parameter_values_of(self, group_name: str) -> Dict[str, Any]:
"""
获取指定分组下所有参数当前值
Args:
group_name: 指定分组的名称
Returns:
返回指定分组下所有参数的名称和值
Raises:
ParameterNotFoundError: 当指定分组不存在时,引发此异常
ParameterError: 无法从对应控件获取某个参数的当前值时,将引发此异常
"""
return self._parameter_area.get_parameter_values_of(group_name)
def set_parameter_value(self, parameter_name: str, value: Any) -> None:
"""
设置参数当前值
Args:
parameter_name: 参数名称
value: 要设置的值
Returns:
无返回值
Raises:
ParameterNotFoundError: 若指定参数不存在,则引发此异常
ParameterError: 若无法将值设置到对应的控件,那么将引发此异常
"""
self._parameter_area.set_parameter_value(parameter_name, value)
def set_parameter_values(self, values: Dict[str, Any]) -> None:
"""
设置多个参数的当前值
Args:
values: 要设置的参数名称和值
Returns:
无返回值
Raises:
ParameterError: 若无法将值设置到对应的控件,那么将引发此异常
"""
self._parameter_area.clear_parameter_error(None)
if not values:
return
self._parameter_area.set_parameter_values(values)
def get_parameter_names(self) -> List[str]:
"""
获取所有参数名称
Returns:
返回当前所有参数名称
"""
return self._parameter_area.get_parameter_names()
def get_parameter_names_of(self, group_name: str) -> List[str]:
"""
获取指定分组下的所有参数名称
Args:
group_name: 分组名称
Returns:
返回指定分组下的所有参数名称
Raises:
ParameterNotFoundError: 当指定分组不存在时,引发此异常
"""
return self._parameter_area.get_parameter_names_of(group_name)
def set_output_dock_property(
self,
*,
title: Optional[str] = None,
visible: Optional[bool] = None,
floating: Optional[bool] = None,
area: Optional[DockWidgetArea] = None,
) -> None:
"""
设置Output Dock的属性
Args:
title: 标题
visible: 是否显示
floating: 是否悬浮
area: 初始停靠区域
Returns:
无返回值
"""
if title is not None:
self.set_output_dock_title(title)
if visible is not None:
self.set_output_dock_visible(visible)
if floating is not None:
self.set_output_dock_floating(floating)
if area is not None:
self.set_output_dock_area(area)
def set_document_dock_property(
self,
*,
title: Optional[str] = None,
visible: Optional[bool] = None,
floating: Optional[bool] = None,
area: Optional[DockWidgetArea] = None,
) -> None:
"""
设置Document Dock的属性
Args:
title: 标题
visible: 是否显示
floating: 是否悬浮
area: 初始停靠区域
Returns:
无返回值
"""
if title is not None:
self.set_document_dock_title(title)
if visible is not None:
self.set_document_dock_visible(visible)
if floating is not None:
self.set_document_dock_floating(floating)
if area is not None:
self.set_document_dock_area(area)
def set_allowed_dock_areas(self, areas: Optional[DockWidgetAreas]) -> None:
"""
设置停靠窗口允许停靠的区域
Args:
areas: 允许停靠的区域
Returns:
无返回值
"""
if areas is None:
return
self._document_dock.setAllowedAreas(areas)
self._output_dock.setAllowedAreas(areas)
def set_output_dock_visible(self, visible: bool) -> None:
"""
设置Output Dock是否显示
Args:
visible: 目标状态
Returns:
无返回值
"""
self._output_dock.setVisible(visible)
def is_output_dock_visible(self) -> bool:
"""
检查Output Dock是否显示
Returns:
返回当前显示状态
"""
return self._output_dock.isVisible()
def set_document_dock_visible(self, visible: bool) -> None:
"""
设置Document Dock是否显示
Args:
visible: 目标状态
Returns:
无返回值
"""
self._document_dock.setVisible(visible)
def is_document_dock_visible(self) -> bool:
"""
检查Document Dock是否显示
Returns:
返回当前显示状态
"""
return self._document_dock.isVisible()
def set_document_dock_floating(self, floating: bool) -> None:
"""
设置Document Dock是否悬浮
Args:
floating: 目标状态
Returns:
无返回值
"""
self._document_dock.setFloating(floating)
def is_document_dock_floating(self) -> bool:
"""
检查Document Dock是否悬浮
Returns:
返回当前悬浮状态
"""
return self._document_dock.isFloating()
def set_output_dock_floating(self, floating: bool) -> None:
"""
设置Output Dock是否悬浮
Args:
floating: 目标状态
Returns:
无返回值
"""
self._output_dock.setFloating(floating)
def is_output_dock_floating(self) -> bool:
"""
检查Output Dock是否悬浮
Returns:
返回当前悬浮状态
"""
return self._output_dock.isFloating()
def set_document_dock_title(self, title: str) -> None:
"""
设置Document Dock标题
Args:
title: 标题
Returns:
无返回值
"""
if title is None:
return
self._document_dock.setWindowTitle(title)
def get_document_dock_title(self) -> str:
"""
获取Document Dock标题
Returns:
返回当前标题
"""
return self._document_dock.windowTitle()
def get_document_dock_size(self) -> Tuple[int, int]:
"""
获取Document Dock尺寸
Returns:
返回当前尺寸
"""
size = self._document_dock.size()
return size.width(), size.height()
def set_output_dock_title(self, title: str) -> None:
"""
设置Output Dock标题
Args:
title: 标题
Returns:
无返回值
"""
if title is None:
return
self._output_dock.setWindowTitle(title)
def get_output_dock_title(self) -> str:
"""
获取Output Dock标题
Returns:
返回当前标题
"""
return self._output_dock.windowTitle()
def set_document_dock_area(self, area: DockWidgetArea) -> None:
"""
设置Document Dock停靠区域
Args:
area: 目标停靠区域
Returns:
无返回值
"""
if not self._document_dock.isAreaAllowed(area):
messagebox.show_warning_message(self, f"Invalid dock area: {area}")
return
self.addDockWidget(area, self._document_dock)
def get_document_dock_area(self) -> DockWidgetArea:
"""
获取Document Dock停靠区域
Returns:
返回当前停靠区域
"""
return self.dockWidgetArea(self._document_dock)
def set_output_dock_area(self, area: DockWidgetArea) -> None:
"""
设置Output Dock停靠区域
Args:
area: 目标停靠区域
Returns:
无返回值
"""
if not self._output_dock.isAreaAllowed(area):
messagebox.show_warning_message(self, f"Invalid dock area: {area}")
return
self.addDockWidget(area, self._output_dock)
def get_output_dock_area(self) -> DockWidgetArea:
"""
获取Output Dock停靠区域
Returns:
返回当前停靠区域
"""
return self.dockWidgetArea(self._output_dock)
def get_output_dock_size(self) -> Tuple[int, int]:
"""
获取Output Dock尺寸
Returns:
返回当前尺寸
"""
size = self._output_dock.size()
return size.width(), size.height()
def resize_document_dock(self, size: Tuple[Optional[int], Optional[int]]) -> None:
"""
调整Document Dock尺寸
注意:停靠窗口的尺寸受到多种因素的影响,无法保证实际的尺寸与开发者设置的尺寸保持一致,尤其时多个停靠窗口停靠在同一区域时具体而言:
- 尺寸的调整受最小和最大尺寸的约束;
- 尺寸调整不会影响主窗口的大小;
- 在空间有限的情况下,将根据各个停靠窗口的相对大小占比进行可以利用空间的调整
Args:
size: 目标尺寸
Returns:
无返回值
"""
width, height = size
if width:
self.resizeDocks([self._document_dock], [width], Qt.Horizontal)
if height:
self.resizeDocks([self._document_dock], [height], Qt.Vertical)
def resize_output_dock(self, size: Tuple[Optional[int], Optional[int]]) -> None:
"""
调整Output Dock尺寸
注意:停靠窗口的尺寸受到多种因素的影响,无法保证实际的尺寸与开发者设置的尺寸保持一致,尤其时多个停靠窗口停靠在同一区域时具体而言:
- 尺寸的调整受最小和最大尺寸的约束;
- 尺寸调整不会影响主窗口的大小;
- 在空间有限的情况下,将根据各个停靠窗口的相对大小占比进行可以利用空间的调整
Args:
size: 目标尺寸
Returns:
无返回值
"""
width, height = size
if width:
self.resizeDocks([self._output_dock], [width], Qt.Horizontal)
if height:
self.resizeDocks([self._output_dock], [height], Qt.Vertical)
def tabify_docks(self) -> None:
"""
使所有Dock窗口选项卡化
注意:当前已悬浮的窗口不受影响
Returns:
无返回值
"""
self.tabifyDockWidget(self._document_dock, self._output_dock)
def set_statusbar_visible(self, visible: bool) -> None:
"""
设置窗口状态栏是否可见
Args:
visible: 目标状态
Returns:
无返回值
"""
self.statusBar().setVisible(visible)
def is_statusbar_visible(self) -> bool:
"""
检查窗口状态栏是否可见
Returns:
返回状态栏当前状态
"""
return self.statusBar().isVisible()
def show_statusbar_message(self, message: str, timeout: int = 3000) -> None:
"""
设置状态栏消息
Args:
message: 消息文本
timeout: 显示的时长
Returns:
无返回值
"""
self.statusBar().showMessage(message, timeout)
def clear_statusbar_message(self) -> None:
"""
清除状态栏消息
Returns:
无返回值
"""
self.statusBar().clearMessage()
def set_execute_button_text(self, text: str) -> None:
"""
设置执行按钮文本
Args:
text: 目标文本
Returns:
无返回值
"""
self._operation_area.set_execute_button_text(text)
def set_cancel_button_text(self, text: str) -> None:
"""
设置取消按钮文本
Args:
text: 目标文本
Returns:
无返回值
"""
self._operation_area.set_cancel_button_text(text)
def set_clear_button_text(self, text: str) -> None:
"""
设置清除按钮文本
Args:
text: 目标文本
Returns:
无返回值
"""
self._operation_area.set_clear_button_text(text)
def set_clear_checkbox_text(self, text: str) -> None:
"""
设置清除选项框文本
Args:
text: 目标文本
Returns:
无返回值
"""
self._operation_area.set_clear_checkbox_text(text)
def set_clear_button_visible(self, visible: bool) -> None:
"""
设置清除按钮是否可见
Args:
visible: 目标状态
Returns:
无返回值
"""
self._operation_area.set_clear_button_visible(visible)
def set_clear_checkbox_visible(self, visible: bool) -> None:
"""
设置清除选项框是否可见
Args:
visible: 目标状态
Returns:
无返回值
"""
self._operation_area.set_clear_checkbox_visible(visible)
def set_clear_checkbox_checked(self, checked: bool) -> None:
"""
设置清除选项框是否选中
Args:
checked: 目标状态
Returns:
无返回值
"""
self._operation_area.set_clear_checkbox_checked(checked)
def is_clear_checkbox_checked(self) -> bool:
"""
检查清除选项框是否选中
Returns:
返回当前状态
"""
return self._operation_area.is_clear_checkbox_checked()
def is_function_executing(self) -> bool:
"""
检查函数是否正在运行
Returns:
返回函数运行状态
"""
return self._executor.is_executing
def is_function_cancelable(self) -> bool:
"""
检查函数是否为可取消函数
Returns:
返回函数是否可取消
"""
return self._executor.is_cancelled
def process_parameter_error(self, e: ParameterError) -> None:
"""
使用内置逻辑处理ParameterError类型的异常
Args:
e: 异常对象
Returns:
无返回值
"""
self._parameter_area.process_parameter_error(e)
def disable_parameter_widgets(self, disabled: bool) -> None:
"""
设置参数控件禁用/启用状态
Args:
disabled: 是否禁用
Returns:
无返回值
"""
self._parameter_area.disable_parameter_widgets(disabled)
def try_cancel_execution(self) -> None:
"""
尝试取消函数执行
Returns:
无返回值
Raises:
FunctionNotCancellableError: 函数未被设置为可取消函数时,将引发此异常
FunctionNotExecutingError: 函数未处于正在执行中时,将引发此异常
"""
self._config: FnExecuteWindowConfig
if not self._bundle.fn_info.cancelable:
raise FunctionNotCancellableError()
if not self._executor.is_executing:
raise FunctionNotExecutingError()
else:
self._executor.try_cancel()
def activate_parameter_group(self, group_name: str) -> None:
"""
激活展开指定参数分组。
Args:
group_name: 参数分组名称
Returns:
无返回值
"""
if group_name == "":
group_name = None
self._parameter_area.activate_parameter_group(group_name)
def scroll_to_parameter(
self,
parameter_name: str,
x: int = 50,
y: int = 50,
highlight_effect: bool = True,
):
"""
滚动到指定参数的位置。
Args:
parameter_name: 参数名称
x: 滚动的X坐标偏移值
y: 滚动的Y坐标偏移值
highlight_effect: 是否对指定控件显示高亮效果
Returns:
无返回值
"""
self._parameter_area.scroll_to_parameter(parameter_name, x, y, highlight_effect)
def before_execute(self, fn_info: FnInfo, arguments: Dict[str, Any]) -> None:
self._config: FnExecuteWindowConfig
super().before_execute(fn_info, arguments)
if self._operation_area.is_clear_checkbox_checked():
self.clear_output()
self._operation_area.set_execute_button_enabled(False)
if self._config.disable_widgets_on_execute:
self._parameter_area.disable_parameter_widgets(True)
self._operation_area.set_cancel_button_enabled(False)
self._parameter_area.clear_parameter_error(None)
def on_execute_start(self, fn_info: FnInfo, arguments: Dict[str, Any]) -> None:
super().on_execute_start(fn_info, arguments)
self._operation_area.set_cancel_button_enabled(True)
if isinstance(self._bundle.window_listener, FnExecuteWindowEventListener):
self._bundle.window_listener.on_execute_start(self)
def on_execute_finish(self, fn_info: FnInfo, arguments: Dict[str, Any]) -> None:
self._config: FnExecuteWindowConfig
super().on_execute_finish(fn_info, arguments)
self._operation_area.set_execute_button_enabled(True)
if self._config.disable_widgets_on_execute:
self._parameter_area.disable_parameter_widgets(False)
self._operation_area.set_cancel_button_enabled(False)
if isinstance(self._bundle.window_listener, FnExecuteWindowEventListener):
self._bundle.window_listener.on_execute_finish(self)
def on_execute_result(
self, fn_info: FnInfo, arguments: Dict[str, Any], result: Any
) -> None:
self._config: FnExecuteWindowConfig
# if callable(self._bundle.on_execute_result):
# self._bundle.on_execute_result(result, arguments.copy())
# return
if isinstance(self._bundle.window_listener, FnExecuteWindowEventListener):
should_continue = self._bundle.window_listener.on_execute_result(
self, result
)
if not should_continue:
return
result_str = self._config.function_result_message.format(result)
if self._config.print_function_result:
self.append_output(result_str, scroll_to_bottom=True)
if self._config.show_function_result:
messagebox.show_info_message(
self, result_str, title=self._config.result_dialog_title
)
def on_execute_error(
self, fn_info: FnInfo, arguments: Dict[str, Any], error: Exception
):
self._config: FnExecuteWindowConfig
if isinstance(self._bundle.window_listener, FnExecuteWindowEventListener):
should_continue = self._bundle.window_listener.on_execute_error(self, error)
if not should_continue:
del error
return
if isinstance(error, ParameterError):
self._parameter_area.process_parameter_error(error)
del error
return
# if callable(self._bundle.on_execute_error):
# self._bundle.on_execute_error(error, arguments.copy())
# del error
# return
error_type = type(error).__name__
error_msg = self._config.function_error_message.format(error_type, str(error))
if self._config.print_function_error:
if not self._config.function_error_traceback:
self.append_output(error_msg, scroll_to_bottom=True)
else:
self.append_output(get_traceback(error) + "\n", scroll_to_bottom=True)
if self._config.show_function_error:
if not self._config.function_error_traceback:
messagebox.show_critical_message(
self, error_msg, title=self._config.error_dialog_title
)
else:
messagebox.show_exception_messagebox(
self, exception=error, title=self._config.error_dialog_title
)
del error
def _on_close(self) -> bool:
self._config: FnExecuteWindowConfig
if self._executor.is_executing:
messagebox.show_warning_message(
self, self._config.function_executing_message
)
return False
return super()._on_close()
def _on_cleanup(self):
super()._on_cleanup()
self._parameter_area.clear_parameters()
def _on_destroy(self):
super()._on_destroy()
# noinspection PyProtectedMember
ucontext._current_window_destroyed()
def _on_cancel_button_clicked(self):
self._config: FnExecuteWindowConfig
try:
self.try_cancel_execution()
except FunctionNotCancellableError:
messagebox.show_warning_message(
self, self._config.uncancelable_function_message
)
except FunctionNotExecutingError:
messagebox.show_warning_message(
self, self._config.function_not_executing_message
)
def _on_execute_button_clicked(self):
self._config: FnExecuteWindowConfig
if self._executor.is_executing:
messagebox.show_warning_message(
self, self._config.function_executing_message
)
return
try:
arguments = self.get_parameter_values()
except ParameterError as e:
self._parameter_area.process_parameter_error(e)
else:
self._executor.execute(self._bundle.fn_info, arguments)
# noinspection PyMethodMayBeStatic
def _on_clear_button_clicked(self):
uoutput.clear_output()
| 33,476 | Python | .py | 912 | 23.199561 | 101 | 0.586683 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,537 | __init__.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/__init__.py | from ._base import (
FnExecuteWindowConfig,
DockWidgetArea,
TopDockWidgetArea,
BottomDockWidgetArea,
LeftDockWidgetArea,
RightDockWidgetArea,
NoDockWidgetArea,
DockWidgetAreas,
AllDockWidgetAreas,
FnExecuteWindowEventListener,
SimpleFnExecuteWindowEventListener,
)
from ._output_area import ProgressBarConfig, OutputBrowserConfig
from ._window import FnExecuteWindow
__all__ = [
"FnExecuteWindowConfig",
"FnExecuteWindow",
"ProgressBarConfig",
"OutputBrowserConfig",
"DockWidgetArea",
"TopDockWidgetArea",
"BottomDockWidgetArea",
"LeftDockWidgetArea",
"RightDockWidgetArea",
"NoDockWidgetArea",
"DockWidgetAreas",
"AllDockWidgetAreas",
"FnExecuteWindowEventListener",
"SimpleFnExecuteWindowEventListener",
]
| 809 | Python | .py | 31 | 21.83871 | 64 | 0.765766 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,538 | _base.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_base.py | import dataclasses
from abc import abstractmethod
from typing import Tuple, Dict, Union, Type, Optional, Literal, Any, Callable, List
from qtpy.QtCore import QSize, Qt
from ._output_area import OutputBrowserConfig, ProgressBarConfig
from ..document_browser import DocumentBrowserConfig
from ...exceptions import ParameterError
from ...executor import ExecuteStateListener
from ...executors import ThreadFunctionExecutor
from ...paramwidget import (
BaseParameterWidget,
BaseParameterWidgetConfig,
)
from ...utils import IconType
from ...window import (
BaseWindow,
BaseWindowConfig,
BaseWindowEventListener,
)
DEFAULT_EXECUTOR_CLASS = ThreadFunctionExecutor
ParameterWidgetType = Union[
Tuple[Type[BaseParameterWidget], Union[BaseParameterWidgetConfig, dict]],
BaseParameterWidgetConfig,
]
DockWidgetArea = Qt.DockWidgetArea
NoDockWidgetArea = Qt.DockWidgetArea.NoDockWidgetArea
BottomDockWidgetArea = Qt.DockWidgetArea.BottomDockWidgetArea
TopDockWidgetArea = Qt.DockWidgetArea.TopDockWidgetArea
LeftDockWidgetArea = Qt.DockWidgetArea.LeftDockWidgetArea
RightDockWidgetArea = Qt.DockWidgetArea.RightDockWidgetArea
DockWidgetAreas = Union[DockWidgetArea, int]
AllDockWidgetAreas = Qt.AllDockWidgetAreas
# noinspection SpellCheckingInspection
@dataclasses.dataclass(frozen=True)
class FnExecuteWindowConfig(BaseWindowConfig):
title: Optional[str] = None
"""窗口标题。"""
size: Union[Tuple[int, int], QSize] = (800, 600)
"""窗口大小。"""
execute_button_text: str = "Execute"
"""执行按钮文本。"""
cancel_button_text: str = "Cancel"
"""取消按钮文本。"""
clear_button_text: str = "Clear"
"""清除按钮文本。"""
clear_button_visible: bool = True
"""是否显示清除按钮。"""
clear_checkbox_text: str = "clear output"
"""清除选项框文本。"""
clear_checkbox_visible: bool = True
"""是否显示清除选项框。"""
clear_checkbox_checked: bool = True
"""是否将清除选项框设置为选中状态。"""
statusbar_visible: bool = False
"""是否显示窗口状态栏"""
initial_docks_state: Literal["auto", "tabified"] = "auto"
"""停靠窗口的初始状态。可选`auto`或`tabified`。当指定为`tabified`时,停靠窗口将组合成一个`Tab`组件,每个停靠窗口都将以`Tab页`的形式出现。"""
output_dock_visible: bool = True
"""是否显示`Output停靠窗口`。"""
output_dock_title: str = "Output"
"""`Output停靠窗口`的标题。"""
output_dock_floating: bool = False
"""是否使`Output停靠窗口`处于悬浮状态。"""
output_dock_initial_area: DockWidgetArea = BottomDockWidgetArea
"""`Output停靠窗口`的初始停靠区域。"""
output_dock_initial_size: Tuple[Optional[int], Optional[int]] = (None, 150)
"""`Output停靠窗口`的初始大小,格式为`(width, height)`,可以只设置其中一个维度,另一个不需要设置的维度置为`None`即可。"""
document_dock_visible: bool = True
"""是否显示`Document停靠窗口`。"""
document_dock_title: str = "Document"
"""`Document停靠窗口`的标题。"""
document_dock_floating: bool = False
"""是否使`Document停靠窗口`处于悬浮状态。"""
document_dock_initial_area: DockWidgetArea = RightDockWidgetArea
"""`Document停靠窗口`的初始停靠区域。"""
document_dock_initial_size: Tuple[Optional[int], Optional[int]] = (450, None)
"""`Document停靠窗口`的初始大小,格式为`(width, height)`,可以只设置其中一个维度,另一个不需要设置的维度置为`None`即可。"""
output_browser_config: Optional[OutputBrowserConfig] = dataclasses.field(
default_factory=OutputBrowserConfig
)
"""`输出浏览器`的配置。"""
document_browser_config: Optional[DocumentBrowserConfig] = dataclasses.field(
default_factory=DocumentBrowserConfig
)
"""`文档浏览器`的配置。"""
default_parameter_group_name: str = "Main Parameters"
"""默认函数参数分组的名称。"""
default_parameter_group_icon: IconType = None
"""默认函数参数分组的图标。"""
parameter_group_icons: Dict[str, IconType] = dataclasses.field(default_factory=dict)
"""除默认函数参数分组外其他函数参数分组的图标"""
disable_widgets_on_execute: bool = False
"""是否在函数执行期间使参数控件处于不可输入状态。"""
print_function_result: bool = True
"""是否在`输出浏览器`中打印函数调用结果。"""
show_function_result: bool = False
"""是否弹窗显示函数调用结果。"""
print_function_error: bool = True
"""是否在`输出浏览器`中打印函数执行过程中发生的异常和错误。"""
show_function_error: bool = True
"""是否弹窗显示函数执行过程中发生的异常和错误。"""
function_error_traceback: bool = True
"""在打印或弹窗显示函数执行过程中发生的异常时,是否显示异常的回溯信息。"""
error_dialog_title: str = "Error"
"""错误信息弹窗的标题。"""
result_dialog_title: str = "Result"
"""函数调用结果弹窗的标题。"""
parameter_error_message: str = "{}: {}"
"""`ParameterError`类型异常的消息模板,模板第一个变量(`{}`)为`参数名称`,第二个变量(`{}`)为`异常的消息(message)`。"""
function_result_message: str = "function result: {}\n"
"""函数调用结果的消息模板,模板变量(`{}`)为函数的返回值。"""
function_error_message: str = "{}: {}\n"
"""函数异常或错误的消息模板,模板第一个变量(`{}`)为`异常的类型`,第二个变量(`{}`)为`异常的消息(message)`。"""
function_executing_message: str = "A function is executing now!"
"""提示消息,用以提示“函数正在执行”。"""
uncancelable_function_message: str = "The function is not cancelable!"
"""提示消息,用以提示“当前函数为不可取消的函数”。"""
function_not_executing_message: str = "No function is executing now!"
"""提示消息,用以提示“当前函数未处于执行状态”。"""
# noinspection SpellCheckingInspection
class BaseFnExecuteWindow(BaseWindow, ExecuteStateListener):
@abstractmethod
def _create_ui(self):
pass
@abstractmethod
def update_progressbar_config(
self, config: Union[ProgressBarConfig, dict, None]
) -> None:
pass
@abstractmethod
def show_progressbar(self) -> None:
pass
@abstractmethod
def hide_progressbar(self) -> None:
pass
@abstractmethod
def update_progress(
self, current_value: int, message: Optional[str] = None
) -> None:
pass
@abstractmethod
def append_output(
self, text: str, html: bool = False, scroll_to_bottom: bool = True
) -> None:
pass
@abstractmethod
def clear_output(self) -> None:
pass
@abstractmethod
def set_document(
self, document: str, document_format: Literal["markdown", "html", "plaintext"]
) -> None:
pass
@abstractmethod
def add_parameter(
self,
parameter_name: str,
config: Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig],
) -> None:
pass
@abstractmethod
def add_parameters(
self,
configs: Dict[str, Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig]],
) -> None:
pass
@abstractmethod
def remove_parameter(
self, parameter_name: str, ignore_unknown_parameter: bool = True
) -> None:
pass
@abstractmethod
def has_parameter(self, parameter_name: str) -> bool:
pass
@abstractmethod
def clear_parameters(self) -> None:
pass
@abstractmethod
def get_parameter_value(self, parameter_name: str) -> Any:
pass
@abstractmethod
def get_parameter_values(self) -> Dict[str, Any]:
pass
@abstractmethod
def set_parameter_value(self, parameter_name: str, value: Any) -> None:
pass
@abstractmethod
def set_parameter_values(self, values: Dict[str, Any]) -> None:
pass
@abstractmethod
def set_output_dock_property(
self,
*,
title: Optional[str] = None,
visible: Optional[bool] = None,
floating: Optional[bool] = None,
area: Optional[DockWidgetArea] = None,
) -> None:
pass
@abstractmethod
def set_document_dock_property(
self,
*,
title: Optional[str] = None,
visible: Optional[bool] = None,
floating: Optional[bool] = None,
area: Optional[DockWidgetArea] = None,
) -> None:
pass
@abstractmethod
def set_allowed_dock_areas(self, areas: Optional[DockWidgetAreas]) -> None:
pass
@abstractmethod
def set_output_dock_visible(self, visible: bool) -> None:
pass
@abstractmethod
def is_output_dock_visible(self) -> bool:
pass
@abstractmethod
def set_document_dock_visible(self, visible: bool) -> None:
pass
@abstractmethod
def is_document_dock_visible(self) -> bool:
pass
@abstractmethod
def set_document_dock_floating(self, floating: bool) -> None:
pass
@abstractmethod
def is_document_dock_floating(self) -> bool:
pass
@abstractmethod
def set_output_dock_floating(self, floating: bool) -> None:
pass
@abstractmethod
def is_output_dock_floating(self) -> bool:
pass
@abstractmethod
def set_document_dock_title(self, title: str) -> None:
pass
@abstractmethod
def get_document_dock_title(self) -> str:
pass
@abstractmethod
def set_output_dock_title(self, title: str) -> None:
pass
@abstractmethod
def get_output_dock_title(self) -> str:
pass
@abstractmethod
def set_document_dock_area(self, area: DockWidgetArea) -> None:
pass
@abstractmethod
def get_document_dock_area(self) -> DockWidgetArea:
pass
@abstractmethod
def set_output_dock_area(self, area: DockWidgetArea) -> None:
pass
@abstractmethod
def get_output_dock_area(self) -> DockWidgetArea:
pass
@abstractmethod
def resize_document_dock(self, size: Tuple[Optional[int], Optional[int]]) -> None:
pass
@abstractmethod
def resize_output_dock(self, size: Tuple[Optional[int], Optional[int]]) -> None:
pass
@abstractmethod
def tabify_docks(self) -> None:
pass
@abstractmethod
def set_statusbar_visible(self, visible: bool) -> None:
pass
@abstractmethod
def is_statusbar_visible(self) -> bool:
pass
@abstractmethod
def show_statusbar_message(self, message: str, timeout: int) -> None:
pass
@abstractmethod
def clear_statusbar_message(self) -> None:
pass
@abstractmethod
def set_execute_button_text(self, text: str) -> None:
pass
@abstractmethod
def set_cancel_button_text(self, text: str) -> None:
pass
@abstractmethod
def set_clear_button_text(self, text: str) -> None:
pass
@abstractmethod
def set_clear_checkbox_text(self, text: str) -> None:
pass
@abstractmethod
def set_clear_button_visible(self, visible: bool) -> None:
pass
@abstractmethod
def set_clear_checkbox_visible(self, visible: bool) -> None:
pass
@abstractmethod
def set_clear_checkbox_checked(self, checked: bool) -> None:
pass
@abstractmethod
def is_clear_checkbox_checked(self) -> bool:
pass
@abstractmethod
def is_function_executing(self) -> bool:
pass
@abstractmethod
def is_function_cancelable(self) -> bool:
pass
@abstractmethod
def process_parameter_error(self, e: ParameterError) -> None:
pass
@abstractmethod
def get_parameter_names(self) -> List[str]:
pass
@abstractmethod
def get_parameter_names_of(self, group_name: str) -> List[str]:
pass
@abstractmethod
def get_document_dock_size(self) -> Tuple[int, int]:
pass
@abstractmethod
def get_output_dock_size(self) -> Tuple[int, int]:
pass
@abstractmethod
def disable_parameter_widgets(self, disabled: bool) -> None:
pass
@abstractmethod
def get_parameter_values_of(self, group_name: str) -> Dict[str, Any]:
pass
@abstractmethod
def try_cancel_execution(self) -> bool:
pass
@abstractmethod
def scroll_to_parameter(
self,
parameter_name: str,
x: int = 50,
y: int = 50,
highlight_effect: bool = True,
) -> None:
pass
@abstractmethod
def activate_parameter_group(self, group_name: str) -> None:
pass
class FnExecuteWindowEventListener(BaseWindowEventListener):
def on_execute_start(self, window: BaseFnExecuteWindow) -> None:
"""
在函数执行开始时回调。
Args:
window: 当前窗口实例
Returns:
无返回值
"""
pass
def on_execute_result(self, window: BaseFnExecuteWindow, result: Any) -> bool:
"""
在函数执行成功(函数返回)时回调。
Args:
window: 当前窗口实例
result: 函数的返回值
Returns:
如果返回`True`,则允许`PyGUIAdapter`执行默认的后续操作,比如打印函数结果或弹窗显示函数结果等,否则阻止执行默认操作。默认返回`True`。
"""
return True
def on_execute_error(self, window: BaseFnExecuteWindow, error: Exception) -> bool:
"""
在函数执行失败(函数抛出异常)时回调。
Args:
window: 当前窗口实例
error: 函数抛出的异常
Returns:
如果返回`True`,则允许`PyGUIAdapter`执行默认的后续操作,比如打印函数异常或弹窗显示函数异常等,否则阻止执行默认操作。默认返回`True`。
"""
return True
def on_execute_finish(self, window: BaseFnExecuteWindow) -> None:
"""
在函数执行结束时回调,无论函数执行是否成功,该回调函数都会被调用。
Args:
window: 当前窗口实例
Returns:
无返回值
"""
pass
class SimpleFnExecuteWindowEventListener(FnExecuteWindowEventListener):
"""
一个简单的`FnExecuteWindowEventListener`实现,方便不喜欢子类化方式的开发者使用。
"""
def __init__(
self,
on_create: Callable[[BaseFnExecuteWindow], None] = None,
on_show: Callable[[BaseFnExecuteWindow], None] = None,
on_hide: Callable[[BaseFnExecuteWindow], None] = None,
on_close: Callable[[BaseFnExecuteWindow], bool] = None,
on_destroy: Callable[[BaseFnExecuteWindow], None] = None,
on_execute_start: Callable[[BaseFnExecuteWindow], None] = None,
on_execute_result: Callable[[BaseFnExecuteWindow, Any], bool] = None,
on_execute_error: Callable[[BaseFnExecuteWindow, Exception], bool] = None,
on_execute_finish: Callable[[BaseFnExecuteWindow], None] = None,
):
"""
构造函数。
Args:
on_create: `on_create`回调函数
on_show: `on_show`回调函数
on_hide: `on_hide`回调函数
on_close: `on_close`回调函数
on_destroy: `on_destroy`回调函数
on_execute_start: `on_execute_start`回调函数
on_execute_result: `on_execute_result`回调函数
on_execute_error: `on_execute_error`回调函数
on_execute_finish: `on_execute_finish`回调函数
"""
self._on_create = on_create
self._on_show = on_show
self._on_hide = on_hide
self._on_close = on_close
self._on_destroy = on_destroy
self._on_execute_start = on_execute_start
self._on_execute_result = on_execute_result
self._on_execute_error = on_execute_error
self._on_execute_finish = on_execute_finish
def on_create(self, window: BaseFnExecuteWindow) -> None:
if self._on_create is not None:
return self._on_create(window)
return super().on_create(window)
def on_show(self, window: BaseFnExecuteWindow) -> None:
if self._on_show is not None:
return self._on_show(window)
return super().on_show(window)
def on_hide(self, window: BaseFnExecuteWindow) -> None:
if self._on_hide is not None:
return self._on_hide(window)
return super().on_hide(window)
def on_close(self, window: BaseFnExecuteWindow) -> bool:
if self._on_close is not None:
return self._on_close(window)
return super().on_close(window)
def on_destroy(self, window: BaseFnExecuteWindow) -> None:
if self._on_destroy is not None:
return self._on_destroy(window)
super().on_destroy(window)
def on_execute_start(self, window: BaseFnExecuteWindow) -> None:
if self._on_execute_start is not None:
return self._on_execute_start(window)
return super().on_execute_start(window)
def on_execute_result(self, window: BaseFnExecuteWindow, result: Any) -> bool:
if self._on_execute_result is not None:
return self._on_execute_result(window, result)
return super().on_execute_result(window, result)
def on_execute_error(self, window: BaseFnExecuteWindow, error: Exception) -> bool:
if self._on_execute_error is not None:
return self._on_execute_error(window, error)
return super().on_execute_error(window, error)
def on_execute_finish(self, window: BaseFnExecuteWindow) -> None:
if self._on_execute_finish is not None:
return self._on_execute_finish(window)
return super().on_execute_finish(window)
| 18,337 | Python | .py | 460 | 28.671739 | 95 | 0.656319 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,539 | area.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_operation_area/area.py | from typing import Optional
from qtpy.QtCore import Signal
from qtpy.QtWidgets import QWidget, QPushButton, QCheckBox, QVBoxLayout, QHBoxLayout
from .._base import FnExecuteWindowConfig
from ....utils import hline
class OperationArea(QWidget):
sig_execute_requested = Signal()
sig_cancel_requested = Signal()
sig_clear_requested = Signal()
def __init__(self, parent: Optional[QWidget], config: FnExecuteWindowConfig):
self._config: FnExecuteWindowConfig = config
self._layout: Optional[QVBoxLayout] = None
self._button_layout: Optional[QHBoxLayout] = None
self._execute_button: Optional[QPushButton] = None
self._clear_button: Optional[QPushButton] = None
self._cancel_button: Optional[QPushButton] = None
self._clear_checkbox: Optional[QCheckBox] = None
super().__init__(parent)
self._layout = QVBoxLayout()
self._layout.setContentsMargins(0, 0, 0, 0)
self._button_layout = QHBoxLayout()
self._execute_button = QPushButton(self)
self._cancel_button = QPushButton(self)
self._clear_button = QPushButton(self)
self._clear_checkbox = QCheckBox(self)
self._button_layout.addWidget(self._execute_button)
self._button_layout.addWidget(self._cancel_button)
self._button_layout.addWidget(self._clear_button)
self._layout.addWidget(self._clear_checkbox)
self._layout.addWidget(hline(self))
self._layout.addLayout(self._button_layout)
# noinspection PyUnresolvedReferences
self._execute_button.clicked.connect(self.sig_execute_requested)
# noinspection PyUnresolvedReferences
self._cancel_button.clicked.connect(self.sig_cancel_requested)
# noinspection PyUnresolvedReferences
self._clear_button.clicked.connect(self.sig_clear_requested)
self.setLayout(self._layout)
self._apply_config()
def _apply_config(self):
self._execute_button.setText(self._config.execute_button_text or "Execute")
self._cancel_button.setText(self._config.cancel_button_text or "Cancel")
self._clear_button.setText(self._config.clear_button_text or "Clear")
self._clear_checkbox.setText(self._config.clear_checkbox_text or "clear output")
self._clear_button.setVisible(self._config.clear_checkbox_visible)
self._clear_checkbox.setVisible(self._config.clear_checkbox_visible)
self._clear_checkbox.setChecked(self._config.clear_checkbox_checked)
def set_execute_button_enabled(self, enabled: bool):
if self._execute_button is not None:
self._execute_button.setEnabled(enabled)
def set_clear_button_enabled(self, enabled: bool):
if self._clear_button is not None:
self._clear_button.setEnabled(enabled)
def set_cancel_button_enabled(self, enabled: bool):
if self._cancel_button is not None:
self._cancel_button.setEnabled(enabled)
def set_clear_button_visible(self, visible: bool):
if self._clear_button is not None:
self._clear_button.setVisible(visible)
def set_cancel_button_visible(self, visible: bool):
if self._cancel_button is not None:
self._cancel_button.setVisible(visible)
def set_clear_checkbox_visible(self, visible: bool):
if self._clear_checkbox is not None:
self._clear_checkbox.setVisible(visible)
def is_clear_checkbox_checked(self) -> bool:
return self._clear_checkbox.isChecked()
def set_clear_checkbox_checked(self, checked: bool):
self._clear_checkbox.setChecked(checked)
def set_execute_button_text(self, text: str):
if self._execute_button is not None:
self._execute_button.setText(text)
def set_cancel_button_text(self, text: str):
if self._cancel_button is not None:
self._cancel_button.setText(text)
def set_clear_button_text(self, text: str):
if self._clear_button is not None:
self._clear_button.setText(text)
def set_clear_checkbox_text(self, text: str):
if self._clear_checkbox is not None:
self._clear_checkbox.setText(text)
| 4,219 | Python | .py | 81 | 43.679012 | 88 | 0.692457 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,540 | area.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_document_area/area.py | from typing import Literal, Optional, Callable
from qtpy.QtWidgets import QWidget, QVBoxLayout
from ...document_browser import DocumentBrowserConfig, DocumentBrowser
from ....utils import set_textbrowser_content
class DocumentArea(QWidget):
# noinspection SpellCheckingInspection
def __init__(
self, parent: QWidget, document_browser_config: Optional[DocumentBrowserConfig]
):
super().__init__(parent)
self._config = document_browser_config or DocumentBrowserConfig()
self._on_parameter_anchor_clicked: Optional[Callable[[str], None]] = None
self._on_group_anchor_clicked: Optional[Callable[[str], None]] = None
# noinspection PyArgumentList
self._layout = QVBoxLayout()
self._layout.setContentsMargins(0, 0, 0, 0)
self._doc_browser = DocumentBrowser(self, document_browser_config)
self._doc_browser.sig_parameter_anchor_clicked.connect(
self._on_parameter_anchor_clicked_internal
)
self._doc_browser.sig_group_anchor_clicked.connect(
self._on_group_anchor_clicked_internal
)
self._layout.addWidget(self._doc_browser)
self.setLayout(self._layout)
def set_document(
self, document: str, document_format: Literal["markdown", "html", "plaintext"]
):
set_textbrowser_content(self._doc_browser, document, document_format)
def _on_parameter_anchor_clicked_internal(self, anchor: str):
if self._on_parameter_anchor_clicked:
self._on_parameter_anchor_clicked(anchor)
def _on_group_anchor_clicked_internal(self, anchor: str):
if self._on_group_anchor_clicked:
self._on_group_anchor_clicked(anchor)
def on_parameter_anchor_clicked(self, callback: Callable[[str], None]):
self._on_parameter_anchor_clicked = callback
def on_group_anchor_clicked(self, callback: Callable[[str], None]):
self._on_group_anchor_clicked = callback
| 1,981 | Python | .py | 39 | 42.974359 | 87 | 0.696058 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,541 | area.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_parameter_area/area.py | import dataclasses
from typing import Optional, Any, Dict, List, Tuple, Type
from qtpy.QtWidgets import QWidget, QVBoxLayout
from .base import BaseParameterArea, BaseParameterGroupBox
from .group import ParameterGroupBox
from .._base import FnExecuteWindowConfig
from ....bundle import FnBundle
from ....exceptions import ParameterError
from ....fn import ParameterInfo
from ....paramwidget import (
BaseParameterWidget,
BaseParameterWidgetConfig,
is_parameter_widget_class,
)
from ....utils import messagebox
from ....widgets import CommonParameterWidgetConfig
class ParameterArea(BaseParameterArea):
def __init__(
self, parent: QWidget, config: FnExecuteWindowConfig, bundle: FnBundle
):
super().__init__(parent)
self._config: FnExecuteWindowConfig = config
self._bundle: FnBundle = bundle
# noinspection PyArgumentList
self._layout = QVBoxLayout()
self._groupbox: Optional[BaseParameterGroupBox] = ParameterGroupBox(
self, self._config
)
self._groupbox.add_default_group()
self._layout.addWidget(self._groupbox)
self.setLayout(self._layout)
@property
def parameter_groupbox(self) -> BaseParameterGroupBox:
return self._groupbox
def add_parameter(
self,
parameter_name: str,
config: Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig],
) -> BaseParameterWidget:
if parameter_name.strip() == "":
raise ValueError("parameter name cannot be empty.")
param_info = self._bundle.fn_info.parameters.get(parameter_name)
widget_class, widget_config = self._process_config(
parameter_name, param_info, config
)
try:
widget = self._groupbox.add_parameter(
parameter_name, widget_class, widget_config
)
if isinstance(widget_config, CommonParameterWidgetConfig):
# apply set_default_value_on_init
# set_value() may raise exceptions, we need to catch ParameterValidationError of them
# typically, this kind of exception is not fatal, it unnecessary to exit the whole program
# when this kind of exception raised
if widget_config.set_default_value_on_init:
widget.set_value(widget_config.default_value)
except ParameterError as e:
# self.process_parameter_error(e)
# return None
raise e
except Exception as e:
# any other exceptions are seen as fatal and will cause the whole program to exit
messagebox.show_exception_messagebox(
self,
message=f"cannot create parameter widget for parameter '{parameter_name}':",
exception=e,
title=self._config.error_dialog_title,
)
exit(-1)
else:
return widget
def remove_parameter(
self, parameter_name: str, ignore_unknown_parameter: bool = True
):
self._groupbox.remove_parameter(
parameter_name, ignore_unknown_parameter=ignore_unknown_parameter
)
def clear_parameters(self):
self._groupbox.clear_parameters()
self._groupbox.add_default_group()
def has_parameter(self, parameter_name: str) -> bool:
return self._groupbox.has_parameter(parameter_name)
def get_parameter_group_names(self) -> List[str]:
return self._groupbox.get_parameter_group_names()
def get_parameter_names(self) -> List[str]:
return self._groupbox.get_parameter_names()
def get_parameter_names_of(self, group_name: str) -> List[str]:
return self._groupbox.get_parameter_names_of(group_name)
def activate_parameter_group(self, group_name: Optional[str]) -> bool:
return self._groupbox.active_parameter_group(group_name)
def scroll_to_parameter(
self,
parameter_name: str,
x: int = 50,
y: int = 50,
highlight_effect: bool = False,
):
self._groupbox.scroll_to_parameter(parameter_name, x, y, highlight_effect)
def get_parameter_value(self, parameter_name: str) -> Any:
return self._groupbox.get_parameter_value(parameter_name)
def get_parameter_values(self) -> Dict[str, Any]:
return self._groupbox.get_parameter_values()
def set_parameter_value(self, parameter_name: str, value: Any):
self._groupbox.set_parameter_value(parameter_name=parameter_name, value=value)
def clear_parameter_error(self, parameter_name: Optional[str]):
self._groupbox.clear_parameter_error(parameter_name)
def set_parameter_values(self, params: Dict[str, Any]) -> List[str]:
return self._groupbox.set_parameter_values(params)
def get_parameter_values_of(self, group_name: Optional[str]) -> Dict[str, Any]:
return self._groupbox.get_parameter_values_of(group_name)
def process_parameter_error(self, e: ParameterError):
self._groupbox.notify_parameter_error(e.parameter_name, e.message)
msg = self._config.parameter_error_message.format(e.parameter_name, e.message)
messagebox.show_critical_message(
self, message=msg, title=self._config.error_dialog_title
)
self._groupbox.scroll_to_parameter(e.parameter_name)
del e
def disable_parameter_widgets(self, disabled: bool):
self._groupbox.disable_parameter_widgets(disabled)
@staticmethod
def _process_config(
param_name: str,
param_info: ParameterInfo,
config: Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig],
) -> Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig]:
assert isinstance(config, tuple) and len(config) == 2
assert is_parameter_widget_class(config[0])
assert isinstance(config[1], BaseParameterWidgetConfig)
widget_class, widget_config = config
# try to get description from parameter info if it is empty in widget_config
if widget_config.description is None or widget_config.description == "":
if param_info.description is not None and param_info.description != "":
widget_config = dataclasses.replace(
widget_config, description=param_info.description
)
widget_config = widget_class.on_post_process_config(
widget_config, param_name, param_info
)
return widget_class, widget_config
| 6,544 | Python | .py | 140 | 37.857143 | 106 | 0.669749 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,542 | __init__.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_parameter_area/__init__.py | from .base import BaseParameterPage, BaseParameterGroupBox, BaseParameterArea
from .area import ParameterArea
| 110 | Python | .py | 2 | 54 | 77 | 0.888889 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,543 | base.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_parameter_area/base.py | from abc import abstractmethod
from typing import Dict, Any, List, Tuple, Type, Optional
from qtpy.QtCore import Signal
from qtpy.QtGui import QIcon
from qtpy.QtWidgets import QWidget, QToolBox
from ....exceptions import ParameterError
from ....paramwidget import BaseParameterWidget, BaseParameterWidgetConfig
class BaseParameterPage(QWidget):
def __init__(self, parent: "BaseParameterGroupBox", group_name: str):
assert isinstance(parent, BaseParameterGroupBox)
self._parent: BaseParameterGroupBox = parent
self._group_name = group_name
super().__init__(parent)
def parent(self) -> "BaseParameterGroupBox":
return super().parent()
@property
def group_name(self) -> str:
return self._group_name
@abstractmethod
def scroll_to(
self,
parameter_name: str,
x: int = 50,
y: int = 50,
highlight_effect: bool = False,
) -> None:
pass
@abstractmethod
def upsert_parameter_widget(
self,
parameter_name: str,
widget_class: Type[BaseParameterWidget],
widget_config: BaseParameterWidgetConfig,
index: Optional[int] = None,
) -> BaseParameterWidget:
pass
@abstractmethod
def insert_parameter_widget(
self,
parameter_name: str,
widget_class: Type[BaseParameterWidget],
widget_config: BaseParameterWidgetConfig,
index: int = -1,
) -> BaseParameterWidget:
pass
@abstractmethod
def update_parameter_widget(
self,
parameter_name: str,
widget_class: Type[BaseParameterWidget],
widget_config: BaseParameterWidgetConfig,
) -> BaseParameterWidget:
pass
@abstractmethod
def get_parameter_widget(
self, parameter_name: str
) -> Optional[BaseParameterWidget]:
pass
@abstractmethod
def has_parameter_widget(self, parameter_name: str) -> bool:
pass
@abstractmethod
def remove_parameter_widget(self, parameter_name: str):
pass
@abstractmethod
def clear_parameter_widgets(self):
pass
@abstractmethod
def parameter_count(self) -> int:
pass
@abstractmethod
def get_parameter_names(self) -> List[str]:
pass
@abstractmethod
def get_parameter_value(self, parameter_name: str) -> Any:
pass
@abstractmethod
def set_parameter_value(self, parameter_name: str, value: Any):
pass
@abstractmethod
def get_parameter_values(self) -> Dict[str, Any]:
pass
@abstractmethod
def set_parameter_values(self, values: Dict[str, Any]):
pass
def disable_parameter_widgets(self, disabled: bool):
pass
# noinspection SpellCheckingInspection
@abstractmethod
def _add_to_scrollarea(self, widget: BaseParameterWidget, index: int):
pass
class BaseParameterGroupBox(QToolBox):
sig_parameter_error = Signal(str, object)
sig_clear_parameter_error = Signal(object)
def __init__(self, parent: QWidget):
super().__init__(parent)
@abstractmethod
def upsert_parameter_group(self, group_name: Optional[str]) -> BaseParameterPage:
pass
@abstractmethod
def add_default_group(self) -> BaseParameterPage:
pass
@abstractmethod
def has_parameter_group(self, group_name: Optional[str]) -> bool:
pass
@abstractmethod
def _get_parameter_group(
self, group_name: Optional[str]
) -> Optional[BaseParameterPage]:
pass
@abstractmethod
def remove_parameter_group(self, group_name: Optional[str]):
pass
@abstractmethod
def get_parameter_group_names(self) -> List[str]:
pass
@abstractmethod
def _get_parameter_group_of(
self, parameter_name: str
) -> Optional[BaseParameterPage]:
pass
@abstractmethod
def has_parameter(self, parameter_name: str) -> bool:
pass
@abstractmethod
def add_parameter(
self,
parameter_name: str,
widget_class: Type[BaseParameterWidget],
widget_config: BaseParameterWidgetConfig,
) -> BaseParameterWidget:
pass
@abstractmethod
def remove_parameter(
self, parameter_name: str, ignore_unknown_parameter: bool = True
):
pass
@abstractmethod
def clear_parameters(self):
pass
@abstractmethod
def get_parameter_value(self, parameter_name: str) -> Any:
pass
@abstractmethod
def get_parameter_values(self) -> Dict[str, Any]:
pass
@abstractmethod
def get_parameter_values_of(self, group_name: Optional[str]) -> Dict[str, Any]:
pass
@abstractmethod
def get_parameter_names(self) -> List[str]:
pass
@abstractmethod
def get_parameter_names_of(self, group_name: str) -> List[str]:
pass
@abstractmethod
def set_parameter_value(self, parameter_name: str, value: Any):
pass
@abstractmethod
def set_parameter_values(self, params: Dict[str, Any]):
pass
@abstractmethod
def active_parameter_group(self, group_name: Optional[str]) -> bool:
pass
@abstractmethod
def scroll_to_parameter(
self,
parameter_name: str,
x: int = 50,
y: int = 50,
highlight_effect: bool = True,
) -> None:
pass
def notify_parameter_error(self, parameter_name: str, error: Any):
# noinspection PyUnresolvedReferences
self.sig_parameter_error.emit(parameter_name, error)
def clear_parameter_error(self, parameter_name: Optional[str]):
# noinspection PyUnresolvedReferences
self.sig_clear_parameter_error.emit(parameter_name)
@abstractmethod
def disable_parameter_widgets(self, disabled: bool):
pass
@abstractmethod
def _get_group_and_widget(
self, parameter_name: str
) -> Tuple[Optional[BaseParameterPage], Optional[BaseParameterWidget]]:
pass
@abstractmethod
def _remove_group(self, group: BaseParameterPage):
pass
@abstractmethod
def _group_name(self, name: Optional[str]) -> str:
pass
@abstractmethod
def _group_icon(self, group_name: Optional[str]) -> QIcon:
pass
class BaseParameterArea(QWidget):
def __init__(self, parent: Optional[QWidget]):
super().__init__(parent)
@property
@abstractmethod
def parameter_groupbox(self) -> BaseParameterGroupBox:
pass
@abstractmethod
def add_parameter(
self,
parameter_name: str,
config: Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig],
) -> BaseParameterWidget:
pass
def add_parameters(
self,
configs: Dict[str, Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig]],
):
for parameter_name, config in configs.items():
self.add_parameter(parameter_name, config)
@abstractmethod
def remove_parameter(
self, parameter_name: str, ignore_unknown_parameter: bool = True
):
pass
@abstractmethod
def clear_parameters(self):
pass
@abstractmethod
def get_parameter_value(self, parameter_name: str) -> Any:
pass
@abstractmethod
def get_parameter_values(self) -> Dict[str, Any]:
pass
@abstractmethod
def set_parameter_value(self, parameter_name: str, value: Any):
pass
@abstractmethod
def set_parameter_values(self, params: Dict[str, Any]) -> List[str]:
pass
@abstractmethod
def has_parameter(self, parameter_name):
pass
@abstractmethod
def get_parameter_group_names(self):
pass
@abstractmethod
def get_parameter_names(self):
pass
@abstractmethod
def get_parameter_names_of(self, group_name):
pass
@abstractmethod
def activate_parameter_group(self, group_name):
pass
@abstractmethod
def get_parameter_values_of(self, group_name):
pass
@abstractmethod
def scroll_to_parameter(
self,
parameter_name: str,
x: int = 50,
y: int = 50,
highlight_effect: bool = False,
):
pass
@abstractmethod
def clear_parameter_error(self, parameter_name):
pass
@abstractmethod
def process_parameter_error(self, e: ParameterError):
pass
@abstractmethod
def disable_parameter_widgets(self, disabled: bool):
pass
| 8,527 | Python | .py | 272 | 24.485294 | 88 | 0.660147 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,544 | group.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_parameter_area/group.py | from collections import OrderedDict
from typing import Dict, Any, List, Tuple, Type, Optional
from qtpy.QtGui import QIcon
from qtpy.QtWidgets import (
QWidget,
QVBoxLayout,
QScrollArea,
QSpacerItem,
QSizePolicy,
)
from .base import BaseParameterPage, BaseParameterGroupBox
from .._base import FnExecuteWindowConfig
from ....exceptions import ParameterAlreadyExistError, ParameterNotFoundError
from ....paramwidget import BaseParameterWidget, BaseParameterWidgetConfig
from ....utils import get_icon
from ....widgets import CommonParameterWidget
class ParameterGroupPage(BaseParameterPage):
# noinspection SpellCheckingInspection
def __init__(self, parent: "ParameterGroupBox", group_name: str):
super().__init__(parent, group_name)
self._parameters: Dict[str, BaseParameterWidget] = OrderedDict()
# noinspection PyArgumentList
self._layout_main = QVBoxLayout()
self._layout_main.setContentsMargins(0, 0, 0, 0)
self.setLayout(self._layout_main)
self._param_scrollarea = QScrollArea(self)
self._param_scrollarea.setWidgetResizable(True)
self._scrollarea_content = QWidget(self._param_scrollarea)
# noinspection PyArgumentList
self._layout_scrollerea_content = QVBoxLayout()
self._scrollarea_content.setLayout(self._layout_scrollerea_content)
self._param_scrollarea.setWidget(self._scrollarea_content)
self._layout_main.addWidget(self._param_scrollarea)
self._bottom_spacer = QSpacerItem(
0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding
)
def scroll_to(
self,
parameter_name: str,
x: int = 50,
y: int = 50,
highlight_effect: bool = False,
) -> None:
widget = self.get_parameter_widget(parameter_name)
if widget is None:
return
self._param_scrollarea.ensureWidgetVisible(widget, x, y)
if highlight_effect and isinstance(widget, CommonParameterWidget):
widget.play_highlight_effect()
def upsert_parameter_widget(
self,
parameter_name: str,
widget_class: Type[BaseParameterWidget],
widget_config: BaseParameterWidgetConfig,
index: Optional[int] = None,
) -> BaseParameterWidget:
if parameter_name.strip() == "":
raise ValueError("parameter_name is an empty-string")
# if there is an old widget for the parameter, remove it from the layout
# and then release it
if parameter_name in self._parameters:
old_widget = self._parameters[parameter_name]
old_index = self._layout_scrollerea_content.indexOf(old_widget)
if old_index >= 0:
self._layout_scrollerea_content.takeAt(index)
old_widget.deleteLater()
del self._parameters[parameter_name]
if index is None:
index = old_index
else:
if index is None:
index = -1
# add new widget to the layout
new_widget = widget_class.new(
self._scrollarea_content, parameter_name, widget_config
)
# noinspection PyUnresolvedReferences
self._parent.sig_parameter_error.connect(new_widget.on_parameter_error)
# noinspection PyUnresolvedReferences
self._parent.sig_clear_parameter_error.connect(
new_widget.on_clear_parameter_error
)
self._add_to_scrollarea(new_widget, index)
self._parameters[parameter_name] = new_widget
return new_widget
def insert_parameter_widget(
self,
parameter_name: str,
widget_class: Type[BaseParameterWidget],
widget_config: BaseParameterWidgetConfig,
index: int = -1,
) -> BaseParameterWidget:
if parameter_name.strip() == "":
raise ValueError("invalid parameter_name: empty-string")
if parameter_name in self._parameters:
raise ParameterAlreadyExistError(parameter_name)
return self.upsert_parameter_widget(
parameter_name, widget_class, widget_config, index
)
def update_parameter_widget(
self,
parameter_name: str,
widget_class: Type[BaseParameterWidget],
widget_config: BaseParameterWidgetConfig,
) -> BaseParameterWidget:
if parameter_name.strip() == "":
raise ValueError("parameter_name is an empty-string")
if parameter_name not in self._parameters:
raise ParameterNotFoundError(parameter_name)
return self.upsert_parameter_widget(
parameter_name, widget_class, widget_config, None
)
def get_parameter_widget(
self, parameter_name: str
) -> Optional[BaseParameterWidget]:
return self._parameters.get(parameter_name, None)
def has_parameter_widget(self, parameter_name: str) -> bool:
if not self._parameters:
return False
return parameter_name in self._parameters
def remove_parameter_widget(self, parameter_name: str):
if parameter_name.strip() == "":
raise ValueError("invalid parameter_name: empty parameter_name")
if parameter_name not in self._parameters:
return
widget = self._parameters[parameter_name]
index = self._layout_scrollerea_content.indexOf(widget)
self._layout_scrollerea_content.takeAt(index)
# noinspection PyUnresolvedReferences
self._parent.sig_parameter_error.disconnect(widget.on_parameter_error)
# noinspection PyUnresolvedReferences
self._parent.sig_clear_parameter_error.disconnect(
widget.on_clear_parameter_error
)
widget.deleteLater()
del self._parameters[parameter_name]
def clear_parameter_widgets(self):
param_names = list(self._parameters.keys())
for param_name in param_names:
self.remove_parameter_widget(param_name)
def parameter_count(self) -> int:
return len(self._parameters)
def get_parameter_names(self) -> List[str]:
return list(self._parameters.keys())
def get_parameter_value(self, parameter_name: str) -> Any:
widget = self.get_parameter_widget(parameter_name)
if widget is None:
raise ParameterNotFoundError(parameter_name)
return widget.get_value()
def set_parameter_value(self, parameter_name: str, value: Any):
widget = self.get_parameter_widget(parameter_name)
if widget is None:
raise ParameterNotFoundError(parameter_name)
widget.set_value(value)
def get_parameter_values(self) -> Dict[str, Any]:
params = OrderedDict()
for param_name, param_widget in self._parameters.items():
if not param_widget:
continue
param_value = param_widget.get_value()
params[param_name] = param_value
return params
def set_parameter_values(self, values: Dict[str, Any]):
for param_name, param_value in values.items():
widget = self.get_parameter_widget(param_name)
if widget is None:
continue
widget.set_value(param_value)
def disable_parameter_widgets(self, disabled: bool):
self._scrollarea_content.setDisabled(disabled)
# noinspection SpellCheckingInspection
def _add_to_scrollarea(self, widget: BaseParameterWidget, index: int):
self._layout_scrollerea_content.removeItem(self._bottom_spacer)
self._layout_scrollerea_content.insertWidget(index, widget)
self._layout_scrollerea_content.addSpacerItem(self._bottom_spacer)
class ParameterGroupBox(BaseParameterGroupBox):
def __init__(self, parent: QWidget, config: FnExecuteWindowConfig):
self._config = config
self._group_pages: Dict[str, BaseParameterPage] = OrderedDict()
super().__init__(parent)
def upsert_parameter_group(self, group_name: Optional[str]) -> BaseParameterPage:
group_name = self._group_name(group_name)
if group_name in self._group_pages:
return self._group_pages[group_name]
page = ParameterGroupPage(self, group_name=group_name)
icon = self._group_icon(group_name)
self.addItem(page, icon, group_name)
self._group_pages[group_name] = page
return page
def add_default_group(self) -> BaseParameterPage:
return self.upsert_parameter_group(None)
def has_parameter_group(self, group_name: Optional[str]) -> bool:
return self._group_name(group_name) in self._group_pages
def _get_parameter_group(
self, group_name: Optional[str]
) -> Optional[BaseParameterPage]:
return self._group_pages.get(self._group_name(group_name), None)
def remove_parameter_group(self, group_name: Optional[str]):
group = self._group_pages.get(self._group_name(group_name), None)
if group is None:
return
self._remove_group(group)
def get_parameter_group_names(self) -> List[str]:
return list(self._group_pages.keys())
def _get_parameter_group_of(
self, parameter_name: str
) -> Optional[BaseParameterPage]:
for group_name, group in self._group_pages.items():
if group.has_parameter_widget(parameter_name):
return group
return None
def has_parameter(self, parameter_name: str) -> bool:
if not self._group_pages:
return False
return any(
group.has_parameter_widget(parameter_name)
for group in self._group_pages.values()
)
def add_parameter(
self,
parameter_name: str,
widget_class: Type[BaseParameterWidget],
widget_config: BaseParameterWidgetConfig,
) -> BaseParameterWidget:
if self.has_parameter(parameter_name):
raise ParameterAlreadyExistError(parameter_name)
group_page = self.upsert_parameter_group(widget_config.group)
return group_page.insert_parameter_widget(
parameter_name, widget_class, widget_config
)
def remove_parameter(
self, parameter_name: str, ignore_unknown_parameter: bool = True
):
group, widget = self._get_group_and_widget(parameter_name)
if group is None or widget is None:
if ignore_unknown_parameter:
return
raise ParameterNotFoundError(parameter_name)
group.remove_parameter_widget(parameter_name)
if group.parameter_count() <= 0:
self._remove_group(group)
def clear_parameters(self):
for group in list(self._group_pages.values()):
self._remove_group(group)
self._group_pages.clear()
def get_parameter_value(self, parameter_name: str) -> Any:
_, widget = self._get_group_and_widget(parameter_name)
if widget is None:
raise ParameterNotFoundError(parameter_name)
return widget.get_value()
def get_parameter_values(self) -> Dict[str, Any]:
params = OrderedDict()
for group_page in self._group_pages.values():
params.update(group_page.get_parameter_values())
return params
def get_parameter_values_of(self, group_name: Optional[str]) -> Dict[str, Any]:
group_name = self._group_name(group_name)
group = self._get_parameter_group(group_name)
if group is None:
raise ParameterNotFoundError(group_name)
return group.get_parameter_values()
def get_parameter_names(self) -> List[str]:
return [
parameter_name
for group_page in self._group_pages.values()
for parameter_name in group_page.get_parameter_names()
]
def get_parameter_names_of(self, group_name: str) -> List[str]:
group = self._get_parameter_group(group_name)
if group is None:
raise ParameterNotFoundError(group_name)
return group.get_parameter_names()
def set_parameter_value(self, parameter_name: str, value: Any):
_, widget = self._get_group_and_widget(parameter_name)
if widget is None:
raise ParameterNotFoundError(parameter_name)
widget.set_value(value)
def set_parameter_values(self, params: Dict[str, Any]):
for group_page in self._group_pages.values():
group_page.set_parameter_values(params)
def active_parameter_group(self, group_name: Optional[str]) -> bool:
group = self._get_parameter_group(group_name)
if group is None:
return False
index = self.indexOf(group)
if index >= 0:
self.setCurrentIndex(index)
return True
return False
def scroll_to_parameter(
self,
parameter_name: str,
x: int = 50,
y: int = 50,
highlight_effect: bool = False,
):
group, widget = self._get_group_and_widget(parameter_name)
if group is None or widget is None:
return
if not self.active_parameter_group(group_name=group.group_name):
return
group.scroll_to(parameter_name, x, y, highlight_effect=highlight_effect)
def disable_parameter_widgets(self, disabled: bool):
for page in self._group_pages.values():
page.disable_parameter_widgets(disabled)
def _get_group_and_widget(
self, parameter_name: str
) -> Tuple[Optional[BaseParameterPage], Optional[BaseParameterWidget]]:
if not self._group_pages:
return None, None
for group_page in self._group_pages.values():
widget = group_page.get_parameter_widget(parameter_name)
if widget is not None:
return group_page, widget
return None, None
def _remove_group(self, group: BaseParameterPage):
if not group:
return
index = self.indexOf(group)
if index >= 0:
self.removeItem(index)
group.clear_parameter_widgets()
group.deleteLater()
if group.group_name in self._group_pages:
del self._group_pages[group.group_name]
def _group_name(self, name: Optional[str]) -> str:
if name is None:
return self._config.default_parameter_group_name
return name
def _group_icon(self, group_name: Optional[str]) -> QIcon:
group_name = self._group_name(group_name)
if group_name == self._config.default_parameter_group_icon:
icon = self._config.default_parameter_group_icon
elif group_name in self._config.parameter_group_icons:
icon = self._config.parameter_group_icons[group_name]
else:
return QIcon()
return get_icon(icon) or QIcon()
| 14,820 | Python | .py | 338 | 34.707101 | 85 | 0.652942 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,545 | browser.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_output_area/browser.py | import dataclasses
from typing import Optional
from qtpy.QtWidgets import QWidget
from ....constants.color import (
COLOR_TERMINAL_BACKGROUND_CLASSIC,
COLOR_TERMINAL_TEXT_CLASSIC,
)
from ....constants.font import FONT_FAMILY, FONT_LARGE
from ....textbrowser import TextBrowserConfig, TextBrowser
@dataclasses.dataclass
class OutputBrowserConfig(TextBrowserConfig):
"""输出浏览器配置类。"""
text_color: str = COLOR_TERMINAL_TEXT_CLASSIC
font_family: str = FONT_FAMILY
font_size: str = FONT_LARGE
background_color: str = COLOR_TERMINAL_BACKGROUND_CLASSIC
class OutputBrowser(TextBrowser):
def __init__(
self, parent: Optional[QWidget], config: Optional[OutputBrowserConfig]
):
config = config or OutputBrowserConfig()
super().__init__(parent, config)
| 825 | Python | .py | 22 | 32.636364 | 78 | 0.750643 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,546 | area.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_output_area/area.py | from typing import Optional
from qtpy.QtWidgets import QWidget, QVBoxLayout
from .browser import OutputBrowserConfig, OutputBrowser
from .progressbar import ProgressBarConfig, ProgressBar
class OutputArea(QWidget):
def __init__(
self, parent: QWidget, output_browser_config: Optional[OutputBrowserConfig]
):
self._progressbar: Optional[ProgressBar] = None
self._output_browser: Optional[OutputBrowser] = None
super().__init__(parent)
# noinspection PyArgumentList
self._layout = QVBoxLayout()
self._layout.setContentsMargins(0, 0, 0, 0)
self._output_browser = OutputBrowser(
self, output_browser_config or OutputBrowserConfig()
)
self._layout.addWidget(self._output_browser)
self._progressbar = ProgressBar(self)
self._layout.addWidget(self._progressbar)
self.setLayout(self._layout)
def show_progressbar(self):
self._progressbar.show()
def hide_progressbar(self):
self._progressbar.hide()
def update_progressbar_config(self, config: ProgressBarConfig):
self._progressbar.update_config(config)
def update_progress(self, current_value: int, message: Optional[str] = None):
self._progressbar.update_progress(current_value, message)
def clear_output(self):
self._output_browser.clear()
def append_output(self, text: str, html: bool = False):
self._output_browser.append_output(text, html)
def scroll_to_bottom(self):
scroll_bar = self._output_browser.verticalScrollBar()
if scroll_bar:
scroll_bar.setValue(scroll_bar.maximum())
| 1,668 | Python | .py | 37 | 37.513514 | 83 | 0.695545 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,547 | __init__.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_output_area/__init__.py | from .area import OutputArea
from .browser import OutputBrowserConfig
from .progressbar import ProgressBarConfig
| 113 | Python | .py | 3 | 36.666667 | 42 | 0.890909 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,548 | progressbar.py | zimolab_PyGUIAdapter/pyguiadapter/windows/fnexec/_output_area/progressbar.py | import dataclasses
from typing import Literal, Optional
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QWidget, QVBoxLayout, QProgressBar, QLabel
_FORMATS = {
"richtext": Qt.TextFormat.RichText,
"markdown": Qt.TextFormat.MarkdownText,
"plaintext": Qt.TextFormat.PlainText,
"autotext": Qt.TextFormat.AutoText,
}
@dataclasses.dataclass
class ProgressBarConfig(object):
min_value: int = 0
max_value: int = 100
inverted_appearance: bool = False
message_visible: bool = False
message_centered: bool = True
message_format: str = "%p%"
show_info_label: bool = False
info_text_centered: bool = False
info_text_format: Literal["richtext", "markdown", "plaintext", "autotext"] = (
"autotext"
)
initial_info: str = ""
class ProgressBar(QWidget):
def __init__(self, parent: QWidget, config: Optional[ProgressBarConfig] = None):
super().__init__(parent)
self._config = None
# noinspection PyArgumentList
self._layout_main = QVBoxLayout()
self._progressbar = QProgressBar(self)
self._info_label = QLabel(self)
self._layout_main.addWidget(self._progressbar)
self._layout_main.addWidget(self._info_label)
self.setLayout(self._layout_main)
self.update_config(config)
def update_config(self, config: Optional[ProgressBarConfig]):
self._config = config
if not self._config:
self.hide()
return
self._progressbar.setRange(self._config.min_value, self._config.max_value)
self._progressbar.setInvertedAppearance(self._config.inverted_appearance)
self._progressbar.setTextVisible(self._config.message_visible)
if self._config.message_centered:
self._progressbar.setAlignment(Qt.AlignCenter)
if self._config.message_format:
self._progressbar.setFormat(self._config.message_format)
self._info_label.setVisible(self._config.show_info_label is True)
if self._config.info_text_centered:
self._info_label.setAlignment(Qt.AlignCenter)
text_format = _FORMATS.get(
self._config.info_text_format, Qt.TextFormat.AutoText
)
self._info_label.setTextFormat(text_format)
self._update_info(self._config.initial_info)
def update_progress(self, current_value: int, info: Optional[str] = None):
self._progressbar.setValue(current_value)
self._update_info(info)
def _update_info(self, info: Optional[str]):
if info is None:
return
if not self._info_label.isVisible():
return
self._info_label.setText(info)
| 2,686 | Python | .py | 65 | 33.907692 | 84 | 0.67408 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,549 | _python.py | zimolab_PyGUIAdapter/pyguiadapter/codeeditor/formatters/_python.py | import warnings
from typing import Optional
from yapf.yapflib.yapf_api import FormatCode
from ..base import BaseCodeFormatter
class PythonFormatter(BaseCodeFormatter):
def format_code(self, text: str) -> Optional[str]:
try:
formatted, changed = FormatCode(text)
except Exception as e:
warnings.warn(f"failed to format code: {e}")
return None
else:
if changed:
return formatted
return None
| 497 | Python | .pyt | 15 | 24.933333 | 56 | 0.648536 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,550 | app.py | 1368129224_tgbot-for-tdl/app.py | import os
import re
import sys
import socket
import asyncio
import logging
import logging.handlers
import tomlkit
from telebot import asyncio_helper
from telebot.types import InlineKeyboardButton, InlineKeyboardMarkup
from telebot.async_telebot import AsyncTeleBot
# global
CFG_PATH = 'tdl_bot_config.toml'
RE_STR = r'\x1b\[[0-9;]*[a-zA-Z]'
KEYBOARD_MAX_ROW_LEN = 6
KEYBOARD_MAX_COL_LEN = 4
KEYBOARD_MAX_ONE_PAGE_LEN = KEYBOARD_MAX_ROW_LEN * KEYBOARD_MAX_COL_LEN
g_config = {
"debug": "False",
"enable_ipv6": "False",
"bot_token": "123456789:abcdefghijk",
"download_path": "/path/to/save/download/media",
"proxy_url": "httpx://USERNAME:PASSWORD@PROXY_HOST:PROXY_PORT",
"tags": ['dog', 'cat']
}
logging.basicConfig(
style="{",
format="{asctime} {levelname:<8} {funcName}:{lineno} {message}",
datefmt="%m-%d %H:%M:%S",
level=logging.DEBUG
)
formatter = logging.Formatter(
style="{",
fmt="{asctime} {levelname:<8} {funcName}:{lineno} {message}",
datefmt="%m-%d %H:%M:%S"
)
file_handler = logging.handlers.RotatingFileHandler(
filename='tdl_bot.log',maxBytes=1 * 1024 * 1024, backupCount=3,
encoding='utf-8')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
logger = logging.getLogger(__name__)
logger.addHandler(file_handler)
def get_config():
if not os.path.isfile(CFG_PATH):
logger.info("Config file not found, generating default config.")
generate_config()
sys.exit()
with open(CFG_PATH, 'r', encoding='utf-8') as f:
config = tomlkit.loads(f.read())
g_config["debug"] = config["debug"]
g_config["enable_ipv6"] = config["enable_ipv6"]
g_config["bot_token"] = config["bot_token"]
g_config["download_path"] = config["download_path"]
g_config["proxy_url"] = config.get("proxy_url", None)
g_config["tags"] = config["tags"]
logger.debug(
f"""
* debug: {g_config['debug']}
* enable_ipv6: {g_config['enable_ipv6']}
* download_path: {g_config['download_path']}
* proxy_url: {g_config['proxy_url']}
* tags: {g_config['tags']}""")
def generate_config():
doc = tomlkit.document()
doc.add(tomlkit.comment("*** TDL telegram bot ***"))
doc.add(tomlkit.comment("TDL: https://github.com/iyear/tdl"))
doc.add(tomlkit.nl())
doc.add("debug", g_config["debug"])
doc.add("enable_ipv6", g_config["enable_ipv6"])
doc.add("bot_token", g_config["bot_token"])
doc.add("download_path", g_config["download_path"])
doc.add(tomlkit.nl())
doc.add(tomlkit.comment("This proxy will be used for both telegram bot and tdl"))
doc.add(tomlkit.comment("If you don't need proxy, please remove the proxy_url keyword"))
doc.add("proxy_url", g_config["proxy_url"])
doc.add(tomlkit.nl())
doc.add(tomlkit.comment(
"To use socks proxy, need to install extra python package:"))
doc.add(tomlkit.comment("pip install python-telegram-bot[socks]"))
doc.add(tomlkit.comment("and set socks proxy:"))
doc.add(tomlkit.comment("proxy_url = \"socks5://user:pass@host:port\""))
doc.add(tomlkit.nl())
doc.add("tags", g_config["tags"])
with open(CFG_PATH, 'w', encoding='utf-8') as f:
tomlkit.dump(doc, f)
logger.info(f"The default configuration {CFG_PATH} is generated.")
sys.exit()
class TagBtn():
def __init__(self, link):
self.tag_len = len(g_config["tags"])
self.link = link
self.retry_markup = None
def button(self, text, callback_data):
return InlineKeyboardButton(text=text, callback_data=callback_data + "#" + self.link)
def get_retry_btns(self):
markup = InlineKeyboardMarkup()
markup.row_width = 2
markup.add(self.button("retry", "retry"), self.button("cancel", "cancel"))
self.retry_markup = markup
def get_btns(self):
markup = InlineKeyboardMarkup()
markup.row_width = KEYBOARD_MAX_ROW_LEN
row = []
for i in range(self.tag_len):
row.append(self.button(g_config["tags"][i], g_config["tags"][i]))
if len(row) == KEYBOARD_MAX_ROW_LEN:
markup.add(*row)
row = []
if i == self.tag_len - 1:
markup.add(*row)
markup.add(self.button("cancel", "cancel"))
return markup
class DownloadTask():
def __init__(self, link, tag):
self.link = link
self.tag = tag
self.path = g_config["download_path"] + "/" + self.tag
self.proxy_url = g_config["proxy_url"]
class Worker():
lock = asyncio.Lock()
def __init__(self, task, msg):
self.task = task
self.msg = msg
async def call_tdl(self, bot):
async with Worker.lock:
proc = await asyncio.create_subprocess_shell(
f"/usr/local/bin/tdl --debug dl -u {self.task.link} --proxy {self.task.proxy_url} -d {self.task.path}",
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
i = 0
while True:
if not proc.stdout:
logger.error(f'Call create_subprocess_shell() failed!')
break
line = await proc.stdout.readline()
line = line.decode()
if line:
i = i + 1
if i == 10 or "done!" in line:
i = 0
line = re.sub(RE_STR, '', line)
if "done!" in line:
logger.info(f'Link: {self.task.link}')
logger.info(f'Download {line.split("...")[-1].strip()}')
await bot.edit_message_text(f'{self.task.link}\n Downlaod {line.split("...")[-1].strip()}', chat_id=self.msg.chat.id, message_id=self.msg.id)
if not line.startswith("CPU") and not line.startswith("[") and not line.startswith("All") and line != '':
process = line.split('...')[1].split()[0]
speed = line.split("...")[-1].split(";")[-1].strip().rstrip("]")
logger.debug(f'Downloading: {process + " " + speed}')
else:
break
await proc.wait()
logger.info(f'Download returncode {proc.returncode}')
if proc.stderr:
line = await proc.stderr.readline()
line = line.decode()
if line:
logger.warning(f'Download stderr: {line}')
if proc.stdout:
line = await proc.stdout.readline()
line = line.decode()
if line:
logger.warning(f'Download stdout: {line}')
if __name__ == "__main__":
get_config()
if g_config["debug"] == "True":
logger.setLevel(logging.DEBUG)
if g_config["enable_ipv6"] == "False":
socket.AF_INET6 = False
if g_config["proxy_url"] is not None:
asyncio_helper.proxy = g_config["proxy_url"]
logger.info(f"logging level: {logger.getEffectiveLevel()}")
bot = AsyncTeleBot(g_config["bot_token"])
@bot.message_handler(commands=['help', 'start'])
async def start_help(message):
text = """Supported command:\n/help to display help message.\n/show_config to display bot config.\n\nHow to use:\nSend message link to bot and select the tag, the download will be performed automatically."""
await bot.reply_to(message, text)
@bot.message_handler(commands=['show_config'])
async def show_config(message):
text = f"debug: {g_config.get('debug')}\nenable_ipv6: {g_config.get('enable_ipv6')}download_path: {g_config.get('download_path')}\nproxy_url: {g_config.get('proxy_url', None)}\ntags: {g_config.get('tags', None)}"
await bot.send_message(message.chat.id, text)
@bot.message_handler(func=lambda message: True)
async def split_links(message):
msgs = message.text.split()
for link in msgs:
if link.startswith("https://t.me/"):
btns = TagBtn(link)
msg = await bot.reply_to(message, text=f"{link}\nchoose tag: ", reply_markup=btns.get_btns())
@bot.callback_query_handler(func=lambda call: True)
async def callback_query(call):
cb, link = call.data.split("#")
if cb == "cancel":
await bot.answer_callback_query(call.id)
await bot.reply_to(call.message, text=f"Canceled")
if cb in g_config["tags"]:
dltask = DownloadTask(link, cb)
await bot.answer_callback_query(call.id)
msg = await bot.edit_message_text(f"{link}\nWill be downloaded in: {dltask.path}", chat_id=call.message.chat.id, message_id=call.message.id)
worker = Worker(dltask, msg)
await asyncio.gather(worker.call_tdl(bot))
asyncio.run(bot.polling())
| 8,851 | Python | .py | 201 | 35.552239 | 220 | 0.602576 | 1368129224/tgbot-for-tdl | 8 | 0 | 0 | AGPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,551 | main.py | lypsoty112_llm-project-skeleton/main.py | from src.controller import Controller
controller = Controller()
message = input("Enter a message: ")
data = {
"history": [{
"content": message, "role": "human"
}]
}
output = controller.run(data)
print(output.message.content)
| 245 | Python | .py | 10 | 21.5 | 43 | 0.692641 | lypsoty112/llm-project-skeleton | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,552 | config.py | lypsoty112_llm-project-skeleton/src/config.py | import os
from typing import Literal
import yaml
from pydantic import Field, BaseModel
from dotenv import load_dotenv
class ChainConfig(BaseModel):
name: str = Field("default", title="The name of the chain")
llm: str = Field("Gpt35", title="The exact name of the llm component to be used. Case-sensitive.")
class LogConfig(BaseModel):
level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = Field("INFO", title="The log level to be used")
file: str | None = Field(None, title="The file to write the logs to")
class ConfigModel(BaseModel):
MAIN_CHAIN: str = Field(..., title="The chain to be used as the main chain")
CHAIN_CONFIGS: list[ChainConfig] = Field([], title="The configurations of the chains to be used in the main chain. Use 'default' as the name for default configurations.")
LOG_CONFIGS: LogConfig = Field(LogConfig(), title="The log configuration to be used")
class Config:
def __init__(self):
load_dotenv(override=True)
# Get the correct config file
# Check for command line arguments
if "CONFIG_FILE" in os.environ:
config_file = os.environ["CONFIG_FILE"]
else:
# Check in the environment variables
config_file = os.getenv("CONFIG_FILE", "./configuration/default.yml")
# Load the yaml file if it exists
assert os.path.exists(config_file), f"Config file {config_file} not found"
# Load the yaml file
config_dict = yaml.safe_load(open(config_file))
# Parse the config
self.config: dict = ConfigModel(**config_dict).model_dump()
# Bring all dict keys lowercase
self.config = {k.lower(): v for k, v in self.config.items()}
def get_property(self, property_name) -> str | dict | list | None:
return self.config[property_name.lower()]
def get_chain_config(self, chain_name) -> dict | None:
configuration = next((x for x in self.config["chain_configs"] if x["name"].lower() == chain_name.lower()), None)
if configuration:
return configuration
# Check if there's a default configuration
return next((x for x in self.config["chain_configs"] if x["name"].lower() == "default"), ChainConfig().model_dump())
| 2,265 | Python | .py | 41 | 48.268293 | 174 | 0.668476 | lypsoty112/llm-project-skeleton | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,553 | controller.py | lypsoty112_llm-project-skeleton/src/controller.py | import sys
from loguru import logger
from src.chains.baseChain import BaseOuterChain
from src.config import Config
from src.models.chains.base import OuterChainInput, OuterChainOutput
from src.chains import * # noqa
class Controller:
main_chain: BaseOuterChain
def __init__(self):
# Get the config
self.config = Config()
logging_config = self.config.get_property("LOG_CONFIGS")
logger.remove()
terminal_format = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> <cyan>{file}:{line}</cyan> <level>{level:>8}</level> {message}"
logger.add(sys.stdout, format=terminal_format, level=logging_config["level"], colorize=True)
# Add a file sink to log to a file
if logging_config["file"]:
logger.add(logging_config["file"], format="{time} {level} {message}", level=logging_config["level"])
# Load the main chain
try:
main_chain = self.config.get_property("main_chain")
assert isinstance(main_chain, str), "Main chain must be a string"
self.main_chain = eval(main_chain)(self.config)
assert isinstance(self.main_chain, BaseOuterChain), "Main chain must be an instance of BaseOuterChain"
except Exception as e:
logger.exception(f"Error loading main chain: {e}")
exit(-1)
self.main_chain.build({})
def run(self, data: OuterChainInput | dict) -> OuterChainOutput:
return self.main_chain.run(data)
async def run_async(self, data: OuterChainInput | dict) -> OuterChainOutput:
return await self.main_chain.run_async(data)
async def stream(self, data: OuterChainInput | dict):
raise NotImplementedError
| 1,720 | Python | .py | 34 | 42.647059 | 136 | 0.673238 | lypsoty112/llm-project-skeleton | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,554 | main.py | lypsoty112_llm-project-skeleton/src/models/main.py | import datetime
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
class Message(BaseModel):
content: str = Field(..., description="Content of the message", example="Hello, how are you?")
role: Literal["human", "ai", "system"] = Field(..., description="Role of the entity sending the message", example="human")
timestamp: datetime.datetime = Field(default_factory=datetime.datetime.now)
class History(BaseModel):
messages: list[Message] = Field([], description="List of messages in the conversation, sorted from earliest to newest.")
def __init_subclass__(cls, **kwargs: ConfigDict):
# Sort messages by timestamp
cls.messages = sorted(cls.messages, key=lambda x: x.timestamp)
return super().__init_subclass__(**kwargs)
| 794 | Python | .py | 13 | 56.307692 | 126 | 0.721649 | lypsoty112/llm-project-skeleton | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,555 | base.py | lypsoty112_llm-project-skeleton/src/models/chains/base.py | from pydantic import BaseModel, Field
from src.models.main import History, Message
class OuterChainInput(BaseModel):
history: History
class OuterChainOutput(BaseModel):
message: Message
metadata: dict = Field({})
class ChainBuildData(BaseModel):
pass
| 274 | Python | .py | 9 | 26.888889 | 44 | 0.794574 | lypsoty112/llm-project-skeleton | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,556 | main.py | lypsoty112_llm-project-skeleton/src/models/llm/main.py | from pydantic import BaseModel, Field
from src.models.main import History, Message
class LlmBuildData(BaseModel):
chat: bool = Field(False, description="Whether the model is a chat model")
temperature: float = Field(0.7, description="Temperature. Might be ignored.")
max_tokens: int = Field(1024, description="Maximum output tokens. Might be ignored.")
streaming: bool = Field(False, description="Whether the model should be streaming the output. Might be ignored.")
max_retries: int = Field(1, description="Maximum retries. Might be ignored.")
class LlmRunData(BaseModel):
text: str = Field(..., description="Text to be processed")
class LlmRunResponse(BaseModel):
text: str = Field(..., description="Generated text")
class LlmChatData(BaseModel):
history: History = Field(..., description="Conversation history")
class LlmChatResponse(BaseModel):
message: Message = Field(..., description="Generated message")
| 958 | Python | .py | 16 | 56 | 117 | 0.75 | lypsoty112/llm-project-skeleton | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,557 | baseChain.py | lypsoty112_llm-project-skeleton/src/chains/baseChain.py | from abc import ABC, abstractmethod
from typing import Type
from langchain_core.runnables import Runnable
from pydantic import BaseModel
from src.components.base.baseComponent import BaseComponent
from src.components.llm.baseLlm import BaseLlm
from src.config import Config
from src.models.chains.base import ChainBuildData, OuterChainInput, OuterChainOutput
from src.components.llm import * # noqa
class BaseChain(BaseComponent, ABC):
_chain: Runnable | None
_llm: BaseLlm | None
def __init__(self, config: Config = None):
super().__init__(config=config)
self._chain_config = self.config.get_chain_config(self.__class__.__name__)
self._chain = None
self.load_llm()
@abstractmethod
def build(self, build_data: ChainBuildData | dict):
pass
@abstractmethod
def run(self, data: Type[BaseModel] | dict) -> BaseModel:
pass
@abstractmethod
async def run_async(self, data: Type[BaseModel] | dict) -> BaseModel:
pass
@abstractmethod
async def stream(self, data: Type[BaseModel] | dict) -> BaseModel:
pass
def load_llm(self):
# Use the config to load the LLM
self._llm = eval(self._chain_config['llm'])(self.config)
@property
def langchain_component(self) -> any:
return self._chain
class BaseOuterChain(BaseChain, ABC):
def __init__(self, config: Config = None):
super().__init__(config=config)
@abstractmethod
def run(self, data: OuterChainInput | dict) -> OuterChainOutput: # NOTE: These types can be changed according to the requirements of your project
pass
@abstractmethod
async def run_async(self, data: OuterChainInput | dict) -> OuterChainOutput: # NOTE: These types can be changed according to the requirements of your project
pass
@abstractmethod
async def stream(self, data: OuterChainInput | dict): # NOTE: These types can be changed according to the requirements of your project
pass
| 2,013 | Python | .py | 47 | 37.148936 | 162 | 0.706667 | lypsoty112/llm-project-skeleton | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,558 | example.py | lypsoty112_llm-project-skeleton/src/chains/example.py | from langchain_core.prompts import PromptTemplate
from loguru import logger
from src.chains.baseChain import BaseOuterChain
from src.config import Config
from src.models.chains.base import ChainBuildData, OuterChainInput, OuterChainOutput
from src.models.main import Message
PROMPT = "Respond to the following message as sarcastically as possible: {message}"
class SarcasticChain(BaseOuterChain):
def __init__(self, config: Config = None):
super().__init__(config=config)
def build(self, build_data: ChainBuildData | dict):
promptTemplate = PromptTemplate(input_types={"message": str}, input_variables=["message"], template=PROMPT)
self._llm.build({"chat": True})
self._chain = promptTemplate | self._llm.langchain_component
def run(self, data: OuterChainInput | dict) -> OuterChainOutput:
logger.info(f"Running SarcasticChain with data: {data}")
# Get the last message from the history
last_message = data['history'][-1]['content']
response = self._chain.invoke({"message": last_message})
return OuterChainOutput(message=Message(content=response.content, role="ai"), metadata=response.response_metadata)
async def run_async(self, data: OuterChainInput | dict) -> OuterChainOutput:
logger.info(f"Running SarcasticChain with data: {data}")
last_message = data['history'][-1]['content']
response = await self._chain.ainvoke({"message": last_message})
return OuterChainOutput(message=Message(content=response.content, role="ai"), metadata=response.response_metadata)
async def stream(self, data: OuterChainInput | dict):
raise NotImplementedError
| 1,684 | Python | .py | 27 | 56.185185 | 122 | 0.731352 | lypsoty112/llm-project-skeleton | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,559 | baseComponent.py | lypsoty112_llm-project-skeleton/src/components/base/baseComponent.py | from abc import ABC, abstractmethod
from typing import Type
from loguru import logger
from pydantic import BaseModel
from src.config import Config
class BaseComponent(ABC):
config: Config
def __init__(self, config: Config = None) -> None:
super().__init__()
self.config = config
if config is None:
logger.warning("No config provided, using default config")
self.config = Config()
@abstractmethod
def build(self, build_data: Type[BaseModel] | dict):
pass
@abstractmethod
def run(self, data: Type[BaseModel] | dict) -> BaseModel:
pass
@abstractmethod
async def run_async(self, data: Type[BaseModel] | dict) -> BaseModel:
pass
@staticmethod
def handle_input(data: Type[BaseModel] | dict, expected: Type[BaseModel]) -> dict:
if isinstance(data, dict):
data = expected(**data)
return data.model_dump()
@staticmethod
def handle_output(data: dict, expected: Type[BaseModel]) -> BaseModel:
return expected(**data)
@property
def langchain_component(self) -> any:
return None
| 1,149 | Python | .py | 33 | 28.272727 | 86 | 0.658824 | lypsoty112/llm-project-skeleton | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,560 | baseLLM.py | lypsoty112_llm-project-skeleton/src/components/llm/baseLLM.py | from abc import ABC, abstractmethod
from langchain_core.language_models.base import BaseLanguageModel
from src.components.base.baseComponent import BaseComponent
from src.config import Config
from src.models.llm.main import LlmBuildData, LlmChatData, LlmChatResponse, LlmRunData, LlmRunResponse
class BaseLlm(BaseComponent, ABC):
_llm: BaseLanguageModel
def __init__(self, config: Config = None) -> None:
super().__init__(config=config)
@abstractmethod
def build(self, build_data: LlmBuildData | dict):
pass
@abstractmethod
def run(self, data: LlmRunData | dict) -> LlmRunResponse:
pass
@abstractmethod
async def run_async(self, data: LlmRunData | dict) -> LlmRunResponse:
pass
@abstractmethod
async def stream(self, data: LlmRunData | dict):
pass
@abstractmethod
def chat(self, data: LlmChatData | dict) -> LlmChatResponse:
pass
@abstractmethod
async def chat_async(self, data: LlmChatData | dict) -> LlmChatResponse:
pass
@abstractmethod
async def chat_stream(self, data: LlmChatData | dict):
pass
@property
def langchain_component(self) -> BaseLanguageModel:
return self._llm
def handle_history(self, history: LlmChatData | dict) -> str:
data = self.handle_input(history, LlmChatData)
return "\n".join(f"{message['role']}: '{message['content']}'" for message in data["history"])
| 1,460 | Python | .py | 36 | 34.611111 | 102 | 0.704255 | lypsoty112/llm-project-skeleton | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,561 | openai.py | lypsoty112_llm-project-skeleton/src/components/llm/openai.py | from langchain_openai import OpenAI, ChatOpenAI
from src.components.llm.baseLlm import BaseLlm
from src.config import Config
from src.models.llm.main import LlmBuildData, LlmChatData, LlmChatResponse, LlmRunData, LlmRunResponse
from src.models.main import Message
class Gpt35(BaseLlm):
def __init__(self, config: Config = None) -> None:
super().__init__(config=config)
def build(self, build_data: LlmBuildData | dict):
build_data = self.handle_input(build_data, LlmBuildData)
if build_data["chat"]:
self._llm = ChatOpenAI(temperature=build_data["temperature"], max_tokens=build_data["max_tokens"], streaming=build_data["streaming"], max_retries=build_data["max_retries"])
else:
self._llm = OpenAI(temperature=build_data["temperature"], max_tokens=build_data["max_tokens"], streaming=build_data["streaming"], max_retries=build_data["max_retries"])
def run(self, data: LlmRunData | dict) -> LlmRunResponse:
data = self.handle_input(data, LlmRunData)
response = self._llm.invoke(data["text"])
return LlmRunResponse(text=response)
async def run_async(self, data: LlmRunData | dict) -> LlmRunResponse:
data = self.handle_input(data, LlmRunData)
response = await self._llm.ainvoke(data["text"])
return LlmRunResponse(text=response)
async def stream(self, data: LlmRunData | dict):
raise NotImplementedError
def chat(self, data: LlmChatData | dict) -> LlmChatResponse:
data = self.handle_history(data)
response = self.run({"text": data})
return LlmChatResponse(text=response)
async def chat_async(self, data: LlmChatData | dict) -> LlmChatResponse:
data = self.handle_history(data)
response = await self.run_async({"text": data})
return LlmChatResponse(text=response)
async def chat_stream(self, data: LlmChatData | dict):
raise NotImplementedError
| 1,953 | Python | .py | 34 | 50.235294 | 184 | 0.700734 | lypsoty112/llm-project-skeleton | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,562 | EcoLens_Static.py | maxprogrammer007_EcoLens/EcoLens/Code File/EcoLens_Static.py | '''
<TEAM ECOLENS>
Members : Arnav Jha, Abhinav Shukla , Harsh Sharma
The E- WASTE OBJECT DETECTION project aims to identify and categorize electronic waste
items using computer vision techniques
The goal is to help users understand how to dispose of e-waste properly by providing
information on each detected item
As the project is still in the intial stage
following code is restricted for circuit elemets only ...
'''
from roboflow import Roboflow
import webbrowser
# Initialize Roboflow API
rf = Roboflow(api_key="cCReFkOrZTB48P1mVjN4")
project = rf.workspace().project("circuit-board")
model = project.version(2).model
# Local image path
image_path = "C:\\Users\\Administrator\\Desktop\\Ecolens\\Test_cases\\test.jpg"
# Infer on a local image
predictions = model.predict(image_path, confidence=40, overlap=30).json()
# infer on an image hosted elsewhere
#predictions = (model.predict("URL_OF_YOUR_IMAGE", hosted=True, confidence=40, overlap=30).json())
# visualize your prediction
model.predict(image_path, confidence=40, overlap=30).save("C:\\Users\\Administrator\\Desktop\\EcoLens\\Prediction\\test_predict.jpg")
print(predictions,type(predictions))
cwc,iwc,twc,rwc,dwc=0,0,0,0,0
# Process predictions and open relevant files or links
for prediction in predictions["predictions"]:
# Check if the prediction is a relevant class
relevant_classes = ["Capacitor", "Inductor", "Transistor","Resistor","Diode"]
if prediction["class"] in relevant_classes:
if prediction["class"] == "Capacitor":
if cwc ==1:
pass
else:
# Open a text file or link related to capacitor
webbrowser.open("file:///C:/Users/Administrator/Desktop/EcoLens/results/capacitor.pdf")
cwc+=1
elif prediction["class"] == "Inductor":
if iwc ==1:
pass
else:
# Open a text file or link related to Inductor
webbrowser.open("file:///C:/Users/Administrator/Desktop/EcoLens/results/Inductor.pdf")
iwc+=1
elif prediction["class"] == "Transistor":
if twc==1:
pass
else:
# Open a text file or link related to Transistor
webbrowser.open("file:///C:/Users/Administrator/Desktop/EcoLens/results/Transistors.pdf")
twc+=1
elif prediction["class"] == "Resistor":
if rwc==1:
pass
else:
#Open a text file or link related to Resistor
webbrowser.open("file:///C:/Users/Administrator/Desktop/EcoLens/results/Resistors.pdf")
rwc+=1
elif prediction["class"] == "Diode":
if dwc ==1:
pass
else:
#Open a text file or link related to Diode
webbrowser.open("file:///C:/Users/Administrator/Desktop/EcoLens/results/Diodes.pdf")
| 2,981 | Python | .py | 65 | 36.938462 | 133 | 0.652522 | maxprogrammer007/EcoLens | 8 | 0 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,563 | v.24.06.10.py | God-2077_python-code/键盘监听/v.24.06.10.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2024/06/10
# @Author : Kissablecho
# @FileName: Keyboard monitoring.py
# @Software: Visual Studio Code
# @Blog :https://blog.csdn.net/y223421
# @Github : https://github.com/God-2077
from datetime import datetime
import keyboard
from configparser import ConfigParser, NoSectionError, NoOptionError
import signal
import sys
import os
import time
# 获取当前脚本的路径
current_script_path = os.path.abspath(__file__)
# 获取当前工作目录的路径
current_working_directory = os.getcwd()
fnfe = False
nse = False
noe = False
# 开始时间
starttime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print("-----------------------------------------------------")
print("start in: " + starttime)
print("脚本的路径: " + current_script_path)
print("工作目录的路径: " + current_working_directory)
# 读取 config.ini 配置文件
conf = ConfigParser() # 需要实例化一个 ConfigParser 对象
config = os.path.join(os.path.dirname(current_script_path), 'config.ini')
try:
# 检查配置文件是否存在
if not os.path.exists(config):
foundstate = False
raise FileNotFoundError(f"配置文件 {config} 不存在")
print(f"配置文件路径: {config}")
foundstate = True
conf.read(config, encoding='utf-8')
if 'config' not in conf:
raise NoSectionError('config')
keypath = conf.get('config', 'file', fallback='Keyboard.txt')
wait_sequence = conf.get('config', 'wait', fallback='654321')
wait_time = conf.getint('config', 'waittime', fallback=300)
exit_sequence = conf.get('config', 'exit', fallback='qqqwe')
except FileNotFoundError as e:
print(f"错误: {e}")
fnfe = True
keypath = os.path.join(os.path.dirname(current_script_path), 'Keyboard.txt')
wait_sequence = '654321'
wait_time = 300
exit_sequence = 'qqqwe'
except NoSectionError as e:
print(f"错误: 配置文件中缺少 {e.section} 部分")
nse = True
keypath = os.path.join(os.path.dirname(current_script_path), 'Keyboard.txt')
wait_sequence = '654321'
wait_time = 300
exit_sequence = 'qqqwe'
except NoOptionError as e:
print(f"错误: 配置文件中缺少 {e.option} 选项")
noe = True
keypath = os.path.join(os.path.dirname(current_script_path), 'Keyboard.txt')
wait_sequence = '654321'
wait_time = 300
exit_sequence = 'qqqwe'
# 打开文件
f = open(keypath, 'a', encoding='utf-8')
print(f"键盘记录文件路径: {keypath}")
print("-----------------------------------------------------", file=f)
print("start in: " + starttime, file=f)
print("脚本的路径: " + current_script_path, file=f)
print("工作目录的路径: " + current_working_directory, file=f)
print(f"键盘记录文件路径: {keypath}", file=f)
if foundstate == True:
print(f"配置文件路径: {config}", file=f)
else:
print("配置文件 Not Found !!!")
if fnfe == True :
print(f"错误: FileNotFoundError", file=f)
if nse == True:
print(f"错误: 配置文件中缺少 config 部分", file=f)
if noe == True:
print(f"错误: 配置文件中缺少 file 选项", file=f)
# 写入文件
f.flush()
# 缓冲区用于检测键盘输入序列
input_buffer = []
input_buffertwo = []
number_buffer = []
# main
def on_key(event):
global input_buffer
global input_buffertwo
global number_buffer
localtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(localtime, ":", event.name)
print(localtime, ":", event.name, file=f)
# 写入文件
f.flush()
# 检测键盘输入并添加到缓冲区
input_buffer.append(event.name)
# 如果缓冲区长度超过待检测序列长度,则删除最早的输入
if len(input_buffer) > len(wait_sequence):
input_buffer.pop(0)
# 检查缓冲区内容是否与待检测序列匹配
if ''.join(input_buffer) == wait_sequence:
print(f"检测到输入序列 {wait_sequence},暂停 {wait_time} 秒")
print(f"检测到输入序列 {wait_sequence},暂停 {wait_time} 秒", file=f)
f.flush()
time.sleep(wait_time)
# 检测退出序列
input_buffertwo.append(event.name)
# 如果缓冲区长度超过待检测序列长度,则删除最早的输入
if len(input_buffertwo) > len(exit_sequence):
input_buffertwo.pop(0)
# 检查缓冲区内容是否与待检测序列匹配
if ''.join(input_buffertwo) == exit_sequence:
print(f"检测到输入序列 {exit_sequence},exiting...")
print(f"检测到输入序列 {exit_sequence},exiting...", file=f)
f.flush()
sys.exit(0)
# 检测连续6个数字输入
if event.name.isdigit():
number_buffer.append(event.name)
if len(number_buffer) > 6:
number_buffer.pop(0)
if len(number_buffer) == 6:
print("number")
print("number", file=f)
f.flush()
else:
number_buffer.clear()
def signal_handler(sig, frame):
exittime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(exittime + ": " "检测到Ctrl+C, exiting...")
print(exittime + ": " "检测到Ctrl+C, exiting...", file=f)
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
keyboard.on_press(on_key)
keyboard.wait()
| 5,380 | Python | .py | 141 | 28.865248 | 80 | 0.646366 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,564 | v.24.03.11.py | God-2077_python-code/键盘监听/v.24.03.11.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2024/03/11
# @Author : Kissablecho
# @FileName: Keyboard monitoring.py
# @Software: Visual Studio Code
# @Blog :https://blog.csdn.net/y223421
import time
import keyboard
from configparser import ConfigParser
import signal
import sys
# 读取config.ini配置文件
conf = ConfigParser() # 需要实例化一个ConfigParser对象
conf.read('config.ini',encoding='utf-8')
# 设置变量
keypath = conf['config']['file']
# 打开文件
f = open(keypath, 'a')
# 开始时间
starttime = time.asctime( time.localtime(time.time()) )
print("-----------------------------------------------------")
print("start in", starttime)
print("-----------------------------------------------------", file=f)
print("start in", starttime, file=f)
# 关闭文件
f.close()
# main
def on_key(event):
localtime = time.asctime( time.localtime(time.time()) )
print (localtime, ":", event.name)
# 打开文件
f = open(keypath, 'a')
print (localtime, ":", event.name, file=f)
# 关闭文件
f.close()
def signal_handler(sig, frame):
print("检测到Ctrl+C, exiting...")
sys.exit(0)
input()
signal.signal(signal.SIGINT, signal_handler)
keyboard.on_press(on_key)
keyboard.wait() | 1,265 | Python | .py | 43 | 25.302326 | 70 | 0.633304 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,565 | v.24.07.16.py | God-2077_python-code/键盘监听/v.24.07.16.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2024/07/16
# @Author : Kissablecho
# @FileName: Keyboard monitoring.py
# @Software: Visual Studio Code
# @Blog :https://blog.csdn.net/y223421
# @Blog : https://buasis.eu.org/
# @Github : https://github.com/God-2077
from datetime import datetime
import keyboard
from configparser import ConfigParser, NoSectionError, NoOptionError
import signal
import sys
import os
import time
import win32gui as w
import win32gui
import win32process
import psutil
# 初始化设置
current_script_path = os.path.abspath(__file__)
current_working_directory = os.getcwd()
timestamp = int(time.time())
wait_sequence, wait_time, exit_sequence, keynumber = '654321', 300, 'qqqwe', 6
starttime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"-----------------------------------------------------\nstart in {starttime}\n脚本的路径: {current_script_path}\n工作目录的路径: {current_working_directory}")
# 读取配置文件
conf = ConfigParser()
config_path = os.environ.get('keymonitor')
try:
if not os.path.exists(config_path):
raise FileNotFoundError(f"配置文件 {config_path} 不存在")
print(f"配置文件路径: {config_path}")
conf.read(config_path, encoding='utf-8')
if 'config' not in conf:
raise NoSectionError('config')
keypath = conf.get('config', 'file', fallback='Keyboard.txt')
wait_sequence = conf.get('config', 'wait', fallback='654321')
wait_time = conf.getint('config', 'waittime', fallback=300)
exit_sequence = conf.get('config', 'exit', fallback='qqqwe')
keynumber = int(conf.get('config', 'keynumber', fallback=9))
except (FileNotFoundError, NoSectionError, NoOptionError) as e:
print(f"错误: {e}")
keypath = os.path.join(os.path.dirname(current_script_path), 'Keyboard.txt')
# 创建路径
os.makedirs(os.path.dirname(keypath), exist_ok=True)
print(f"键盘记录文件路径: {keypath}")
# 初始化键盘记录文件
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"-----------------------------------------------------\nstart in {starttime}\n脚本的路径: {current_script_path}\n工作目录的路径: {current_working_directory}\n键盘记录文件路径: {keypath}\n")
input_buffer, input_buffertwo, number_buffer = [], [], []
# 键盘按键事件处理函数
def on_key(event):
global timestamp
input_buffertwo.append(event.name)
if len(input_buffertwo) > len(exit_sequence):
input_buffertwo.pop(0)
if ''.join(input_buffertwo) == exit_sequence:
log_exit_sequence()
input_buffer.append(event.name)
if len(input_buffer) > len(wait_sequence):
input_buffer.pop(0)
if ''.join(input_buffer) == wait_sequence:
log_wait_sequence()
if int(time.time()) > timestamp:
log_key(event.name)
detect_continuous_numbers(event.name)
# 记录退出序列的函数
def log_exit_sequence():
localtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime}: 检测到输入序列 {exit_sequence},exiting...")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{localtime}: 检测到输入序列 {exit_sequence},exiting...\n")
sys.exit(0)
# 记录等待序列的函数
def log_wait_sequence():
global timestamp
timestamp = int(time.time()) + wait_time
localtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime}: 检测到输入序列 {wait_sequence},暂停 {wait_time} 秒")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{localtime}: 检测到输入序列 {wait_sequence},暂停 {wait_time} 秒\n")
for i in range(wait_time, 0, -1):
print(f"\r等待 {i} 秒!", end="", flush=True)
time.sleep(1)
print()
# 记录按键的函数
def log_key(key_name):
localtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime} : {key_name}")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{localtime} : {key_name}\n")
# 检测连续数字的函数
def detect_continuous_numbers(key_name):
global keynumber
if key_name.isdigit():
number_buffer.append(key_name)
if len(number_buffer) > keynumber:
number_buffer.pop(0)
if len(number_buffer) == keynumber:
log_continuous_numbers()
jiluhudcwtitle()
else:
number_buffer.clear()
# 记录连续数字的函数
def log_continuous_numbers():
localtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime} : number")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{localtime} : number\n")
number_buffer.clear()
# 信号处理函数,捕捉Ctrl+C
def signal_handler(sig, frame):
exittime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{exittime}: 检测到Ctrl+C, exiting...")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{exittime}: 检测到Ctrl+C, exiting...\n")
sys.exit(0)
# 记录当前活动窗口的标题和程序名
def jiluhudcwtitle():
title = w.GetWindowText (w.GetForegroundWindow())
process_name = active_window_process_name()
if title == "":
title = "无"
localtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime} : 活动窗口程序名'{process_name}'")
print(f"{localtime} : 活动窗口标题'{title}'")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{localtime} : 活动窗口程序名'{process_name}'\n")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{localtime} : 活动窗口 '{title}'\n")
# 当前活动窗口的程序名
def active_window_process_name():
try:
pid = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())
return(psutil.Process(pid[-1]).name())
except:
pass
# 注册信号处理函数
signal.signal(signal.SIGINT, signal_handler)
# 监听键盘按键事件
keyboard.on_press(on_key)
# 等待键盘事件
keyboard.wait() | 6,100 | Python | .py | 145 | 34.124138 | 182 | 0.650074 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,566 | v.24.06.15.py | God-2077_python-code/键盘监听/v.24.06.15.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2024/06/15
# @Author : Kissablecho
# @FileName: Keyboard monitoring.py
# @Software: Visual Studio Code
# @Blog :https://blog.csdn.net/y223421
# @Blog : https://buasis.eu.org/
# @Github : https://github.com/God-2077
import datetime
import keyboard
from configparser import ConfigParser, NoSectionError, NoOptionError
import signal
import sys
import os
import time
# 获取当前脚本的路径
current_script_path = os.path.abspath(__file__)
# 获取当前工作目录的路径
current_working_directory = os.getcwd()
fnfe = False
nse = False
noe = False
timestamp = int(time.time())
# 开始时间
starttime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print("-----------------------------------------------------")
print(starttime + ": Start...")
print("脚本的路径: " + current_script_path)
print("工作目录的路径: " + current_working_directory)
# 读取 config.ini 配置文件
conf = ConfigParser() # 需要实例化一个 ConfigParser 对象
config = os.path.join(os.path.dirname(current_script_path), 'config.ini')
try:
# 检查配置文件是否存在
if not os.path.exists(config):
foundstate = False
raise FileNotFoundError(f"配置文件 {config} 不存在")
print(f"配置文件路径: {config}")
foundstate = True
conf.read(config, encoding='utf-8')
if 'config' not in conf:
raise NoSectionError('config')
keypath = conf.get('config', 'file', fallback='Keyboard.txt')
wait_sequence = conf.get('config', 'wait', fallback='654321')
wait_time = conf.getint('config', 'waittime', fallback=300)
exit_sequence = conf.get('config', 'exit', fallback='qqqwe')
except FileNotFoundError as e:
print(f"错误: {e}")
fnfe = True
fnfetext = f"错误: {e}"
keypath = os.path.join(os.path.dirname(current_script_path), 'Keyboard.txt')
wait_sequence = '654321'
wait_time = 300
exit_sequence = 'qqqwe'
except NoSectionError as e:
print(f"错误: 配置文件中缺少 {e.section} 部分")
nse = True
nsetext = f"错误: 配置文件中缺少 {e.section} 部分"
keypath = os.path.join(os.path.dirname(current_script_path), 'Keyboard.txt')
wait_sequence = '654321'
wait_time = 300
exit_sequence = 'qqqwe'
except NoOptionError as e:
print(f"错误: 配置文件中缺少 {e.option} 选项")
noe = True
noetext = f"错误: 配置文件中缺少 {e.option} 选项"
keypath = os.path.join(os.path.dirname(current_script_path), 'Keyboard.txt')
wait_sequence = '654321'
wait_time = 300
exit_sequence = 'qqqwe'
# 打开文件
f = open(keypath, 'a', encoding='utf-8')
print(f"键盘记录文件路径: {keypath}")
print("-----------------------------------------------------", file=f)
print(starttime + ": Start...", file=f)
print("脚本的路径: " + current_script_path, file=f)
print("工作目录的路径: " + current_working_directory, file=f)
print(f"键盘记录文件路径: {keypath}", file=f)
if foundstate == True:
print(f"配置文件路径: {config}", file=f)
else:
print("配置文件 Not Found !!!")
if fnfe == True :
print(fnfetext, file=f)
if nse == True:
print(nsetext, file=f)
if noe == True:
print(noetext, file=f)
# 写入文件
f.flush()
# 缓冲区用于检测键盘输入序列
input_buffer = []
input_buffertwo = []
number_buffer = []
# main
def on_key(event):
global input_buffer
global input_buffertwo
global number_buffer
global timestamp
global f
# 检测退出序列
input_buffertwo.append(event.name)
# 如果缓冲区长度超过待检测序列长度,则删除最早的输入
if len(input_buffertwo) > len(exit_sequence):
input_buffertwo.pop(0)
# 检查缓冲区内容是否与待检测序列匹配
if ''.join(input_buffertwo) == exit_sequence:
localtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime}: 检测到输入序列 {exit_sequence},exiting...")
print(f"{localtime}: 检测到输入序列 {exit_sequence},exiting...", file=f)
f.flush()
sys.exit(0)
# 检测键盘输入并添加到缓冲区
input_buffer.append(event.name)
# 如果缓冲区长度超过待检测序列长度,则删除最早的输入
if len(input_buffer) > len(wait_sequence):
input_buffer.pop(0)
# 检查缓冲区内容是否与待检测序列匹配
if ''.join(input_buffer) == wait_sequence:
timestamp = int(time.time()) + int(wait_time)
localtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime}: 检测到输入序列 {wait_sequence},暂停 {wait_time} 秒")
print(f"{localtime}: 检测到输入序列 {wait_sequence},暂停 {wait_time} 秒", file=f)
f.flush()
for i in range(wait_time, 0, -1):
print("\r", "等待 {} 秒!".format(i), end="", flush=True)
time.sleep(1)
# time.sleep(wait_time)
if int(time.time()) > timestamp:
localtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime} : {event.name}")
print(f"{localtime} : {event.name}", file=f)
# 检测连续数字输入
if event.name.isdigit():
number_buffer.append(event.name)
if len(number_buffer) > 6:
number_buffer.pop(0)
if len(number_buffer) == 6:
localtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime} : number")
print(f"{localtime} : number", file=f)
f.flush()
number_buffer.clear()
else:
number_buffer.clear()
def signal_handler(sig, frame):
exittime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(exittime + ": " "检测到Ctrl+C, exiting...")
print(exittime + ": " "检测到Ctrl+C, exiting...", file=f)
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
keyboard.on_press(on_key)
keyboard.wait()
| 6,199 | Python | .py | 155 | 30.380645 | 89 | 0.626629 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,567 | v.24.06.16.py | God-2077_python-code/键盘监听/v.24.06.16.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2024/06/16
# @Author : Kissablecho
# @FileName: Keyboard monitoring.py
# @Software: Visual Studio Code
# @Blog :https://blog.csdn.net/y223421
# @Blog : https://buasis.eu.org/
# @Github : https://github.com/God-2077
from datetime import datetime
import keyboard
from configparser import ConfigParser, NoSectionError, NoOptionError
import signal
import sys
import os
import time
# 初始化设置
current_script_path = os.path.abspath(__file__)
current_working_directory = os.getcwd()
timestamp = int(time.time())
wait_sequence, wait_time, exit_sequence, keynumber = '654321', 300, 'qqqwe', 6
starttime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"-----------------------------------------------------\nstart in {starttime}\n脚本的路径: {current_script_path}\n工作目录的路径: {current_working_directory}")
# 读取配置文件
conf = ConfigParser()
config_path = os.path.join(os.path.dirname(current_script_path), 'config.ini')
try:
if not os.path.exists(config_path):
raise FileNotFoundError(f"配置文件 {config_path} 不存在")
print(f"配置文件路径: {config_path}")
conf.read(config_path, encoding='utf-8')
if 'config' not in conf:
raise NoSectionError('config')
keypath = conf.get('config', 'file', fallback='Keyboard.txt')
wait_sequence = conf.get('config', 'wait', fallback='654321')
wait_time = conf.getint('config', 'waittime', fallback=300)
exit_sequence = conf.get('config', 'exit', fallback='qqqwe')
keynumber = conf.get('config', 'keynumber', fallback=6)
except (FileNotFoundError, NoSectionError, NoOptionError) as e:
print(f"错误: {e}")
keypath = os.path.join(os.path.dirname(current_script_path), 'Keyboard.txt')
# 初始化键盘记录文件
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"-----------------------------------------------------\nstart in {starttime}\n脚本的路径: {current_script_path}\n工作目录的路径: {current_working_directory}\n键盘记录文件路径: {keypath}\n")
input_buffer, input_buffertwo, number_buffer = [], [], []
# 键盘按键事件处理函数
def on_key(event):
global timestamp
input_buffertwo.append(event.name)
if len(input_buffertwo) > len(exit_sequence):
input_buffertwo.pop(0)
if ''.join(input_buffertwo) == exit_sequence:
log_exit_sequence()
input_buffer.append(event.name)
if len(input_buffer) > len(wait_sequence):
input_buffer.pop(0)
if ''.join(input_buffer) == wait_sequence:
log_wait_sequence()
if int(time.time()) > timestamp:
log_key(event.name)
detect_continuous_numbers(event.name)
# 记录退出序列的函数
def log_exit_sequence():
localtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime}: 检测到输入序列 {exit_sequence},exiting...")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{localtime}: 检测到输入序列 {exit_sequence},exiting...\n")
sys.exit(0)
# 记录等待序列的函数
def log_wait_sequence():
global timestamp
timestamp = int(time.time()) + wait_time
localtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime}: 检测到输入序列 {wait_sequence},暂停 {wait_time} 秒")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{localtime}: 检测到输入序列 {wait_sequence},暂停 {wait_time} 秒\n")
for i in range(wait_time, 0, -1):
print(f"\r等待 {i} 秒!", end="", flush=True)
time.sleep(1)
print()
# 记录按键的函数
def log_key(key_name):
localtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime} : {key_name}")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{localtime} : {key_name}\n")
# 检测连续数字的函数
def detect_continuous_numbers(key_name):
global keynumber
if key_name.isdigit():
number_buffer.append(key_name)
if len(number_buffer) > keynumber:
number_buffer.pop(0)
if len(number_buffer) == keynumber:
log_continuous_numbers()
else:
number_buffer.clear()
# 记录连续数字的函数
def log_continuous_numbers():
localtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{localtime} : number")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{localtime} : number\n")
number_buffer.clear()
# 信号处理函数,捕捉Ctrl+C
def signal_handler(sig, frame):
exittime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(f"{exittime}: 检测到Ctrl+C, exiting...")
with open(keypath, 'a', encoding='utf-8') as f:
f.write(f"{exittime}: 检测到Ctrl+C, exiting...\n")
sys.exit(0)
# 注册信号处理函数
signal.signal(signal.SIGINT, signal_handler)
# 监听键盘按键事件
keyboard.on_press(on_key)
# 等待键盘事件
keyboard.wait() | 5,039 | Python | .py | 117 | 35.410256 | 182 | 0.648589 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,568 | psql_terminal.py | God-2077_python-code/psql_terminal/psql_terminal.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import psycopg2
import sys
connection = None # 初始化为 None
connection_string = "postgresql://aaaaaaa:[YOUR-PASSWORD]@aaaaaaaaaa.aa.aa:6543/aaaaa" # 你的url
try:
connection = psycopg2.connect(connection_string)
cursor = connection.cursor()
print("Connected to the database. Enter SQL commands to execute, or type 'exit' to quit.")
while True:
query = input("postgres=# ")
if query.lower() in ('exit', 'quit', '\q'):
break
try:
cursor.execute(query)
if cursor.description:
rows = cursor.fetchall()
for row in rows:
print(row)
else:
connection.commit()
print(f"Executed: {cursor.rowcount} rows affected.")
except Exception as e:
print(f"Error: {e}")
connection.rollback()
except Exception as error:
print("Error while connecting to PostgreSQL:", error)
finally:
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
| 1,211 | Python | .py | 33 | 25.909091 | 95 | 0.58452 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,569 | v.24-03-30.网易云音乐歌单批连下载歌曲.py | God-2077_python-code/网易云音乐歌单批量下载歌曲/v.24-03-30.网易云音乐歌单批连下载歌曲.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import os
import json
# JSON链接
# json_url = "https://api.injahow.cn/meting/?type=playlist&id=9313871605"
playlist = input("歌单ID:")
if playlist == '':
print("必须输入歌单ID")
exit()
json_url = "https://api.injahow.cn/meting/?type=playlist&id=" + playlist
# 下载路径
# download_path = "./s"
print(r"默认下载路径 D:\down")
download_path = input("下载路径:")
if download_path == '':
download_path = r"D:\down"
# 创建下载路径
os.makedirs(download_path, exist_ok=True)
def download_song(url, song_path):
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length'))
downloaded_size = 0
with open(song_path, "wb") as song_file:
for data in response.iter_content(chunk_size=4096):
downloaded_size += len(data)
song_file.write(data)
progress = downloaded_size / total_size * 100
print(f"正在下载 {song_path},进度:{progress:.2f}%\r", end="")
print(f"下载完成 {song_path}")
def safe_filename(filename):
# 将特殊字符(/)改成(-)
return filename.replace("/", "-")
# 发送GET请求获取JSON数据
response = requests.get(json_url)
data = json.loads(response.text)
# 遍历每首歌曲
for song in data:
# 歌曲信息
name = song["name"]
artist = song["artist"]
url = song["url"]
lrc = song["lrc"]
# 歌曲文件名和路径
song_filename = f"{safe_filename(name)} - {safe_filename(artist)}.mp3"
song_path = os.path.join(download_path, song_filename)
# 下载歌曲
download_song(url, song_path)
# 下载歌词
lrc_response = requests.get(lrc)
lrc_filename = f"{safe_filename(name)} - {safe_filename(artist)}.lrc"
lrc_path = os.path.join(download_path, lrc_filename)
with open(lrc_path, "wb") as lrc_file:
lrc_file.write(lrc_response.content)
print("The and.")
a = input() | 2,107 | Python | .py | 57 | 27.824561 | 75 | 0.637673 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,570 | v.24-10-06.py | God-2077_python-code/网易云音乐歌单批量下载歌曲/v.24-10-06.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import requests
from mutagen.mp3 import MP3
import time
import signal
import sys
import re
from tabulate import tabulate
def download_file(url, file_path, file_type, index, total_files, timeout=10):
try:
response = requests.get(url, stream=True, timeout=timeout)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
with open(file_path, "wb") as file:
for data in response.iter_content(chunk_size=4096):
downloaded_size += len(data)
file.write(data)
progress = downloaded_size / total_size * 100 if total_size > 0 else 0
print(f"正在下载 [{index}/{total_files}][{file_type}] {file_path},进度:{progress:.2f}%\r", end="")
print(f"下载完成 [{index}/{total_files}][{file_type}] {file_path}")
return True
except requests.exceptions.RequestException as e:
print(f"下载 [{index}/{total_files}][{file_type}] {file_path} 失败:{e}")
return False
def download_lyrics(url, lrc_path, song_index, total_songs):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
with open(lrc_path, "w", encoding="utf-8") as lrc_file:
lrc_file.write(response.content.decode('utf-8'))
print(f"下载完成 [{song_index}/{total_songs}][LRC] {lrc_path}")
return True
except requests.exceptions.RequestException as e:
print(f"下载歌词失败:{e}")
return False
def safe_filename(filename):
invalid_chars = '\\/:*?"<>|'
for char in invalid_chars:
filename = filename.replace(char, '_')
return filename
def delete_file(file_path):
if os.path.exists(file_path):
os.remove(file_path)
print(f"删除文件:{file_path}")
def song_table(data):
table_data = []
for idx, item in enumerate(data, start=1):
name = item['name']
artist = item['artist']
url_id = re.search(r'\d+', item['url']).group()
table_data.append([idx, name, artist, url_id])
table_headers = ["序号", "标题", "艺术家", "ID"]
table = tabulate(table_data, table_headers, tablefmt="pipe")
print(table)
def exit_ctrl_c(sig, frame):
print("\n退出程序...")
sys.exit(0)
def welcome():
print("welcome")
print("欢迎使用我开发的小程序")
print("Github Rope: https://github.com/God-2077/python-code/")
print("-------------------------")
print("网易云音乐歌单批量下载歌曲")
def download_playlist(playlist_id, download_path):
if not playlist_id.isdigit():
print("歌单ID必须为数字")
return
error_song_name = []
error_song_id = []
api_urls = [
"https://meting.qjqq.cn/?type=playlist&id=",
"https://api.injahow.cn/meting/?type=playlist&id=",
"https://meting-api.mnchen.cn/?type=playlist&id=",
"https://meting-api.mlj-dragon.cn/meting/?type=playlist&id="
]
selected_api = None
data = None
for api_url in api_urls:
try:
response = requests.get(f"{api_url}{playlist_id}", timeout=10)
# if requests.status_codes != 200:
# print("出错了...")
# print(f"状态码:{requests.status_codes}")
# return
response.raise_for_status()
data = response.json()
selected_api = api_url
if 'error' in data:
error = data.get("error", "")
print("出错了...")
print(f"错误详细:{error}")
return
break
except requests.exceptions.RequestException as e:
print(f"API {api_url} 请求失败:{e}")
continue
if not data:
print("所有API都无法获取数据")
return
os.makedirs(download_path, exist_ok=True)
print(f"Meting API: {selected_api}")
total_songs = len(data)
print(f"歌单共有 {total_songs} 首歌曲")
song_table(data)
envisage_size = total_songs * 7.7
print(f"歌单共有 {total_songs} 首歌曲,预计歌曲文件总大小为 {envisage_size} MB")
chose = str(input("是否继续下载?(yes): "))
if chose not in ["y", "", "yes"]:
print("退出程序...")
sys.exit(0)
chose = str(input("是否下载小于 60 秒的歌曲(可能为试听音乐)?(not): "))
if chose not in ["y", "", "yes"]:
downtrymusic = 1
else:
downtrymusic = 0
successful_downloads = 0
failed_downloads = []
def signal_handler(sig, frame):
print("\n检测到Ctrl+C, exiting gracefully...")
print(f"程序运行完成,共 {total_songs} 首歌曲,成功下载 {successful_downloads} 首歌曲")
if failed_downloads:
print(f"共有 {len(failed_downloads)} 首歌曲下载失败")
print("失败列表如下")
table_data = [[i + 1, error_song_name[i], error_song_id[i]] for i in range(len(error_song_name))]
print(tabulate(table_data, headers=["序号", "标题 - 艺术家", "ID"], tablefmt="grid"))
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
for index, song in enumerate(data, start=1):
name = song.get("name", "")
artist = song.get("artist", "")
url = song.get("url", "")
lrc = song.get("lrc", "")
pic = song.get("pic", "")
if not name or not artist or not url or not lrc:
print(f"歌曲信息不完整:{song}")
continue
song_filename = f"{safe_filename(name)} - {safe_filename(artist)}.mp3"
song_name = f"{safe_filename(name)} - {safe_filename(artist)}"
song_path = os.path.join(download_path, song_filename)
retry_count = 0
while retry_count < 5:
if download_file(url, song_path, "MP3", index, total_songs):
successful_downloads += 1
state = True
break
else:
retry_count += 1
print(f"重试下载 [{index}/{total_songs}][MP3] {song_path},次数:{retry_count}")
state = False
time.sleep(1)
if state == False:
print("")
match = re.search(r'\d+', url)
error_song_id.append(int(match.group()))
error_song_name.append(song_name)
failed_downloads.append(match)
if state == True:
try:
audio = MP3(song_path)
audio_duration = audio.info.length
if downtrymusic == 1:
if audio_duration < 60:
print(f"歌曲时长小于一分钟,删除歌曲和取消下载歌词和图片:{song_path}")
delete_file(song_path)
audio_duration_TF = False
successful_downloads -= 1
match = re.search(r'\d+', url)
error_song_id.append(int(match.group()))
error_song_name.append(song_name)
else:
print(f"歌曲时长为 {audio_duration} 秒")
audio_duration_TF = True
else:
print(f"歌曲时长为 {audio_duration} 秒")
audio_duration_TF = True
except Exception as e:
print(f"无法获取歌曲时长:{e}")
print("应该为 VIP 单曲,删除歌曲文件和取消下载歌词和图片")
delete_file(song_path)
audio_duration_TF = False
successful_downloads -= 1
match = re.search(r'\d+', url)
error_song_id.append(int(match.group()))
error_song_name.append(song_name)
failed_downloads.append(match)
if audio_duration_TF:
lrc_filename = f"{safe_filename(name)} - {safe_filename(artist)}.lrc"
lrc_path = os.path.join(download_path, lrc_filename)
retry_count = 0
while retry_count < 5:
if download_lyrics(lrc, lrc_path, index, total_songs):
break
else:
retry_count += 1
print(f"重试下载 [{index}/{total_songs}][LRC] {lrc_path},次数:{retry_count}")
time.sleep(1)
pic_filename = f"{safe_filename(name)} - {safe_filename(artist)}.jpg"
pic_path = os.path.join(download_path, pic_filename)
retry_count = 0
while retry_count < 5:
if download_file(pic, pic_path, "PIC", index, total_songs):
break
else:
retry_count += 1
print(f"重试下载 [{index}/{total_songs}][PIC] {pic_path},次数:{retry_count}")
time.sleep(1)
print(f"程序运行完成,共 {total_songs} 首歌曲,成功下载 {successful_downloads} 首歌曲")
if failed_downloads or error_song_name:
print(f"共有 {len(failed_downloads)} 首歌曲下载失败")
print("失败列表如下")
table_data = [[i + 1, error_song_name[i], error_song_id[i]] for i in range(len(error_song_name))]
print(tabulate(table_data, headers=["序号", "标题 - 艺术家", "ID"], tablefmt="grid"))
if __name__ == "__main__":
signal.signal(signal.SIGINT, exit_ctrl_c)
welcome()
playlist_id = input("歌单ID:")
download_path = input(r"下载路径(默认为 ./down):") or r"./down"
download_playlist(playlist_id, download_path)
| 9,901 | Python | .py | 221 | 30.529412 | 109 | 0.54688 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,571 | v.24-04-04.优化.py | God-2077_python-code/网易云音乐歌单批量下载歌曲/v.24-04-04.优化.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import json
import requests
from urllib.parse import quote
def download_song(url, song_path):
try:
response = requests.get(url, stream=True)
response.raise_for_status() # 检查请求是否成功
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
with open(song_path, "wb") as song_file:
for data in response.iter_content(chunk_size=4096):
downloaded_size += len(data)
song_file.write(data)
progress = downloaded_size / total_size * 100 if total_size > 0 else 0
print(f"正在下载 {song_path},进度:{progress:.2f}%\r", end="")
print(f"下载完成 {song_path}")
except requests.exceptions.RequestException as e:
print(f"下载 {song_path} 失败:{e}")
def safe_filename(filename):
# 将特殊字符(/)改成(-)
return filename.replace("/", "-")
def download_playlist(playlist_id, download_path):
if not playlist_id.isdigit():
print("歌单ID必须为数字")
return
# 创建下载路径
os.makedirs(download_path, exist_ok=True)
# JSON链接
json_url = f"https://api.injahow.cn/meting/?type=playlist&id={quote(playlist_id)}"
try:
# 发送GET请求获取JSON数据
response = requests.get(json_url)
response.raise_for_status() # 检查请求是否成功
data = response.json()
# 遍历每首歌曲
for song in data:
# 歌曲信息
name = song.get("name", "")
artist = song.get("artist", "")
url = song.get("url", "")
lrc = song.get("lrc", "")
if not name or not artist or not url or not lrc:
print(f"歌曲信息不完整:{song}")
continue
# 歌曲文件名和路径
song_filename = f"{safe_filename(name)} - {safe_filename(artist)}.mp3"
song_path = os.path.join(download_path, song_filename)
# 下载歌曲
download_song(url, song_path)
# 下载歌词
lrc_response = requests.get(lrc)
lrc_filename = f"{safe_filename(name)} - {safe_filename(artist)}.lrc"
lrc_path = os.path.join(download_path, lrc_filename)
with open(lrc_path, "wb") as lrc_file:
lrc_file.write(lrc_response.content)
print("全部歌曲下载完成")
except requests.exceptions.RequestException as e:
print(f"下载歌单失败:{e}")
if __name__ == "__main__":
playlist_id = input("歌单ID:")
download_path = input(r"下载路径(默认为 D:\down):") or r"D:\down"
download_playlist(playlist_id, download_path)
| 2,845 | Python | .py | 65 | 30.292308 | 86 | 0.585386 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,572 | v.24-07-18.py | God-2077_python-code/网易云音乐歌单批量下载歌曲/v.24-07-18.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import requests
from mutagen.mp3 import MP3
import time
import signal
import sys
import re
from tabulate import tabulate
def download_song(url, song_path, song_index, total_songs, yuan_name):
global error_song_id
global error_song_name
try:
response = requests.get(url, stream=True, timeout=10)
response.raise_for_status() # 检查请求是否成功
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
with open(song_path, "wb") as song_file:
for data in response.iter_content(chunk_size=4096):
downloaded_size += len(data)
song_file.write(data)
progress = downloaded_size / total_size * 100 if total_size > 0 else 0
print(f"正在下载 [{song_index}/{total_songs}][MP3] {song_path},进度:{progress:.2f}%\r", end="")
print(f"下载完成 [{song_index}/{total_songs}][MP3] {song_path}")
return True
except requests.exceptions.RequestException as e:
print(f"下载 [{song_index}/{total_songs}][MP3] {song_path} 失败:{e}")
match = re.search(r'\d+', url)
error_song_id.append(int(match.group()))
error_song_name.append(yuan_name)
return False
def download_pic(url, pic_path, song_index, total_songs):
try:
response = requests.get(url, stream=True, timeout=10)
response.raise_for_status() # 检查请求是否成功
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
with open(pic_path, "wb") as pic_file:
for data in response.iter_content(chunk_size=4096):
downloaded_size += len(data)
pic_file.write(data)
progress = downloaded_size / total_size * 100 if total_size > 0 else 0
print(f"正在下载 [{song_index}/{total_songs}][PIC] {pic_path},进度:{progress:.2f}%\r", end="")
print(f"下载完成 [{song_index}/{total_songs}][PIC] {pic_path}")
return True
except requests.exceptions.RequestException as e:
print(f"下载 [{song_index}/{total_songs}][PIC] {pic_path} 失败:{e}")
return False
def download_lyrics(url, lrc_path, song_index, total_songs):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
with open(lrc_path, "w", encoding="utf-8") as lrc_file:
lrc_file.write(response.content.decode('utf-8'))
print(f"下载完成 [{song_index}/{total_songs}][LRC] {lrc_path}")
return True
except requests.exceptions.RequestException as e:
print(f"下载歌词失败:{e}")
return False
def safe_filename(filename):
invalid_chars = '\\/:*?"<>|'
for char in invalid_chars:
filename = filename.replace(char, '_')
return filename
def delete_file(file_path):
if os.path.exists(file_path):
os.remove(file_path)
print(f"删除文件:{file_path}")
def song_table(data):
table_data = []
for idx, item in enumerate(data, start=1):
name = item['name']
artist = item['artist']
url_id = re.search(r'\d+', item['url']).group()
table_data.append([idx, name, artist, url_id])
table_headers = ["序号", "标题", "艺术家", "ID"]
table = tabulate(table_data, table_headers, tablefmt="pipe")
print(table)
def exit_ctrl_c(sig, frame):
print()
print("退出程序...")
sys.exit(0)
def welcome():
print("welcome")
print("欢迎使用我开发的小程序")
print("Github Rope: https://github.com/God-2077/python-code/")
print("-------------------------")
print("网易云音乐歌单批量下载歌曲")
def download_playlist(playlist_id, download_path):
if not playlist_id.isdigit():
print("歌单ID必须为数字")
return
global error_song_id
global error_song_name
error_song_name = []
error_song_id = []
api_urls = [
# "https://api.injahow.cn/meting/?type=playlist&id=",
"https://meting.qjqq.cn/?type=playlist&id=",
"https://meting-api.mnchen.cn/?type=playlist&id=",
"https://meting-api.mlj-dragon.cn/meting/?type=playlist&id="
]
selected_api = None
data = None
for api_url in api_urls:
try:
response = requests.get(f"{api_url}{playlist_id}", timeout=10)
response.raise_for_status()
data = response.json()
selected_api = api_url
if 'error' in data:
error = data.get("error", "")
print("出错了...")
print(f"错误详细:{error}")
return
break
except requests.exceptions.RequestException as e:
print(f"API {api_url} 请求失败:{e}")
continue
if not data:
print("所有API都无法获取数据")
return
os.makedirs(download_path, exist_ok=True)
print(f"Meting API: {api_url}")
total_songs = len(data)
print(f"歌单共有 {total_songs} 首歌曲")
song_table(data)
envisage_size = total_songs * 7.7
print(f"歌单共有 {total_songs} 首歌曲,预计歌曲文件总大小为 {envisage_size} MB")
chose = str(input("是否继续下载?(yes): "))
if chose not in ["y", "", "yes"]:
print("退出程序...")
sys.exit(0)
successful_downloads = 0
failed_downloads = []
def signal_handler(sig, frame):
print("检测到Ctrl+C, exiting gracefully...")
print(f"程序运行完成,共 {total_songs} 首歌曲,成功下载 {successful_downloads} 首歌曲")
if failed_downloads:
print(f"共有 {len(failed_downloads)} 首歌曲下载失败")
print("失败列表如下")
table_data = [[i + 1, error_song_name[i], error_song_id[i]] for i in range(len(error_song_name))]
print(tabulate(table_data, headers=["序号", "标题 - 艺术家", "ID"], tablefmt="grid"))
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
for index, song in enumerate(data, start=1):
name = song.get("name", "")
artist = song.get("artist", "")
url = song.get("url", "")
lrc = song.get("lrc", "")
pic = song.get("pic", "")
if not name or not artist or not url or not lrc:
print(f"歌曲信息不完整:{song}")
continue
song_filename = f"{safe_filename(name)} - {safe_filename(artist)}.mp3"
song_name = f"{safe_filename(name)} - {safe_filename(artist)}"
song_path = os.path.join(download_path, song_filename)
retry_count = 0
while retry_count < 5:
if download_song(url, song_path, index, total_songs, song_name):
successful_downloads += 1
break
else:
retry_count += 1
print(f"重试下载 [{index}/{total_songs}][MP3] {song_path},次数:{retry_count}")
time.sleep(1)
try:
audio = MP3(song_path)
audio_duration = audio.info.length
if audio_duration < 60:
print(f"歌曲时长小于一分钟,删除歌曲和取消下载歌词和图片:{song_path}")
delete_file(song_path)
audio_duration_TF = False
failed_downloads.append(song.get('id', ''))
successful_downloads -= 1
match = re.search(r'\d+', url)
error_song_id.append(int(match.group()))
error_song_name.append(song_name)
else:
print(f"歌曲时长为 {audio_duration} 秒")
audio_duration_TF = True
except Exception as e:
print(f"无法获取歌曲时长:{e}")
print("应该为 VIP 单曲,删除歌曲文件和取消下载歌词和图片")
audio_duration_TF = False
delete_file(song_path)
audio_duration_TF = False
failed_downloads.append(song.get('id', ''))
successful_downloads -= 1
match = re.search(r'\d+', url)
error_song_id.append(int(match.group()))
error_song_name.append(song_name)
if audio_duration_TF:
lrc_filename = f"{safe_filename(name)} - {safe_filename(artist)}.lrc"
lrc_path = os.path.join(download_path, lrc_filename)
retry_count = 0
while retry_count < 5:
if download_lyrics(lrc, lrc_path, index, total_songs):
break
else:
retry_count += 1
print(f"重试下载 [{index}/{total_songs}][LRC] {lrc_path},次数:{retry_count}")
time.sleep(1)
pic_filename = f"{safe_filename(name)} - {safe_filename(artist)}.jpg"
pic_path = os.path.join(download_path, pic_filename)
retry_count = 0
while retry_count < 5:
if download_pic(pic, pic_path, index, total_songs):
break
else:
retry_count += 1
print(f"重试下载 [{index}/{total_songs}][PIC] {pic_path},次数:{retry_count}")
time.sleep(1)
print(f"程序运行完成,共 {total_songs} 首歌曲,成功下载 {successful_downloads} 首歌曲")
if failed_downloads:
print(f"共有 {len(failed_downloads)} 首歌曲下载失败")
print("失败列表如下")
# 创建表格数据,第一列是序号,从1开始
table_data = [[i + 1, error_song_name[i], error_song_id[i]] for i in range(len(error_song_name))]
# 打印表格
print(tabulate(table_data, headers=["序号", "标题 - 艺术家", "ID"], tablefmt="grid"))
if __name__ == "__main__":
signal.signal(signal.SIGINT, exit_ctrl_c)
welcome()
playlist_id = input("歌单ID:")
download_path = input(r"下载路径(默认为 ./down):") or r"./down"
download_playlist(playlist_id, download_path)
| 10,225 | Python | .py | 228 | 31.671053 | 109 | 0.574032 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,573 | v.23-04-04.多线程.py | God-2077_python-code/网易云音乐歌单批量下载歌曲/v.23-04-04.多线程.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import json
import requests
from urllib.parse import quote
from concurrent.futures import ThreadPoolExecutor
log_msg = {}
log_index = 0
def show_log(f:bool=False):
global log_index
if f or log_index % 20 == 0:
p_msg = ""
os.system('cls')
for k in log_msg.keys():
msg = log_msg[k]
p_msg += msg + "\n"
print(p_msg, end="", flush=True)
log_index+=1
def download_song(url, song_path):
try:
response = requests.get(url, stream=True)
response.raise_for_status() # 检查请求是否成功
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
with open(song_path, "wb") as song_file:
for data in response.iter_content(chunk_size=4096):
downloaded_size += len(data)
song_file.write(data)
progress = downloaded_size / total_size * 100 if total_size > 0 else 0
log_msg[key] = f"正在下载 {song_path},进度:{progress:.2f}%\r"
show_log()
log_msg[key] = f"下载完成 {song_path}"
show_log(True)
except requests.exceptions.RequestException as e:
print(f"下载 {song_path} 失败:{e}")
def safe_filename(filename):
# 将特殊字符(/)改成(-)
return filename.replace("/", "-")
def download_playlist(playlist_id, download_path):
if not playlist_id.isdigit():
print("歌单ID必须为数字")
return
# 创建下载路径
os.makedirs(download_path, exist_ok=True)
# JSON链接
json_url = f"https://api.injahow.cn/meting/?type=playlist&id={quote(playlist_id)}"
try:
# 发送GET请求获取JSON数据
response = requests.get(json_url)
response.raise_for_status() # 检查请求是否成功
data = response.json()
# Function to download a song
def download_song_wrapper(song):
name = song.get("name", "")
artist = song.get("artist", "")
url = song.get("url", "")
lrc = song.get("lrc", "")
if not name or not artist or not url or not lrc:
print(f"歌曲信息不完整:{song}")
return
# 歌曲文件名和路径
song_filename = f"{safe_filename(name)} - {safe_filename(artist)}.mp3"
song_path = os.path.join(download_path, song_filename)
# 下载歌曲
download_song(url, song_path)
# 下载歌词
lrc_response = requests.get(lrc)
lrc_filename = f"{safe_filename(name)} - {safe_filename(artist)}.lrc"
lrc_path = os.path.join(download_path, lrc_filename)
with open(lrc_path, "wb") as lrc_file:
lrc_file.write(lrc_response.content)
# Use ThreadPoolExecutor to download songs concurrently
with ThreadPoolExecutor(max_workers=16) as executor:
executor.map(download_song_wrapper, data)
print("全部歌曲下载完成")
except requests.exceptions.RequestException as e:
print(f"下载歌单失败:{e}")
if __name__ == "__main__":
playlist_id = input("歌单ID:")
download_path = input(r"下载路径(默认为 D:\down):") or r"D:\down"
# max = input(r"下载线程(默认为 5):") or "5"
download_playlist(playlist_id, download_path)
| 3,484 | Python | .py | 83 | 29.975904 | 86 | 0.589447 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,574 | v.24-04-05.最终版.py | God-2077_python-code/网易云音乐歌单批量下载歌曲/v.24-04-05.最终版.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import json
import requests
import librosa
from urllib.parse import quote
import time
import signal
import sys
def download_song(url, song_path, song_index, total_songs):
try:
response = requests.get(url, stream=True)
response.raise_for_status() # 检查请求是否成功
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
with open(song_path, "wb") as song_file:
for data in response.iter_content(chunk_size=4096):
downloaded_size += len(data)
song_file.write(data)
progress = downloaded_size / total_size * 100 if total_size > 0 else 0
print(f"正在下载 [{song_index}/{total_songs}] {song_path},进度:{progress:.2f}%\r", end="")
print(f"下载完成 [{song_index}/{total_songs}] {song_path}")
return True
except requests.exceptions.RequestException as e:
print(f"下载 [{song_index}/{total_songs}] {song_path} 失败:{e}")
return False
# def safe_filename(filename):
# # 将特殊字符(/)改成(-)
# return filename.replace("/", "-")
def safe_filename(filename):
# 将无效字符替换为下划线
invalid_chars = '\\/:*?"<>|'
for char in invalid_chars:
filename = filename.replace(char, '_')
return filename
def delete_file(file_path):
if os.path.exists(file_path):
os.remove(file_path)
print(f"删除文件:{file_path}")
def download_playlist(playlist_id, download_path):
if not playlist_id.isdigit():
print("歌单ID必须为数字")
return
# JSON链接
api_urls = [
"https://api.injahow.cn/meting/?type=playlist&id=",
"https://meting.qjqq.cn/?type=playlist&id="
]
selected_api = None
data = None
for api_url in api_urls:
try:
response = requests.get(f"{api_url}{playlist_id}")
response.raise_for_status() # 检查请求是否成功
data = response.json()
selected_api = api_url
if 'error' in data:
error = data.get("error", "")
print("出错了...")
print(f"错误详细:{error}")
return # Exit the function if error is encountered in JSON response
break
except requests.exceptions.RequestException as e:
print(f"API {api_url} 请求失败:{e}")
continue
if not data:
print("所有API都无法获取数据")
return
# 创建下载路径
os.makedirs(download_path, exist_ok=True)
total_songs = len(data)
print(f"歌单共有 {total_songs} 首歌曲")
successful_downloads = 0
failed_downloads = []
def signal_handler(sig, frame):
print("检测到Ctrl+C, exiting gracefully...")
print(f"程序运行完成,共 {total_songs} 首歌曲,成功下载 {successful_downloads} 首歌曲")
if failed_downloads:
print(f"共有 {len(failed_downloads)} 首歌曲下载失败,id为:{','.join(failed_downloads)}")
sys.exit(0)
input()
signal.signal(signal.SIGINT, signal_handler)
for index, song in enumerate(data, start=1):
# 歌曲信息
name = song.get("name", "")
artist = song.get("artist", "")
url = song.get("url", "")
lrc = song.get("lrc", "")
# duration = song.get("duration", 0) # 歌曲时长,单位:秒
if not name or not artist or not url or not lrc:
print(f"歌曲信息不完整:{song}")
continue
# 歌曲文件名和路径
song_filename = f"{safe_filename(name)} - {safe_filename(artist)}.mp3"
song_path = os.path.join(download_path, song_filename)
# 下载歌曲
retry_count = 0
while retry_count < 5:
if download_song(url, song_path, index, total_songs):
successful_downloads += 1
break
else:
retry_count += 1
print(f"重试下载 [{index}/{total_songs}] {song_path},次数:{retry_count}")
time.sleep(1) # 等待1秒后重试
# 下载歌词
lrc_response = requests.get(lrc)
lrc_filename = f"{safe_filename(name)} - {safe_filename(artist)}.lrc"
lrc_path = os.path.join(download_path, lrc_filename)
with open(lrc_path, "w", encoding="utf-8") as lrc_file: # 修改这里,指定编码为utf-8
lrc_file.write(lrc_response.content.decode('utf-8')) # 将内容以utf-8解码后写入文件
# 检查歌曲时长是否小于一分钟
# if duration < 60:
# print(f"歌曲时长小于一分钟,删除歌曲和歌词:{song_path}")
# delete_file(song_path)
# lrc_filename = f"{safe_filename(name)} - {safe_filename(artist)}.lrc"
# lrc_path = os.path.join(download_path, lrc_filename)
# delete_file(lrc_path)
# failed_downloads.append(song.get('id', '')) # 添加到下载失败列表
# successful_downloads -= 1 # 减去下载成功计数
# 使用librosa获取音频持续时间
try:
audio_duration = librosa.get_duration(path=song_path)
if audio_duration < 60:
print(f"歌曲时长小于一分钟,删除歌曲和歌词:{song_path}")
delete_file(song_path)
delete_file(lrc_path)
failed_downloads.append(song.get('id', '')) # 添加到下载失败列表
successful_downloads -= 1 # 减去下载成功计数
else:
print(f"歌曲时长为 {audio_duration} 秒")
except Exception as e:
print(f"无法获取歌曲时长:{e}")
# failed_downloads.append(song.get('id', ''))
print(f"程序运行完成,共 {total_songs} 首歌曲,成功下载 {successful_downloads} 首歌曲")
if failed_downloads:
# print(f"共有 {len(failed_downloads)} 首歌曲下载失败,id为:{','.join(failed_downloads)}")
print(f"共有 {len(failed_downloads)} 首歌曲下载失败...")
if __name__ == "__main__":
playlist_id = input("歌单ID:")
download_path = input(r"下载路径(默认为 D:\down):") or r"D:\down"
download_playlist(playlist_id, download_path)
| 6,677 | Python | .py | 143 | 31.461538 | 101 | 0.568397 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,575 | v.24-07-19.py | God-2077_python-code/网易云音乐歌单批量下载歌曲/v.24-07-19.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import requests
from mutagen.mp3 import MP3
import time
import signal
import sys
import re
from tabulate import tabulate
def download_file(url, file_path, file_type, index, total_files, timeout=10):
try:
response = requests.get(url, stream=True, timeout=timeout)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
with open(file_path, "wb") as file:
for data in response.iter_content(chunk_size=4096):
downloaded_size += len(data)
file.write(data)
progress = downloaded_size / total_size * 100 if total_size > 0 else 0
print(f"正在下载 [{index}/{total_files}][{file_type}] {file_path},进度:{progress:.2f}%\r", end="")
print(f"下载完成 [{index}/{total_files}][{file_type}] {file_path}")
return True
except requests.exceptions.RequestException as e:
print(f"下载 [{index}/{total_files}][{file_type}] {file_path} 失败:{e}")
return False
def download_lyrics(url, lrc_path, song_index, total_songs):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
with open(lrc_path, "w", encoding="utf-8") as lrc_file:
lrc_file.write(response.content.decode('utf-8'))
print(f"下载完成 [{song_index}/{total_songs}][LRC] {lrc_path}")
return True
except requests.exceptions.RequestException as e:
print(f"下载歌词失败:{e}")
return False
def safe_filename(filename):
invalid_chars = '\\/:*?"<>|'
for char in invalid_chars:
filename = filename.replace(char, '_')
return filename
def delete_file(file_path):
if os.path.exists(file_path):
os.remove(file_path)
print(f"删除文件:{file_path}")
def song_table(data):
table_data = []
for idx, item in enumerate(data, start=1):
name = item['name']
artist = item['artist']
url_id = re.search(r'\d+', item['url']).group()
table_data.append([idx, name, artist, url_id])
table_headers = ["序号", "标题", "艺术家", "ID"]
table = tabulate(table_data, table_headers, tablefmt="pipe")
print(table)
def exit_ctrl_c(sig, frame):
print("\n退出程序...")
sys.exit(0)
def welcome():
print("welcome")
print("欢迎使用我开发的小程序")
print("Github Rope: https://github.com/God-2077/python-code/")
print("-------------------------")
print("网易云音乐歌单批量下载歌曲")
def download_playlist(playlist_id, download_path):
if not playlist_id.isdigit():
print("歌单ID必须为数字")
return
error_song_name = []
error_song_id = []
api_urls = [
"https://meting.qjqq.cn/?type=playlist&id=",
"https://api.injahow.cn/meting/?type=playlist&id=",
"https://meting-api.mnchen.cn/?type=playlist&id=",
"https://meting-api.mlj-dragon.cn/meting/?type=playlist&id="
]
selected_api = None
data = None
for api_url in api_urls:
try:
response = requests.get(f"{api_url}{playlist_id}", timeout=10)
response.raise_for_status()
data = response.json()
selected_api = api_url
if 'error' in data:
error = data.get("error", "")
print("出错了...")
print(f"错误详细:{error}")
return
break
except requests.exceptions.RequestException as e:
print(f"API {api_url} 请求失败:{e}")
continue
if not data:
print("所有API都无法获取数据")
return
os.makedirs(download_path, exist_ok=True)
print(f"Meting API: {selected_api}")
total_songs = len(data)
print(f"歌单共有 {total_songs} 首歌曲")
song_table(data)
envisage_size = total_songs * 7.7
print(f"歌单共有 {total_songs} 首歌曲,预计歌曲文件总大小为 {envisage_size} MB")
chose = str(input("是否继续下载?(yes): "))
if chose not in ["y", "", "yes"]:
print("退出程序...")
sys.exit(0)
successful_downloads = 0
failed_downloads = []
def signal_handler(sig, frame):
print("\n检测到Ctrl+C, exiting gracefully...")
print(f"程序运行完成,共 {total_songs} 首歌曲,成功下载 {successful_downloads} 首歌曲")
if failed_downloads:
print(f"共有 {len(failed_downloads)} 首歌曲下载失败")
print("失败列表如下")
table_data = [[i + 1, error_song_name[i], error_song_id[i]] for i in range(len(error_song_name))]
print(tabulate(table_data, headers=["序号", "标题 - 艺术家", "ID"], tablefmt="grid"))
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
for index, song in enumerate(data, start=1):
name = song.get("name", "")
artist = song.get("artist", "")
url = song.get("url", "")
lrc = song.get("lrc", "")
pic = song.get("pic", "")
if not name or not artist or not url or not lrc:
print(f"歌曲信息不完整:{song}")
continue
song_filename = f"{safe_filename(name)} - {safe_filename(artist)}.mp3"
song_name = f"{safe_filename(name)} - {safe_filename(artist)}"
song_path = os.path.join(download_path, song_filename)
retry_count = 0
while retry_count < 5:
if download_file(url, song_path, "MP3", index, total_songs):
successful_downloads += 1
state = True
break
else:
retry_count += 1
print(f"重试下载 [{index}/{total_songs}][MP3] {song_path},次数:{retry_count}")
state = False
time.sleep(1)
if state == False:
print("")
match = re.search(r'\d+', url)
error_song_id.append(int(match.group()))
error_song_name.append(song_name)
failed_downloads.append(match)
if state == True:
try:
audio = MP3(song_path)
audio_duration = audio.info.length
if audio_duration < 60:
print(f"歌曲时长小于一分钟,删除歌曲和取消下载歌词和图片:{song_path}")
delete_file(song_path)
audio_duration_TF = False
successful_downloads -= 1
match = re.search(r'\d+', url)
error_song_id.append(int(match.group()))
error_song_name.append(song_name)
else:
print(f"歌曲时长为 {audio_duration} 秒")
audio_duration_TF = True
except Exception as e:
print(f"无法获取歌曲时长:{e}")
print("应该为 VIP 单曲,删除歌曲文件和取消下载歌词和图片")
delete_file(song_path)
audio_duration_TF = False
successful_downloads -= 1
match = re.search(r'\d+', url)
error_song_id.append(int(match.group()))
error_song_name.append(song_name)
failed_downloads.append(match)
if audio_duration_TF:
lrc_filename = f"{safe_filename(name)} - {safe_filename(artist)}.lrc"
lrc_path = os.path.join(download_path, lrc_filename)
retry_count = 0
while retry_count < 5:
if download_lyrics(lrc, lrc_path, index, total_songs):
break
else:
retry_count += 1
print(f"重试下载 [{index}/{total_songs}][LRC] {lrc_path},次数:{retry_count}")
time.sleep(1)
pic_filename = f"{safe_filename(name)} - {safe_filename(artist)}.jpg"
pic_path = os.path.join(download_path, pic_filename)
retry_count = 0
while retry_count < 5:
if download_file(pic, pic_path, "PIC", index, total_songs):
break
else:
retry_count += 1
print(f"重试下载 [{index}/{total_songs}][PIC] {pic_path},次数:{retry_count}")
time.sleep(1)
print(f"程序运行完成,共 {total_songs} 首歌曲,成功下载 {successful_downloads} 首歌曲")
if failed_downloads:
print(f"共有 {len(failed_downloads)} 首歌曲下载失败")
print("失败列表如下")
table_data = [[i + 1, error_song_name[i], error_song_id[i]] for i in range(len(error_song_name))]
print(tabulate(table_data, headers=["序号", "标题 - 艺术家", "ID"], tablefmt="grid"))
if __name__ == "__main__":
signal.signal(signal.SIGINT, exit_ctrl_c)
welcome()
playlist_id = input("歌单ID:")
download_path = input(r"下载路径(默认为 ./down):") or r"./down"
download_playlist(playlist_id, download_path)
| 9,297 | Python | .py | 208 | 30.822115 | 109 | 0.554471 | God-2077/python-code | 8 | 3 | 1 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,576 | health_check.py | sean89503_Invidious_Cast/health_check.py | import time
def update_health_status():
"""Updates the last health check time variable."""
global last_health_check_time # Declare the variable as global
last_health_check_time = time.time()
# Optional: You can add additional health check logic here
# For example, checking database connection or external service status
# Make the variable accessible from outside the module (if needed)
last_health_check_time = None # Initialize the variable
| 467 | Python | .py | 9 | 48.555556 | 71 | 0.772124 | sean89503/Invidious_Cast | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,577 | app.py | sean89503_Invidious_Cast/app.py | from flask import Flask, request, send_from_directory, render_template, redirect, flash, Response
import xml.etree.ElementTree as ET
import os
from datetime import datetime
import time
import logging
from multiprocessing import Process
import yt_dlp
app = Flask(__name__)
#########Set Peramiters
file_path = "channels.txt"
XML_DIRECTORY = os.path.join(os.getcwd(), 'xml_files')
CAST_DOMAIN = os.getenv('CAST_DOMAIN')
CAST_TRUSTED_NETWORK = os.getenv('CAST_TRUSTED_NETWORK','127.0.0.1').split(',')
logging.basicConfig(level=logging.INFO)
main_logger = logging.getLogger(__name__)
process_logger = logging.getLogger('cast')
def fetch_url(video_id, typed):
# Define the video URL
video_url = f'https://www.youtube.com/watch?v={video_id}'
# Create yt_dlp options
ydl_opts = {
'quiet': True, # Suppress output
}
# Create yt_dlp object
ydl = yt_dlp.YoutubeDL(ydl_opts)
try:
# Get video info
with ydl:
video_info = ydl.extract_info(video_url, download=False)
# Check if formats are available
if 'formats' in video_info:
# Filter formats to find the desired one (e.g., format ID '22' or '251')
if typed == 'audio':
format_id = '251'
else:
format_id = '22' # Or use type or any specific logic to determine the format ID
selected_format = next(
(f for f in video_info['formats'] if f.get('format_id') == format_id), None
)
if selected_format:
direct_url = selected_format['url']
return direct_url
else:
print("Error: Desired format not found.")
else:
print("Error: No formats available for the video.")
except yt_dlp.utils.DownloadError as e:
print("Error:", e)
# Handle the error condition if needed
#####START OF WEB APP ###############
@app.route('/manage')
def index():
remote_addr = request.remote_addr
if any(remote_addr.startswith(pattern) for pattern in CAST_TRUSTED_NETWORK):
cleanit()
with open(file_path, 'r') as file:
lines = file.readlines() # Read all lines from the file
return render_template('manage.html', lines=lines)
else:
return redirect('/')
@app.route('/add_line', methods=['POST'])
def add_line():
remote_addr = request.remote_addr
if any(remote_addr.startswith(pattern) for pattern in CAST_TRUSTED_NETWORK):
new_line = request.form.get('new_line') # Get the new line from the form
# Check if the file is empty
file_empty = os.stat(file_path).st_size == 0
with open(file_path, 'a') as file:
if not file_empty: # If the file is not empty, add a newline character before the new line
file.write('\n')
file.write(new_line) # Append the new line to the file
cleanit()
return redirect('/manage')
def cleanit():
line_to_remove = '' # Get the line to remove from the form
with open(file_path, 'r') as file:
lines = file.readlines() # Read all lines from the file
with open(file_path, 'w') as file:
for line in lines:
if line.strip() != line_to_remove.strip() and line.strip() != '': # Remove if not an empty line or just spaces
file.write(line)
@app.route('/remove_line', methods=['POST'])
def remove_line():
remote_addr = request.remote_addr
if any(remote_addr.startswith(pattern) for pattern in CAST_TRUSTED_NETWORK):
new_line = request.form.get('new_line') # Get the new line from the form
line_to_remove = request.form.get('line_to_remove') # Get the line to remove from the form
print(line_to_remove)
with open(file_path, 'r') as file:
lines = file.readlines() # Read all lines from the file
with open(file_path, 'w') as file:
for line in lines:
if line.strip() != line_to_remove.strip(): # Write all lines except the one to remove
file.write(line)
cleanit()
return redirect('/manage')
@app.route('/url')
def url():
video_id = request.args.get('id')
typed = request.args.get('type')
direct_url = fetch_url(video_id, typed)
'''data = fetch_videos_info(video_id, 'max')
time.sleep(10)
for returnedvideo in data:
video = returnedvideo.get('videodir')
audio = returnedvideo.get('audiodir')
if typed == 'audio':
return redirect(f'{audio[0]}')
if typed != 'audio':
return redirect(f'{video[0]}')
'''
if direct_url:
return redirect(direct_url)
else:
return "Error: Failed to fetch the URL."
@app.route('/xml_files/<path:filename>')
def download_file(filename):
return send_from_directory(XML_DIRECTORY, filename)
@app.route('/')
def list_files():
files = [f for f in os.listdir(XML_DIRECTORY) if f.endswith('.xml')]
file_links = ''.join([f'<a href="/xml_files/{filename}">{filename}</a><br>' for filename in files])
# Add the HTML <img> tag for the logo
logo_url = 'https://github.com/sean89503/Invidious_Cast/blob/main/logo.png?raw=true'
logo_html = f'<img src="{logo_url}" alt="Logo" style="width: 100px; height: 100px;"><br>'
return f'{logo_html}<h1>XML Files:</h1>{file_links}'
def generate_opml(files, domain):
opml_content = '<?xml version="1.0" encoding="UTF-8"?><opml version="1.0">'
for filename in files:
filepath = os.path.join(XML_DIRECTORY, filename)
if filename.endswith('.xml'):
try:
tree = ET.parse(filepath)
root = tree.getroot()
replacements = {'&': '&', '-': '-'}
channel_title = root.find('channel/title').text.translate(str.maketrans(replacements)) if root.find('channel/title') is not None else ''
# Include text attribute only if title exists
outline_text = f'text="{channel_title}"' if channel_title else 'text="TEST"'
opml_content += f'<outline type="rss" {outline_text} xmlUrl="{domain}/xml_files/{filename}" />'
#opml_content += f'<outline xmlUrl="{domain}/xml_files/{filename}" />'
except Exception as e:
print(f"Error parsing {filename}: {e}")
opml_content += '</opml>'
return opml_content
@app.route('/opml')
def get_opml():
domain = request.args.get('domain')
if domain == None:
domain = CAST_DOMAIN
if domain != None:
return redirect(f'/opml?domain={domain}')
if domain:
files = [f for f in os.listdir(XML_DIRECTORY) if f.endswith('.xml')]
opml_data = generate_opml(files, domain)
return Response(opml_data, mimetype='text/xml')
else:
# Redirect to form if no domain submitted
return redirect('/')
files = [f for f in os.listdir(XML_DIRECTORY) if f.endswith('.xml')]
opml_data = generate_opml(files, domain)
return Response(opml_data, mimetype='text/xml')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5895)
| 7,118 | Python | .py | 164 | 36.054878 | 141 | 0.624184 | sean89503/Invidious_Cast | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,578 | main.py | sean89503_Invidious_Cast/main.py | import xml.etree.ElementTree as ET
import os
from datetime import datetime
import time
import logging
import multiprocessing
from multiprocessing import Process
from app import app
from waitress import serve
import yt_dlp
import json
#########Set Peramiters
file_path = "channels.txt"
CAST_DOMAIN = os.getenv('CAST_DOMAIN')
if CAST_DOMAIN == None:
CAST_DOMAIN = 'NEEDStoBEset'
CRON = os.getenv('CAST_CRON')
if CRON == None:
CRON = 86400
XML_DIRECTORY = os.path.join(os.getcwd(), 'xml_files')
logging.basicConfig(level=logging.INFO)
process_logger = logging.getLogger('ydl')
process_logger.setLevel(logging.ERROR)
########### START OF CRON APP
def update_health_status():
global last_health_check_time
last_health_check_time = time.time()
def get_channel_uploads(channel_id, max_videos):
# Create yt_dlp options
ydl_opts = {
"quiet": True, # Suppress output
"no-warnings": True, # Try to suppress warnings (might not work for all)
"ignoreerrors": True, # Ignore download errors
"extract_flat": True, # Extract flat playlist
"playlistend": max_videos, # Limit the number of videos to retrieve
"logger": process_logger, # Custom logger to handle warnings
}
# Create yt_dlp object
ydl = yt_dlp.YoutubeDL(ydl_opts)
ogchannelid = channel_id
try:
# Get channel metadata
channel_url = ''
if channel_id.startswith('UC'):
channel_id = channel_id.replace('UC', 'UU', 1) # Replace at most once
if channel_id.startswith('UU'):
channel_url = f'https://www.youtube.com/playlist?list={channel_id}'
if channel_id.startswith('PLN'):
channel_url = f'https://www.youtube.com/playlist?list={channel_id}'
if channel_id.startswith('RUMBLE'):
channel_id = channel_id.replace('RUMBLE', '', 1) # Replace at most once
channel_url = f'https://rumble.com/c/{channel_id}'
with ydl:
channel_info = ydl.extract_info(channel_url, download=False)
output_file = "channel_info.json"
with open(output_file, "w") as json_file:
json.dump(channel_info, json_file, indent=4)
if channel_info is not None:
if ogchannelid.startswith('UC'):
detailed_info = ydl.extract_info(f'https://www.youtube.com/channel/{ogchannelid}', download=False)
if detailed_info:
'''output_file = "channel_detail.json"
with open(output_file, "w") as json_file:
json.dump(detailed_info, json_file, indent=4)'''
# Extract URL from the first thumbnail or detailed view
thumbnails = detailed_info.get('thumbnails', [])
avatar_thumbnail = next((thumb for thumb in thumbnails if thumb.get('id') == 'avatar_uncropped'), None)
if avatar_thumbnail:
thumbnail_url = avatar_thumbnail.get('url')
else:
thumbnail_url = thumbnails[1].get('url', '') # Default if no thumbnails found
channel_info['thumbnail_url'] = thumbnail_url
output_file = "channel_uploads.json"
with open(output_file, "w") as json_file:
json.dump(channel_info, json_file, indent=4)
# Check if channel_info is not None and contains videos
if channel_info is not None:
return channel_info
#videos = [video for video in channel_info['entries'] if video.get('is_live') != True]
#data = json.loads(videos)
#return data
else:
print("Channel information not available or no videos found.")
return []
except yt_dlp.utils.DownloadError as e:
print("Error:", e)
return []
def fetch_all(channel_data, filter, limit):
videos = []
count = 0
for video in channel_data['entries']:
videoid = video.get('id')
videoURL = video.get('url')
if video.get('availability') is None:
fetchdetail = fetch_video_info(videoURL) # Assuming fetch_video_info is defined elsewhere
if fetchdetail is not None:
duration = fetchdetail.get('duration', 0)
if duration !=0:
description = fetchdetail.get('description', '')
published = fetchdetail.get('pub_date', '')
thumbnail = fetchdetail.get('thumbnail', '')
webpage_url = fetchdetail.get('webpage_url', '')
if published:
pub_date = datetime.strptime(published, '%Y%m%d')
published_unix = int(pub_date.timestamp())
video['description'] = description
video['published'] = published_unix
video['duration'] = duration
video['thumbnail'] = thumbnail
video['webpage_url'] = webpage_url
videos.append(video)
count += 1 # Increment count
if count == limit:
break # Stop iterating if limit is reached
return videos # Return all processed videos
def fetch_video_info(videoURL):
# Create yt_dlp options with custom logger
ydl_opts = {
"quiet": True, # Suppress output
"no-warnings": True, # Try to suppress warnings (might not work for all)
"logger": process_logger, # Custom logger to handle warnings
}
# Create yt_dlp object
ydl = yt_dlp.YoutubeDL(ydl_opts)
try:
# Get video info
with ydl:
video_info = ydl.extract_info(videoURL, download=False)
'''output_file = "videouploads.json"
with open(output_file, "w") as json_file:
json.dump(video_info, json_file, indent=4)'''
if video_info != None:
return {
'description': video_info.get('description', 'N/A'),
'pub_date': video_info.get('upload_date', 'N/A'),
'duration': video_info.get('duration', 'N/A'),
'thumbnail': video_info.get('thumbnail', 'N/A'),
'webpage_url': video_info.get('webpage_url', 'N/A'),
}
except yt_dlp.utils.DownloadError as e:
print("Error:", e)
return None
def format_published_date(unix_timestamp):
# Convert Unix timestamp to datetime object
dt_object = datetime.fromtimestamp(unix_timestamp)
# Format the datetime object as a string in the desired format using strftime
formatted_date = dt_object.strftime('%Y-%m-%d %H:%M:%S')
return formatted_date
def format_duration(seconds):
# Convert total seconds to hours, minutes, and remaining seconds
hours, remainder = divmod(seconds, 3600)
minutes, seconds = divmod(remainder, 60)
# Format duration as HH:MM:SS
formatted_duration = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
return formatted_duration
def create_podcast_feed(type_param, channel_info, channel_id, filter, vidioquality, limit, latest):
# Define the namespace if present in the XML
namespace = {
'atom': 'http://www.w3.org/2005/Atom',
'yt': 'http://www.youtube.com/xml/schemas/2015',
'media': 'http://search.yahoo.com/mrss/',
'itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd',
'dc': 'http://purl.org/dc/elements/1.1/'
}
# Create the RSS root element with iTunes and atom namespaces
rss = ET.Element('rss', {'version': '2.0', 'xmlns:itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd', 'xmlns:atom': 'http://www.w3.org/2005/Atom'})
channel = ET.SubElement(rss, 'channel')
# Extract channel information
title = channel_info.get('title', 'Default Author') # Use a default author if not available
# Check if the title starts with "Uploads from" and strip it if it does
if title.startswith('Uploads from'):
title = title[len('Uploads from'):].strip()
pubDate = datetime.now()
unixdate= int(pubDate.timestamp())
formatted_date = format_published_date(unixdate)
description = channel_info.get('description', '') # Use a default author if not available
authorId = channel_info.get('id', '')
link = channel_info.get('channel_url', '')
BACKUPIMAGE = channel_info.get('thumbnails')[1].get('url')
image_url = channel_info.get('thumbnail_url',BACKUPIMAGE)
generator = 'InvidiousCast'
last_build_date = 'Your Last Build Date'
author = channel_info.get('uploader', 'Default Author') # Use a default author if not available
# Add channel elements without namespace prefixes
ET.SubElement(channel, 'title').text = title
ET.SubElement(channel, 'pubDate').text = formatted_date
ET.SubElement(channel, 'generator').text = 'InvidiousCast'
#ET.SubElement(channel, 'podcast:locked').text = 'yes'
ET.SubElement(channel, 'link').text = link
ET.SubElement(channel, 'language').text = 'English'
ET.SubElement(channel, 'copyright').text = description
ET.SubElement(channel, 'description').text = author
ET.SubElement(channel, 'docs').text = 'google.com'
ET.SubElement(channel, 'managingEditor').text = '[email protected]'
# Add image element
image_elem = ET.SubElement(channel, 'image')
ET.SubElement(image_elem, 'url').text = image_url
# Add iTunes-specific tags
itunes_explicit = 'No'
itunes_image_href = image_url
itunes_owner = ET.SubElement(channel, 'itunes:owner')
is_family_friendly = channel_info.get('isFamilyFriendly', False)
itunes_explicit = 'No' if is_family_friendly else 'Yes'
ET.SubElement(channel, 'itunes:summary').text = description
ET.SubElement(channel, 'itunes:author').text = author
ET.SubElement(channel, 'itunes:keyword').text = ''
ET.SubElement(channel, 'itunes:category').text = 'TV & Film'
ET.SubElement(channel, 'itunes:image', href=itunes_image_href)
ET.SubElement(channel, 'itunes:explicit').text = itunes_explicit
ET.SubElement(channel, 'itunes:owner').text = ''
ET.SubElement(itunes_owner, 'itunes:name').text = title
ET.SubElement(itunes_owner, 'itunes:email').text = '[email protected]'
ET.SubElement(channel, 'itunes:block').text = 'yes'
ET.SubElement(channel, 'itunes:type').text = 'episodic'
# Extract and add episodes
logging.info(f'Creating feed for {authorId}({author}), type:{type_param}, limit:{limit}, filter: {filter}')
for video in latest:
video_id = video.get('id', '')
title = video.get('title', 'Untitled Video')
pubfromvid = video.get('published')
formatted_date = format_published_date(pubfromvid)
length_seconds = video.get('duration', 0)
itunes_duration = format_duration(int(length_seconds))
linkbackup = f'https://www.youtube.com/watch?v={video_id}'
videolink = video.get('webpage_url', linkbackup)
description = video.get('description', 'error')
description = f"{description}\nLink: {videolink}"
thumbnail_urlbackup = f'https://i3.ytimg.com/vi/{video_id}/maxresdefault.jpg'
thumbnail_url = video.get('thumbnail', thumbnail_urlbackup)
modified_url = f'{CAST_DOMAIN}/url?id={video_id}&type={type_param}'
if type_param == 'audio':
enclosure_type = 'audio/m4a'
else:
enclosure_type = 'video/mp4'
item = ET.SubElement(channel, 'item')
ET.SubElement(item, 'title').text = title
ET.SubElement(item, 'itunes:title').text = title
ET.SubElement(item, 'pubDate').text = formatted_date
ET.SubElement(item, 'guid', {'isPermaLink': 'false'}).text = f'{videolink}'
ET.SubElement(item, 'link').text = videolink
ET.SubElement(item, 'description').text = description
ET.SubElement(item, 'enclosure', {'url': modified_url, 'length': str(length_seconds), 'type': enclosure_type})
ET.SubElement(item, 'itunes:duration').text = itunes_duration
ET.SubElement(item, 'itunes:explicit').text = 'false'
ET.SubElement(item, 'itunes:block').text = 'yes'
ET.SubElement(item, 'itunes:subtitle').text = description
ET.SubElement(item, 'itunes:episodeType').text = 'full'
ET.SubElement(item, 'itunes:author').text = author
ET.SubElement(item, 'itunes:image', {'href': thumbnail_url})
# Convert the XML tree to string
rss_str = ET.tostring(rss, encoding='utf-8').decode('utf-8')
#print('Found videos')
return rss_str
def handle_podcast_request(channel_id, channel_type, channel_limit, filter, latest, channel_data):
vidioquality = '720p' # Default video quality
# Check if the XML directory exists
if not os.path.exists(XML_DIRECTORY):
try:
os.makedirs(XML_DIRECTORY)
except OSError as e:
print(f"Error creating directory: {e}")
return None
# Fetch channel information using the API
channel_info = channel_data #fetch_channel_info(channel_id)
if not channel_info:
return 'Error: Unable to fetch channel information.', 500
else:
# Create the podcast feed from the XML content
podcast_feed = create_podcast_feed( channel_type, channel_info, channel_id, filter, vidioquality, channel_limit, latest)
# Save the XML content to a file in the XML directory
if not os.path.exists(XML_DIRECTORY):
os.makedirs(XML_DIRECTORY)
filename = f'{channel_id}.xml'
filepath = os.path.join(XML_DIRECTORY, filename)
#print(f'saving to xml')
with open(filepath, 'w', encoding='utf-8') as xml_file:
xml_file.write(podcast_feed)
print('saved')
return podcast_feed
# Return the modified XML with correct content type
#return podcast_feed, {'Content-Type': 'application/xml'}
#else:
#return f'Error: Unable to fetch data from the URL. Status code: {response.status_code}', response.status_code
def read_channel_ids_from_file(file_path, max_retries=5):
print('...............................................................................................................')
print('######..##..##..##..##..######..#####...######...####...##..##...####............####....####....####...######.',)
print('..##....##..##..##..##....##....##..##....##....##..##..##..##..##..............##..##..##..##..##........##...',)
print('..##....##.###..##..##....##....##..##....##....##..##..##..##...####...........##......######...####.....##...',)
print('..##....##..##...####.....##....##..##....##....##..##..##..##......##..........##..##..##..##......##....##...',)
print('######..##..##....##....######..#####...######...####....####....####............####...##..##...####.....##...',)
print('...............................................................................................................',)
"""
Reads channel IDs and information from a file.
Args:
file_path (str): The path to the file containing channel data.
max_retries (int, optional): The maximum number of times to retry waiting for the file to exist. Defaults to 5.
Returns:
list or None: If the file exists and is valid, returns a list of channel data.
"""
while True: # Run indefinitely in a loop
# Wait for file to exist with a timeout
for attempt in range(max_retries):
if os.path.exists(file_path):
break
logging.warning(f"Waiting for file '{file_path}' to be available... (Attempt {attempt + 1}/{max_retries})")
time.sleep(5)
else:
logging.error("File not found after retries: {}".format(file_path))
return None
try:
with open(file_path, 'r') as file:
logging.info('Looking at subscriptions...')
for line in file.read().splitlines():
update_health_status()
parts = line.strip().split(':')
channel_id = parts[0]
channel_type = parts[1].lower() if len(parts) > 1 else 'video'
limit = int(parts[2]) if len(parts) > 2 else 5
filter = parts[3].lower() if len(parts) > 2 else 'none'
if channel_id == '':
logging.error(f'error on grabbing line in channels.txt check if blank line')
continue # Skip processing this line and move to the next one
if channel_id.startswith('@'): #if a user puts in the @userid for youtube it will grab the channelid of the user
ydl_opts = {
"quiet": True, # Suppress output
"ignoreerrors": True, # Ignore download errors
"extract_flat": True, # Extract flat playlist
"playlistend": 1, # Limit the number of videos to retrieve
}
# Create yt_dlp object
ydl = yt_dlp.YoutubeDL(ydl_opts)
try:
channel_url = f'https://www.youtube.com/{channel_id}'
with ydl:
channel_info = ydl.extract_info(channel_url, download=False)
channel_id = channel_info.get('channel_id')
except yt_dlp.utils.DownloadError as e:
logging.error('Error in making podcastfeed')
continue
channel_data = get_channel_uploads(channel_id, limit)
title = channel_data.get('title')
# Check if the title starts with "Uploads from" and strip it if it does
if title.startswith('Uploads from'):
title = title[len('Uploads from'):].strip()
chlatest = fetch_all(channel_data, filter,1)
if chlatest is not None:
if len(chlatest) > 0:
video_id = chlatest[0]['id']
else:
print(f"No videos found for {title} ")
else:
logging.error(f'error on grabbing chlatest for {title} ({channel_id})')
return None
xmllatest = find_latest_video(channel_id)
if video_id != xmllatest:
if xmllatest == 'nofile':
logging.info(f'Found new feed item {title} ({channel_id})')
print(f'Found new feed item {title} ({channel_id})')
else:
logging.info(f'Found new videos ({video_id}) only have {xmllatest} on {title} ({channel_id})')
print(f'Found new videos ({video_id}) only have {xmllatest} on {title} ({channel_id})')
chlatest = fetch_all(channel_data, filter, limit)
latest = chlatest
complete = handle_podcast_request(channel_id, channel_type, limit, filter, latest, channel_data)
time.sleep(.2)
logging.info(f'Done updating {title} ({channel_id})')
print(f'Done updating {title} ({channel_id})')
if complete is None:
logging.error('Error in making podcastfeed')
return None
else:
logging.info(f'Done Checking {title} ({channel_id})')
except ValueError:
logging.warning(f"Invalid channel type '{channel_type}' for channel {title} ")
logging.info(f'Finished round of lookups. Will look agian in {CRON} seconds ')
time.sleep(int(CRON)) # Delay for 60 seconds before checking the file again
def find_latest_video(filename):
"""
Extracts the first video ID from a specified XML file.
Args:
filename (str): The filename (including the '.xml' extension).
Returns:
str: The first video ID found in the XML file, or None if no video is found or errors occur.
"""
try:
# Construct the full filepath using XML_DIRECTORY and filename
filepath = os.path.join(XML_DIRECTORY, filename)
filepath = f'{filepath}.xml'
if os.path.exists(file_path):
# Read the XML content from the file
with open(filepath, 'rb') as f:
xml_content = f.read()
# Parse the XML content (modify if content is a string)
if isinstance(xml_content, bytes):
root = ET.fromstring(xml_content)
else:
root = ET.fromstring(xml_content.encode('utf-8'))
# Find the first child element named 'item' under the 'channel' element
item_element = root.find('channel/item')
if item_element is None:
return None
# Find the first child element named 'enclosure' under the 'item' element
enclosure_element = item_element.find('enclosure')
if enclosure_element is None:
return None
# Extract the video ID from the enclosure URL (assuming specific format)
enclosure_url = enclosure_element.get('url')
if not enclosure_url:
return None
video_id_parts = enclosure_url.split('=')
if len(video_id_parts) > 1:
return video_id_parts[1].split('&')[0]
else:
return None
else:
return 'hhhhd'
except Exception as e:
return 'nofile'
def worker(queue):
while True:
task = queue.get()
if task is None:
break
print(f"Processing task {task}")
# Perform data processing on the task (e.g., calculations, transformations)
result = task * 2 # Example data processing operation
print(f"Processed task result: {result}")
time.sleep(1) # Simulate processing time
def run_with_workers(port, num_workers, queue):
# Create and start worker processes
processes = [Process(target=worker, args=(queue,)) for _ in range(num_workers)]
for process in processes:
process.start()
# Serve the Flask app with Waitress
serve(app, host='0.0.0.0', port=port)
if __name__ == '__main__':
# Create a multiprocessing Queue
queue = multiprocessing.Queue()
def start_link_updater(file_path):
process = Process(target=read_channel_ids_from_file, args=(file_path,))
process.daemon = True
process.start()
start_link_updater(file_path)
run_with_workers(5895,12, queue)
| 23,612 | Python | .py | 444 | 40.632883 | 155 | 0.564487 | sean89503/Invidious_Cast | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,579 | app.py | MaxMLang_RAG-nificent/src/app.py | import os
from typing import List
import dotenv
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.chains import ConversationalRetrievalChain
from langchain.chat_models import ChatOpenAI
from langchain_groq import ChatGroq
from langchain_pinecone import Pinecone
from langchain.docstore.document import Document
from langchain.memory import ChatMessageHistory, ConversationBufferMemory
from chainlit.input_widget import Select, Switch, Slider
import re
import chainlit as cl
dotenv.load_dotenv()
pdf_data = {
"WHO guideline on control and elimination of human schistosomiasis (2022)":"https://iris.who.int/bitstream/handle/10665/351856/9789240041608-eng.pdf",
"WHO guidelines for malaria (2023)":"https://iris.who.int/bitstream/handle/10665/373339/WHO-UCN-GMP-2023.01-Rev.1-eng.pdf"
}
@cl.on_chat_start
async def on_chat_start():
settings = await cl.ChatSettings(
[
Select(
id="model",
label="Choose Model",
values=["llama-3.1-8b-instant", "llama-3.1-70b-versatile", "gpt-3.5-turbo", 'llama3-70b-8192', 'llama3-8b-8192','mixtral-8x7b-32768', 'gemma-7b-it'],
initial_index=0,
),
Slider(
id="temperature",
label="Model - Temperature",
initial=1,
min=0,
max=2,
step=0.1,
)]).send()
await setup_agent(settings)
# Let the user know that the system is ready
await cl.Message(content="Hello, I am here to help you with questions on your provided PDF files.").send()
@cl.on_settings_update
async def setup_agent(settings):
embeddings = OpenAIEmbeddings()
docsearch = Pinecone.from_existing_index(index_name=os.getenv("PINECONE_INDEX_NAME"), embedding=embeddings,
namespace=os.getenv("PINECONE_NAME_SPACE"))
retriever = docsearch.as_retriever(search_type="similarity")
message_history = ChatMessageHistory()
memory = ConversationBufferMemory(
memory_key="chat_history",
output_key="answer",
chat_memory=message_history,
return_messages=True,
)
if (settings['model'] == "gpt-3.5-turbo"):
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature = settings['temperature'], streaming=True)
else:
llm = ChatGroq(model_name=settings['model'], temperature = settings['temperature'], streaming= True, api_key=os.getenv("GROQ_API_KEY"))
# Create a chain that uses the Pinecone vector store
chain = ConversationalRetrievalChain.from_llm(
llm,
chain_type="stuff",
retriever=retriever,
memory=memory,
return_source_documents=True,
)
cl.user_session.set("chain", chain)
@cl.on_message
async def main(message: cl.Message):
chain = cl.user_session.get("chain") # type: ConversationalRetrievalChain
cb = cl.AsyncLangchainCallbackHandler()
res = await chain.acall(message.content, callbacks=[cb])
answer = res["answer"]
source_documents = res["source_documents"] # type: List[Document]
print(source_documents)
elements = [] # type: List[cl.Element]
if source_documents:
for source_doc in source_documents:
page_num = source_doc.metadata.get("page", "")
pdf_title = source_doc.metadata.get("source", "")
# Create a text element for the source citation
elements.append(
cl.Text(
content=source_doc.page_content,
name=f"page_{page_num}",
)
)
# Create a list of unique source citations with links
source_citations = []
for doc in source_documents:
if doc.metadata.get('page') and doc.metadata.get('source'):
pdf_title = doc.metadata['source']
# Extract the PDF title and year using regex
match = re.search(r"/(.+?)\s*(\(\d{4}\))\.pdf$", pdf_title)
if match:
pdf_title_short = match.group(1)
year = match.group(2)
page_num = int(doc.metadata['page'])
citation = f"{pdf_title_short} {year}, Page {page_num}"
# Get the URL from the pdf_data dictionary
url = pdf_data.get(f"{pdf_title_short} {year}", "")
if url:
# Create a clickable link to the exact page
citation_link = f"[{citation}]({url}#page={page_num})"
source_citations.append(citation_link)
else:
source_citations.append(citation)
source_citations = list(set(source_citations))
if source_citations:
answer += "\n" + "\n" + "Sources:\n" + "\n".join(source_citations)
else:
answer += "\nNo sources found"
await cl.Message(content=answer, elements=elements).send() | 5,034 | Python | .py | 111 | 35.153153 | 165 | 0.61504 | MaxMLang/RAG-nificent | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,580 | data_ingestion.py | MaxMLang_RAG-nificent/src/data_ingestion.py | import os
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_pinecone import PineconeVectorStore
from langchain_community.document_loaders import PyPDFLoader
from langchain_community.document_loaders import DirectoryLoader
import dotenv
dotenv.load_dotenv()
file_path = '../pdf_data'
directory_loader = DirectoryLoader(file_path, loader_cls=PyPDFLoader)
raw_docs = directory_loader.load()
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200,
)
docs = text_splitter.split_documents(raw_docs)
print('split docs', docs)
print('creating vector store...')
embeddings = OpenAIEmbeddings()
PineconeVectorStore.from_documents(docs, embeddings, index_name=os.getenv("PINECONE_INDEX_NAME"), namespace=os.getenv('PINECONE_NAME_SPACE'))
print('Data ingestion finished') | 882 | Python | .py | 21 | 40.238095 | 141 | 0.832356 | MaxMLang/RAG-nificent | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,581 | test_persist.py | TshineZheng_Filamentor/test/test_persist.py |
import os
import consts
def setup_module():
consts.setup()
def teardown_module():
# 删除 test_channel.txt
import os
os.remove(f'{consts.STORAGE_PATH}pytest.channel')
def test_update_printer_channel():
import utils.persist as persist
persist.update_printer_channel('pytest', 3)
with open(f'{consts.STORAGE_PATH}pytest.channel', 'r') as f:
assert f.read() == '3'
def test_get_printer_channel():
import utils.persist as persist
# 文件不存在
if os.path.exists(f'{consts.STORAGE_PATH}pytest.channel'):
os.remove(f'{consts.STORAGE_PATH}pytest.channel')
assert persist.get_printer_channel('pytest') == 0
# 写个错误的内容
with open(f'{consts.STORAGE_PATH}pytest.channel', 'w') as f:
f.write('a')
assert persist.get_printer_channel('pytest') == 0
# 数值测试
with open(f'{consts.STORAGE_PATH}pytest.channel', 'w') as f:
f.write('11')
assert persist.get_printer_channel('pytest') == 11
with open(f'{consts.STORAGE_PATH}pytest.channel', 'w') as f:
f.write('2')
assert persist.get_printer_channel('pytest') == 2
| 1,150 | Python | .py | 30 | 31.7 | 64 | 0.673221 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,582 | test_bambu_client.py | TshineZheng_Filamentor/test/test_bambu_client.py |
def test_bambu():
from impl.bambu_client import BambuClient, BambuClientConfig
import paho.mqtt.client as mqtt
client = BambuClient(BambuClientConfig("127.0.0.1", 'lan_pwd', "device_serial"))
msg = """
{"print":{"upgrade_state":{"sequence_id":0,"progress":"100","status":"UPGRADE_SUCCESS","consistency_request":false,"dis_state":3,"err_code":0,"force_upgrade":false,"message":"0%, 0B/s","module":"ota","new_version_state":2,"cur_state_code":0,"new_ver_list":[]},"ipcam":{"ipcam_dev":"1","ipcam_record":"disable","timelapse":"disable","resolution":"1080p","tutk_server":"disable","mode_bits":3},"xcam":{"buildplate_marker_detector":true},"upload":{"status":"idle","progress":0,"message":""},"nozzle_temper":212.03125,"nozzle_target_temper":0,"bed_temper":75.0625,"bed_target_temper":0,"chamber_temper":5,"mc_print_stage":"1","heatbreak_fan_speed":"9","cooling_fan_speed":"0","big_fan1_speed":"0","big_fan2_speed":"0","mc_percent":100,"mc_remaining_time":0,"ams_status":0,"ams_rfid_status":0,"hw_switch_state":1,"spd_mag":100,"spd_lvl":2,"print_error":0,"lifecycle":"product","wifi_signal":"-28dBm","gcode_state":"FINISH","gcode_file_prepare_percent":"100","queue_number":0,"queue_total":0,"queue_est":0,"queue_sts":0,"project_id":"13717146","profile_id":"13775275","task_id":"28660947","subtask_id":"28660948","subtask_name":"小圆片","gcode_file":"","stg":[],"stg_cur":255,"print_type":"idle","home_flag":595084688,"mc_print_line_number":"2820","mc_print_sub_stage":0,"sdcard":true,"force_upgrade":false,"mess_production_state":"active","layer_num":2,"total_layer_num":2,"s_obj":[],"filam_bak":[],"fan_gear":0,"nozzle_diameter":"0.4","nozzle_type":"stainless_steel","cali_version":0,"hms":[],"online":{"ahb":false,"rfid":false,"version":2020871969},"ams":{"ams":[],"ams_exist_bits":"0","tray_exist_bits":"0","tray_is_bbl_bits":"0","tray_tar":"254","tray_now":"254","tray_pre":"254","tray_read_done_bits":"0","tray_reading_bits":"0","version":6,"insert_flag":true,"power_on_flag":false},"vt_tray":{"id":"254","tag_uid":"0000000000000000","tray_id_name":"","tray_info_idx":"GFG99","tray_type":"PETG","tray_sub_brands":"","tray_color":"000000FF","tray_weight":"0","tray_diameter":"0.00","tray_temp":"0","tray_time":"0","bed_temp_type":"0","bed_temp":"0","nozzle_temp_max":"270","nozzle_temp_min":"220","xcam_info":"000000000000000000000000","tray_uuid":"00000000000000000000000000000000","remain":0,"k":0.039999999105930328,"n":1,"cali_idx":-1},"lights_report":[{"node":"chamber_light","mode":"off"}],"command":"push_status","msg":0,"sequence_id":"12122"}}
"""
client.process_message(msg) | 2,610 | Python | .py | 8 | 321.75 | 2,347 | 0.674248 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,583 | test_app_config.py | TshineZheng_Filamentor/test/test_app_config.py | import json
from app_config import AppConfig, ChannelRelation, DetectRelation, IDBrokenDetect, IDController, IDPrinterClient
from impl.bambu_client import BambuClient, BambuClientConfig
from impl.mqtt_broken_detect import MQTTBrokenDetect
from impl.yba_ams_controller import YBAAMSController
from mqtt_config import MQTTConfig
def make_config() -> AppConfig:
config = AppConfig()
config.printer_list = [
IDPrinterClient('bambu_1', BambuClient(BambuClientConfig("127.0.0.1", 'lan_pwd', "device_serial"))),
IDPrinterClient('bambu_2', BambuClient(BambuClientConfig("127.0.0.2", 'lan_pwd', "device_serial"))),
]
config.controller_list = [
IDController('yba_ams_1', YBAAMSController('192.168.10.1', 1883, 4)),
IDController('yba_ams_2', YBAAMSController('192.168.10.2', 1883, 3)),
]
config.detect_list = [
IDBrokenDetect('mqtt_detect_1', MQTTBrokenDetect(MQTTConfig('192.168.10.2', 1833, 'client_id', 'username', 'password'))),
IDBrokenDetect('mqtt_detect_2', MQTTBrokenDetect(MQTTConfig('192.168.10.2', 1833, 'client_id', 'username', 'password'))),
]
config.channel_relations = [
ChannelRelation('bambu_1', 'yba_ams_1', 0),
ChannelRelation('bambu_1', 'yba_ams_1', 1),
ChannelRelation('bambu_1', 'yba_ams_1', 2),
# ChannelRelation('bambu_1', 'yba_ams_1', 3),
ChannelRelation('bambu_2', 'yba_ams_2', 0),
ChannelRelation('bambu_2', 'yba_ams_2', 1),
ChannelRelation('bambu_2', 'yba_ams_2', 2),
]
config.detect_relations = [
DetectRelation('bambu_1', 'mqtt_detect_1'),
DetectRelation('bambu_2', 'mqtt_detect_2'),
]
config.mqtt_config = MQTTConfig('192.168.10.1', 1833, 'client_id', 'username', 'password')
return config
def test_app_config_json():
config = make_config()
json_data = json.dumps(config.to_dict(), indent=4)
config.load_from_dict(json.loads(json_data))
assert config.to_dict() == json.loads(json_data)
def test_add_printer():
config = make_config()
bambu_client = BambuClient(BambuClientConfig("127.0.0.3", 'lan_pwd', "device_serial"))
assert config.add_printer('bambu_3', bambu_client) == True
assert config.printer_list[-1].id == 'bambu_3'
assert config.add_printer('bambu_3', bambu_client) == False
def test_remove_printer():
config = make_config()
config.remove_printer('bambu_1')
for i in config.printer_list:
assert i.id != 'bambu_1'
for i in config.channel_relations:
assert i.printer_id != 'bambu_1'
for i in config.detect_relations:
assert i.printer_id != 'bambu_1'
def test_add_controller():
config = make_config()
bambu_client = BambuClient(BambuClientConfig("127.0.0.3", 'lan_pwd', "device_serial"))
assert config.add_controller('yba_ams_3', bambu_client, 'ams1') == True,any
assert config.controller_list[-1].id == 'yba_ams_3'
assert config.add_controller('yba_ams_3', bambu_client,'ams1') == False,any
def test_remove_controller():
config = make_config()
config.remove_controller('yba_ams_1')
for i in config.controller_list:
assert i.id != 'yba_ams_1'
for i in config.channel_relations:
assert i.controller_id != 'yba_ams_1'
def test_add_detect():
config = make_config()
bambu_client = BambuClient(BambuClientConfig("127.0.0.3", 'lan_pwd', "device_serial"))
assert config.add_detect('mqtt_detect_3', bambu_client) == True
assert config.detect_list[-1].id == 'mqtt_detect_3'
assert config.add_detect('mqtt_detect_3', bambu_client) == False
def test_remove_detect():
config = make_config()
config.remove_detect('mqtt_detect_1')
for i in config.detect_list:
assert i.id != 'mqtt_detect_1'
def test_add_channel_relation():
config = make_config()
# 增加已经被使用的通道
assert config.add_channel_setting('bambu_2', 'yba_ams_1', 0) == False
assert config.add_channel_setting('bambu_1', 'yba_ams_2', 0) == False
# 增加一个在控制器中不存在的通道
assert config.add_channel_setting('bambu_1', 'yba_ams_1', 4) == False
# 增加一个通道到一个不存在的打印机
assert config.add_channel_setting('bambu_3', 'yba_ams_1', 0) == False
# 增加一个不存在的控制器到打印机
assert config.add_channel_setting('bambu_1', 'yba_ams_3', 0) == False
# 增加未使用的通道
assert config.add_channel_setting('bambu_1', 'yba_ams_1', 3) == True
def test_remove_channel_relation():
config = make_config()
config.remove_channel_setting('bambu_1', 'yba_ams_1', 0)
for i in config.channel_relations:
assert not (i.printer_id == 'bambu_1' and i.controller_id == 'yba_ams_1' and i.channel==0)
def test_add_detect_relation():
config = make_config()
# 增加已经被使用的检测
assert config.add_detect_setting('bambu_1', 'mqtt_detect_1') == False
# 增加不存在的检测器
assert config.add_detect_setting('bambu_1', 'mqtt_detect_9') == False
# 增加未使用的检测
config.add_detect('mqtt_detect_9', BambuClient(BambuClientConfig("127.0.0.3", 'lan_pwd', "device_serial")))
assert config.add_detect_setting('bambu_1', 'mqtt_detect_9') == True
def test_remove_detect_relation():
config = make_config()
config.remove_detect_setting('bambu_1', 'mqtt_detect_1')
for i in config.detect_relations:
assert i.detect_id != 'mqtt_detect_1'
| 5,616 | Python | .py | 111 | 42.225225 | 133 | 0.656753 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,584 | test_bambu_gcode.py | TshineZheng_Filamentor/test/test_bambu_gcode.py |
def test_get_first_fila_from_gcode_file():
from impl.bambu_client import BambuClient
url = 'https://raw.githubusercontent.com/TshineZheng/Filamentor/main/test/test.3mf'
path = 'Metadata/plate_1.gcode'
fila_channel = BambuClient.get_first_fila_from_gcode(url, path)
assert fila_channel == 0
| 313 | Python | .py | 6 | 47.333333 | 87 | 0.743421 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,585 | broken_detect.py | TshineZheng_Filamentor/src/broken_detect.py | from abc import abstractmethod
from src.base_unit import BaseUnit
class BrokenDetect(BaseUnit):
def __init__(self):
super().__init__()
@staticmethod
@abstractmethod
def type_name() -> str:
pass
@abstractmethod
def to_dict(self) -> dict:
"""保存配置
"""
return {
'safe_time': self.get_safe_time(),
}
@abstractmethod
def start(self):
super().start()
@abstractmethod
def stop(self):
super().stop()
@abstractmethod
def is_filament_broken(self) -> bool:
pass
def get_safe_time(self) -> float:
# 返回一个秒数,用于退料安全距离,默认为 0 s
return 0
| 726 | Python | .py | 28 | 17.535714 | 46 | 0.580093 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,586 | controller.py | TshineZheng_Filamentor/src/controller.py | from abc import abstractmethod
from enum import Enum
from typing import List
from src.base_unit import BaseUnit
from src.broken_detect import BrokenDetect
from src.utils.log import LOGE
class ChannelAction(Enum):
"""控制类型
"""
NONE = -1 # 待机(根据控制器类型自动判断是松开还是送料)
PUSH = 1 # 送
PULL = 2 # 退
STOP = 0 # 停(也可以是松)
class Controller(BaseUnit):
"""料架控制器
"""
@staticmethod
def generate_controller(type: str, info: dict) -> 'Controller':
"""生成控制器
Args:
type (str): 控制器类型
info (dict): 控制器信息
Returns:
Controller: 返回控制器
Exceptions:
ControllerInfoError: 控制器信息错误
ControllerTypeNotMatch: 控制器类型不支持
"""
from src.web.controller.exceptions import ControllerInfoError, ControllerTypeNotMatch
from src.impl.yba_ams_controller import YBAAMSController
from src.impl.yba_ams_py_controller import YBAAMSPYController
from src.impl.yba_ams_servo_controller import YBAAMSServoController
from src.impl.yba_single_buffer_controller import YBASingleBufferController
try:
if type == YBAAMSController.type_name():
return YBAAMSController.from_dict(info)
elif type == YBAAMSPYController.type_name():
return YBAAMSPYController.from_dict(info)
elif type == YBAAMSServoController.type_name():
return YBAAMSServoController.from_dict(info)
elif type == YBASingleBufferController.type_name():
return YBASingleBufferController.from_dict(info)
except:
raise ControllerInfoError()
raise ControllerTypeNotMatch()
@staticmethod
@abstractmethod
def type_name() -> str:
pass
def __init__(self, channel_total: int):
"""构造
Args:
channel_total (int): 通道数量
"""
self.channel_total = channel_total
super().__init__()
@abstractmethod
def start(self):
"""启动控制器
"""
super().start()
@abstractmethod
def stop(self):
"""停止控制器
"""
super().stop()
@abstractmethod
def control(self, channel_index: int, action: ChannelAction) -> bool:
"""控制通道
Args:
channel_index (int): 通道序号, 0 <= channel_index < channel_count
action (ChannelAction): 控制类型
"""
if channel_index < 0 or channel_index >= self.channel_total:
LOGE(f'通道序号 {channel_index} 超出范围')
return False
return True
@abstractmethod
def to_dict(self) -> dict:
"""保存配置
"""
pass
@abstractmethod
def is_initiative_push(self, channel_index: int) -> bool:
"""是否主动送料
Returns:
bool: 是否主动送料
"""
pass
@abstractmethod
def get_channel_states(self) -> List[int]:
"""获取通道状态
Returns:
List[int]: 通道状态
"""
pass
def get_broken_detect(self) -> 'BrokenDetect':
return None
| 3,352 | Python | .py | 98 | 22.877551 | 93 | 0.602234 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,587 | mqtt_config.py | TshineZheng_Filamentor/src/mqtt_config.py | class MQTTConfig:
def __init__(self, server: str = None, port: int = 1883, client_id: str = 'Filamentor-MQTT', username: str = '',
password: str = ''):
self.server = server
self.port = port
self.client_id = client_id
self.username = username
self.password = password
@classmethod
def from_dict(cls, json_data: dict):
return cls(
server=json_data['server'],
port=json_data['port'],
client_id=json_data['client_id'],
username=json_data['username'],
password=json_data['password']
)
def to_dict(self) -> dict:
return {
'server': self.server,
'port': self.port,
'client_id': self.client_id,
'username': self.username,
'password': self.password
}
| 869 | Python | .py | 25 | 24.68 | 116 | 0.534442 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,588 | printer_client.py | TshineZheng_Filamentor/src/printer_client.py | from abc import abstractmethod
from enum import Enum
from typing import Any, Callable
from src.base_unit import BaseUnit
from src.broken_detect import BrokenDetect
class Action(Enum):
CHANGE_FILAMENT = 0 # 更换通道
FILAMENT_SWITCH = 1 # 打印机断料检测器状态改变
TASK_START = 2 # 接到任务
TASK_PREPARE = 3 # 准备开始
TASK_FINISH = 4 # 打印完成
TASK_FAILED = 5 # 打印失败
class FilamentState(Enum):
NO = 0 # 无料
YES = 1 # 有料
UNKNOWN = 2 # 未知
class PrinterClient(BaseUnit):
def __init__(self):
super().__init__()
# action 回调列表
self.action_callbacks: list[Callable[[Action, Any], None]] = []
@staticmethod
@abstractmethod
def type_name() -> str:
"""打印机类型
Returns:
str: 返回打印机的类型
"""
pass
@abstractmethod
def start(self):
"""启动打印机连接
"""
super().start()
@abstractmethod
def stop(self):
"""关闭打印机连接
"""
super().stop()
@abstractmethod
def resume(self):
"""打印机恢复打印,主要用于暂停换料后
"""
pass
@abstractmethod
def on_unload(self, pre_tem: int = 255):
"""卸载时回调
Args:
pre_tem (int, optional): 可用于卸载时提前升温,加快换色速度. Defaults to 255.
"""
pass
@abstractmethod
def refresh_status(self):
"""刷新打印机状态,通过 on action 回调数据
"""
pass
@abstractmethod
def filament_broken_detect(self) -> BrokenDetect:
"""返回打印自己的断料检测器
Returns:
BrokenDetect: 检测器对象
"""
pass
@abstractmethod
def isPrinting(self) -> bool:
"""是否正在打印
Returns:
bool: 是否正在打印
"""
pass
@abstractmethod
def to_dict(self) -> dict:
"""输出打印机的相关配置
"""
pass
def add_on_action(self, callback: Callable[[Action, Any], None]):
"""增加 on action 回调
Args:
callback (Callable[[Action, Any], None]): 回调函数
"""
self.action_callbacks.append(callback)
def remove_on_action(self, callback: Callable[[Action, Any], None]):
"""移除 on action 回调
Args:
callback (Callable[[Action, Any], None]): 回调函数
"""
if callback in self.action_callbacks:
self.action_callbacks.remove(callback)
def on_action(self, action: Action, data: Any = None):
"""回调派发, 打印机的信息派发给所有订阅的回调
Args:
action (Action): 动作
data (Any, optional): 动作数据. Defaults to None.
"""
for callback in self.action_callbacks:
callback(action, data)
| 3,013 | Python | .py | 96 | 19.479167 | 72 | 0.567176 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,589 | core_services.py | TshineZheng_Filamentor/src/core_services.py | def stop():
import src.ams_core as ams_core
import src.app_config as app_config
from src.utils.log import LOGI
LOGI('关闭所有连接')
# stop all
for a in ams_core.ams_list:
a.stop()
for p in app_config.config.printer_list:
p.client.stop()
for c in app_config.config.controller_list:
c.controller.stop()
for d in app_config.config.detect_list:
d.detect.stop()
def start():
import src.ams_core as ams_core
import src.app_config as app_config
from src.utils.log import LOGI
LOGI('启动所有连接')
# 启动所有控制器
for c in app_config.config.controller_list:
c.controller.start()
# 启动所有断料检测
for d in app_config.config.detect_list:
d.detect.start()
ams_core.ams_list.clear()
# 启动所有打印机 和 对应AMS 连接
for p in app_config.config.printer_list:
p.client.start()
ams = ams_core.AMSCore(p.id)
ams.start()
ams_core.ams_list.append(ams)
def restart():
stop()
start()
def hasPrintTaskRunning():
from src.ams_core import ams_list
#TODO: 这里没有分开判断,需要优化
for a in ams_list:
if a.hasTask():
return True
return False | 1,281 | Python | .py | 42 | 22.071429 | 47 | 0.64191 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,590 | consts.py | TshineZheng_Filamentor/src/consts.py | STORAGE_PATH = 'data/' # 数据存储目录
FIX_Z = False
FIX_Z_GCODE = None
# FIX_Z_TEMP = None
FIX_Z_PAUSE_COUNT = None
PAUSE_Z_OFFSET = 3.0
DO_HOME_Z_HEIGHT = 10.0
LAYER_HEIGHT = 0.2
def setup():
import os
if not os.path.exists(STORAGE_PATH):
os.mkdir(STORAGE_PATH)
global FIX_Z
global FIX_Z_GCODE
# global FIX_Z_TEMP
global FIX_Z_PAUSE_COUNT
global PAUSE_Z_OFFSET
global DO_HOME_Z_HEIGHT
global LAYER_HEIGHT
FIX_Z = True if os.getenv("FIX_Z", '0') == '1' else False
# FIX_Z_TEMP = int(os.getenv("FIX_Z_TEMP", '0'))
FIX_Z_PAUSE_COUNT = int(os.getenv("FIX_Z_PAUSE_COUNT", '0'))
PAUSE_Z_OFFSET = float(os.getenv("PAUSE_Z_OFFSET", '3'))
DO_HOME_Z_HEIGHT = float(os.getenv("DO_HOME_Z_HEIGHT", '170.0'))
LAYER_HEIGHT = float(os.getenv("LAYER_HEIGHT", '0.2'))
fix_z_gcode_path = os.getenv("FIX_Z_GCODE")
if FIX_Z and fix_z_gcode_path:
from src.utils.log import LOGI, LOGE
# LOGI(f'FIX_Z_TEMP: {FIX_Z_TEMP}')
LOGI(f'FIX_Z_PAUSE_COUNT: {FIX_Z_PAUSE_COUNT}')
LOGI(f'PAUSE_Z_OFFSET: {PAUSE_Z_OFFSET}')
LOGI(f'DO_HOME_Z_HEIGHT: {DO_HOME_Z_HEIGHT}')
LOGI(f'LAYER_HEIGHT: {LAYER_HEIGHT}')
LOGI(f'Z 轴抬高 gcode 文件路径为:{fix_z_gcode_path}')
try:
with open(fix_z_gcode_path, 'r') as f:
FIX_Z_GCODE = f.read().replace('\n', '\\n')
LOGI('修复 Z 轴抬高 gcode 读取成功')
except Exception as e:
LOGE(f'修复 Z 轴抬高文件读取失败:{fix_z_gcode_path}')
LOGE(e)
| 1,598 | Python | .py | 41 | 30.804878 | 68 | 0.59973 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,591 | ams_core.py | TshineZheng_Filamentor/src/ams_core.py | import threading
import time
from datetime import datetime
from typing import Callable, List
import src.printer_client as printer
from src.controller import ChannelAction, Controller
from src.utils.log import TAGLOG
import src.utils.persist as persist
from src.app_config import config
LOAD_TIMEOUT = 30 # 装料超时,超时会尝试抖动耗材
LOAD_WARNING = 120 # 装料失败警告时间
UNLOAD_TIMEOUT = 30 # 退料超时,超时会尝试抖动耗材
UNLOAD_WARNING = 120 # 退料失败警告时间
PRINTER_UNLOAD_TIMEOUT = 5 # 打印机退料超时
PRINTER_UNLOAD_WARNING = 20 # 打印机退料失败警告时间
class AMSCore(TAGLOG):
def __init__(
self,
use_printer: str
) -> None:
self.use_printer = use_printer
self.fila_cur = persist.get_printer_channel(use_printer)
self.fila_next = 0
self.change_count = 0
self.fila_changing = False
self.task_name = None
self.task_log_id = None
self.printer_fila_state = printer.FilamentState.UNKNOWN
self.printer_client = config.get_printer(use_printer)
self.change_tem = config.get_printer_change_tem(use_printer)
self.broken_detects = config.get_printer_broken_detect(use_printer)
if self.broken_detects is None or len(self.broken_detects) == 0:
self.broken_detects = [self.printer_client.filament_broken_detect()] # 如果没有自定义断线检测,使用打印默认的
self.LOGI('没有配置断料检测器,若控制器没有断料检测,默认将使用打印机自己的断料检测器')
self.channels: List[tuple[Controller, int]] = [] # 控制器对象, 通道在控制器上的序号
for c in config.get_printer_channel_settings(use_printer):
self.channels.append([config.get_controller(c.controller_id), c.channel])
self.LOGI(f'通道数量: {len(self.channels)}, 断料检测器数量: {len(self.broken_detects)}, 当前通道: {self.fila_cur+1}')
for c, i in self.channels:
self.LOGD(f'通道: {c.type_name()} {i}')
for bd in self.broken_detects:
self.LOGD(f'断料检测器: {bd.type_name()}')
def tag(self):
return self.use_printer
def driver_control(self, printer_ch: int, action: ChannelAction = ChannelAction.NONE):
"""控制通道
Args:
printer_ch (int): 打印机通道
action (ChannelAction, optional): 通道动作, 如果动作为ChannelAction.NONE, 则自动根据控制器类型设置待机状态. Defaults to ChannelAction.NONE.
"""
# FIXME: 这里最好加个任务结束判断,避免任务结束后,还在自动控制通道动作
c, i = self.channels[printer_ch]
if action == ChannelAction.NONE:
action = ChannelAction.PUSH if c.is_initiative_push(i) else ChannelAction.STOP
c.control(i, action)
self.LOGD(f'{action} {printer_ch} ({c.type_name()} {i})')
def on_resumed(self):
self.driver_control(self.fila_cur, ChannelAction.NONE)
def is_filament_broken(self, printer_ch: int) -> bool:
"""当所有断料检测器都没有料时,返回 True
Returns:
bool: _description_
"""
# 如果控制器有自己的断料检测器,则只判断控制器是否断料
c, i = self.channels[printer_ch]
if c.get_broken_detect() is not None:
return c.get_broken_detect().is_filament_broken()
# 否则,判断所有断料检测器是否断料
for bd in self.broken_detects:
if bd.is_filament_broken() is not True:
return False
return True
def get_pull_safe_time(self, printer_ch: int) -> int:
# 如果控制器有自己的断料检测器,则返回控制器的退料时间
c, i = self.channels[printer_ch]
if c.get_broken_detect() is not None:
return c.get_broken_detect().get_safe_time()
# 否则,返回所有断料检测器最大的退料时间
return max([bd.get_safe_time() for bd in self.broken_detects])
def fila_shake(self, channel: int, action: ChannelAction, shake_time=1):
self.driver_control(channel, ChannelAction.PULL if action == ChannelAction.PUSH else ChannelAction.PUSH)
time.sleep(shake_time)
self.driver_control(channel, ChannelAction.PUSH if action == ChannelAction.PUSH else ChannelAction.PULL)
def on_printer_action(self, action: printer.Action, data):
self.LOGD(f'收到打印机 {self.use_printer} 消息 {action} {"" if data is None else data}')
if action == printer.Action.CHANGE_FILAMENT:
self.run_filament_change(data['next_extruder'], data['next_filament_temp'])
if action == printer.Action.FILAMENT_SWITCH:
self.printer_fila_state = data
if action == printer.Action.TASK_START:
self.__on_task_started(data['subtask_name'], data['first_filament'])
if action == printer.Action.TASK_FINISH:
self.__on_task_stopped(action)
if action == printer.Action.TASK_FAILED:
self.__on_task_stopped(action)
def __on_task_started(self, task_name: str, first_filament: int):
self.fila_changing = False
self.task_name = task_name
self.change_count = 0 # 重置换色次数
self.start_task_log() # 开始记录打印日志
self.LOGI(f"接到打印任务: {self.task_name}, 第一个通道: {first_filament + 1}")
if first_filament < 0 or first_filament >= len(self.channels):
self.LOGE(f'开始通道{first_filament}不正常')
# TODO: 如果打印机没有料,就不要送料了,且提示用户进那个料
self.driver_control(self.fila_cur, ChannelAction.NONE)
if first_filament != self.fila_cur:
self.LOGI("打印的第一个通道不是AMS当前通道, 需要换色")
def __on_task_stopped(self, action: printer.Action):
# TODO: 最好能强制通知所有通道,后续优化
self.driver_control(self.fila_next, ChannelAction.STOP) # 有可能是换料过程中停止打印,所以要考虑未换料完成的情况
time.sleep(1)
self.driver_control(self.fila_cur, ChannelAction.STOP)
if self.task_log_id:
self.LOGI(f"{self.task_name} {'打印完成' if action == printer.Action.TASK_FINISH else '打印失败'}")
self.task_name = None
self.stop_task_log()
def start_task_log(self):
from loguru import logger as LOG
import src.consts as consts
self.task_log_id = LOG.add(
sink=f'{consts.STORAGE_PATH}/logs/task/{datetime.now().strftime("%Y%m%d-%H%M%S")}_{self.task_name}.log',
enqueue=True,
encoding='utf-8',
backtrace=True,
diagnose=True,
)
def stop_task_log(self):
if self.task_log_id is not None:
from loguru import logger as LOG
LOG.remove(self.task_log_id)
self.task_log_id = None
def start(self):
# TODO: 判断打印机是否有料,如果有料则仅送料,否则需要送料并调用打印机加载材料
# TODO: 如果可以,最好能自主判断当前打印机的料是哪个通道
self.printer_client.add_on_action(self.on_printer_action)
self.printer_client.refresh_status()
self.LOGI('AMS 启动')
def stop(self):
self.printer_client.remove_on_action(self.on_printer_action)
def hasTask(self):
return self.printer_client.isPrinting()
def run_filament_change(self, next_filament: int, next_filament_temp: int, before_done: Callable = None):
if self.fila_changing:
return
if not self.hasTask():
return
self.fila_changing = True
self.thread = threading.Thread(
target=self.filament_change, args=(next_filament, next_filament_temp, before_done,))
self.thread.start()
def update_cur_fila(self, fila: int):
self.fila_cur = fila
persist.update_printer_channel(self.use_printer, self.fila_cur)
def filament_change(self, next_filament: int, next_filament_temp: int, before_done: Callable = None):
# FIXME: 要增加通道不匹配的判断,比如接到换第4通道,结果我们只有3通道,可以呼叫用户确认,再继续
self.change_count += 1
self.fila_next = next_filament
self.LOGI(f'第 {self.change_count} 次换色, 当前通道 {self.fila_cur + 1},下个通道 {self.fila_next + 1}')
if self.fila_cur == self.fila_next:
self.printer_client.resume()
self.LOGI("通道相同,无需换色, 恢复打印")
self.fila_changing = False
return
self.driver_control(self.fila_cur, ChannelAction.STOP) # 停止当前通道
time.sleep(0.5)
self.LOGI(f"打印机开始回退耗材")
self.printer_client.on_unload(next_filament_temp)
self.LOGI(f'通道 {self.fila_cur + 1} 开始回抽')
self.driver_control(self.fila_cur, ChannelAction.PULL) # 回抽当前通道
# 等待打印机小绿点消失,如果超过一定时间,估计是卡五通了
ts = datetime.now().timestamp()
max_unload_time = ts + PRINTER_UNLOAD_WARNING
while self.printer_fila_state != printer.FilamentState.NO:
if not self.hasTask():
return
if max_unload_time < datetime.now().timestamp():
self.LOGI("打印机耗材退不出来,摇人吧(需要手动把料从打印机的头上撤回)")
# TODO: 发出警报
time.sleep(2)
elif datetime.now().timestamp() - ts > PRINTER_UNLOAD_TIMEOUT:
self.printer_client.refresh_status()
self.LOGI(f"打印机退料卡头了?都{PRINTER_UNLOAD_TIMEOUT}秒了,小绿点还没消失,抖一下")
self.fila_shake(self.fila_next, ChannelAction.PULL)
ts = datetime.now().timestamp()
self.LOGI("打印机退料完成")
ts = datetime.now().timestamp()
max_pull_time = ts + UNLOAD_WARNING # 最大退料时间,如果超出这个时间,则提醒用户
# 等待所有断料检测器都没有料
while not self.is_filament_broken(self.fila_cur):
if not self.hasTask():
return
if max_pull_time < datetime.now().timestamp():
self.LOGI("退不出来,摇人吧(需要手动把料撤回)")
# TODO: 发出警报
elif datetime.now().timestamp() - ts > UNLOAD_TIMEOUT:
self.LOGI("退料超时,抖一抖")
self.fila_shake(self.fila_cur, ChannelAction.PULL)
ts = datetime.now().timestamp()
time.sleep(2)
self.LOGI("退料检测到位")
safe_time = self.get_pull_safe_time(self.fila_cur)
if safe_time > 0:
time.sleep(safe_time) # 再退一点
self.LOGI("退料到安全距离")
self.driver_control(self.fila_cur, ChannelAction.STOP) # 停止抽回
time.sleep(1) # 休息下呗,万一板子反映不过来呢
# 强行让打印机材料状态变成无,避免万一竹子消息延迟或什么的,不要完全相信别人的接口,如果可以自己判断的话(使用自定义断料检测器有效)
self.printer_fila_state = printer.FilamentState.NO
self.driver_control(self.fila_next, ChannelAction.PUSH) # 输送下一个通道
self.LOGI(f"开始输送下一个通道 {self.fila_next + 1}")
ts = datetime.now().timestamp()
max_push_time = ts + LOAD_WARNING # 最大送料时间,如果超出这个时间,则提醒用户
# 到料目前还只能通过打印机判断,只能等了,不断刷新
while self.printer_fila_state != printer.FilamentState.YES: # 等待打印机料线到达
if not self.hasTask():
return
if max_push_time < datetime.now().timestamp():
self.LOGI("送不进去,摇人吧(需要手动把料送进去)")
self.driver_control(self.fila_next, ChannelAction.STOP) # 送不进去就停止送料
time.sleep(2)
# TODO: 发出警报
elif datetime.now().timestamp() - ts > LOAD_TIMEOUT:
self.LOGI("送料超时,抖一抖")
self.fila_shake(self.fila_next, ChannelAction.PUSH)
self.printer_client.refresh_status()
ts = datetime.now().timestamp()
self.update_cur_fila(self.fila_next)
self.LOGI("料线到达,换色完成")
if before_done:
before_done()
self.printer_client.resume()
self.LOGI("恢复打印")
self.on_resumed()
self.fila_changing = False
ams_list: list[AMSCore] = []
| 13,118 | Python | .py | 235 | 37.310638 | 126 | 0.626062 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,592 | main.py | TshineZheng_Filamentor/src/main.py | from fastapi import FastAPI
import src.web as web
app = FastAPI()
web.init(app)
@app.on_event("startup")
async def startup_event():
from loguru import logger
import sys
import src.consts as consts
import src.core_services as core_services
import src.web.front as front
from dotenv import load_dotenv
load_dotenv()
logger.remove(0)
logger.add(sys.stderr, level="INFO")
consts.setup()
core_services.start()
front.start()
@app.on_event("shutdown")
async def shutdown_event():
import src.core_services as core_services
import src.web.front as front
core_services.stop()
front.stop()
| 651 | Python | .py | 24 | 23.125 | 45 | 0.723748 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,593 | base_unit.py | TshineZheng_Filamentor/src/base_unit.py | from abc import ABC, abstractmethod
class BaseUnit(ABC):
def __init__(self):
self.is_running = False
@abstractmethod
def start(self):
self.is_running = True
@abstractmethod
def stop(self):
self.is_running = False
def get_sync_info(self) -> dict:
"""同步时返回的信息
Returns:
dict: 同步内容
"""
return {}
| 414 | Python | .py | 16 | 17.25 | 36 | 0.576087 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,594 | app_config.py | TshineZheng_Filamentor/src/app_config.py | import json
import os
from typing import List, Tuple
from src import consts
from src.broken_detect import BrokenDetect
from src.controller import Controller
from src.impl.bambu_client import BambuClient
from src.impl.mqtt_broken_detect import MQTTBrokenDetect
from src.impl.yba_ams_controller import YBAAMSController
from src.impl.yba_ams_py_controller import YBAAMSPYController
from src.impl.yba_ams_servo_controller import YBAAMSServoController
from src.impl.yba_single_buffer_controller import YBASingleBufferController
from src.mqtt_config import MQTTConfig
from src.printer_client import PrinterClient
from src.utils.log import LOGE, LOGI
class ChannelRelation:
def __init__(self, printer_id: str, controller_id: str, channel: int, filament_type: str = 'GENERAL',
filament_color: str = '#FFFFFF') -> None:
"""打印机和通道的绑定关系
Args:
printer_id (str): 打印机ID
controller_id (str): 通道板子ID
channel (int): 通道在板子上的编号
"""
self.printer_id = printer_id
self.controller_id = controller_id
self.channel = channel
self.filament_type = filament_type
self.filament_color = filament_color
def to_dict(self):
return {
"printer_id": self.printer_id,
"controller_id": self.controller_id,
"channel": self.channel,
"filament_type": self.filament_type,
"filament_color": self.filament_color
}
@classmethod
def from_dict(cls, data: dict):
return cls(
data["printer_id"],
data["controller_id"],
data["channel"],
data["filament_type"],
data["filament_color"]
)
class DetectRelation:
"""打印机和断料检测器的绑定关系
Aegs:
printer_id (str): 打印机ID
detect_id (str): 检测器ID
"""
def __init__(self, printer_id: str, detect_id: str) -> None:
self.printer_id = printer_id
self.detect_id = detect_id
def to_dict(self):
return {
"printer_id": self.printer_id,
"detect_id": self.detect_id
}
@classmethod
def from_dict(cls, data: dict):
return cls(
data["printer_id"],
data["detect_id"]
)
class IDPrinterClient:
def __init__(self, id: str, client: PrinterClient, change_temp: int = 255, alias: str = None) -> None:
self.id = id
self.client = client
self.change_temp = change_temp
self.alias = alias
def to_dict(self):
return {
"id": self.id,
'type': self.client.type_name(),
"alias": self.alias,
"info": self.client.to_dict(),
"change_temp": self.change_temp
}
@classmethod
def from_dict(cls, data: dict):
id = data["id"]
type = data["type"]
change_temp = data["change_temp"]
alias = data["alias"]
client = None
if type == BambuClient.type_name():
client = BambuClient.from_dict(data["info"])
return cls(id, client, change_temp, alias)
class IDController:
def __init__(self, id: str, controller: Controller, alias: str = None) -> None:
self.id = id
self.controller = controller
self.alias = alias
def to_dict(self):
return {
"id": self.id,
'type': self.controller.type_name(),
"alias": self.alias,
"info": self.controller.to_dict()
}
@classmethod
def from_dict(cls, data: dict):
id = data["id"]
type = data["type"]
alias = data["alias"]
controller = Controller.generate_controller(type, data["info"])
return cls(id, controller, alias)
class IDBrokenDetect:
def __init__(self, id: str, detect: BrokenDetect, alias: str = None) -> None:
self.id = id
self.detect = detect
self.alias = alias
def to_dict(self):
return {
"id": self.id,
'type': self.detect.type_name(),
"alias": self.alias,
"info": self.detect.to_dict()
}
@classmethod
def from_dict(cls, data: dict):
id = data["id"]
type = data["type"]
alias = data["alias"]
detect = None
if type == MQTTBrokenDetect.type_name():
detect = MQTTBrokenDetect.from_dict(data["info"])
return cls(id, detect, alias)
class AMSSettings:
def __init__(self, cur_filament: int, change_temp: int) -> None:
pass
class AppConfig():
def __init__(self) -> None:
self.printer_list: List[IDPrinterClient] = []
self.controller_list: List[IDController] = []
self.detect_list: List[IDBrokenDetect] = []
self.channel_relations: List[ChannelRelation] = []
self.detect_relations: List[DetectRelation] = []
self.mqtt_config: MQTTConfig = MQTTConfig()
self.load_from_file()
def load_from_dict(self, data: dict):
if "printer_list" in data:
self.printer_list = [IDPrinterClient.from_dict(i) for i in data["printer_list"]]
if "controller_list" in data:
self.controller_list = [IDController.from_dict(i) for i in data["controller_list"]]
if "detect_list" in data:
self.detect_list = [IDBrokenDetect.from_dict(i) for i in data["detect_list"]]
if "channel_relations" in data:
self.channel_relations = [ChannelRelation.from_dict(i) for i in data["channel_relations"]]
if "detect_relations" in data:
self.detect_relations = [DetectRelation.from_dict(i) for i in data["detect_relations"]]
if "mqtt_config" in data:
self.mqtt_config = MQTTConfig.from_dict(data["mqtt_config"])
def load_from_file(self):
if not os.path.exists(f'{consts.STORAGE_PATH}filamentor_config.json'):
LOGI("没有找到配置文件,忽略")
return
try:
with open(f'{consts.STORAGE_PATH}filamentor_config.json', 'r') as f:
data = json.load(f)
self.load_from_dict(data)
except Exception as e:
LOGE(f"读取配置文件失败{e}")
pass
def to_dict(self):
return {
"printer_list": [i.to_dict() for i in self.printer_list],
"controller_list": [i.to_dict() for i in self.controller_list],
"detect_list": [i.to_dict() for i in self.detect_list],
"channel_relations": [i.to_dict() for i in self.channel_relations],
"detect_relations": [i.to_dict() for i in self.detect_relations],
"mqtt_config": self.mqtt_config.to_dict()
}
def save(self):
with open(f'{consts.STORAGE_PATH}filamentor_config.json', 'w') as f:
json.dump(self.to_dict(), f, ensure_ascii=False, indent=4)
def add_printer(self, id: str, client: PrinterClient, alias: str, change_temp: int):
self.printer_list.append(IDPrinterClient(id, client, change_temp=change_temp, alias=alias))
def remove_printer(self, id: str):
for p in self.printer_list[:]:
if p.id == id:
self.printer_list.remove(p)
# 删除所有控制器和检测的引用
for c in self.channel_relations[:]:
if c.printer_id == id:
self.channel_relations.remove(c)
for d in self.detect_relations[:]:
if d.printer_id == id:
self.detect_relations.remove(d)
return
def add_controller(self, id: str, controller: Controller, alias: str) -> Tuple[bool, str]:
# 确保控制器不重复
for p in self.controller_list:
if p.controller.type_name() == controller.type_name():
# YBA-AMS like controller exists
if controller.type_name() == YBAAMSController.type_name() or controller.type_name() == YBAAMSPYController.type_name() or controller.type_name() == YBAAMSServoController.type_name() or controller.type_name() == YBASingleBufferController.type_name():
if isinstance(controller, (YBAAMSController, YBAAMSPYController, YBAAMSServoController, YBASingleBufferController)):
if p.controller.ip == controller.ip:
return False, '控制器已存在'
self.controller_list.append(IDController(id, controller, alias))
return True, '控制器创建成功'
def remove_controller(self, id: str):
for p in self.controller_list[:]:
if p.id == id:
self.controller_list.remove(p)
# 删除所有该控制器的通道引用
for c in self.channel_relations[:]:
if c.controller_id == id:
self.channel_relations.remove(c)
def add_detect(self, id: str, detect: BrokenDetect, alias: str) -> bool:
# 确保id不重复
for p in self.detect_list:
if p.id == id:
return False
self.detect_list.append(IDBrokenDetect(id, detect, alias))
return True
def remove_detect(self, id: str):
for p in self.detect_list[:]:
if p.id == id:
self.detect_list.remove(p)
# 删除所有检测器的引用
for c in self.detect_relations[:]:
if c.detect_id == id:
self.detect_relations.remove(c)
def add_channel_setting(self, printer_id: str, controller_id: str, channel: int) -> bool:
if not self.is_printer_exist(printer_id):
return False
if not self.is_channel_exist(controller_id, channel):
return False
if self.is_channel_relation_exist(controller_id, channel):
return False
self.channel_relations.append(ChannelRelation(printer_id, controller_id, channel))
return True
def remove_channel_setting(self, printer_id: str, controller_id: str, channel_id: int):
for p in self.channel_relations[:]:
if controller_id == p.controller_id and channel_id == p.channel and printer_id == p.printer_id:
self.channel_relations.remove(p)
def add_detect_setting(self, printer_id: str, detect_id: str) -> bool:
if not self.is_detect_exist(detect_id):
return False
# 确保控制器的通道只被添加一次
if self.is_detect_relation_exist(detect_id):
return False
self.detect_relations.append(DetectRelation(printer_id, detect_id))
return True
def remove_detect_setting(self, printer_id: str, detect_id: str):
for p in self.detect_relations[:]:
if printer_id == p.printer_id and detect_id == p.detect_id:
self.detect_relations.remove(p)
def is_printer_exist(self, id: str) -> bool:
for p in self.printer_list:
if p.id == id:
return True
return False
def is_channel_exist(self, controller_id: str, channel_id: int) -> bool:
for p in self.controller_list:
if p.id == controller_id:
if channel_id < p.controller.channel_total and channel_id >= 0:
return True
return False
def is_detect_exist(self, id: str) -> bool:
for p in self.detect_list:
if p.id == id:
return True
return False
def is_channel_relation_exist(self, controller_id: str, channel_index: int) -> bool:
for p in self.channel_relations:
if p.controller_id == controller_id and p.channel == channel_index:
return True
return False
def is_detect_relation_exist(self, detect_id: str) -> bool:
for p in self.detect_relations:
if p.detect_id == detect_id:
return True
return False
def get_printer_channel_settings(self, printer_id: str) -> List[ChannelRelation]:
return [p for p in self.channel_relations if p.printer_id == printer_id]
def get_printer(self, printer_id: str) -> PrinterClient:
for p in self.printer_list:
if p.id == printer_id:
return p.client
return None
def get_printer_change_tem(self, printer_id: str) -> int:
for p in self.printer_list:
if p.id == printer_id:
return p.change_temp
return 255
def set_printer_change_tem(self, printer_id: str, tem: int):
for p in self.printer_list:
if p.id == printer_id:
p.change_temp = tem
self.save()
return
def get_printer_broken_detect(self, printer_id: str) -> List[BrokenDetect]:
t = [p for p in self.detect_relations if p.printer_id == printer_id]
return [p.detect for p in self.detect_list if p.id in [d.detect_id for d in t]]
def get_controller(self, controller_id: str) -> Controller:
for p in self.controller_list:
if p.id == controller_id:
return p.controller
return None
config = AppConfig()
| 13,298 | Python | .py | 304 | 32.575658 | 264 | 0.593928 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,595 | yba_ams_controller.py | TshineZheng_Filamentor/src/impl/yba_ams_controller.py | import threading
import time
from typing import List
from src.controller import ChannelAction, Controller
import socket
from src.utils.log import LOGE, LOGI
ams_head = b'\x2f\x2f\xff\xfe\x01\x02'
class YBAAMSController(Controller):
@staticmethod
def type_name() -> str:
return "yba_ams"
def __init__(self, ip: str, port: int, channel_count: int):
super().__init__(channel_count)
self.ip: str = ip
self.port: str = port
self.sock: socket.socket = None
self.ch_state: List[int] = [0] * channel_count
self.thread: threading.Thread = None
self.lock = threading.Lock()
def __eq__(self, other):
if isinstance(other, YBAAMSController):
return self.ip == other.ip
return False
def get_channel_states(self) -> List[int]:
return self.ch_state
def __str__(self):
return self.type_name()
@classmethod
def from_dict(cls, json_data: dict):
return cls(
json_data["ip"],
json_data["port"],
json_data["channel_total"]
)
def to_dict(self) -> dict:
return {
'ip': self.ip,
'port': self.port,
'channel_total': self.channel_total
}
def start(self):
super().start()
self.connect()
self.thread = threading.Thread(target=self.heartbeat, name=f"yba-ams({self.ip}) heartbeat")
self.thread.start()
def stop(self):
super().stop()
self.disconnect()
if self.thread:
self.thread.join()
self.sock = None
self.thread = None
def connect(self):
self.disconnect()
if self.is_running:
self.sock = self.connect_to_server(self.ip, self.port)
def disconnect(self):
if self.sock:
try:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
self.sock = None
except Exception as e:
LOGE(f"关闭socket失败: {e}")
# 向YBA发送指令
def send_ams(self, data):
"""发送数据到服务器,如果连接断开,自动重新连接并重新发送"""
if self.sock is None:
self.connect()
while True:
try:
self.sock.settimeout(3)
self.sock.sendall(data)
self.sock.settimeout(None)
return
except Exception as e:
LOGE(f"向YBA发送指令失败: {e}")
LOGE("尝试重新连接...")
self.connect()
LOGE("重新连接成功,尝试再次发送")
def ams_control(self, ch, fx):
self.send_ams(ams_head + bytes([ch]) + bytes([fx]))
self.ch_state[ch] = fx
def connect_to_server(self, server_ip, server_port):
"""尝试连接到服务器,并返回socket对象"""
while True:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((server_ip, server_port))
LOGI(f"连接到 YBA-AMS ({server_ip})成功")
return sock
except Exception as e:
LOGE(f"连接到 YBA-AMS 失败: {e}")
LOGE("2秒后尝试重新连接...")
time.sleep(2)
def heartbeat(self):
while self.is_running:
if self.sock is None:
time.sleep(1)
else:
for t in range(5):
for i in self.channel_total:
if not self.is_running:
break
self.ams_control(i, self.ch_state[i]) # 心跳+同步状态 先这样写,后面再改
time.sleep(0.3)
time.sleep(1)
def control(self, channel_index: int, action: ChannelAction) -> bool:
if False == super().control(channel_index, action):
return False
if action == ChannelAction.PUSH:
self.ams_control(channel_index, 1)
elif action == ChannelAction.PULL:
self.ams_control(channel_index, 2)
elif action == ChannelAction.STOP:
self.ams_control(channel_index, 0)
return True
def is_initiative_push(self, channel_index: int) -> bool:
return True
| 4,392 | Python | .py | 119 | 24.10084 | 99 | 0.538442 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,596 | bambu_client.py | TshineZheng_Filamentor/src/impl/bambu_client.py | from datetime import datetime
import json
import math
import os
import ssl
import threading
import time
from typing import Any
import paho.mqtt.client as mqtt
from src import consts
from src.broken_detect import BrokenDetect
import src.utils.gcode_util as gcode_util
from src.utils.json_util import ast
from src.utils.log import LOGD, LOGE, LOGI, LOGW, TAGLOG
from src.printer_client import Action, FilamentState, PrinterClient
# 定义服务器信息和认证信息
MQTT_PORT = 8883
BAMBU_CLIENT_ID = "Filamentor-Bambu-Client"
# noinspection SpellCheckingInspection
USERNAME = "bblp"
bambu_resume = '{"print":{"command":"resume","sequence_id":"1"},"user_id":"1"}'
bambu_pause = '{"print": {"sequence_id": "0","command": "pause","param": ""}}'
bambu_unload = '{"print":{"command":"ams_change_filament","curr_temp":220,"sequence_id":"1","tar_temp":220,"target":255},"user_id":"1"}'
bambu_load = '{"print":{"command":"ams_change_filament","curr_temp":220,"sequence_id":"1","tar_temp":220,"target":254},"user_id":"1"}'
bambu_done = '{"print":{"command":"ams_control","param":"done","sequence_id":"1"},"user_id":"1"}'
bambu_clear = '{"print":{"command": "clean_print_error","sequence_id":"1"},"user_id":"1"}'
bambu_status = '{"pushing": {"sequence_id": "0", "command": "pushall"}}'
bambu_start_push = '{"pushing": {"sequence_id": "0", "command": "start"}}'
MAGIC_CHANNEL = 1000
MAGIC_COMMAND = 2000
MAGIC_AWAIT = MAGIC_COMMAND
class BambuClientConfig(object):
def __init__(self, printer_ip: str, lan_password: str, device_serial: str) -> None:
self.printer_ip = printer_ip
self.lan_password = lan_password
self.device_serial = device_serial
class BambuClient(PrinterClient, TAGLOG):
_watchdog = None
@staticmethod
def type_name() -> str:
return "bambu_client"
def tag(self):
return self.type_name()
def __eq__(self, other):
if isinstance(other, BambuClient):
return self.config.printer_ip == other.config.printer_ip
return False
def __init__(self, config: BambuClientConfig):
super().__init__()
self.fbd = BambuBrokenDetect(self)
self.config = config
self.TOPIC_SUBSCRIBE = f"device/{config.device_serial}/report"
self.TOPIC_PUBLISH = f"device/{config.device_serial}/request"
client = mqtt.Client(client_id=BAMBU_CLIENT_ID)
# 设置回调函数
client.on_connect = self.on_connect
client.on_disconnect = self.on_disconnect
client.on_message = self.on_message
client.reconnect_delay_set(min_delay=1, max_delay=1)
client.tls_set(tls_version=ssl.PROTOCOL_TLS, cert_reqs=ssl.CERT_NONE)
client.tls_insecure_set(True)
# 设置用户名和密码
client.username_pw_set(USERNAME, config.lan_password)
self.client = client
self.clean()
self.read_env()
def read_env(self):
self.change_count = int(os.getenv("CHANGE_COUNT", '0'))
self.latest_home_change_count = int(os.getenv("LATEST_HOME_CHANGE_COUNT", '0'))
LOGI(f'CHANGE_COUNT: {self.change_count}')
LOGI(f'LATEST_HOME_CHANGE_COUNT: {self.latest_home_change_count}')
def isPrinting(self):
return self.print_status == 'PAUSE' or self.print_status == 'RUNNING'
def clean(self):
self.wating_pause_flag = False
self.mc_percent = 0
self.mc_remaining_time = 0
self.magic_command = 0
self.cur_layer = 0
self.new_fila_temp = 0
self.pre_fila_temp = 0
self.next_extruder = -1
self.change_count = 0
self.latest_home_change_count = 0
self.gcodeInfo = gcode_util.GCodeInfo()
self.print_status = 'unkonw'
# self.trigger_pause = False
@classmethod
def from_dict(cls, config: dict):
return cls(
BambuClientConfig(
config["printer_ip"],
config["lan_password"],
config["device_serial"]
))
def to_dict(self) -> dict:
return {
'printer_ip': self.config.printer_ip,
'lan_password': self.config.lan_password,
'device_serial': self.config.device_serial
}
def publish_gcode_await(self, gcode, after_gcode=None):
save_percent = self.mc_percent
self.publish_gcode(f'{gcode}\nM400\nM73 P101\n{after_gcode if after_gcode else ""}\n')
ts = 0
while self.mc_percent != 101:
if ts < datetime.now().timestamp():
self.publish_status()
ts = datetime.now().timestamp() + 0.5
self.publish_gcode(f'M73 P{save_percent}\n')
def publish_gcode(self, g_code):
operation_code = '{"print": {"sequence_id": "1", "command": "gcode_line", "param": "' + g_code + '"},"user_id":"1"}'
self.client.publish(self.TOPIC_PUBLISH, operation_code)
def publish_resume(self):
self.client.publish(self.TOPIC_PUBLISH, bambu_resume)
def publish_status(self):
self.client.publish(self.TOPIC_PUBLISH, bambu_status)
def publish_clear(self):
self.client.publish(self.TOPIC_PUBLISH, bambu_clear)
def publish_pause(self):
self.client.publish(self.TOPIC_PUBLISH, bambu_pause)
# noinspection PyUnusedLocal
def on_connect(self,
client_: mqtt.Client,
userdata: None,
flags: dict[str, Any],
result_code: int,
properties: mqtt.Properties | None = None, ):
if result_code == 0:
LOGI("连接竹子成功")
# 连接成功后订阅主题
client_.subscribe(self.TOPIC_SUBSCRIBE, qos=1)
LOGI('健康监控线程 - 启动')
self._watchdog = WatchdogThread(self)
self._watchdog.start()
else:
LOGE(f"连接竹子失败,错误代码 {result_code}")
# noinspection PyUnusedLocal
def on_disconnect(self,
client_: mqtt.Client,
userdata: None,
result_code: int):
if not self.is_running:
return
LOGE("连接已断开,请检查打印机状态,以及是否有其它应用占用了打印机")
if self._watchdog is not None:
LOGW("健康监控线程 - 关闭")
self._watchdog.stop()
self._watchdog.join()
def on_message(self, client, userdata, message: mqtt.MQTTMessage):
try:
payload = str(message.payload.decode('utf-8'))
self.process_message(payload)
except Exception as e:
LOGE(f"mqtt数据解析失败: {e}")
return
def process_message(self, payload):
try:
json_data = json.loads(payload)
LOGD(f'bambu_mqtt_msg -> {payload}')
except Exception as e:
LOGE(f"JSON解析失败: {e}")
return
# These are events from the bambu cloud mqtt feed and allow us to detect when a local
# device has connected/disconnected (e.g. turned on/off)
if json_data.get("event"):
if json_data.get("event").get("event") == "client.connected":
LOGD("Client connected event received.")
self.on_disconnect() # We aren't guaranteed to recieve a client.disconnected event.
self.on_connect()
elif json_data.get("event").get("event") == "client.disconnected":
LOGD("Client disconnected event received.")
self.on_disconnect()
return
self._watchdog.received_data()
if 'print' not in json_data:
return
json_print = json_data["print"]
if 'gcode_state' in json_print:
gcode_state = json_print["gcode_state"]
if gcode_state != self.print_status:
if self.print_status != 'unkonw':
if 'PAUSE' == gcode_state:
self.wating_pause_flag = True
if 'FINISH' == gcode_state:
self.on_action(Action.TASK_FINISH)
self.clean()
if 'FAILED' == gcode_state:
if ast(json_print, 'print_error', 50348044):
self.on_action(Action.TASK_FAILED)
self.clean()
self.print_status = gcode_state
if "hw_switch_state" in json_print:
self.on_action(Action.FILAMENT_SWITCH,
FilamentState.YES if json_print["hw_switch_state"] == 1 else FilamentState.NO)
if 'command' in json_print:
if json_print["command"] == 'project_file':
if 'param' in json_print and 'url' in json_data['print'] and 'subtask_name' in json_data['print']:
p = json_data['print']['param']
url = json_data['print']['url']
subtask_name = json_data['print']['subtask_name']
self.gcodeInfo = gcode_util.decodeFromZipUrl(url, p)
self.on_action(Action.TASK_START, {
'first_filament': self.gcodeInfo.first_channel,
'subtask_name': subtask_name
})
if not self.isPrinting():
return
if 'mc_percent' in json_print:
self.mc_percent = json_print["mc_percent"]
if 'mc_remaining_time' in json_print:
self.mc_remaining_time = json_print["mc_remaining_time"]
if 'layer_num' in json_print:
layer_num = json_print["layer_num"]
if layer_num >= MAGIC_CHANNEL:
# 解码 num
num_adjusted = layer_num - MAGIC_CHANNEL
# 提取 next_extruder
next_extruder = num_adjusted // 1000
# 提取 new_filament_temp
new_filament_temp = num_adjusted % 1000
if next_extruder != self.next_extruder:
LOGI(f'next_extruder: {next_extruder} new_filament_temp: {new_filament_temp}')
if ast(json_print, 'gcode_state', 'PAUSE'): # 暂停状态
# self.trigger_pause = False
self.next_extruder = next_extruder
self.new_fila_temp = new_filament_temp
self.change_count += 1
# FIXME: 这里实际上应该是当前耗材温度,而不是新耗材温度
# 因为恢复暂停时会自动恢复之前的温度,所以这里的温度操作,实际上是为了维持温度,避免因为暂停导致温度暂停
# 而且换料后,有一小断耗材还在打印头上,需要挤出,也需要维持之前的温度
self.on_action(Action.CHANGE_FILAMENT, {
'next_extruder': next_extruder,
'next_filament_temp': self.pre_fila_temp if self.pre_fila_temp > 0 else new_filament_temp
})
self.pre_fila_temp = new_filament_temp
else:
self.publish_status()
else:
self.cur_layer = layer_num
def refresh_status(self):
self.publish_status()
def fix_z(self, pre_tem):
cc = self.change_count - self.latest_home_change_count # 计算距离上一次回中后换了几次色了
modle_z = self.cur_layer * self.gcodeInfo.layer_height # 当前模型已经打印了多高
need_z_home = False
if consts.FIX_Z_PAUSE_COUNT == 0: # 高度判断
z_height = cc * consts.PAUSE_Z_OFFSET + modle_z # 计算当前z高度
LOGI(f'暂停次数:{self.change_count}, 抬高次数{cc}, 当前z高度{z_height}')
if z_height > consts.DO_HOME_Z_HEIGHT: # 如果当前高度超过回中预设高度则回中
need_z_home = True
else:
if cc >= consts.FIX_Z_PAUSE_COUNT: # 次数判断
need_z_home = True
if need_z_home:
LOGI('修复z高度')
self.publish_gcode_await(f'G1 E-28 F500\n{consts.FIX_Z_GCODE}\nG1 Z{modle_z + 2} F30000\n', after_gcode=f'M104 S{pre_tem}\n')
self.latest_home_change_count = self.change_count
else:
self.pull_filament(pre_tem)
def on_unload(self, pre_tem=255):
super().on_unload(pre_tem)
if consts.FIX_Z and consts.FIX_Z_GCODE:
self.fix_z(pre_tem)
else:
self.pull_filament(pre_tem)
def pull_filament(self, pre_tem=255):
# 抽回一段距离,提前升温
self.publish_gcode_await('G1 E-28 F500\n', f'M104 S{pre_tem}\n')
def resume(self):
super().resume()
self.publish_gcode_await('M83\nG1 E3 F500\n') # 夹紧耗材
self.publish_resume()
self.publish_clear()
self.publish_status()
def start(self):
super().start()
self.client.connect(self.config.printer_ip, MQTT_PORT, 60)
self.client.subscribe(self.TOPIC_SUBSCRIBE, qos=1)
self.client.loop_start()
self.fbd.start()
def stop(self):
super().stop()
self.client.disconnect()
self.client.loop_stop()
self.fbd.stop()
def filament_broken_detect(self) -> BrokenDetect:
return self.fbd
def _on_watchdog_fired(self):
self.client.publish(self.TOPIC_PUBLISH, bambu_start_push)
class BambuBrokenDetect(BrokenDetect):
@staticmethod
def type_name() -> str:
return "bambu_broken_detect"
def __init__(self, bambu_client: BambuClient):
self.bambu_client = bambu_client
self.fila_state = FilamentState.UNKNOWN
def is_filament_broken(self) -> bool:
return FilamentState.NO == self.fila_state
def get_safe_time(self) -> float:
return 2
def on_printer_action(self, action: Action, data):
if Action.FILAMENT_SWITCH == action:
self.fila_state = data
def start(self):
self.bambu_client.add_on_action(self.on_printer_action)
def stop(self):
self.bambu_client.remove_on_action(self.on_printer_action)
def to_dict(self) -> dict:
return super().to_dict()
class WatchdogThread(threading.Thread):
def __init__(self, client: BambuClient):
self._client = client
self._watchdog_fired = False
self._stop_event = threading.Event()
self._last_received_data = time.time()
super().__init__()
self.setName(f"{self._client.config.printer_ip}-Watchdog-{threading.get_native_id()}")
def stop(self):
self._stop_event.set()
def received_data(self):
self._last_received_data = time.time()
def run(self):
LOGI("Watchdog thread started.")
WATCHDOG_TIMER = 30
while True:
# Wait out the remainder of the watchdog delay or 1s, whichever is higher.
interval = time.time() - self._last_received_data
wait_time = max(1, WATCHDOG_TIMER - interval)
if self._stop_event.wait(wait_time):
# Stop event has been set. Exit thread.
break
interval = time.time() - self._last_received_data
if not self._watchdog_fired and (interval > WATCHDOG_TIMER):
LOGD(f"Watchdog fired. No data received for {math.floor(interval)} seconds for {self._client.config.printer_ip}.")
self._watchdog_fired = True
self._client._on_watchdog_fired()
elif interval < WATCHDOG_TIMER:
self._watchdog_fired = False
LOGI("Watchdog thread exited.")
| 15,819 | Python | .py | 340 | 33.641176 | 137 | 0.584451 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,597 | yba_ams_servo_controller.py | TshineZheng_Filamentor/src/impl/yba_ams_servo_controller.py | from src.impl.yba_ams_py_controller import YBAAMSPYController
class YBAAMSServoController(YBAAMSPYController):
@staticmethod
def type_name() -> str:
return "yba_ams_servo"
def is_initiative_push(self, channel_index: int) -> bool:
return False | 277 | Python | .py | 7 | 33.714286 | 61 | 0.731061 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,598 | yba_single_buffer_controller.py | TshineZheng_Filamentor/src/impl/yba_single_buffer_controller.py | from src.broken_detect import BrokenDetect
from src.impl.yba_ams_py_controller import YBAAMSPYController
ams_head = b'\x2f\x2f\xff\xfe\x01\x02'
class YBASingleBufferController(YBAAMSPYController):
@staticmethod
def type_name() -> str:
return "yba_ams_single_buffer"
def __init__(self, ip: str, port: int, channel_count: int, safe_time: int):
super().__init__(ip, port, channel_count)
self.fila_broken_safe_time = safe_time
self.fbd = YBABrokenDetect(self)
self.is_fila_broken = False
def ams_control(self, ch, fx):
for i in range(self.channel_total):
self.ch_state[i] = 0
self.ch_state[ch] = fx
self.send_ams(ams_head + bytes([ch]) + bytes([fx]))
def on_recv(self, type: int, data):
super().on_recv(type, data)
if type == 2:
self.is_fila_broken = data == '0'
def get_broken_detect(self) -> BrokenDetect:
if self.fila_broken_safe_time <= 0:
return None
return self.fbd
def connect(self):
super().connect()
self.refresh_fila_broken()
def refresh_fila_broken(self):
self.send_ams(b'\x2f\x2f\xff\xfe\xfd')
def to_dict(self) -> dict:
d = super().to_dict()
d['fila_broken_safe_time'] = self.fila_broken_safe_time
return d
@classmethod
def from_dict(cls, json_data: dict):
return cls(
json_data["ip"],
json_data["port"],
json_data["channel_total"],
json_data["fila_broken_safe_time"]
)
def is_initiative_push(self, channel_index: int) -> bool:
return False
class YBABrokenDetect(BrokenDetect):
def __init__(self, parent: YBASingleBufferController):
super().__init__()
self.parent = parent
@staticmethod
def type_name() -> str:
return 'yba_ams_single_buffer_broken_detect'
def get_safe_time(self) -> int:
return self.parent.fila_broken_safe_time
def is_filament_broken(self) -> bool:
self.parent.refresh_fila_broken()
return self.parent.is_fila_broken
def to_dict(self) -> dict:
return super().to_dict()
def start(self):
pass
def stop(self):
pass
| 2,267 | Python | .py | 62 | 28.66129 | 79 | 0.611188 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
2,288,599 | mqtt_broken_detect.py | TshineZheng_Filamentor/src/impl/mqtt_broken_detect.py | import time
from src.broken_detect import BrokenDetect
from src.utils.log import LOGE, LOGI
from src.mqtt_config import MQTTConfig
import paho.mqtt.client as mqtt
TOPIC = '/openams/filament_broken_detect'
class MQTTBrokenDetect(BrokenDetect):
"""断料检测服务
通过监听 {TOPIC} 主题,检测打印机是否断料
当监听数据为 "1" 时表示有料,当监听数据为 "0" 时表示无料
"""
@staticmethod
def type_name() -> str:
return 'mqtt_broken_detect'
def __init__(self, mqtt_config: MQTTConfig):
super().__init__()
self.mqtt_config = mqtt_config
self.topic = TOPIC
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=f'{mqtt_config.client_id}_{time.time()}')
self.client.username_pw_set(mqtt_config.username, mqtt_config.password)
self.client.on_connect = self.on_connect
self.client.on_disconnect = self.on_disconnect
self.client.on_message = self.on_message
self.latest_state = None
@classmethod
def from_dict(cls, json_data: dict):
return cls(MQTTConfig.from_dict(json_data['mqtt_config']))
def to_dict(self) -> dict:
return {
'mqtt_config': self.mqtt_config.to_dict()
}
def start(self):
super().start()
# 连接到MQTT服务器
self.client.connect(self.mqtt_config.server, self.mqtt_config.port, 60)
# 订阅主题
self.client.subscribe(self.topic, qos=1)
# 启动循环,以便客户端能够处理回调
self.client.loop_start()
def stop(self):
super().stop()
self.client.disconnect()
def on_connect(self, client, userdata, flags, rc, properties):
if rc == 0:
LOGI("连接MQTT成功")
self.client.subscribe(self.topic, qos=1)
else:
LOGE(f"连接MQTT失败,错误代码 {rc}")
def on_disconnect(self, client, userdata, disconnect_flags, rc, properties):
if not self.is_running:
return
LOGE("MQTT连接已断开,正在尝试重新连接")
self.reconnect(client)
def reconnect(self, client, delay=3):
while True:
LOGE("尝试重新连接MQTT...")
try:
client.reconnect()
break # 重连成功则退出循环
except:
LOGE(f"重连MQTT失败 {delay} 秒后重试...")
time.sleep(delay) # 等待一段时间后再次尝试
def on_message(self, client, userdata, message):
payload = str(message.payload.decode('utf-8'))
if payload == '1' or payload == '0':
if self.latest_state != payload:
self.latest_state = payload
LOGI(f"断料检测:{'有料' if payload == '1' else '无料'}")
def get_latest_state(self):
return self.latest_state
def is_filament_broken(self) -> bool:
"""判断是否断料
Returns:
bool: 是否断料
"""
if self.latest_state == '0':
return True
else:
return False
def get_safe_time(self) -> int:
return 2.5
| 3,211 | Python | .py | 81 | 27.098765 | 119 | 0.598504 | TshineZheng/Filamentor | 8 | 2 | 0 | AGPL-3.0 | 9/5/2024, 10:48:34 PM (Europe/Amsterdam) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.