PyPDF2.utils.PdfReadError: Unexpected destination '/__WKANCHOR_2'

本文介绍如何使用Python和wkhtmltopdf将网页内容转换为PDF,并利用ghostscript合并多个PDF文件。文中详细展示了从获取博客文章链接到生成PDF文档的具体步骤,包括解决wkhtmltopdf限制和合并PDF中出现的问题。

在学习这篇文章之前,对于一点都不懂python的朋友,可以去看下我之前写过的博客文章,也都是学习过程中的一些收获,感兴趣的可以去看看http://www.flybi.net/blog/seng

之所以写这篇文章,是因为在学习《Python网络数据采集》的时候,书中提到了访问pdf的方法,于是我就想是否能将天善博客内容转成PDF文档,这个功能会很有用,以后可以方便查找。

思路:使用命令行工具wkhtmltopdf,可以将html 转成 PDF,Python有个包python-pdfkit,方便了wkhtmltopdf和Python的结合。不过目前wkhtmltopdf读取的页面数有限制,文档很多的话会生成多个PDF,这样就需要合并,试过很多种合并方法,最终使用ghostscript解决的。

接下来具体介绍一下做法。



1wkhtmltopdf功能简介




下载页面:http://wkhtmltopdf.org/downloads.html

 使用0.12.3 Linux版下载后直接解压即可。

 tar -xvf wkhtmltox-0.13.0-alpha-7b36694_linux-centos6-amd64.rpm.part
 sudo ln -s ./wkhtmltox/
bin/wkhtmltopdf /usr/bin/wkhtmltopdf

使用示例如下:

wkhtmltopdf  'http://www.flybi.net/blog/seng/3645' 'http://www.flybi.net/blog/seng/3599'  sengblog.pdf

注意:天善使用的javascript,好像对这个有影响,只能生成一个页面,要等javascript运行完,加参数即可--javascript-delay 2000,或者屏蔽掉也可以--disable-javascript

wkhtmltopdf  --javascript-delay 2000 'http://www.flybi.net/blog/seng/3645' 'http://www.flybi.net/blog/seng/3599'  sengblog.pdf

如果出问题,可以看一下大纲的信息:

wkhtmltopdf  --dump-outline out.xsl  toc 'http://www.flybi.net/blog/seng/3645' 'http://www.flybi.net/blog/seng/3599'  sengblog.pdf



2pdfkit调用的接口




参考网站:https://pypi.python.org/pypi/pdfkit

Install python-pdfkit:
$ pip install pdfkit
简单的示例:
import pdfkit
pdfkit.from_url([ 'http://www.flybi.net/blog/seng/3645',
'http://www.flybi.net/blog/seng/3599'], 'sengblog.pdf')  



3生成blog的PDF文件




以我的博客为例

我的首页:

http://www.flybi.net/people/seng

我的博客就5页,获取这些链接就可以了

http://www.flybi.net/blog/id-seng__page-1

核心逻辑如下:

(1)获取所有blog具体页面的URL;

(2)排序:暂时偷个懒,先按默认字符排序了;

(3)生成pdf文档,注意目前测试只能包含有限的页面,目前使用20个,按类似以下格式sengblog20160419_1_20生成;

(4)合并pdf文档。

目前没有现成代码,一开始使用http://www.pdfmerge.com/手工做的,后找到更好的办法,下面详细介绍如何合并。



4合并PDF文档




因为wkhtmltopdf有限制,文档多了,需要生成多个pdf文件,原来使用http://www.pdfmerge.com/在线服务合并文档,感觉不完美,合并更多文件就比较麻烦了,找了一些工具最终解决了,测试了PyPDF2、pdftk、ghostscript,都能合并,不过PyPDF2、pdftk对wkhtmltopdf生成的文档的outline合并有问题,特别是PyPDF2需要修改代码,才能完成合并。所以最后选用了ghostscript来完成合并。

相关工具版本要求:

ghostscript:9.19

wkhtmltopdf:0.12.3 (with patched qt)

ghostscript的安装使用:

下载:

http://ghostscript.com/download/gsdnld.html

帮助文档:

http://www.ghostscript.com/doc/9.19/Use.htm

命令示例:

gs-919-linux_x86_64 -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=./output/all_coffee.pdf coffee1_20.pdf coffee21_40.pdf
linux_x86_64 -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=all_seng.pdf seng*.pdf

PyPDF2的安装使用:

PyPDF2版本:1.25.1

https://pypi.python.org/pypi/PyPDF2/1.25.1

https://github.com/mstamy2/PyPDF2

安装:

pip install PyPDF2

使用示例:

from PyPDF2 import PdfFileMerger
merger = PdfFileMerger()
input1 = 
open("hql_1_20.pdf""rb")
input2 = 
open("hql_21_40.pdf""rb")
merger.append(input1)
merger.append(input2)
# Write to an output PDF document
output = 
open("hql_all.pdf""wb")
merger.
write(output)

--------------------

注意合并wkhtmltopdf系统会出错:

PdfReadError: Unexpected destination '/__WKANCHOR_2'

#fix PyPDF2 merge outline出问题的解决

#参考https://github.com/mstamy2/PyPDF2/issues/193

I had the same problem. For a quick and dirty fix I commented out the lines 1225 and 1226 in the file pdf.py of the package PyPDF2 which raise the exception:

    # if destination found, then create outline
    if dest:
        if isinstance(dest, ArrayObject):
            outline = self._buildDestination(title, dest)
        elif isinstance(dest, Str) and dest in self._namedDests:
            outline = self._namedDests[dest]
            outline[NameObject("/Title")] = title
        # else:
        #     raise utils.PdfReadError("Unexpected destination %r" % dest)
    return outline

pdf.py 1225-1226按如下屏蔽即可
# if destination found, then 
create outline
if dest:
    
if isinstance(dest, ArrayObject):
        
outline = self._buildDestination(title, dest)
    elif isinstance(dest, 
Strand dest in self._namedDests:
        
outline = self._namedDests[dest]
        
outline[NameObject("/Title")] = title
    #### 
else:
    ####     
raise utils.PdfReadError("Unexpected destination %r" % dest)
return outline

pdftk的安装使用:

安装:

sudo yum install libgcj
sudo rpm -
i pdftk-2.02-1.*.rpm

使用:

pdftk a1*.pdf cat output combined.pdf  

outline的手工修复:

pdftk支持outline的编辑,可以参考这个,

http://stackoverflow.com/questions/296****79/merge-pdfs-with-pdftk-with-bookmarks

pdftk hql_1_20.pdf dump_data > in1.info

#手工修改in1.info文件

pdftk hql_1_20.pdf update_info in1.info output out.pdf.

当然程序还有些欠缺:

1.uft8的文件名在linux能使用,到windows下就软乱码了。

2.wkhtmltopdf读取html遇到503错误,需要再次检查和重新读取。


rom collections import OrderedDict, namedtuple import functools import itertools import warnings import torch from ..parameter import Parameter import torch.utils.hooks as hooks from torch import Tensor, device, dtype from typing import Union, Tuple, Any, Callable, Iterator, Set, Optional, overload, TypeVar, Mapping, Dict from ...utils.hooks import RemovableHandle _grad_t = Union[Tuple[Tensor, ...], Tensor] # See https://mypy.readthedocs.io/en/latest/generics.html#generic-methods-and-generic-self for the use # of `T` to annotate `self`. Many methods of `Module` return `self` and we want those return values to be # the type of the subclass, not the looser type of `Module`. T = TypeVar('T', bound='Module') class _IncompatibleKeys(namedtuple('IncompatibleKeys', ['missing_keys', 'unexpected_keys'])): def __repr__(self): if not self.missing_keys and not self.unexpected_keys: return '<All keys matched successfully>' return super(_IncompatibleKeys, self).__repr__() __str__ = __repr__ class ModuleAttributeError(AttributeError): """ When `__getattr__` raises AttributeError inside a property, AttributeError is raised with the property name instead of the attribute that initially raised AttributeError, making the error message uninformative. Using `ModuleAttributeError` instead fixes this issue.""" def _addindent(s_, numSpaces): s = s_.split('\n') # don't do anything for single-line stuff if len(s) == 1: return s_ first = s.pop(0) s = [(numSpaces * ' ') + line for line in s] s = '\n'.join(s) s = first + '\n' + s return s r"""This tracks hooks common to all modules that are executed before/after calling forward and backward. This is global state used for debugging/profiling purposes""" _global_backward_hooks = OrderedDict() _global_forward_pre_hooks = OrderedDict() _global_forward_hooks = OrderedDict() def register_module_forward_pre_hook(hook: Callable[..., None]) -> RemovableHandle: r"""Registers a forward pre-hook common to all modules. .. warning :: This adds global state to the `nn.module` module and it is only intended for debugging/profiling purposes. The hook will be called every time before :func:`forward` is invoked. It should have the following signature:: hook(module, input) -> None or modified input The input contains only the positional arguments given to the module. Keyword arguments won't be passed to the hooks and only to the ``forward``. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned(unless that value is already a tuple). This hook has precedence over the specific module hooks registered with ``register_forward_pre_hook``. Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` """ handle = hooks.RemovableHandle(_global_forward_pre_hooks) _global_forward_pre_hooks[handle.id] = hook return handle def register_module_forward_hook(hook: Callable[..., None]) -> RemovableHandle: r"""Registers a global forward hook for all the modules .. warning :: This adds global state to the `nn.module` module and it is only intended for debugging/profiling purposes. The hook will be called every time after :func:`forward` has computed an output. It should have the following signature:: hook(module, input, output) -> None or modified output The input contains only the positional arguments given to the module. Keyword arguments won't be passed to the hooks and only to the ``forward``. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called after :func:`forward` is called. Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` This hook will be executed before specific module hooks registered with ``register_forward_hook``. """ handle = hooks.RemovableHandle(_global_forward_hooks) _global_forward_hooks[handle.id] = hook return handle def register_module_backward_hook( hook: Callable[['Module', _grad_t, _grad_t], Union[None, Tensor]] ) -> RemovableHandle: r"""Registers a backward hook common to all the modules. .. warning :: This adds global state to the `nn.module` module and it is only intended for debugging/profiling purposes. The current implementation will not have the presented behavior for complex :class:`Module` that perform many operations. In some failure cases, :attr:`grad_input` and :attr:`grad_output` will only contain the gradients for a subset of the inputs and outputs. For such :class:`Module`, you should use :func:`torch.Tensor.register_hook` directly on a specific input or output to get the required gradients. The hook will be called every time the gradients with respect to module inputs are computed. The hook should have the following signature:: hook(module, grad_input, grad_output) -> Tensor or None The :attr:`grad_input` and :attr:`grad_output` may be tuples if the module has multiple inputs or outputs. The hook should not modify its arguments, but it can optionally return a new gradient with respect to input that will be used in place of :attr:`grad_input` in subsequent computations. :attr:`grad_input` will only correspond to the inputs given as positional arguments. Global hooks are called before hooks registered with `register_backward_hook` Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` """ handle = hooks.RemovableHandle(_global_backward_hooks) _global_backward_hooks[handle.id] = hook return handle # Trick mypy into not applying contravariance rules to inputs by defining # forward as a value, rather than a function. See also # https://github.com/python/mypy/issues/8795 def _forward_unimplemented(self, *input: Any) -> None: r"""Defines the computation performed at every call. Should be overridden by all subclasses. .. note:: Although the recipe for forward pass needs to be defined within this function, one should call the :class:`Module` instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them. """ raise NotImplementedError class Module: r"""Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will have their parameters converted too when you call :meth:`to`, etc. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool """ dump_patches: bool = False r"""This allows better BC support for :meth:`load_state_dict`. In :meth:`state_dict`, the version number will be saved as in the attribute `_metadata` of the returned state dict, and thus pickled. `_metadata` is a dictionary with keys that follow the naming convention of state dict. See ``_load_from_state_dict`` on how to use this information in loading. If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module's `_load_from_state_dict` method can compare the version number and do appropriate changes if the state dict is from before the change.""" _version: int = 1 training: bool def __init__(self): """ Initializes internal Module state, shared by both nn.Module and ScriptModule. """ torch._C._log_api_usage_once("python.nn_module") self.training = True self._parameters = OrderedDict() self._buffers = OrderedDict() self._non_persistent_buffers_set = set() self._backward_hooks = OrderedDict() self._forward_hooks = OrderedDict() self._forward_pre_hooks = OrderedDict() self._state_dict_hooks = OrderedDict() self._load_state_dict_pre_hooks = OrderedDict() self._modules = OrderedDict() forward: Callable[..., Any] = _forward_unimplemented def register_buffer(self, name: str, tensor: Optional[Tensor], persistent: bool = True) -> None: r"""Adds a buffer to the module. This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm's ``running_mean`` is not a parameter, but is part of the module's state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by setting :attr:`persistent` to ``False``. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module's :attr:`state_dict`. Buffers can be accessed as attributes using given names. Args: name (string): name of the buffer. The buffer can be accessed from this module using the given name tensor (Tensor): buffer to be registered. persistent (bool): whether the buffer is part of this module's :attr:`state_dict`. Example:: >>> self.register_buffer('running_mean', torch.zeros(num_features)) """ if persistent is False and isinstance(self, torch.jit.ScriptModule): raise RuntimeError("ScriptModule does not support non-persistent buffers") if '_buffers' not in self.__dict__: raise AttributeError( "cannot assign buffer before Module.__init__() call") elif not isinstance(name, torch._six.string_classes): raise TypeError("buffer name should be a string. " "Got {}".format(torch.typename(name))) elif '.' in name: raise KeyError("buffer name can't contain \".\"") elif name == '': raise KeyError("buffer name can't be empty string \"\"") elif hasattr(self, name) and name not in self._buffers: raise KeyError("attribute '{}' already exists".format(name)) elif tensor is not None and not isinstance(tensor, torch.Tensor): raise TypeError("cannot assign '{}' object to buffer '{}' " "(torch Tensor or None required)" .format(torch.typename(tensor), name)) else: self._buffers[name] = tensor if persistent: self._non_persistent_buffers_set.discard(name) else: self._non_persistent_buffers_set.add(name) def register_parameter(self, name: str, param: Optional[Parameter]) -> None: r"""Adds a parameter to the module. The parameter can be accessed as an attribute using given name. Args: name (string): name of the parameter. The parameter can be accessed from this module using the given name param (Parameter): parameter to be added to the module. """ if '_parameters' not in self.__dict__: raise AttributeError( "cannot assign parameter before Module.__init__() call") elif not isinstance(name, torch._six.string_classes): raise TypeError("parameter name should be a string. " "Got {}".format(torch.typename(name))) elif '.' in name: raise KeyError("parameter name can't contain \".\"") elif name == '': raise KeyError("parameter name can't be empty string \"\"") elif hasattr(self, name) and name not in self._parameters: raise KeyError("attribute '{}' already exists".format(name)) if param is None: self._parameters[name] = None elif not isinstance(param, Parameter): raise TypeError("cannot assign '{}' object to parameter '{}' " "(torch.nn.Parameter or None required)" .format(torch.typename(param), name)) elif param.grad_fn: raise ValueError( "Cannot assign non-leaf Tensor to parameter '{0}'. Model " "parameters must be created explicitly. To express '{0}' " "as a function of another Tensor, compute the value in " "the forward() method.".format(name)) else: self._parameters[name] = param def add_module(self, name: str, module: Optional['Module']) -> None: r"""Adds a child module to the current module. The module can be accessed as an attribute using the given name. Args: name (string): name of the child module. The child module can be accessed from this module using the given name module (Module): child module to be added to the module. """ if not isinstance(module, Module) and module is not None: raise TypeError("{} is not a Module subclass".format( torch.typename(module))) elif not isinstance(name, torch._six.string_classes): raise TypeError("module name should be a string. Got {}".format( torch.typename(name))) elif hasattr(self, name) and name not in self._modules: raise KeyError("attribute '{}' already exists".format(name)) elif '.' in name: raise KeyError("module name can't contain \".\"") elif name == '': raise KeyError("module name can't be empty string \"\"") self._modules[name] = module def _apply(self, fn): for module in self.children(): module._apply(fn) def compute_should_use_set_data(tensor, tensor_applied): if torch._has_compatible_shallow_copy_type(tensor, tensor_applied): # If the new tensor has compatible tensor type as the existing tensor, # the current behavior is to change the tensor in-place using `.data =`, # and the future behavior is to overwrite the existing tensor. However, # changing the current behavior is a BC-breaking change, and we want it # to happen in future releases. So for now we introduce the # `torch.__future__.get_overwrite_module_params_on_conversion()` # global flag to let the user control whether they want the future # behavior of overwriting the existing tensor or not. return not torch.__future__.get_overwrite_module_params_on_conversion() else: return False for key, param in self._parameters.items(): if param is not None: # Tensors stored in modules are graph leaves, and we don't want to # track autograd history of `param_applied`, so we have to use # `with torch.no_grad():` with torch.no_grad(): param_applied = fn(param) should_use_set_data = compute_should_use_set_data(param, param_applied) if should_use_set_data: param.data = param_applied else: assert isinstance(param, Parameter) assert param.is_leaf self._parameters[key] = Parameter(param_applied, param.requires_grad) if param.grad is not None: with torch.no_grad(): grad_applied = fn(param.grad) should_use_set_data = compute_should_use_set_data(param.grad, grad_applied) if should_use_set_data: param.grad.data = grad_applied else: assert param.grad.is_leaf self._parameters[key].grad = grad_applied.requires_grad_(param.grad.requires_grad) for key, buf in self._buffers.items(): if buf is not None: self._buffers[key] = fn(buf) return self def apply(self: T, fn: Callable[['Module'], None]) -> T: r"""Applies ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self. Typical use includes initializing the parameters of a model (see also :ref:`nn-init-doc`). Args: fn (:class:`Module` -> None): function to be applied to each submodule Returns: Module: self Example:: >>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[ 1., 1.], [ 1., 1.]]) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[ 1., 1.], [ 1., 1.]]) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) """ for module in self.children(): module.apply(fn) fn(self) return self def cuda(self: T, device: Optional[Union[int, device]] = None) -> T: r"""Moves all model parameters and buffers to the GPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized. Arguments: device (int, optional): if specified, all parameters will be copied to that device Returns: Module: self """ return self._apply(lambda t: t.cuda(device)) def cpu(self: T) -> T: r"""Moves all model parameters and buffers to the CPU. Returns: Module: self """ return self._apply(lambda t: t.cpu()) def type(self: T, dst_type: Union[dtype, str]) -> T: r"""Casts all parameters and buffers to :attr:`dst_type`. Arguments: dst_type (type or string): the desired type Returns: Module: self """ return self._apply(lambda t: t.type(dst_type)) def float(self: T) -> T: r"""Casts all floating point parameters and buffers to float datatype. Returns: Module: self """ return self._apply(lambda t: t.float() if t.is_floating_point() else t) def double(self: T) -> T: r"""Casts all floating point parameters and buffers to ``double`` datatype. Returns: Module: self """ return self._apply(lambda t: t.double() if t.is_floating_point() else t) def half(self: T) -> T: r"""Casts all floating point parameters and buffers to ``half`` datatype. Returns: Module: self """ return self._apply(lambda t: t.half() if t.is_floating_point() else t) def bfloat16(self: T) -> T: r"""Casts all floating point parameters and buffers to ``bfloat16`` datatype. Returns: Module: self """ return self._apply(lambda t: t.bfloat16() if t.is_floating_point() else t) @overload def to(self: T, device: Optional[Union[int, device]] = ..., dtype: Optional[Union[dtype, str]] = ..., non_blocking: bool = ...) -> T: ... @overload def to(self: T, dtype: Union[dtype, str], non_blocking: bool = ...) -> T: ... @overload def to(self: T, tensor: Tensor, non_blocking: bool = ...) -> T: ... def to(self, *args, **kwargs): r"""Moves and/or casts the parameters and buffers. This can be called as .. function:: to(device=None, dtype=None, non_blocking=False) .. function:: to(dtype, non_blocking=False) .. function:: to(tensor, non_blocking=False) .. function:: to(memory_format=torch.channels_last) Its signature is similar to :meth:`torch.Tensor.to`, but only accepts floating point desired :attr:`dtype` s. In addition, this method will only cast the floating point parameters and buffers to :attr:`dtype` (if given). The integral parameters and buffers will be moved :attr:`device`, if that is given, but with dtypes unchanged. When :attr:`non_blocking` is set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices. See below for examples. .. note:: This method modifies the module in-place. Args: device (:class:`torch.device`): the desired device of the parameters and buffers in this module dtype (:class:`torch.dtype`): the desired floating point type of the floating point parameters and buffers in this module tensor (torch.Tensor): Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module memory_format (:class:`torch.memory_format`): the desired memory format for 4D parameters and buffers in this module (keyword only argument) Returns: Module: self Example:: >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) """ device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs) if dtype is not None: if not dtype.is_floating_point: raise TypeError('nn.Module.to only accepts floating point ' 'dtypes, but got desired dtype={}'.format(dtype)) def convert(t): if convert_to_format is not None and t.dim() == 4: return t.to(device, dtype if t.is_floating_point() else None, non_blocking, memory_format=convert_to_format) return t.to(device, dtype if t.is_floating_point() else None, non_blocking) return self._apply(convert) def register_backward_hook( self, hook: Callable[['Module', _grad_t, _grad_t], Union[None, Tensor]] ) -> RemovableHandle: r"""Registers a backward hook on the module. .. warning :: The current implementation will not have the presented behavior for complex :class:`Module` that perform many operations. In some failure cases, :attr:`grad_input` and :attr:`grad_output` will only contain the gradients for a subset of the inputs and outputs. For such :class:`Module`, you should use :func:`torch.Tensor.register_hook` directly on a specific input or output to get the required gradients. The hook will be called every time the gradients with respect to module inputs are computed. The hook should have the following signature:: hook(module, grad_input, grad_output) -> Tensor or None The :attr:`grad_input` and :attr:`grad_output` may be tuples if the module has multiple inputs or outputs. The hook should not modify its arguments, but it can optionally return a new gradient with respect to input that will be used in place of :attr:`grad_input` in subsequent computations. :attr:`grad_input` will only correspond to the inputs given as positional arguments. Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` """ handle = hooks.RemovableHandle(self._backward_hooks) self._backward_hooks[handle.id] = hook return handle def register_forward_pre_hook(self, hook: Callable[..., None]) -> RemovableHandle: r"""Registers a forward pre-hook on the module. The hook will be called every time before :func:`forward` is invoked. It should have the following signature:: hook(module, input) -> None or modified input The input contains only the positional arguments given to the module. Keyword arguments won't be passed to the hooks and only to the ``forward``. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned(unless that value is already a tuple). Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` """ handle = hooks.RemovableHandle(self._forward_pre_hooks) self._forward_pre_hooks[handle.id] = hook return handle def register_forward_hook(self, hook: Callable[..., None]) -> RemovableHandle: r"""Registers a forward hook on the module. The hook will be called every time after :func:`forward` has computed an output. It should have the following signature:: hook(module, input, output) -> None or modified output The input contains only the positional arguments given to the module. Keyword arguments won't be passed to the hooks and only to the ``forward``. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called after :func:`forward` is called. Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` """ handle = hooks.RemovableHandle(self._forward_hooks) self._forward_hooks[handle.id] = hook return handle def _slow_forward(self, *input, **kwargs): tracing_state = torch._C._get_tracing_state() if not tracing_state or isinstance(self.forward, torch._C.ScriptMethod): return self.forward(*input, **kwargs) recording_scopes = torch.jit._trace._trace_module_map is not None if recording_scopes: name = torch.jit._trace._trace_module_map[self] if self in torch.jit._trace._trace_module_map else None if name: cur_scope_name = tracing_state.current_scope() tracing_state.push_scope(name) else: recording_scopes = False try: result = self.forward(*input, **kwargs) finally: if recording_scopes: tracing_state.pop_scope() return result def _call_impl(self, *input, **kwargs): for hook in itertools.chain( _global_forward_pre_hooks.values(), self._forward_pre_hooks.values()): result = hook(self, input) if result is not None: if not isinstance(result, tuple): result = (result,) input = result if torch._C._get_tracing_state(): result = self._slow_forward(*input, **kwargs) else: result = self.forward(*input, **kwargs) for hook in itertools.chain( _global_forward_hooks.values(), self._forward_hooks.values()): hook_result = hook(self, input, result) if hook_result is not None: result = hook_result if (len(self._backward_hooks) > 0) or (len(_global_backward_hooks) > 0): var = result while not isinstance(var, torch.Tensor): if isinstance(var, dict): var = next((v for v in var.values() if isinstance(v, torch.Tensor))) else: var = var[0] grad_fn = var.grad_fn if grad_fn is not None: for hook in itertools.chain( _global_backward_hooks.values(), self._backward_hooks.values()): wrapper = functools.partial(hook, self) functools.update_wrapper(wrapper, hook) grad_fn.register_hook(wrapper) return result __call__ : Callable[..., Any] = _call_impl def __setstate__(self, state): self.__dict__.update(state) # Support loading old checkpoints that don't have the following attrs: if '_forward_pre_hooks' not in self.__dict__: self._forward_pre_hooks = OrderedDict() if '_state_dict_hooks' not in self.__dict__: self._state_dict_hooks = OrderedDict() if '_load_state_dict_pre_hooks' not in self.__dict__: self._load_state_dict_pre_hooks = OrderedDict() if '_non_persistent_buffers_set' not in self.__dict__: self._non_persistent_buffers_set = set() def __getattr__(self, name: str) -> Union[Tensor, 'Module']: if '_parameters' in self.__dict__: _parameters = self.__dict__['_parameters'] if name in _parameters: return _parameters[name] if '_buffers' in self.__dict__: _buffers = self.__dict__['_buffers'] if name in _buffers: return _buffers[name] if '_modules' in self.__dict__: modules = self.__dict__['_modules'] if name in modules: return modules[name] raise ModuleAttributeError("'{}' object has no attribute '{}'".format( type(self).__name__, name)) def __setattr__(self, name: str, value: Union[Tensor, 'Module']) -> None: def remove_from(*dicts_or_sets): for d in dicts_or_sets: if name in d: if isinstance(d, dict): del d[name] else: d.discard(name) params = self.__dict__.get('_parameters') if isinstance(value, Parameter): if params is None: raise AttributeError( "cannot assign parameters before Module.__init__() call") remove_from(self.__dict__, self._buffers, self._modules, self._non_persistent_buffers_set) self.register_parameter(name, value) elif params is not None and name in params: if value is not None: raise TypeError("cannot assign '{}' as parameter '{}' " "(torch.nn.Parameter or None expected)" .format(torch.typename(value), name)) self.register_parameter(name, value) else: modules = self.__dict__.get('_modules') if isinstance(value, Module): if modules is None: raise AttributeError( "cannot assign module before Module.__init__() call") remove_from(self.__dict__, self._parameters, self._buffers, self._non_persistent_buffers_set) modules[name] = value elif modules is not None and name in modules: if value is not None: raise TypeError("cannot assign '{}' as child module '{}' " "(torch.nn.Module or None expected)" .format(torch.typename(value), name)) modules[name] = value else: buffers = self.__dict__.get('_buffers') if buffers is not None and name in buffers: if value is not None and not isinstance(value, torch.Tensor): raise TypeError("cannot assign '{}' as buffer '{}' " "(torch.Tensor or None expected)" .format(torch.typename(value), name)) buffers[name] = value else: object.__setattr__(self, name, value) def __delattr__(self, name): if name in self._parameters: del self._parameters[name] elif name in self._buffers: del self._buffers[name] self._non_persistent_buffers_set.discard(name) elif name in self._modules: del self._modules[name] else: object.__delattr__(self, name) def _register_state_dict_hook(self, hook): r"""These hooks will be called with arguments: `self`, `state_dict`, `prefix`, `local_metadata`, after the `state_dict` of `self` is set. Note that only parameters and buffers of `self` or its children are guaranteed to exist in `state_dict`. The hooks may modify `state_dict` inplace or return a new one. """ handle = hooks.RemovableHandle(self._state_dict_hooks) self._state_dict_hooks[handle.id] = hook return handle def _save_to_state_dict(self, destination, prefix, keep_vars): r"""Saves module state to `destination` dictionary, containing a state of the module, but not its descendants. This is called on every submodule in :meth:`~torch.nn.Module.state_dict`. In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic. Arguments: destination (dict): a dict where state will be stored prefix (str): the prefix for parameters and buffers used in this module """ for name, param in self._parameters.items(): if param is not None: destination[prefix + name] = param if keep_vars else param.detach() for name, buf in self._buffers.items(): if buf is not None and name not in self._non_persistent_buffers_set: destination[prefix + name] = buf if keep_vars else buf.detach() # The user can pass an optional arbitrary mappable object to `state_dict`, in which case `state_dict` returns # back that same object. But if they pass nothing, an `OrederedDict` is created and returned. T_destination = TypeVar('T_destination', bound=Mapping[str, Tensor]) @overload def state_dict(self, destination: T_destination, prefix: str = ..., keep_vars: bool = ...) -> T_destination: ... # TODO: annotate with OrderedDict not Dict, but there is a problem: # https://docs.python.org/3/library/typing.html#typing.OrderedDict @overload def state_dict(self, prefix: str = ..., keep_vars: bool = ...) -> Dict[str, Tensor]: ... def state_dict(self, destination=None, prefix='', keep_vars=False): r"""Returns a dictionary containing a whole state of the module. Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Returns: dict: a dictionary containing a whole state of the module Example:: >>> module.state_dict().keys() ['bias', 'weight'] """ if destination is None: destination = OrderedDict() destination._metadata = OrderedDict() destination._metadata[prefix[:-1]] = local_metadata = dict(version=self._version) self._save_to_state_dict(destination, prefix, keep_vars) for name, module in self._modules.items(): if module is not None: module.state_dict(destination, prefix + name + '.', keep_vars=keep_vars) for hook in self._state_dict_hooks.values(): hook_result = hook(self, destination, prefix, local_metadata) if hook_result is not None: destination = hook_result return destination def _register_load_state_dict_pre_hook(self, hook): r"""These hooks will be called with arguments: `state_dict`, `prefix`, `local_metadata`, `strict`, `missing_keys`, `unexpected_keys`, `error_msgs`, before loading `state_dict` into `self`. These arguments are exactly the same as those of `_load_from_state_dict`. """ handle = hooks.RemovableHandle(self._load_state_dict_pre_hooks) self._load_state_dict_pre_hooks[handle.id] = hook return handle def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): r"""Copies parameters and buffers from :attr:`state_dict` into only this module, but not its descendants. This is called on every submodule in :meth:`~torch.nn.Module.load_state_dict`. Metadata saved for this module in input :attr:`state_dict` is provided as :attr:`local_metadata`. For state dicts without metadata, :attr:`local_metadata` is empty. Subclasses can achieve class-specific backward compatible loading using the version number at `local_metadata.get("version", None)`. .. note:: :attr:`state_dict` is not the same object as the input :attr:`state_dict` to :meth:`~torch.nn.Module.load_state_dict`. So it can be modified. Arguments: state_dict (dict): a dict containing parameters and persistent buffers. prefix (str): the prefix for parameters and buffers used in this module local_metadata (dict): a dict containing the metadata for this module. See strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` with :attr:`prefix` match the names of parameters and buffers in this module missing_keys (list of str): if ``strict=True``, add missing keys to this list unexpected_keys (list of str): if ``strict=True``, add unexpected keys to this list error_msgs (list of str): error messages should be added to this list, and will be reported together in :meth:`~torch.nn.Module.load_state_dict` """ for hook in self._load_state_dict_pre_hooks.values(): hook(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) persistent_buffers = {k: v for k, v in self._buffers.items() if k not in self._non_persistent_buffers_set} local_name_params = itertools.chain(self._parameters.items(), persistent_buffers.items()) local_state = {k: v for k, v in local_name_params if v is not None} for name, param in local_state.items(): key = prefix + name if key in state_dict: input_param = state_dict[key] # Backward compatibility: loading 1-dim tensor from 0.3.* to version 0.4+ if len(param.shape) == 0 and len(input_param.shape) == 1: input_param = input_param[0] if input_param.shape != param.shape: # local shape should match the one in checkpoint error_msgs.append('size mismatch for {}: copying a param with shape {} from checkpoint, ' 'the shape in current model is {}.' .format(key, input_param.shape, param.shape)) continue try: with torch.no_grad(): param.copy_(input_param) except Exception as ex: error_msgs.append('While copying the parameter named "{}", ' 'whose dimensions in the model are {} and ' 'whose dimensions in the checkpoint are {}, ' 'an exception occurred : {}.' .format(key, param.size(), input_param.size(), ex.args)) elif strict: missing_keys.append(key) if strict: for key in state_dict.keys(): if key.startswith(prefix): input_name = key[len(prefix):] input_name = input_name.split('.', 1)[0] # get the name of param/buffer/child if input_name not in self._modules and input_name not in local_state: unexpected_keys.append(key) def load_state_dict(self, state_dict: Union[Dict[str, Tensor], Dict[str, Tensor]], strict: bool = True): r"""Copies parameters and buffers from :attr:`state_dict` into this module and its descendants. If :attr:`strict` is ``True``, then the keys of :attr:`state_dict` must exactly match the keys returned by this module's :meth:`~torch.nn.Module.state_dict` function. Arguments: state_dict (dict): a dict containing parameters and persistent buffers. strict (bool, optional): whether to strictly enforce that the keys in :attr:`state_dict` match the keys returned by this module's :meth:`~torch.nn.Module.state_dict` function. Default: ``True`` Returns: ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields: * **missing_keys** is a list of str containing the missing keys * **unexpected_keys** is a list of str containing the unexpected keys """ missing_keys = [] unexpected_keys = [] error_msgs = [] # copy state_dict so _load_from_state_dict can modify it metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if metadata is not None: state_dict._metadata = metadata def load(module, prefix=''): local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {}) module._load_from_state_dict( state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs) for name, child in module._modules.items(): if child is not None: load(child, prefix + name + '.') load(self) load = None # break load->load reference cycle if strict: if len(unexpected_keys) > 0: error_msgs.insert( 0, 'Unexpected key(s) in state_dict: {}. '.format( ', '.join('"{}"'.format(k) for k in unexpected_keys))) if len(missing_keys) > 0: error_msgs.insert( 0, 'Missing key(s) in state_dict: {}. '.format( ', '.join('"{}"'.format(k) for k in missing_keys))) if len(error_msgs) > 0: raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format( self.__class__.__name__, "\n\t".join(error_msgs))) return _IncompatibleKeys(missing_keys, unexpected_keys) def _named_members(self, get_members_fn, prefix='', recurse=True): r"""Helper method for yielding various names + members of modules.""" memo = set() modules = self.named_modules(prefix=prefix) if recurse else [(prefix, self)] for module_prefix, module in modules: members = get_members_fn(module) for k, v in members: if v is None or v in memo: continue memo.add(v) name = module_prefix + ('.' if module_prefix else '') + k yield name, v def parameters(self, recurse: bool = True) -> Iterator[Parameter]: r"""Returns an iterator over module parameters. This is typically passed to an optimizer. Args: recurse (bool): if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module. Yields: Parameter: module parameter Example:: >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L) """ for name, param in self.named_parameters(recurse=recurse): yield param def named_parameters(self, prefix: str = '', recurse: bool = True) -> Iterator[Tuple[str, Tensor]]: r"""Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself. Args: prefix (str): prefix to prepend to all parameter names. recurse (bool): if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module. Yields: (string, Parameter): Tuple containing the name and parameter Example:: >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size()) """ gen = self._named_members( lambda module: module._parameters.items(), prefix=prefix, recurse=recurse) for elem in gen: yield elem def buffers(self, recurse: bool = True) -> Iterator[Tensor]: r"""Returns an iterator over module buffers. Args: recurse (bool): if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Yields: torch.Tensor: module buffer Example:: >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L) """ for name, buf in self.named_buffers(recurse=recurse): yield buf def named_buffers(self, prefix: str = '', recurse: bool = True) -> Iterator[Tuple[str, Tensor]]: r"""Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself. Args: prefix (str): prefix to prepend to all buffer names. recurse (bool): if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Yields: (string, torch.Tensor): Tuple containing the name and buffer Example:: >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size()) """ gen = self._named_members( lambda module: module._buffers.items(), prefix=prefix, recurse=recurse) for elem in gen: yield elem def children(self) -> Iterator['Module']: r"""Returns an iterator over immediate children modules. Yields: Module: a child module """ for name, module in self.named_children(): yield module def named_children(self) -> Iterator[Tuple[str, 'Module']]: r"""Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself. Yields: (string, Module): Tuple containing a name and child module Example:: >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module) """ memo = set() for name, module in self._modules.items(): if module is not None and module not in memo: memo.add(module) yield name, module def modules(self) -> Iterator['Module']: r"""Returns an iterator over all modules in the network. Yields: Module: a module in the network Note: Duplicate modules are returned only once. In the following example, ``l`` will be returned only once. Example:: >>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True) """ for name, module in self.named_modules(): yield module def named_modules(self, memo: Optional[Set['Module']] = None, prefix: str = ''): r"""Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself. Yields: (string, Module): Tuple of name and module Note: Duplicate modules are returned only once. In the following example, ``l`` will be returned only once. Example:: >>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True)) """ if memo is None: memo = set() if self not in memo: memo.add(self) yield prefix, self for name, module in self._modules.items(): if module is None: continue submodule_prefix = prefix + ('.' if prefix else '') + name for m in module.named_modules(memo, submodule_prefix): yield m def train(self: T, mode: bool = True) -> T: r"""Sets the module in training mode. This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`, etc. Args: mode (bool): whether to set training mode (``True``) or evaluation mode (``False``). Default: ``True``. Returns: Module: self """ self.training = mode for module in self.children(): module.train(mode) return self def eval(self: T) -> T: r"""Sets the module in evaluation mode. This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`, etc. This is equivalent with :meth:`self.train(False) <torch.nn.Module.train>`. Returns: Module: self """ return self.train(False) def requires_grad_(self: T, requires_grad: bool = True) -> T: r"""Change if autograd should record operations on parameters in this module. This method sets the parameters' :attr:`requires_grad` attributes in-place. This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training). Args: requires_grad (bool): whether autograd should record operations on parameters in this module. Default: ``True``. Returns: Module: self """ for p in self.parameters(): p.requires_grad_(requires_grad) return self def zero_grad(self, set_to_none: bool = False) -> None: r"""Sets gradients of all model parameters to zero. See similar function under :class:`torch.optim.Optimizer` for more context. Arguments: set_to_none (bool): instead of setting to zero, set the grads to None. See :meth:`torch.optim.Optimizer.zero_grad` for details. """ if getattr(self, '_is_replica', False): warnings.warn( "Calling .zero_grad() from a module created with nn.DataParallel() has no effect. " "The parameters are copied (in a differentiable manner) from the original module. " "This means they are not leaf nodes in autograd and so don't accumulate gradients. " "If you need gradients in your forward method, consider using autograd.grad instead.") for p in self.parameters(): if p.grad is not None: if set_to_none: p.grad = None else: if p.grad.grad_fn is not None: p.grad.detach_() else: p.grad.requires_grad_(False) p.grad.zero_() def share_memory(self: T) -> T: return self._apply(lambda t: t.share_memory_()) def _get_name(self): return self.__class__.__name__ def extra_repr(self) -> str: r"""Set the extra representation of the module To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable. """ return '' def __repr__(self): # We treat the extra repr like the sub-module, one item per line extra_lines = [] extra_repr = self.extra_repr() # empty string will be split into list [''] if extra_repr: extra_lines = extra_repr.split('\n') child_lines = [] for key, module in self._modules.items(): mod_str = repr(module) mod_str = _addindent(mod_str, 2) child_lines.append('(' + key + '): ' + mod_str) lines = extra_lines + child_lines main_str = self._get_name() + '(' if lines: # simple one-liner info, which most builtin Modules will use if len(extra_lines) == 1 and not child_lines: main_str += extra_lines[0] else: main_str += '\n ' + '\n '.join(lines) + '\n' main_str += ')' return main_str def __dir__(self): module_attrs = dir(self.__class__) attrs = list(self.__dict__.keys()) parameters = list(self._parameters.keys()) modules = list(self._modules.keys()) buffers = list(self._buffers.keys()) keys = module_attrs + attrs + parameters + modules + buffers # Eliminate attrs that are not legal Python variable names keys = [key for key in keys if not key[0].isdigit()] return sorted(keys) def _replicate_for_data_parallel(self): replica = self.__new__(type(self)) replica.__dict__ = self.__dict__.copy() # replicas do not have parameters themselves, the replicas reference the original # module. replica._parameters = OrderedDict() replica._buffers = replica._buffers.copy() replica._modules = replica._modules.copy() replica._is_replica = True return replica 报错:File "D:\Anconda\envs\my_test_1\lib\site-packages\torch\nn\modules\module.py", line 1051, in load_state_dict raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format( RuntimeError: Error(s) in loading state_dict for LLFlow: Missing key(s) in state_dict: "flowUpsamplerNet.layers.3.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.3.affine.SF.resConv.2.bias", "flowUpsamplerNet.layers.4.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.4.affine.SF.resConv.2.bias", "flowUpsamplerNet.layers.5.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.5.affine.SF.resConv.2.bias", "flowUpsamplerNet.layers.6.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.6.affine.SF.resConv.2.bias", "flowUpsamplerNet.layers.10.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.10.affine.SF.resConv.2.bias", "flowUpsamplerNet.layers.11.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.11.affine.SF.resConv.2.bias", "flowUpsamplerNet.layers.12.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.12.affine.SF.resConv.2.bias", "flowUpsamplerNet.layers.13.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.13.affine.SF.resConv.2.bias", "flowUpsamplerNet.layers.17.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.17.affine.SF.resConv.2.bias", "flowUpsamplerNet.layers.18.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.18.affine.SF.resConv.2.bias", "flowUpsamplerNet.layers.19.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.19.affine.SF.resConv.2.bias", "flowUpsamplerNet.layers.20.affine.SF.resConv.2.weight", "flowUpsamplerNet.layers.20.affine.SF.resConv.2.bias". Unexpected key(s) in state_dict: "flowUpsamplerNet.layers.3.affine.SF.resConv.1.weight", "flowUpsamplerNet.layers.3.affine.SF.resConv.1.bias", "flowUpsamplerNet.layers.4.affine.SF.resConv.1.weight", "flowUpsamplerNet.
05-20
WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell. WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell. [PS7 18:56:13] C:\Users\Administrator\Desktop [master] > # 增强版 Install-Socat 函数 [PS7 18:56:18] C:\Users\Administrator\Desktop [master] > function Install-Socat { >> param( >> [Parameter(Mandatory = $false)] >> [string]$InstallDrive = "E:", >> >> [Parameter(Mandatory = $false)] >> [string]$InstallDir = "Program Files\Socat" >> ) >> >> # 1. 规范化路径处理 >> $fullPath = [System.IO.Path]::GetFullPath("$InstallDrive\$InstallDir").TrimEnd('\') >> >> # 2. 验证文件系统权限 >> if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { >> Write-Warning "需要管理员权限安装程序" >> return $null >> } >> >> # 3. 检查现有安装 >> $existingPath = Get-Command socat -ErrorAction SilentlyContinue | >> Select-Object -ExpandProperty Source -First 1 >> >> if ($existingPath) { >> Write-Host "已安装于: $existingPath" -ForegroundColor Green >> return $existingPath >> } >> >> # 4. 创建安装目录(带错误处理) >> try { >> if (-not (Test-Path $fullPath)) { >> New-Item -Path $fullPath -ItemType Directory -Force | Out-Null >> } >> } catch { >> Write-Error "创建目录失败: $($_.Exception.Message)" >> return $null >> } >> >> # 5. 文件下载(带重试机制) >> $tempFile = Join-Path $env:TEMP "socat-win64.zip" >> $downloadUrl = "https://sourceforge.net/projects/unix-utils/files/socat/1.7.4.4/socat-1.7.4.4-win64.zip/download" >> >> try { >> Invoke-WebRequest $downloadUrl -OutFile $tempFile -UseBasicParsing -RetryIntervalSec 5 >> } catch { >> Write-Error "下载失败: $($_.Exception.Message)" >> return $null >> } >> >> # 6. 解压缩(带文件验证) >> try { >> Expand-Archive -Path $tempFile -DestinationPath $fullPath -Force >> $socatExe = Join-Path $fullPath "socat.exe" >> >> if (-not (Test-Path $socatExe -PathType Leaf)) { >> throw "解压后未找到 socat.exe" >> } >> } catch { >> Write-Error "解压失败: $($_.Exception.Message)" >> return $null >> } >> >> # 7. 环境变量更新(避免重复添加) >> $currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine") >> if ($currentPath -notlike "*$fullPath*") { >> $newPath = $currentPath + ";$fullPath" >> [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine") >> } >> >> # 8. 更新当前会话PATH >> $env:Path += ";$fullPath" >> >> # 9. 返回完整路径(带验证) >> if (Test-Path $socatExe) { >> return $socatExe >> } else { >> Write-Error "安装后文件验证失败" >> return $null >> } >> } [PS7 18:56:19] C:\Users\Administrator\Desktop [master] > [PS7 18:56:19] C:\Users\Administrator\Desktop [master] > # 增强版 New-TcpTunnel 函数 [PS7 18:56:19] C:\Users\Administrator\Desktop [master] > function New-TcpTunnel { >> param( >> [int]$LocalPort = 8443, >> [string]$RemoteHost = "google.com", >> [int]$RemotePort = 443, >> [string]$SocatPath = $null >> ) >> >> # 1. 获取socat路径(带自动安装) >> $socatBinary = if ($SocatPath -and (Test-Path $SocatPath)) { >> $SocatPath >> } else { >> $installedPath = Install-Socat >> if (-not $installedPath) { >> throw "socat安装失败" >> } >> $installedPath >> } >> >> # 2. 路径空格处理 >> if ($socatBinary -match '\s') { >> $socatBinary = "`"$socatBinary`"" >> } >> >> # 3. 创建日志文件 >> $logFile = Join-Path $env:TEMP "socat-$LocalPort.log" >> >> # 4. 启动进程(带错误处理) >> try { >> Start-Process -FilePath $socatBinary ` >> -ArgumentList "TCP-LISTEN:$LocalPort,fork,reuseaddr TCP:$($RemoteHost):$RemotePort" ` >> -NoNewWindow ` >> -RedirectStandardOutput $logFile ` >> -RedirectStandardError $logFile ` >> -PassThru >> } catch { >> Write-Error "启动socat失败: $($_.Exception.Message)" >> throw >> } >> >> # 5. 验证端口监听 >> Start-Sleep -Seconds 2 >> $portStatus = Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue >> >> if (-not $portStatus) { >> throw "隧道创建失败,端口 $LocalPort 未监听" >> } >> >> # 返回进程信息 >> return @{ >> Process = $process >> Port = $LocalPort >> LogFile = $logFile >> } >> } [PS7 18:56:19] C:\Users\Administrator\Desktop [master] > WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell. WARNING:: The term 'WARNING:' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:39] C:\Users\Administrator\Desktop [master] > WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell. WARNING:: The term 'WARNING:' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:39] C:\Users\Administrator\Desktop [master] > [PS7 18:56:13] C:\Users\Administrator\Desktop [master] > # 增强版 Install-Socat 函数 ParserError: Line | 1 | [PS7 18:56:13] C:\Users\Administrator\Desktop [master] > # 增强版 Instal … | ~ | Missing ] at end of attribute or type literal. [PS7 18:56:39] C:\Users\Administrator\Desktop [master] > [PS7 18:56:18] C:\Users\Administrator\Desktop [master] > function Install-Socat { >> >> param( >> >> [Parameter(Mandatory = $false)] >> >> [string]$InstallDrive = "E:", >> >> >> >> [Parameter(Mandatory = $false)] >> >> [string]$InstallDir = "Program Files\Socat" >> >> ) >> >> ParserError: Line | 1 | [PS7 18:56:18] C:\Users\Administrator\Desktop [master] > function Ins … | ~ | Missing ] at end of attribute or type literal. [PS7 18:56:39] C:\Users\Administrator\Desktop [master] > >> # 1. 规范化路径处理 >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:39] C:\Users\Administrator\Desktop [master] > >> $fullPath = [System.IO.Path]::GetFullPath("$InstallDrive\$InstallDir").TrimEnd('\') >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:39] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:39] C:\Users\Administrator\Desktop [master] > >> # 2. 验证文件系统权限 >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:39] C:\Users\Administrator\Desktop [master] > >> if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { >> >> Write-Warning "需要管理员权限安装程序" >> >> return $null >> >> } >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:40] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:40] C:\Users\Administrator\Desktop [master] > >> # 3. 检查现有安装 >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:40] C:\Users\Administrator\Desktop [master] > >> $existingPath = Get-Command socat -ErrorAction SilentlyContinue | >> >> Select-Object -ExpandProperty Source -First 1 >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:40] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:40] C:\Users\Administrator\Desktop [master] > >> if ($existingPath) { >> >> Write-Host "已安装于: $existingPath" -ForegroundColor Green >> >> return $existingPath >> >> } >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:40] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:40] C:\Users\Administrator\Desktop [master] > >> # 4. 创建安装目录(带错误处理) >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:40] C:\Users\Administrator\Desktop [master] > >> try { >> >> if (-not (Test-Path $fullPath)) { >> >> New-Item -Path $fullPath -ItemType Directory -Force | Out-Null >> >> } >> >> } catch { >> >> Write-Error "创建目录失败: $($_.Exception.Message)" >> >> return $null >> >> } >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:40] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:40] C:\Users\Administrator\Desktop [master] > >> # 5. 文件下载(带重试机制) >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:41] C:\Users\Administrator\Desktop [master] > >> $tempFile = Join-Path $env:TEMP "socat-win64.zip" >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:41] C:\Users\Administrator\Desktop [master] > >> $downloadUrl = "https://sourceforge.net/projects/unix-utils/files/socat/1.7.4.4/socat-1.7.4.4-win64.zip/download" >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:41] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:41] C:\Users\Administrator\Desktop [master] > >> try { >> >> Invoke-WebRequest $downloadUrl -OutFile $tempFile -UseBasicParsing -RetryIntervalSec 5 >> >> } catch { >> >> Write-Error "下载失败: $($_.Exception.Message)" >> >> return $null >> >> } >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:41] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:41] C:\Users\Administrator\Desktop [master] > >> # 6. 解压缩(带文件验证) >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:41] C:\Users\Administrator\Desktop [master] > >> try { >> >> Expand-Archive -Path $tempFile -DestinationPath $fullPath -Force >> >> $socatExe = Join-Path $fullPath "socat.exe" >> >> >> >> if (-not (Test-Path $socatExe -PathType Leaf)) { >> >> throw "解压后未找到 socat.exe" >> >> } >> >> } catch { >> >> Write-Error "解压失败: $($_.Exception.Message)" >> >> return $null >> >> } >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:41] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:41] C:\Users\Administrator\Desktop [master] > >> # 7. 环境变量更新(避免重复添加) >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:41] C:\Users\Administrator\Desktop [master] > >> $currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine") >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > >> if ($currentPath -notlike "*$fullPath*") { >> >> $newPath = $currentPath + ";$fullPath" >> >> [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine") >> >> } >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > >> # 8. 更新当前会话PATH >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > >> $env:Path += ";$fullPath" >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > >> # 9. 返回完整路径(带验证) >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > >> if (Test-Path $socatExe) { >> >> return $socatExe >> >> } else { >> >> Write-Error "安装后文件验证失败" >> >> return $null >> >> } Test-Path: Value cannot be null. (Parameter 'The provided Path argument was null or an empty collection.') >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > >> } ParserError: Line | 1 | >> } | ~ | Unexpected token '}' in expression or statement. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > [PS7 18:56:19] C:\Users\Administrator\Desktop [master] > ParserError: Line | 1 | [PS7 18:56:19] C:\Users\Administrator\Desktop [master] > | ~ | Missing ] at end of attribute or type literal. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > [PS7 18:56:19] C:\Users\Administrator\Desktop [master] > # 增强版 New-TcpTunnel 函数 ParserError: Line | 1 | [PS7 18:56:19] C:\Users\Administrator\Desktop [master] > # 增强版 New-Tc … | ~ | Missing ] at end of attribute or type literal. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > [PS7 18:56:19] C:\Users\Administrator\Desktop [master] > function New-TcpTunnel { >> >> param( >> >> [int]$LocalPort = 8443, >> >> [string]$RemoteHost = "google.com", >> >> [int]$RemotePort = 443, >> >> [string]$SocatPath = $null >> >> ) >> >> ParserError: Line | 1 | [PS7 18:56:19] C:\Users\Administrator\Desktop [master] > function New … | ~ | Missing ] at end of attribute or type literal. [PS7 18:56:42] C:\Users\Administrator\Desktop [master] > >> # 1. 获取socat路径(带自动安装) >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:43] C:\Users\Administrator\Desktop [master] > >> $socatBinary = if ($SocatPath -and (Test-Path $SocatPath)) { >> >> $SocatPath >> >> } else { >> >> $installedPath = Install-Socat >> >> if (-not $installedPath) { >> >> throw "socat安装失败" >> >> } >> >> $installedPath >> >> } >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:43] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:43] C:\Users\Administrator\Desktop [master] > >> # 2. 路径空格处理 >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:43] C:\Users\Administrator\Desktop [master] > >> if ($socatBinary -match '\s') { >> >> $socatBinary = "`"$socatBinary`"" >> >> } >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:43] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:43] C:\Users\Administrator\Desktop [master] > >> # 3. 创建日志文件 >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:43] C:\Users\Administrator\Desktop [master] > >> $logFile = Join-Path $env:TEMP "socat-$LocalPort.log" >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:43] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:43] C:\Users\Administrator\Desktop [master] > >> # 4. 启动进程(带错误处理) >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:43] C:\Users\Administrator\Desktop [master] > >> try { >> >> Start-Process -FilePath $socatBinary ` >> >> -ArgumentList "TCP-LISTEN:$LocalPort,fork,reuseaddr TCP:$($RemoteHost):$RemotePort" ` >> >> -NoNewWindow ` >> >> -RedirectStandardOutput $logFile ` >> >> -RedirectStandardError $logFile ` >> >> -PassThru >> >> } catch { >> >> Write-Error "启动socat失败: $($_.Exception.Message)" >> >> throw >> >> } ParserError: Line | 4 | >> -NoNewWindow ` | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ | The output stream for this command is already redirected. [PS7 18:56:44] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:44] C:\Users\Administrator\Desktop [master] > >> # 5. 验证端口监听 >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:44] C:\Users\Administrator\Desktop [master] > >> Start-Sleep -Seconds 2 >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:44] C:\Users\Administrator\Desktop [master] > >> $portStatus = Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:44] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:44] C:\Users\Administrator\Desktop [master] > >> if (-not $portStatus) { >> >> throw "隧道创建失败,端口 $LocalPort 未监听" >> >> } >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:44] C:\Users\Administrator\Desktop [master] > >> >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:44] C:\Users\Administrator\Desktop [master] > >> # 返回进程信息 >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:44] C:\Users\Administrator\Desktop [master] > >> return @{ >> >> Process = $process ParserError: Line | 1 | >> return @{ | ~ | Missing closing '}' in statement block or type definition. [PS7 18:56:44] C:\Users\Administrator\Desktop [master] > >> Port = $LocalPort >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:45] C:\Users\Administrator\Desktop [master] > >> LogFile = $logFile >>: The term '>>' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. [PS7 18:56:45] C:\Users\Administrator\Desktop [master] > >> } ParserError: Line | 1 | >> } | ~ | Unexpected token '}' in expression or statement. [PS7 18:56:45] C:\Users\Administrator\Desktop [master] > >> } ParserError: Line | 1 | >> } | ~ | Unexpected token '}' in expression or statement. [PS7 18:56:45] C:\Users\Administrator\Desktop [master] > [PS7 18:56:19] C:\Users\Administrator\Desktop [master] ># 创建隧道(自动处理安装) ParserError: Line | 1 | [PS7 18:56:19] C:\Users\Administrator\Desktop [master] ># 创建隧道(自动处理安装 … | ~ | Missing ] at end of attribute or type literal. [PS7 18:56:49] C:\Users\Administrator\Desktop [master] > $tunnel = New-TcpTunnel -LocalPort 8443 -RemoteHost "google.com" -RemotePort 80 Install-Socat: Line | 13 | $installedPath = Install-Socat | ~~~~~~~~~~~~~ | 解压失败: Start-Process: Line | 30 | Start-Process -FilePath $socatBinary ` | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | This command cannot be run because "RedirectStandardOutput" and "RedirectStandardError" are same. Give different inputs and Run your command again. Exception: Line | 46 | throw "隧道创建失败,端口 $LocalPort 未监听" | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | 隧道创建失败,端口 8443 未监听 [PS7 18:56:54] C:\Users\Administrator\Desktop [master] > [PS7 18:56:54] C:\Users\Administrator\Desktop [master] > # 验证隧道状态 [PS7 18:56:54] C:\Users\Administrator\Desktop [master] > Get-Process -Id $tunnel.Process.Id Get-Process: Cannot bind argument to parameter 'Id' because it is null. [PS7 18:56:55] C:\Users\Administrator\Desktop [master] > Get-Content $tunnel.LogFile -Tail 10 Get-Content: Cannot bind argument to parameter 'Path' because it is null. [PS7 18:56:55] C:\Users\Administrator\Desktop [master] > # 测试端口连接 [PS7 18:56:56] C:\Users\Administrator\Desktop [master] > Test-NetConnection -ComputerName localhost -Port 8443 WARNING: TCP connect to (::1 : 8443) failed WARNING: TCP connect to (127.0.0.1 : 8443) failed ComputerName : localhost RemoteAddress : ::1 RemotePort : 8443 InterfaceAlias : Loopback Pseudo-Interface 1 SourceAddress : ::1 PingSucceeded : True PingReplyDetails (RTT) : 0 ms TcpTestSucceeded : False [PS7 18:57:03] C:\Users\Administrator\Desktop [master] > [PS7 18:57:03] C:\Users\Administrator\Desktop [master] > # 使用curl测试 [PS7 18:57:03] C:\Users\Administrator\Desktop [master] > curl -v http://localhost:8443 * Host localhost:8443 was resolved. * IPv6: ::1 * IPv4: 127.0.0.1 * Trying [::1]:8443... * Trying 127.0.0.1:8443... * connect to ::1 port 8443 from :: port 53916 failed: Connection refused * connect to 127.0.0.1 port 8443 from 0.0.0.0 port 53917 failed: Connection refused * Failed to connect to localhost port 8443 after 2260 ms: Could not connect to server * closing connection #0 [PS7 18:57:05] C:\Users\Administrator\Desktop [master] >
最新发布
09-07
PowerShell 7 环境已加载 (版本: 7.3.6) PowerShell 7 环境已加载 (版本: 7.3.6) PS C:\Users\Administrator\Desktop> # E:\AI_System\core\config_loader.py PS C:\Users\Administrator\Desktop> import sys import: The term 'import' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> import os import: The term 'import' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> import json import: The term 'import' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> from pathlib import Path ParserError: Line | 1 | from pathlib import Path | ~~~~ | The 'from' keyword is not supported in this version of the language. PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> class ConfigLoader: >> def __init__(self, config_dir=None): ParserError: Line | 2 | def __init__(self, config_dir=None): | ~ | Missing 'class' body in 'class' declaration. PS C:\Users\Administrator\Desktop> # 设置默认配置目录 PS C:\Users\Administrator\Desktop> if not config_dir: ParserError: Line | 1 | if not config_dir: | ~ | Missing '(' after 'if' in if statement. PS C:\Users\Administrator\Desktop> config_dir = Path(__file__).resolve().parent.parent / "config" __file__: The term '__file__' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> self.config_dir = Path(config_dir) config_dir: The term 'config_dir' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> self.configs = {} self.configs: The term 'self.configs' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> def load_config(self, config_name): ParserError: Line | 1 | def load_config(self, config_name): | ~ | Missing argument in parameter list. PS C:\Users\Administrator\Desktop> """加载指定配置文件""" "加载指定配置文件" PS C:\Users\Administrator\Desktop> # 支持多种文件格式 PS C:\Users\Administrator\Desktop> possible_extensions = [".json", ".yaml", ".yml", ".py"] possible_extensions: The term 'possible_extensions' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> config_path = None config_path: The term 'config_path' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 查找存在的配置文件 PS C:\Users\Administrator\Desktop> for ext in possible_extensions: ParserError: Line | 1 | for ext in possible_extensions: | ~ | Missing opening '(' after keyword 'for'. PS C:\Users\Administrator\Desktop> test_path = self.config_dir / f"{config_name}{ext}" test_path: The term 'test_path' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> if test_path.exists(): ParserError: Line | 1 | if test_path.exists(): | ~ | Missing '(' after 'if' in if statement. PS C:\Users\Administrator\Desktop> config_path = test_path config_path: The term 'config_path' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> break PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> if not config_path: ParserError: Line | 1 | if not config_path: | ~ | Missing '(' after 'if' in if statement. PS C:\Users\Administrator\Desktop> raise FileNotFoundError(f"配置文件不存在: {config_name} in {self.config_dir}") f配置文件不存在: {config_name} in {self.config_dir}: The term 'f配置文件不存在: {config_name} in {self.config_dir}' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 根据文件类型加载配置 PS C:\Users\Administrator\Desktop> if config_path.suffix == ".json": ParserError: Line | 1 | if config_path.suffix == ".json": | ~ | Missing '(' after 'if' in if statement. PS C:\Users\Administrator\Desktop> with open(config_path, 'r', encoding='utf-8') as f: ParserError: Line | 1 | with open(config_path, 'r', encoding='utf-8') as f: | ~ | Missing argument in parameter list. PS C:\Users\Administrator\Desktop> self.configs[config_name] = json.load(f) f: The term 'f' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> elif config_path.suffix in [".yaml", ".yml"]: elif: The term 'elif' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> try: try:: The term 'try:' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> import yaml import: The term 'import' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> with open(config_path, 'r', encoding='utf-8') as f: ParserError: Line | 1 | with open(config_path, 'r', encoding='utf-8') as f: | ~ | Missing argument in parameter list. PS C:\Users\Administrator\Desktop> self.configs[config_name] = yaml.safe_load(f) f: The term 'f' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> except ImportError: except: The term 'except' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> raise ImportError("请安装 PyYAML 库以支持 YAML 配置") raise: The term 'raise' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> elif config_path.suffix == ".py": elif: The term 'elif' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> # 动态导入 Python 配置文件 PS C:\Users\Administrator\Desktop> spec = importlib.util.spec_from_file_location(config_name, config_path) ParserError: Line | 1 | … spec = importlib.util.spec_from_file_location(config_name, config_ … | ~ | Missing argument in parameter list. PS C:\Users\Administrator\Desktop> module = importlib.util.module_from_spec(spec) spec: The term 'spec' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> spec.loader.exec_module(module) spec.loader.exec_module: The term 'spec.loader.exec_module' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> self.configs[config_name] = module.__dict__ self.configs[config_name]: The term 'self.configs[config_name]' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> return self.configs[config_name] self.configs[config_name]: The term 'self.configs[config_name]' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> def get_config(self, config_name, default=None): ParserError: Line | 1 | def get_config(self, config_name, default=None): | ~ | Missing argument in parameter list. PS C:\Users\Administrator\Desktop> """获取已加载的配置""" "获取已加载的配置" PS C:\Users\Administrator\Desktop> return self.configs.get(config_name, default or {}) ParserError: Line | 1 | return self.configs.get(config_name, default or {}) | ~ | Missing argument in parameter list. PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> def reload_config(self, config_name): ParserError: Line | 1 | def reload_config(self, config_name): | ~ | Missing argument in parameter list. PS C:\Users\Administrator\Desktop> """重新加载配置""" "重新加载配置" PS C:\Users\Administrator\Desktop> if config_name in self.configs: ParserError: Line | 1 | if config_name in self.configs: | ~ | Missing '(' after 'if' in if statement. PS C:\Users\Administrator\Desktop> del self.configs[config_name] PS C:\Users\Administrator\Desktop> return self.load_config(config_name) config_name: The term 'config_name' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 创建全局配置加载器实例 PS C:\Users\Administrator\Desktop> config_loader = ConfigLoader() ParserError: Line | 1 | config_loader = ConfigLoader() | ~ | An expression was expected after '('. PS C:\Users\Administrator\Desktop> # E:\AI_System\Start-Server.ps1 PS C:\Users\Administrator\Desktop> param( >> [switch]$DebugMode, >> [int]$Port = 5000, >> [string]$Env = "dev" >> ) PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 1. 设置项目根目录 PS C:\Users\Administrator\Desktop> $projectRoot = $PSScriptRoot PS C:\Users\Administrator\Desktop> Set-Location $projectRoot PS C:\Users\Administrator> PS C:\Users\Administrator> # 2. 激活虚拟环境 PS C:\Users\Administrator> $venvPath = Join-Path $projectRoot "web_ui\.venv" Join-Path: Cannot bind argument to parameter 'Path' because it is an empty string. PS C:\Users\Administrator> if (-not (Test-Path (Join-Path $venvPath "Scripts\Activate.ps1"))) { >> Write-Host "创建虚拟环境..." -ForegroundColor Yellow >> python -m venv $venvPath >> } InvalidOperation: The variable '$venvPath' cannot be retrieved because it has not been set. PS C:\Users\Administrator> PS C:\Users\Administrator> . (Join-Path $venvPath "Scripts\Activate.ps1") InvalidOperation: The variable '$venvPath' cannot be retrieved because it has not been set. PS C:\Users\Administrator> Write-Host "虚拟环境已激活 ($(python --version))" -ForegroundColor Green 虚拟环境已激活 (Python 3.10.10) PS C:\Users\Administrator> PS C:\Users\Administrator> # 3. 安装依赖 PS C:\Users\Administrator> $requirements = Join-Path $projectRoot "requirements.txt" Join-Path: Cannot bind argument to parameter 'Path' because it is an empty string. PS C:\Users\Administrator> if (Test-Path $requirements) { >> pip install -r $requirements >> } InvalidOperation: The variable '$requirements' cannot be retrieved because it has not been set. PS C:\Users\Administrator> PS C:\Users\Administrator> # 4. 设置环境变量 PS C:\Users\Administrator> $env:AI_ENV = $Env PS C:\Users\Administrator> $env:FLASK_APP = "server.py" PS C:\Users\Administrator> $env:FLASK_ENV = if ($DebugMode) { "development" } else { "production" } PS C:\Users\Administrator> PS C:\Users\Administrator> # 5. 启动服务器 PS C:\Users\Administrator> if ($DebugMode) { >> Write-Host "启动调试模式 (端口: $Port)..." -ForegroundColor Cyan >> python -m debugpy --listen 0.0.0.0:$Port -m flask run --port $Port >> } else { >> Write-Host "启动生产模式 (端口: $Port)..." -ForegroundColor Cyan >> python -m flask run --port $Port >> } 启动生产模式 (端口: 5000)... Disabling PyTorch because PyTorch >= 2.1 is required but found 2.0.0 None of PyTorch, TensorFlow >= 2.0, or Flax have been found. Models won't be available and only tokenizers, configuration and file/data utilities can be used. Traceback (most recent call last): File "E:\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "E:\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "E:\Python310\lib\site-packages\flask\__main__.py", line 3, in <module> main() File "E:\Python310\lib\site-packages\flask\cli.py", line 1131, in main cli.main() File "E:\Python310\lib\site-packages\click\core.py", line 1363, in main rv = self.invoke(ctx) File "E:\Python310\lib\site-packages\click\core.py", line 1830, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "E:\Python310\lib\site-packages\click\core.py", line 1226, in invoke return ctx.invoke(self.callback, **ctx.params) File "E:\Python310\lib\site-packages\click\core.py", line 794, in invoke return callback(*args, **kwargs) File "E:\Python310\lib\site-packages\click\decorators.py", line 93, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "E:\Python310\lib\site-packages\click\core.py", line 794, in invoke return callback(*args, **kwargs) File "E:\Python310\lib\site-packages\flask\cli.py", line 979, in run_command raise e from None File "E:\Python310\lib\site-packages\flask\cli.py", line 963, in run_command app: WSGIApplication = info.load_app() # pyright: ignore File "E:\Python310\lib\site-packages\flask\cli.py", line 349, in load_app app = locate_app(import_name, name) File "E:\Python310\lib\site-packages\flask\cli.py", line 245, in locate_app __import__(module_name) File "C:\Users\Administrator\server.py", line 3, in <module> from transformers import pipeline File "<frozen importlib._bootstrap>", line 1075, in _handle_fromlist File "E:\Python310\lib\site-packages\transformers\utils\import_utils.py", line 2292, in __getattr__ module = self._get_module(self._class_to_module[name]) File "E:\Python310\lib\site-packages\transformers\utils\import_utils.py", line 2322, in _get_module raise e File "E:\Python310\lib\site-packages\transformers\utils\import_utils.py", line 2320, in _get_module return importlib.import_module("." + module_name, self.__name__) File "E:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "E:\Python310\lib\site-packages\transformers\pipelines\__init__.py", line 29, in <module> from ..models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING, AutoImageProcessor File "E:\Python310\lib\site-packages\transformers\models\auto\image_processing_auto.py", line 28, in <module> from ...image_processing_utils_fast import BaseImageProcessorFast File "E:\Python310\lib\site-packages\transformers\image_processing_utils_fast.py", line 43, in <module> from .processing_utils import Unpack File "E:\Python310\lib\site-packages\transformers\processing_utils.py", line 36, in <module> from .audio_utils import load_audio File "E:\Python310\lib\site-packages\transformers\audio_utils.py", line 39, in <module> import soundfile as sf File "E:\Python310\lib\site-packages\soundfile.py", line 212, in <module> _snd = _ffi.dlopen(_explicit_libname) OSError: cannot load library 'libsndfile.dll': error 0x7e PS C:\Users\Administrator> # E:\AI_System\web_ui\server.py PS C:\Users\Administrator> import os import: The term 'import' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> import sys import: The term 'import' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> from pathlib import Path ParserError: Line | 1 | from pathlib import Path | ~~~~ | The 'from' keyword is not supported in this version of the language. PS C:\Users\Administrator> from flask import Flask, jsonify ParserError: Line | 1 | from flask import Flask, jsonify | ~~~~ | The 'from' keyword is not supported in this version of the language. PS C:\Users\Administrator> PS C:\Users\Administrator> # 添加项目根目录到搜索路径 PS C:\Users\Administrator> project_root = Path(__file__).resolve().parent.parent __file__: The term '__file__' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> sys.path.insert(0, str(project_root)) ParserError: Line | 1 | sys.path.insert(0, str(project_root)) | ~ | Missing expression after ','. PS C:\Users\Administrator> PS C:\Users\Administrator> print(f"项目根目录: {project_root}") f项目根目录: {project_root}: The term 'f项目根目录: {project_root}' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> PS C:\Users\Administrator> # 导入配置加载器 PS C:\Users\Administrator> from core.config_loader import config_loader ParserError: Line | 1 | from core.config_loader import config_loader | ~~~~ | The 'from' keyword is not supported in this version of the language. PS C:\Users\Administrator> PS C:\Users\Administrator> app = Flask(__name__) __name__: The term '__name__' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> PS C:\Users\Administrator> # 加载配置 PS C:\Users\Administrator> try: try:: The term 'try:' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> system_config = config_loader.load_config("system_config") system_config: The term 'system_config' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> hardware_config = config_loader.load_config("hardware_config") hardware_config: The term 'hardware_config' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> model_config = config_loader.load_config("model_registry") model_config: The term 'model_config' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> except Exception as e: except: The term 'except' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> print(f"配置加载错误: {e}") f配置加载错误: {e}: The term 'f配置加载错误: {e}' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> system_config = {} system_config: The term 'system_config' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> hardware_config = {} hardware_config: The term 'hardware_config' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> model_config = {} model_config: The term 'model_config' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> PS C:\Users\Administrator> @app.route('/') ParserError: Line | 1 | @app.route('/') | ~~~~ | The splatting operator '@' cannot be used to reference variables in an expression. '@app' can be used only as an | argument to a command. To reference variables in an expression use '$app'. PS C:\Users\Administrator> def index(): ParserError: Line | 1 | def index(): | ~ | An expression was expected after '('. PS C:\Users\Administrator> return jsonify({ >> "status": "running", >> "project_root": str(project_root), >> "system_config": system_config >> }) ParserError: Line | 2 | "status": "running", | ~ | Unexpected token ':' in expression or statement. PS C:\Users\Administrator> PS C:\Users\Administrator> @app.route('/config/<name>') ParserError: Line | 1 | @app.route('/config/<name>') | ~~~~ | The splatting operator '@' cannot be used to reference variables in an expression. '@app' can be used only as an | argument to a command. To reference variables in an expression use '$app'. PS C:\Users\Administrator> def get_config(name): name: The term 'name' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> config = config_loader.get_config(name, {}) ParserError: Line | 1 | config = config_loader.get_config(name, {}) | ~ | Missing argument in parameter list. PS C:\Users\Administrator> return jsonify(config) config: The term 'config' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> PS C:\Users\Administrator> if __name__ == '__main__': ParserError: Line | 1 | if __name__ == '__main__': | ~ | Missing '(' after 'if' in if statement. PS C:\Users\Administrator> port = int(os.getenv('FLASK_PORT', 5000)) InvalidOperation: The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. PS C:\Users\Administrator> app.run(host='0.0.0.0', port=port) ParserError: Line | 1 | app.run(host='0.0.0.0', port=port) | ~ | Missing argument in parameter list. PS C:\Users\Administrator> # 创建启动脚本 PS C:\Users\Administrator> $startScript = @' >> param( >> [switch]$DebugMode, >> [int]$Port = 5000, >> [string]$Env = "dev" >> ) >> >> $projectRoot = $PSScriptRoot >> Set-Location $projectRoot >> >> # ... 完整脚本内容 ... >> '@ PS C:\Users\Administrator> PS C:\Users\Administrator> Set-Content -Path "E:\AI_System\Start-Server.ps1" -Value $startScript -Encoding UTF8 PS C:\Users\Administrator> PS C:\Users\Administrator> # 创建快捷函数 PS C:\Users\Administrator> function Start-AIServer { >> param( >> [switch]$Debug, >> [int]$Port = 5000 >> ) >> >> & "E:\AI_System\Start-Server.ps1" -DebugMode:$Debug -Port $Port >> } PS C:\Users\Administrator> PS C:\Users\Administrator> # 添加到配置文件 PS C:\Users\Administrator> $profileContent = @" >> # AI 系统快捷命令 >> function Start-AIServer { >> param([switch]`$Debug, [int]`$Port = 5000) >> & "E:\AI_System\Start-Server.ps1" -DebugMode:`$Debug -Port `$Port >> } >> >> Set-Alias aistart Start-AIServer >> "@ PS C:\Users\Administrator> PS C:\Users\Administrator> Add-Content -Path $PROFILE -Value $profileContent -Encoding UTF8 PS C:\Users\Administrator> # 1. 打开 PowerShell PS C:\Users\Administrator> & "$env:ProgramFiles\PowerShell\7\pwsh.exe" PowerShell 7.3.6 A new PowerShell stable release is available: v7.5.2 Upgrade now, or check out the release page at: https://aka.ms/PowerShell-Release?tag=v7.5.2 PowerShell 7 环境已加载 (版本: 7.3.6) PS C:\Users\Administrator> # 热重载配置 PS C:\Users\Administrator> @app.route('/reload/<name>') ParserError: Line | 1 | @app.route('/reload/<name>') | ~~~~ | The splatting operator '@' cannot be used to reference variables in an expression. '@app' can be used only as an | argument to a command. To reference variables in an expression use '$app'. PS C:\Users\Administrator> def reload_config(name): name: The term 'name' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> try: try:: The term 'try:' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> config_loader.reload_config(name) name: The term 'name' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> return jsonify({"status": "success", "config": name}) ParserError: Line | 1 | return jsonify({"status": "success", "config": name}) | ~ | Unexpected token ':' in expression or statement. PS C:\Users\Administrator> except Exception as e: except: The term 'except' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> return jsonify({"status": "error", "message": str(e)}), 500 ParserError: Line | 1 | return jsonify({"status": "error", "message": str(e)}), 500 | ~ | Unexpected token ':' in expression or statement. PS C:\Users\Administrator> # 根据环境加载不同配置 PS C:\Users\Administrator> env = os.getenv("AI_ENV", "dev") env: The term 'env' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> config_loader.load_config(f"system_config_{env}") fsystem_config_{env}: The term 'fsystem_config_{env}' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> # 配置回退机制 PS C:\Users\Administrator> try: try:: The term 'try:' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> model_config = config_loader.load_config("model_registry") model_config: The term 'model_config' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> except FileNotFoundError: except: The term 'except' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator> model_config = config_loader.load_config("default_model_registry") model_config: The term 'model_config' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Administrator>
08-24
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值