Python_API_String Services_re.compile

本文介绍如何使用Python的re模块编译正则表达式,并通过实例演示了如何利用编译后的正则表达式对象执行搜索操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

API文档:

re.compile(pattern[, flags])
Compile a regular expression pattern into a regular expression object, which can be used for matching using its match() and search() methods, described below.

The expression’s behaviour can be modified by specifying a flags value. Values can be any of the following variables, combined using bitwise OR (the | operator).

翻译文档:

   参数:

       pattern:正则表达式字符串

       [flags]:标志对正则表达式进行小处理

  描述:

        方法返回一个正则表达式对象,可直接调用match()和search()方法

例子:

  #! /usr/bin/env python
#coding=utf-8

import re

patternRe = re.compile('^AA')
print patternRe.search('AAbbb')

输出:

<_sre.SRE_Match object at 0x016490C8>



这是什么错误 OR: Exception in ASGI application + Exception Group Traceback (most recent call last): | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/_utils.py", line 76, in collapse_excgroups | yield | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/base.py", line 186, in __call__ | async with anyio.create_task_group() as task_group: | ^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 763, in __aexit__ | raise BaseExceptionGroup( | ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception) +-+---------------- 1 ---------------- | Traceback (most recent call last): | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/uvicorn/protocols/http/httptools_impl.py", line 409, in run_asgi | result = await app( # type: ignore[func-returns-value] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ | return await self.app(scope, receive, send) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/fastapi/applications.py", line 1054, in __call__ | await super().__call__(scope, receive, send) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/applications.py", line 113, in __call__ | await self.middleware_stack(scope, receive, send) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/errors.py", line 187, in __call__ | raise exc | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/errors.py", line 165, in __call__ | await self.app(scope, receive, _send) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/cors.py", line 85, in __call__ | await self.app(scope, receive, send) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/base.py", line 185, in __call__ | with collapse_excgroups(): | ^^^^^^^^^^^^^^^^^^^^ | File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/contextlib.py", line 158, in __exit__ | self.gen.throw(value) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/_utils.py", line 82, in collapse_excgroups | raise exc | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/base.py", line 187, in __call__ | response = await self.dispatch_func(request, call_next) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/06.renwu/00.fix_bug/test-automation-platform-backend/src/app/middlewares/request_logger_middleware.py", line 17, in dispatch | response = await call_next(request) | ^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/base.py", line 163, in call_next | raise app_exc | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/base.py", line 149, in coro | await self.app(scope, receive_or_disconnect, send_no_error) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app | raise exc | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app | await app(scope, receive, sender) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/routing.py", line 715, in __call__ | await self.middleware_stack(scope, receive, send) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/routing.py", line 735, in app | await route.handle(scope, receive, send) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/routing.py", line 288, in handle | await self.app(scope, receive, send) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/routing.py", line 76, in app | await wrap_app_handling_exceptions(app, request)(scope, receive, send) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app | raise exc | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app | await app(scope, receive, sender) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/routing.py", line 73, in app | response = await f(request) | ^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/fastapi/routing.py", line 301, in app | raw_response = await run_endpoint_function( | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/fastapi/routing.py", line 212, in run_endpoint_function | return await dependant.call(**values) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/06.renwu/00.fix_bug/test-automation-platform-backend/src/app/api/v1/ai.py", line 67, in query_ai_analysis_data_table | ai_analysis_data = await ai.analysis_report_time(db, ai_analysis_data) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/06.renwu/00.fix_bug/test-automation-platform-backend/src/app/services/ai.py", line 362, in analysis_report_time | cursor_num = await db.execute(stmt_num) | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py", line 461, in execute | result = await greenlet_spawn( | ^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 190, in greenlet_spawn | result = context.switch(*args, **kwargs) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 2362, in execute | return self._execute_internal( | ^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 2247, in _execute_internal | result: Result[Any] = compile_state_cls.orm_execute_statement( | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py", line 305, in orm_execute_statement | result = conn.execute( | ^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1418, in execute | return meth( | ^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py", line 515, in _execute_on_connection | return connection._execute_clauseelement( | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1632, in _execute_clauseelement | compiled_sql, extracted_params, cache_hit = elem._compile_w_cache( | ^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py", line 703, in _compile_w_cache | compiled_sql = self._compiler( | ^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py", line 316, in _compiler | return dialect.statement_compiler(dialect, self, **kw) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 1429, in __init__ | Compiled.__init__(self, dialect, statement, **kwargs) | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 870, in __init__ | self.string = self.process(self.statement, **compile_kwargs) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 915, in process | return obj._compiler_dispatch(self, **kwargs) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py", line 141, in _compiler_dispatch | return meth(self, **kw) # type: ignore # noqa: E501 | ^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4824, in visit_select | text = self._compose_select_body( | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4973, in _compose_select_body | f._compiler_dispatch( | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py", line 141, in _compiler_dispatch | return meth(self, **kw) # type: ignore # noqa: E501 | ^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py", line 1607, in visit_join | self.process( | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 915, in process | return obj._compiler_dispatch(self, **kwargs) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py", line 141, in _compiler_dispatch | return meth(self, **kw) # type: ignore # noqa: E501 | ^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4309, in visit_lateral | return "LATERAL %s" % self.visit_alias(lateral_, **kw) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4262, in visit_alias | inner = alias.element._compiler_dispatch( | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py", line 141, in _compiler_dispatch | return meth(self, **kw) # type: ignore # noqa: E501 | ^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4305, in visit_subquery | return self.visit_alias(subquery, **kw) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4234, in visit_alias | inner = alias.element._compiler_dispatch( | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py", line 141, in _compiler_dispatch | return meth(self, **kw) # type: ignore # noqa: E501 | ^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4734, in visit_select | froms = self._setup_select_stack( | ^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4904, in _setup_select_stack | froms = compile_state._get_display_froms( | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py", line 4793, in _get_display_froms | raise exc.InvalidRequestError( | sqlalchemy.exc.InvalidRequestError: Select statement '<sqlalchemy.sql.selectable.Select object at 0x1394546e0>' returned no FROM clauses due to auto-correlation; specify correlate(<tables>) to control correlation manually. +------------------------------------ During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/uvicorn/protocols/http/httptools_impl.py", line 409, in run_asgi result = await app( # type: ignore[func-returns-value] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/fastapi/applications.py", line 1054, in __call__ await super().__call__(scope, receive, send) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/applications.py", line 113, in __call__ await self.middleware_stack(scope, receive, send) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/errors.py", line 187, in __call__ raise exc File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/errors.py", line 165, in __call__ await self.app(scope, receive, _send) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/cors.py", line 85, in __call__ await self.app(scope, receive, send) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/base.py", line 185, in __call__ with collapse_excgroups(): ^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/contextlib.py", line 158, in __exit__ self.gen.throw(value) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/_utils.py", line 82, in collapse_excgroups raise exc File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/base.py", line 187, in __call__ response = await self.dispatch_func(request, call_next) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/06.renwu/00.fix_bug/test-automation-platform-backend/src/app/middlewares/request_logger_middleware.py", line 17, in dispatch response = await call_next(request) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/base.py", line 163, in call_next raise app_exc File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/base.py", line 149, in coro await self.app(scope, receive_or_disconnect, send_no_error) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app raise exc File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app await app(scope, receive, sender) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/routing.py", line 715, in __call__ await self.middleware_stack(scope, receive, send) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/routing.py", line 735, in app await route.handle(scope, receive, send) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/routing.py", line 288, in handle await self.app(scope, receive, send) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/routing.py", line 76, in app await wrap_app_handling_exceptions(app, request)(scope, receive, send) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app raise exc File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app await app(scope, receive, sender) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/starlette/routing.py", line 73, in app response = await f(request) ^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/fastapi/routing.py", line 301, in app raw_response = await run_endpoint_function( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/fastapi/routing.py", line 212, in run_endpoint_function return await dependant.call(**values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/06.renwu/00.fix_bug/test-automation-platform-backend/src/app/api/v1/ai.py", line 67, in query_ai_analysis_data_table ai_analysis_data = await ai.analysis_report_time(db, ai_analysis_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/06.renwu/00.fix_bug/test-automation-platform-backend/src/app/services/ai.py", line 362, in analysis_report_time cursor_num = await db.execute(stmt_num) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py", line 461, in execute result = await greenlet_spawn( ^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 190, in greenlet_spawn result = context.switch(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 2362, in execute return self._execute_internal( ^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 2247, in _execute_internal result: Result[Any] = compile_state_cls.orm_execute_statement( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py", line 305, in orm_execute_statement result = conn.execute( ^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1418, in execute return meth( ^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py", line 515, in _execute_on_connection return connection._execute_clauseelement( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1632, in _execute_clauseelement compiled_sql, extracted_params, cache_hit = elem._compile_w_cache( ^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py", line 703, in _compile_w_cache compiled_sql = self._compiler( ^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py", line 316, in _compiler return dialect.statement_compiler(dialect, self, **kw) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 1429, in __init__ Compiled.__init__(self, dialect, statement, **kwargs) File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 870, in __init__ self.string = self.process(self.statement, **compile_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 915, in process return obj._compiler_dispatch(self, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py", line 141, in _compiler_dispatch return meth(self, **kw) # type: ignore # noqa: E501 ^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4824, in visit_select text = self._compose_select_body( ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4973, in _compose_select_body f._compiler_dispatch( File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py", line 141, in _compiler_dispatch return meth(self, **kw) # type: ignore # noqa: E501 ^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py", line 1607, in visit_join self.process( File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 915, in process return obj._compiler_dispatch(self, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py", line 141, in _compiler_dispatch return meth(self, **kw) # type: ignore # noqa: E501 ^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4309, in visit_lateral return "LATERAL %s" % self.visit_alias(lateral_, **kw) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4262, in visit_alias inner = alias.element._compiler_dispatch( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py", line 141, in _compiler_dispatch return meth(self, **kw) # type: ignore # noqa: E501 ^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4305, in visit_subquery return self.visit_alias(subquery, **kw) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4234, in visit_alias inner = alias.element._compiler_dispatch( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py", line 141, in _compiler_dispatch return meth(self, **kw) # type: ignore # noqa: E501 ^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4734, in visit_select froms = self._setup_select_stack( ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py", line 4904, in _setup_select_stack froms = compile_state._get_display_froms( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qxz5mik/platform_work/04.code/test-automation-platform-backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py", line 4793, in _get_display_froms raise exc.InvalidRequestError( sqlalchemy.exc.InvalidRequestError: Select statement '<sqlalchemy.sql.selectable.Select object at 0x1394546e0>' returned no FROM clauses due to auto-correlation; specify correlate(<tables>) to control correlation manually.
08-07
#下面程序运行时报错: C:\Users\Administrator\AppData\Local\Programs\Python\Python312\python.exe C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\utils\generic.py Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\utils\generic.py", line 34, in <module> from ..utils import logging ImportError: attempted relative import with no known parent package 进程已结束,退出代码为 1 ------------------------------------------------------------------------------------------------ import inspect import json import os import tempfile import warnings from collections import OrderedDict, UserDict, defaultdict from collections.abc import Iterable, MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import dataclass, fields, is_dataclass from enum import Enum from functools import partial, wraps from typing import Any, Callable, ContextManager, Optional, TypedDict import numpy as np from packaging import version from ..utils import logging from .import_utils import ( get_torch_version, is_flax_available, is_mlx_available, is_tf_available, is_torch_available, is_torch_fx_proxy, requires, ) _CAN_RECORD_REGISTRY = {} logger = logging.get_logger(__name__) if is_torch_available(): # required for @can_return_tuple decorator to work with torchdynamo import torch # noqa: F401 from ..model_debugging_utils import model_addition_debugger_context class cached_property(property): """ Descriptor that mimics @property but caches output in member variable. From tensorflow_datasets Built-in in functools from Python 3.8. """ def __get__(self, obj, objtype=None): # See docs.python.org/3/howto/descriptor.html#properties if obj is None: return self if self.fget is None: raise AttributeError("unreadable attribute") attr = "__cached_" + self.fget.__name__ cached = getattr(obj, attr, None) if cached is None: cached = self.fget(obj) setattr(obj, attr, cached) return cached # vendored from distutils.util def strtobool(val): """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(f"invalid truth value {val!r}") def infer_framework_from_repr(x): """ Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the frameworks in a smart order, without the need to import the frameworks). """ representation = str(type(x)) if representation.startswith("<class 'torch."): return "pt" elif representation.startswith("<class 'tensorflow."): return "tf" elif representation.startswith("<class 'jax"): return "jax" elif representation.startswith("<class 'numpy."): return "np" elif representation.startswith("<class 'mlx."): return "mlx" def _get_frameworks_and_test_func(x): """ Returns an (ordered since we are in Python 3.7+) dictionary framework to test function, which places the framework we can guess from the repr first, then Numpy, then the others. """ framework_to_test = { "pt": is_torch_tensor, "tf": is_tf_tensor, "jax": is_jax_tensor, "np": is_numpy_array, "mlx": is_mlx_array, } preferred_framework = infer_framework_from_repr(x) # We will test this one first, then numpy, then the others. frameworks = [] if preferred_framework is None else [preferred_framework] if preferred_framework != "np": frameworks.append("np") frameworks.extend([f for f in framework_to_test if f not in [preferred_framework, "np"]]) return {f: framework_to_test[f] for f in frameworks} def is_tensor(x): """ Tests if `x` is a `torch.Tensor`, `tf.Tensor`, `jaxlib.xla_extension.DeviceArray`, `np.ndarray` or `mlx.array` in the order defined by `infer_framework_from_repr` """ # This gives us a smart order to test the frameworks with the corresponding tests. framework_to_test_func = _get_frameworks_and_test_func(x) for test_func in framework_to_test_func.values(): if test_func(x): return True # Tracers if is_torch_fx_proxy(x): return True if is_flax_available(): from jax.core import Tracer if isinstance(x, Tracer): return True return False def _is_numpy(x): return isinstance(x, np.ndarray) def is_numpy_array(x): """ Tests if `x` is a numpy array or not. """ return _is_numpy(x) def _is_torch(x): import torch return isinstance(x, torch.Tensor) def is_torch_tensor(x): """ Tests if `x` is a torch tensor or not. Safe to call even if torch is not installed. """ return False if not is_torch_available() else _is_torch(x) def _is_torch_device(x): import torch return isinstance(x, torch.device) def is_torch_device(x): """ Tests if `x` is a torch device or not. Safe to call even if torch is not installed. """ return False if not is_torch_available() else _is_torch_device(x) def _is_torch_dtype(x): import torch if isinstance(x, str): if hasattr(torch, x): x = getattr(torch, x) else: return False return isinstance(x, torch.dtype) def is_torch_dtype(x): """ Tests if `x` is a torch dtype or not. Safe to call even if torch is not installed. """ return False if not is_torch_available() else _is_torch_dtype(x) def _is_tensorflow(x): import tensorflow as tf return isinstance(x, tf.Tensor) def is_tf_tensor(x): """ Tests if `x` is a tensorflow tensor or not. Safe to call even if tensorflow is not installed. """ return False if not is_tf_available() else _is_tensorflow(x) def _is_tf_symbolic_tensor(x): import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(tf, "is_symbolic_tensor"): return tf.is_symbolic_tensor(x) return isinstance(x, tf.Tensor) def is_tf_symbolic_tensor(x): """ Tests if `x` is a tensorflow symbolic tensor or not (ie. not eager). Safe to call even if tensorflow is not installed. """ return False if not is_tf_available() else _is_tf_symbolic_tensor(x) def _is_jax(x): import jax.numpy as jnp # noqa: F811 return isinstance(x, jnp.ndarray) def is_jax_tensor(x): """ Tests if `x` is a Jax tensor or not. Safe to call even if jax is not installed. """ return False if not is_flax_available() else _is_jax(x) def _is_mlx(x): import mlx.core as mx return isinstance(x, mx.array) def is_mlx_array(x): """ Tests if `x` is a mlx array or not. Safe to call even when mlx is not installed. """ return False if not is_mlx_available() else _is_mlx(x) def to_py_obj(obj): """ Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list. """ if isinstance(obj, (int, float)): return obj elif isinstance(obj, (dict, UserDict)): return {k: to_py_obj(v) for k, v in obj.items()} elif isinstance(obj, (list, tuple)): try: arr = np.array(obj) if np.issubdtype(arr.dtype, np.integer) or np.issubdtype(arr.dtype, np.floating): return arr.tolist() except Exception: pass return [to_py_obj(o) for o in obj] framework_to_py_obj = { "pt": lambda obj: obj.tolist(), "tf": lambda obj: obj.numpy().tolist(), "jax": lambda obj: np.asarray(obj).tolist(), "np": lambda obj: obj.tolist(), } # This gives us a smart order to test the frameworks with the corresponding tests. framework_to_test_func = _get_frameworks_and_test_func(obj) for framework, test_func in framework_to_test_func.items(): if test_func(obj): return framework_to_py_obj[framework](obj) # tolist also works on 0d np arrays if isinstance(obj, np.number): return obj.tolist() else: return obj def to_numpy(obj): """ Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a Numpy array. """ framework_to_numpy = { "pt": lambda obj: obj.detach().cpu().numpy(), "tf": lambda obj: obj.numpy(), "jax": lambda obj: np.asarray(obj), "np": lambda obj: obj, } if isinstance(obj, (dict, UserDict)): return {k: to_numpy(v) for k, v in obj.items()} elif isinstance(obj, (list, tuple)): return np.array(obj) # This gives us a smart order to test the frameworks with the corresponding tests. framework_to_test_func = _get_frameworks_and_test_func(obj) for framework, test_func in framework_to_test_func.items(): if test_func(obj): return framework_to_numpy[framework](obj) return obj class ModelOutput(OrderedDict): """ Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular python dictionary. <Tip warning={true}> You can't unpack a `ModelOutput` directly. Use the [`~utils.ModelOutput.to_tuple`] method to convert it to a tuple before. </Tip> """ def __init_subclass__(cls) -> None: """Register subclasses as pytree nodes. This is necessary to synchronize gradients when using `torch.nn.parallel.DistributedDataParallel` with `static_graph=True` with modules that output `ModelOutput` subclasses. """ if is_torch_available(): if version.parse(get_torch_version()) >= version.parse("2.2"): from torch.utils._pytree import register_pytree_node register_pytree_node( cls, _model_output_flatten, partial(_model_output_unflatten, output_type=cls), serialized_type_name=f"{cls.__module__}.{cls.__name__}", ) else: from torch.utils._pytree import _register_pytree_node _register_pytree_node( cls, _model_output_flatten, partial(_model_output_unflatten, output_type=cls), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Subclasses of ModelOutput must use the @dataclass decorator # This check is done in __init__ because the @dataclass decorator operates after __init_subclass__ # issubclass() would return True for issubclass(ModelOutput, ModelOutput) when False is needed # Just need to check that the current class is not ModelOutput is_modeloutput_subclass = self.__class__ != ModelOutput if is_modeloutput_subclass and not is_dataclass(self): raise TypeError( f"{self.__module__}.{self.__class__.__name__} is not a dataclass." " This is a subclass of ModelOutput and so must use the @dataclass decorator." ) def __post_init__(self): """Check the ModelOutput dataclass. Only occurs if @dataclass decorator has been used. """ class_fields = fields(self) # Safety and consistency checks if not len(class_fields): raise ValueError(f"{self.__class__.__name__} has no fields.") if not all(field.default is None for field in class_fields[1:]): raise ValueError(f"{self.__class__.__name__} should not have more than one required field.") first_field = getattr(self, class_fields[0].name) other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:]) if other_fields_are_none and not is_tensor(first_field): if isinstance(first_field, dict): iterator = first_field.items() first_field_iterator = True else: try: iterator = iter(first_field) first_field_iterator = True except TypeError: first_field_iterator = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(iterator): if not isinstance(element, (list, tuple)) or len(element) != 2 or not isinstance(element[0], str): if idx == 0: # If we do not have an iterator of key/values, set it as attribute self[class_fields[0].name] = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f"Cannot set key/value for {element}. It needs to be a tuple (key, value)." ) break setattr(self, element[0], element[1]) if element[1] is not None: self[element[0]] = element[1] elif first_field is not None: self[class_fields[0].name] = first_field else: for field in class_fields: v = getattr(self, field.name) if v is not None: self[field.name] = v def __delitem__(self, *args, **kwargs): raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.") def setdefault(self, *args, **kwargs): raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.") def pop(self, *args, **kwargs): raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.") def update(self, *args, **kwargs): raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.") def __getitem__(self, k): if isinstance(k, str): inner_dict = dict(self.items()) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__(self, name, value): if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(name, value) super().__setattr__(name, value) def __setitem__(self, key, value): # Will raise a KeyException if needed super().__setitem__(key, value) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(key, value) def __reduce__(self): if not is_dataclass(self): return super().__reduce__() callable, _args, *remaining = super().__reduce__() args = tuple(getattr(self, field.name) for field in fields(self)) return callable, args, *remaining def to_tuple(self) -> tuple[Any]: """ Convert self to a tuple containing all the attributes/keys that are not `None`. """ return tuple(self[k] for k in self.keys()) if is_torch_available(): import torch.utils._pytree as _torch_pytree def _model_output_flatten(output: ModelOutput) -> tuple[list[Any], "_torch_pytree.Context"]: return list(output.values()), list(output.keys()) def _model_output_unflatten( values: Iterable[Any], context: "_torch_pytree.Context", output_type=None, ) -> ModelOutput: return output_type(**dict(zip(context, values))) if version.parse(get_torch_version()) >= version.parse("2.2"): _torch_pytree.register_pytree_node( ModelOutput, _model_output_flatten, partial(_model_output_unflatten, output_type=ModelOutput), serialized_type_name=f"{ModelOutput.__module__}.{ModelOutput.__name__}", ) else: _torch_pytree._register_pytree_node( ModelOutput, _model_output_flatten, partial(_model_output_unflatten, output_type=ModelOutput), ) class ExplicitEnum(str, Enum): """ Enum with more explicit error message for missing values. """ @classmethod def _missing_(cls, value): raise ValueError( f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}" ) class PaddingStrategy(ExplicitEnum): """ Possible values for the `padding` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an IDE. """ LONGEST = "longest" MAX_LENGTH = "max_length" DO_NOT_PAD = "do_not_pad" class TensorType(ExplicitEnum): """ Possible values for the `return_tensors` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an IDE. """ PYTORCH = "pt" TENSORFLOW = "tf" NUMPY = "np" JAX = "jax" MLX = "mlx" class ContextManagers: """ Wrapper for `contextlib.ExitStack` which enters a collection of context managers. Adaptation of `ContextManagers` in the `fastcore` library. """ def __init__(self, context_managers: list[ContextManager]): self.context_managers = context_managers self.stack = ExitStack() def __enter__(self): for context_manager in self.context_managers: self.stack.enter_context(context_manager) def __exit__(self, *args, **kwargs): self.stack.__exit__(*args, **kwargs) def can_return_loss(model_class): """ Check if a given model can return loss. Args: model_class (`type`): The class of the model. """ framework = infer_framework(model_class) if framework == "tf": signature = inspect.signature(model_class.call) # TensorFlow models elif framework == "pt": signature = inspect.signature(model_class.forward) # PyTorch models else: signature = inspect.signature(model_class.__call__) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def find_labels(model_class): """ Find the labels used by a given model. Args: model_class (`type`): The class of the model. """ model_name = model_class.__name__ framework = infer_framework(model_class) if framework == "tf": signature = inspect.signature(model_class.call) # TensorFlow models elif framework == "pt": signature = inspect.signature(model_class.forward) # PyTorch models else: signature = inspect.signature(model_class.__call__) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def flatten_dict(d: MutableMapping, parent_key: str = "", delimiter: str = "."): """Flatten a nested dict into a single level dict.""" def _flatten_dict(d, parent_key="", delimiter="."): for k, v in d.items(): key = str(parent_key) + delimiter + str(k) if parent_key else k if v and isinstance(v, MutableMapping): yield from flatten_dict(v, key, delimiter=delimiter).items() else: yield key, v return dict(_flatten_dict(d, parent_key, delimiter)) @contextmanager def working_or_temp_dir(working_dir, use_temp_dir: bool = False): if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def transpose(array, axes=None): """ Framework-agnostic version of `numpy.transpose` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.transpose(array, axes=axes) elif is_torch_tensor(array): return array.T if axes is None else array.permute(*axes) elif is_tf_tensor(array): import tensorflow as tf return tf.transpose(array, perm=axes) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.transpose(array, axes=axes) else: raise ValueError(f"Type not supported for transpose: {type(array)}.") def reshape(array, newshape): """ Framework-agnostic version of `numpy.reshape` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.reshape(array, newshape) elif is_torch_tensor(array): return array.reshape(*newshape) elif is_tf_tensor(array): import tensorflow as tf return tf.reshape(array, newshape) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.reshape(array, newshape) else: raise ValueError(f"Type not supported for reshape: {type(array)}.") def squeeze(array, axis=None): """ Framework-agnostic version of `numpy.squeeze` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.squeeze(array, axis=axis) elif is_torch_tensor(array): return array.squeeze() if axis is None else array.squeeze(dim=axis) elif is_tf_tensor(array): import tensorflow as tf return tf.squeeze(array, axis=axis) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.squeeze(array, axis=axis) else: raise ValueError(f"Type not supported for squeeze: {type(array)}.") def expand_dims(array, axis): """ Framework-agnostic version of `numpy.expand_dims` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.expand_dims(array, axis) elif is_torch_tensor(array): return array.unsqueeze(dim=axis) elif is_tf_tensor(array): import tensorflow as tf return tf.expand_dims(array, axis=axis) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.expand_dims(array, axis=axis) else: raise ValueError(f"Type not supported for expand_dims: {type(array)}.") def tensor_size(array): """ Framework-agnostic version of `numpy.size` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.size(array) elif is_torch_tensor(array): return array.numel() elif is_tf_tensor(array): import tensorflow as tf return tf.size(array) elif is_jax_tensor(array): return array.size else: raise ValueError(f"Type not supported for tensor_size: {type(array)}.") def infer_framework(model_class): """ Infers the framework of a given model without using isinstance(), because we cannot guarantee that the relevant classes are imported or available. """ for base_class in inspect.getmro(model_class): module = base_class.__module__ name = base_class.__name__ if module.startswith("tensorflow") or module.startswith("keras") or name == "TFPreTrainedModel": return "tf" elif module.startswith("torch") or name == "PreTrainedModel": return "pt" elif module.startswith("flax") or module.startswith("jax") or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(f"Could not infer framework from class {model_class}.") def torch_int(x): """ Casts an input to a torch int64 tensor if we are in a tracing context, otherwise to a Python int. """ if not is_torch_available(): return int(x) import torch return x.to(torch.int64) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x) def torch_float(x): """ Casts an input to a torch float32 tensor if we are in a tracing context, otherwise to a Python float. """ if not is_torch_available(): return int(x) import torch return x.to(torch.float32) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x) def filter_out_non_signature_kwargs(extra: Optional[list] = None): """ Decorator to filter out named arguments that are not in the function signature. This decorator ensures that only the keyword arguments that match the function's signature, or are specified in the `extra` list, are passed to the function. Any additional keyword arguments are filtered out and a warning is issued. Parameters: extra (`Optional[list]`, *optional*): A list of extra keyword argument names that are allowed even if they are not in the function's signature. Returns: Callable: A decorator that wraps the function and filters out invalid keyword arguments. Example usage: ```python @filter_out_non_signature_kwargs(extra=["allowed_extra_arg"]) def my_function(arg1, arg2, **kwargs): print(arg1, arg2, kwargs) my_function(arg1=1, arg2=2, allowed_extra_arg=3, invalid_arg=4) # This will print: 1 2 {"allowed_extra_arg": 3} # And issue a warning: "The following named arguments are not valid for `my_function` and were ignored: 'invalid_arg'" ``` """ extra = extra or [] extra_params_to_pass = set(extra) def decorator(func): sig = inspect.signature(func) function_named_args = set(sig.parameters.keys()) valid_kwargs_to_pass = function_named_args.union(extra_params_to_pass) # Required for better warning message is_instance_method = "self" in function_named_args is_class_method = "cls" in function_named_args # Mark function as decorated func._filter_out_non_signature_kwargs = True @wraps(func) def wrapper(*args, **kwargs): valid_kwargs = {} invalid_kwargs = {} for k, v in kwargs.items(): if k in valid_kwargs_to_pass: valid_kwargs[k] = v else: invalid_kwargs[k] = v if invalid_kwargs: invalid_kwargs_names = [f"'{k}'" for k in invalid_kwargs] invalid_kwargs_names = ", ".join(invalid_kwargs_names) # Get the class name for better warning message if is_instance_method: cls_prefix = args[0].__class__.__name__ + "." elif is_class_method: cls_prefix = args[0].__name__ + "." else: cls_prefix = "" warnings.warn( f"The following named arguments are not valid for `{cls_prefix}{func.__name__}`" f" and were ignored: {invalid_kwargs_names}", UserWarning, stacklevel=2, ) return func(*args, **valid_kwargs) return wrapper return decorator class TransformersKwargs(TypedDict, total=False): """ Keyword arguments to be passed to the loss function Attributes: num_items_in_batch (`Optional[torch.Tensor]`, *optional*): Number of items in the batch. It is recommended to pass it when you are doing gradient accumulation. output_hidden_states (`Optional[bool]`, *optional*): Most of the models support outputing all hidden states computed during the forward pass. output_attentions (`Optional[bool]`, *optional*): Turn this on to return the intermediary attention scores. output_router_logits (`Optional[bool]`, *optional*): For MoE models, this allows returning the router logits to compute the loss. cumulative_seqlens_q (`torch.LongTensor`, *optional*) Gets cumulative sequence length for query state. cumulative_seqlens_k (`torch.LongTensor`, *optional*) Gets cumulative sequence length for key state. max_length_q (`int`, *optional*): Maximum sequence length for query state. max_length_k (`int`, *optional*): Maximum sequence length for key state. """ num_items_in_batch: Optional["torch.Tensor"] output_hidden_states: Optional[bool] output_attentions: Optional[bool] output_router_logits: Optional[bool] cumulative_seqlens_q: Optional["torch.LongTensor"] cumulative_seqlens_k: Optional["torch.LongTensor"] max_length_q: Optional[int] max_length_k: Optional[int] def is_timm_config_dict(config_dict: dict[str, Any]) -> bool: """Checks whether a config dict is a timm config dict.""" return "pretrained_cfg" in config_dict def is_timm_local_checkpoint(pretrained_model_path: str) -> bool: """ Checks whether a checkpoint is a timm model checkpoint. """ if pretrained_model_path is None: return False # in case it's Path, not str pretrained_model_path = str(pretrained_model_path) is_file = os.path.isfile(pretrained_model_path) is_dir = os.path.isdir(pretrained_model_path) # pretrained_model_path is a file if is_file and pretrained_model_path.endswith(".json"): with open(pretrained_model_path) as f: config_dict = json.load(f) return is_timm_config_dict(config_dict) # pretrained_model_path is a directory with a config.json if is_dir and os.path.exists(os.path.join(pretrained_model_path, "config.json")): with open(os.path.join(pretrained_model_path, "config.json")) as f: config_dict = json.load(f) return is_timm_config_dict(config_dict) return False def set_attribute_for_modules(module: "torch.nn.Module", key: str, value: Any): """ Set a value to a module and all submodules. """ setattr(module, key, value) for submodule in module.children(): set_attribute_for_modules(submodule, key, value) def del_attribute_from_modules(module: "torch.nn.Module", key: str): """ Delete a value from a module and all submodules. """ # because we might remove it previously in case it's a shared module, e.g. activation function if hasattr(module, key): delattr(module, key) for submodule in module.children(): del_attribute_from_modules(submodule, key) def can_return_tuple(func): """ Decorator to wrap model method, to call output.to_tuple() if return_dict=False passed as a kwarg or use_return_dict=False is set in the config. Note: output.to_tuple() convert output to tuple skipping all `None` values. """ @wraps(func) def wrapper(self, *args, **kwargs): return_dict = self.config.return_dict if hasattr(self, "config") else True return_dict_passed = kwargs.pop("return_dict", return_dict) if return_dict_passed is not None: return_dict = return_dict_passed output = func(self, *args, **kwargs) if not return_dict and not isinstance(output, tuple): output = output.to_tuple() return output return wrapper # if is_torch_available(): # @torch._dynamo.disable @dataclass @requires(backends=("torch",)) class OutputRecorder: """ Configuration for recording outputs from a model via hooks. Attributes: target_class (Type): The class (e.g., nn.Module) to which the hook will be attached. index (Optional[int]): If the output is a tuple/list, optionally record only at a specific index. layer_name (Optional[str]): Name of the submodule to target (if needed), e.g., "transformer.layer.3.attn". class_name (Optional[str]): Name of the class to which the hook will be attached. Could be the suffix of class name in some cases. """ target_class: "type[torch.nn.Module]" index: Optional[int] = 0 layer_name: Optional[str] = None class_name: Optional[str] = None def check_model_inputs(func): """ Decorator to intercept specific layer outputs without using hooks. Compatible with torch.compile (Dynamo tracing). """ @wraps(func) def wrapper(self, *args, **kwargs): use_cache = kwargs.get("use_cache") if use_cache is None: use_cache = getattr(self.config, "use_cache", False) return_dict = kwargs.pop("return_dict", None) if return_dict is None: return_dict = getattr(self.config, "return_dict", True) if getattr(self, "gradient_checkpointing", False) and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False kwargs["use_cache"] = use_cache all_args = kwargs.copy() if "kwargs" in all_args: for k, v in all_args["kwargs"].items(): all_args[k] = v capture_flags = _CAN_RECORD_REGISTRY.get(str(self.__class__), {}) # there is a weak ref for executorch recordable_keys = { f"output_{k}": all_args.get( f"output_{k}", getattr( self.config, f"output_{k}", all_args.get("output_attentions", getattr(self.config, "output_attentions", False)), ), ) for k in capture_flags } collected_outputs = defaultdict(tuple) monkey_patched_layers = [] def make_capture_wrapper(module, orig_forward, key, index): @wraps(orig_forward) def wrapped_forward(*args, **kwargs): if key == "hidden_states" and len(collected_outputs[key]) == 0: collected_outputs[key] += (args[0],) if kwargs.get("debug_io", False): with model_addition_debugger_context( module, kwargs.get("debug_io_dir", "~/model_debug"), kwargs.get("prune_layers") ): output = orig_forward(*args, **kwargs) else: output = orig_forward(*args, **kwargs) if not isinstance(output, tuple): collected_outputs[key] += (output,) elif output[index] is not None: if key not in collected_outputs: collected_outputs[key] = (output[index],) else: collected_outputs[key] += (output[index],) return output return wrapped_forward if any(recordable_keys.values()): capture_tasks = [] for key, layer_specs in capture_flags.items(): if not recordable_keys.get(f"output_{key}", False): continue if not isinstance(layer_specs, list): layer_specs = [layer_specs] for specs in layer_specs: if not isinstance(specs, OutputRecorder): index = 0 if "hidden_states" in key else 1 class_name = None if not isinstance(specs, str) else specs target_class = specs if not isinstance(specs, str) else None specs = OutputRecorder(target_class=target_class, index=index, class_name=class_name) capture_tasks.append((key, specs)) for name, module in self.named_modules(): for key, specs in capture_tasks: # The second check is for multimodals where only backbone layer suffix is available if (specs.target_class is not None and isinstance(module, specs.target_class)) or ( specs.class_name is not None and name.endswith(specs.class_name) ): if specs.layer_name is not None and specs.layer_name not in name: continue # Monkey patch forward original_forward = module.forward module.forward = make_capture_wrapper(module, original_forward, key, specs.index) monkey_patched_layers.append((module, original_forward)) outputs = func(self, *args, **kwargs) # Restore original forward methods for module, original_forward in monkey_patched_layers: module.forward = original_forward # Inject collected outputs into model output for key in collected_outputs: if key == "hidden_states": collected_outputs[key] = collected_outputs[key][:-1] if hasattr(outputs, "vision_hidden_states"): collected_outputs[key] += (outputs.vision_hidden_states,) elif hasattr(outputs, "last_hidden_state"): collected_outputs[key] += (outputs.last_hidden_state,) outputs[key] = collected_outputs[key] elif key == "attentions": if isinstance(capture_flags[key], list) and len(capture_flags[key]) == 2: outputs[key] = collected_outputs[key][0::2] outputs["cross_" + key] = collected_outputs[key][1::2] else: outputs[key] = collected_outputs[key] else: outputs[key] = collected_outputs[key] if return_dict is False: outputs = outputs.to_tuple() return outputs return wrapper class GeneralInterface(MutableMapping): """ Dict-like object keeping track of a class-wide mapping, as well as a local one. Allows to have library-wide modifications though the class mapping, as well as local modifications in a single file with the local mapping. """ # Class instance object, so that a call to `register` can be reflected into all other files correctly, even if # a new instance is created (in order to locally override a given function) _global_mapping = {} def __init__(self): self._local_mapping = {} def __getitem__(self, key): # First check if instance has a local override if key in self._local_mapping: return self._local_mapping[key] return self._global_mapping[key] def __setitem__(self, key, value): # Allow local update of the default functions without impacting other instances self._local_mapping.update({key: value}) def __delitem__(self, key): del self._local_mapping[key] def __iter__(self): # Ensure we use all keys, with the overwritten ones on top return iter({**self._global_mapping, **self._local_mapping}) def __len__(self): return len(self._global_mapping.keys() | self._local_mapping.keys()) @classmethod def register(cls, key: str, value: Callable): cls._global_mapping.update({key: value}) def valid_keys(self) -> list[str]: return list(self.keys())
最新发布
08-08
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="error__6">Operation failed. Please try later.</string> <string name="error_263">No default tenant found, please contact service provider.</string> <string name="error__107">Failed to connect to the camera. Try again later.</string> <string name="error_004">Invalid email address.</string> <string name="error_006">Incorrect mobile number.</string> <string name="error_009">The phone number has already been registered once, please use another number or use this number to login.</string> <string name="error_010">Incorrect verification code.</string> <string name="error_011">The email address has been bound.</string> <string name="error_012">Failed to log in to the app. Please log in again.</string> <string name="error_018">Invalid application ID.</string> <string name="error_019">Invalid operation.</string> <string name="error_024">Invalid plug-in.</string> <string name="error_025">Operation failed. Please try later.</string> <string name="error_026">Plug-in does not exist.</string> <string name="error_027">Failed to log in to the app. Please log in again.</string> <string name="error_030">The terminal has been bound.</string> <string name="error_031">Operation failed. Please try later.</string> <string name="error_032">The terminal does not bind to this account.</string> <string name="error_033">Terminals are being operated by other users.</string> <string name="error_034">Operation failed. Please try later.</string> <string name="error_035">Failed to obtain the application list.</string> <string name="error_036">Failed to obtain the application image.</string> <string name="error_037">Failed to obtain the application version.</string> <string name="error_038">Failed to obtain the Wi-Fi coverage information.</string> <string name="error_040">The email address has not been bound to an account.</string> <string name="error_042">Operation failed. Please try later.</string> <string name="error_044">Operation failed. Please try later.</string> <string name="error_048">Operation failed. Please try later.</string> <string name="error_050">Operation failed. Please try later.</string> <string name="error_051">Operation failed. Please try later.</string> <string name="error_056">Configuration page query failed.</string> <string name="error_057">Operation failed. Please try later.</string> <string name="error_058">Plug-in list query failed.</string> <string name="error_059">Plug-in image query failed.</string> <string name="error_060">Operation failed. Please try later.</string> <string name="error_061">Operation failed. Please try later.</string> <string name="error_063">Invalid broadband account.</string> <string name="error_064">Operation failed. Please try later.</string> <string name="error_066">Invalid account type.</string> <string name="error_067">The password cannot be empty.</string> <string name="error_068">The confirmation password cannot be empty.</string> <string name="error_069">The account cannot be empty.</string> <string name="error_070">Incorrect PPPoE account.</string> <string name="error_072">The cloud account is empty.</string> <string name="error_073">Incorrect cloud account type.</string> <string name="error_075">The cloud account is registered.</string> <string name="error_076">The cloud account does not exist.</string> <string name="error_077">You have not bound any broadband account or gateway.</string> <string name="error_078">The MAC address of the device is not registered to the cloud platform. </string> <string name="error_081">The current binding relationship does not exist.</string> <string name="error_082">The user account does not exist.</string> <string name="error_087">Binding failed, No broadband account.</string> <string name="error_093">You have not bound any broadband account.</string> <string name="error_094">The number of gateways to be bound has reached the maximum. New gateways cannot be bound.</string> <string name="error_097">Broadband account verification is not currently available.</string> <string name="error_098">The device already exists.</string> <string name="error_099">The Wi-Fi SSID already exists.</string> <string name="error_100">The Wi-Fi SSID is empty.</string> <string name="error_101">The account is added.</string> <string name="error_103">The password will expire soon.</string> <string name="error_105">The user account is locked.</string> <string name="error_106">User login failed.</string> <string name="error_107">Exceeded the number limit of accounts that can be logged in at the same time.</string> <string name="error_108">Password complexity is invalid.</string> <string name="error_110">Incorrect mobile phone type.</string> <string name="error_111">The mobile phone version is empty.</string> <string name="error_112">Exceeded the password resetting limit in 24 hours.</string> <string name="error_113">Exceeded the number limit of security question attempts. The password resetting is locked.</string> <string name="error_114">Incorrect answer to the security question.</string> <string name="error_115">Invalid parameter for the security question.</string> <string name="error_116">Incorrect old password.</string> <string name="error_117">No plug-in version.</string> <string name="error_118">Incorrect password.</string> <string name="error_121">Invalid order number.</string> <string name="error_122">WO cloud account has been registered.</string> <string name="error_123">WO cloud account does not exist.</string> <string name="error_124">WO cloud client authentication failed.</string> <string name="error_133">Failed to join.</string> <string name="error_139">Only administrators have this permission.</string> <string name="error_144">The log file size exceeds 5 MB and cannot be uploaded.</string> <string name="error_145">Plug-in already exists.</string> <string name="error_146">Plug-in version already exists.</string> <string name="error_150">The log switch has been enabled.</string> <string name="error_151">The log switch has been disabled.</string> <string name="error_152">Failed to query third-party authentication information.</string> <string name="error_153">Failed to forward plug-in third-party authentication information.</string> <string name="error_154">Duplicate room name.</string> <string name="error_155">The message template cannot be left empty.</string> <string name="error_156">The message template does not exist.</string> <string name="error_157">The mapping SMS template does not exist.</string> <string name="error_158">The SMS gateway is unavailable.</string> <string name="error_159">The plug-in service name is left empty or does not exist.</string> <string name="error_160">The plug-in service code is left empty or does not exist.</string> <string name="error_161">The plug-in random code is left blank or does not exist.</string> <string name="error_162">The mobile number cannot be left empty.</string> <string name="error_163">Failed to connect to the SMS gateway.</string> <string name="error_164">Failed to bind the SMS gateway.</string> <string name="error_165">Failed to send the SMS message.</string> <string name="error_166">SMS sending timed out.</string> <string name="error_171">The email address for receiving an authentication code is not the email address of the administrator.</string> <string name="error_172">The format of the message notification switch is incorrect.</string> <string name="error_173">The user password of the storage service fails the verification.</string> <string name="error_174">Status of the gateway to which the user is bound is invalid.</string> <string name="error_175">The email server is not configured.</string> <string name="error_176">Failed to send the email.</string> <string name="error_184">Sender authentication on the email server failed.</string> <string name="error_185">Incorrect email address.</string> <string name="error_186">Operation failed. Please try later.</string> <string name="error_187">Operation failed. Please try later.</string> <string name="error_189">You do not have the permission to access the gateway.</string> <string name="error_192">This type of message is not currently supported by the SMS gateway.</string> <string name="error_193">Sessiontimeout must be specified if the speed-up interface oper_type is set to 0.</string> <string name="error_196">Image size too large.</string> <string name="error_197">Incorrect image format.</string> <string name="error_198">The plug-in software version is not available.</string> <string name="error_199">Mandatory parameter symbolicName not found.</string> <string name="error_200">The plug-in record is empty.</string> <string name="error_204">BSS is not configured.</string> <string name="error_205">Failed to register the cloud account.</string> <string name="error_209">Mandatory parameter #{field} is not carried or is left empty.</string> <string name="error_210">Invalid request format.</string> <string name="error_211">The password has expired.</string> <string name="error_212">The user is blocked.</string> <string name="error_213">The MAC address is not bound.</string> <string name="error_215">You have not purchased such type of device.</string> <string name="error_216">Failed to identify the device type.</string> <string name="error_217">The number of devices of this type exceeds the maximum allowed by the package.</string> <string name="error_218">The package has not been activated.</string> <string name="error_222">Cloud storage has not been configured on the web page.</string> <string name="error_226">The account is not bound to a mobile number.</string> <string name="error_227">The account is not bound to an email address.</string> <string name="error_228">The cloud storage parameters cannot be left empty.</string> <string name="error_230">Failed to create the temporary Amazon Cloud certificate.</string> <string name="error_231">The verification code has expired.</string> <string name="error_232">No profile image has been uploaded for the user.</string> <string name="error_233">The application has not been purchased.</string> <string name="error_234">Incorrect cloud storage configuration.</string> <string name="error_236">Failed to obtain the cloud token.</string> <string name="error_237">Non-current administrator to create sub-accounts</string> <string name="error_244">The mobile number cannot be used for login.</string> <string name="error_245">The email address cannot be used for login.</string> <string name="error_246">The account cannot be modified repeatedly.</string> <string name="error_248">The plug-in is the latest version.</string> <string name="error_249">The login has expired.</string> <string name="error_250">The plug-in is the latest version.</string> <string name="error_251">Users with no service provisioned cannot bind a gateway.</string> <string name="error_252">The mobile number bound to the new administrator does not match the number segment specified by the carrier.</string> <string name="error_253">The mobile phone number bound to the new administrator is not used.</string> <string name="error_254">The mobile phone number bound to the new administrator has been used.</string> <string name="error_256">Your account has been disabled.</string> <string name="error_1018">Your password has been reset, please set a new password on the cloud platform</string> <string name="error_30000001">Operation failed. Please try later.</string> <string name="error_30000101">The account already exists.</string> <string name="error_30000102">The account does not exist.</string> <string name="error_30000103">The new account already exists.</string> <string name="error_30000104">The mobile number already exists.</string> <string name="error_30000105">The email address already exists.</string> <string name="error_30000106">The package does not exist.</string> <string name="error_30000107">Product ID{#{field}} does not exist.</string> <string name="error_30000108">Incorrect email address format.</string> <string name="error_30000109">The password does not meet the complexity requirements. Enter a correct one.</string> <string name="error_30000110">The account is not an administrator account.</string> <string name="error_30000111">No gateway has been bound for the account.</string> <string name="error_30000112">Multiple gateways have been bound for the account.</string> <string name="error_30000113">The gateway bound to this account has been enabled for remote management.</string> <string name="error_30000114">The gateway bound to this account has suspended remote management</string> <string name="error_30000115">The package is not specified.</string> <string name="error_30000116">Failed to delete the storage service file.</string> <string name="error_30000121">Unknown northbound bundle operation.</string> <string name="error_30000122">The plug-in software version is not found.</string> <string name="error_30000123">The plug-in software version already exists.</string> <string name="error_30000124">Mandatory parameter symbolicName is not specified.</string> <string name="error_30000125">The plug-in record is empty.</string> <string name="error_30000126">The plug-in has been bound to an app.</string> <string name="error_30000127">The plug-in does not exist.</string> <string name="error_30000128">The format of the mobile number is incorrect.</string> <string name="error_30000129">A new account cannot be the same as the old account.</string> <string name="error_30000130">The password must be different from previous passwords.</string> <string name="error__1004">The service package is not available for use.</string> <string name="error__1008">The entered broadband account is inconsistent with the one used for dial-up access.</string> <string name="error__1011">The user is offline.</string> <string name="error__1012">Subscribed services have expired.</string> <string name="error__1014">The IP address is outside the IP address range that has access to smart speed-up.</string> <string name="error__1015">The remaining quota is zero.</string> <string name="error_2002">The room does not exist.</string> <string name="error_2003">The device SN does not exist.</string> <string name="error_2004">The device is already added.</string> <string name="error_2005">No such device service is purchased.</string> <string name="error_2006">The package is not activated.</string> <string name="error_2007">The number of devices exceeds the limit of package.</string> <string name="error_2008">The device name already exists.</string> <string name="error_10100502">The service is invalid.</string> <string name="error_10100503">The service has ceased.</string> <string name="error_10100505">The service package does not exist.</string> <string name="error_10100508">BOD services do not support accumulation.</string> <string name="error_10100509">No basic-bandwidth information is available to calculate the amount of additional BOD bandwidth required.</string> <string name="error_10100601">The service is not subscribed.</string> <string name="error_10100602">The service is in used.</string> <string name="error_10100604">The service is not in use and the acceleration does not need to be stopped.</string> <string name="error_999">Operation failed. Please try later.</string> <string name="error_999108">Operation failed. Please try later.</string> <string name="error_999100">Service cannot parse XML-request and detect necessary fields</string> <string name="error_999101">Account for requested login or contract number is not found (for methods like balance checking)</string> <string name="error_999102">The contract attachment of the requested number is not found.</string> <string name="error_999103">Service with the requested number is not found</string> <string name="error_999104">Wrong phone number format</string> <string name="error_999105">Wrong email format</string> <string name="error_999106">Password doesn\'t meet the requirements (too short, etc)</string> <string name="error_999107">Error of internal account identification</string> <string name="error_999200">Method is not supported or not currently available</string> <string name="error_999202">BSS returns an error indicating that changing the mobile phone number failed.</string> <string name="error_999203">BSS returns an error indicating that changing the email address failed.</string> <string name="error_999300">Error during internal request processing in billing system (it will be returned XML-structure with details of the error)</string> <string name="error_network_err">Connection timed out. Check your network connection.</string> <string name="error_40000002">The length exceeds the maximum limit.</string> <string name="error_40000005">The parameter value exceeds the maximum value.</string> <string name="error_40000006">The parameter value is less than the minimum value.</string> <string name="error_80010001">The scene name already exists.</string> <string name="error_80010002">The scene name is empty.</string> <string name="error_80010003">The scene contains non-existing or deleted devices.</string> <string name="error_80010004">The scene name does not exist.</string> <string name="error_80000001">The plug-in name is empty.</string> <string name="error_80000002">The data flag is empty.</string> <string name="error_80010005">The action of the device is empty.</string> <string name="error_80010006">The device type does not exist.</string> <string name="error_80011001">The app name does not exist.</string> <string name="error_80011002">The operation name is empty.</string> <string name="error_80011003">The service name does not exist.</string> <string name="error_80012001">The camera password is incorrect or locked.</string> <string name="error_80013001">More rooms are created than allowed.</string> <string name="error_80010007">Incorrect time format in the scheduled scene.</string> <string name="error_80010008">The action name is empty.</string> <string name="error_80010009">Name of trigger condition is empty.</string> <string name="error_1013">The MAC address of your gateway does not exist on the server.</string> <string name="logo_homeGatewayService.token.invalid">Your login has expired.</string> <string name="error_1014">The number of verification codes sent in your account has reached the maximum. Please try again tomorrow.</string> <string name="error_0x02163dc3">The number of same characters in a row in the password has exceeded the maximum.</string> <string name="error_0x02163dcc">Failed to input the correct old password.</string> <string name="error_0x02163dc1">The password does not meet requirements.</string> <string name="error_0x02163dc2">The length of the password does not meet requirements.</string> <string name="error_0x021639b8">The new password must contain at least two characters that are not used in the old password.</string> <string name="error_0x02163dc4">The password does not comply with the repetition policy.</string> <string name="error_0x02163dc6">The operation does not comply with the minimum modification time interval.</string> <string name="error_0035014004">Password entered incorrectly too many times, please wait %1$s minutes and try again.</string> <string name="error_276">The mobile number has been registered with another broadband service provider and cannot be invited.</string> <string name="error_across_tenant">The mobile number has been registered with another broadband service provider, so you cannot invite it.</string> <string name="error__11">Operation failed. Please try later.</string> <string name="error__12">Operation failed. Please try later.</string> <string name="error_HomeGatewayService_parameter_invalid">Incorrect request parameter.</string> <string name="error_HomeGatewayService_cmdtype_invalid">The current platform version does not support this function.</string> <string name="error_HomeGatewayService_service_invalid">Server error.</string> <string name="error_HomeGatewayService_homegateway_no_permission">You do not have permission to manage the gateway.</string> <string name="error_281">Failed to send the SMS message. Please contact your broadband service provider.</string> <string name="error_282">The server fails to send an SMS message because the mobile number is invalid.</string> <string name="error_283">The server fails to send an SMS message because the mobile number is invalid.</string> <string name="error_284">The server is busy sending SMS messages. Please try again later.</string> <string name="error_285">The server is busy sending SMS messages. Please try again later.</string> <string name="error_286">The server fails to send the SMS message because the content is invalid.</string> <string name="error_287">The server fails to send an SMS message because the number is in the blacklist.</string> <string name="error_288">The SMS message sent by the server contains sensitive words. Change your gateway remarks and try again.</string> <string name="error_0">Operation successful.</string> <string name="error_7">The gateway is busy and cannot process the current request. Try again later.</string> <string name="error__1">Operation failed. Please try later.</string> <string name="error__2">Network request timed out.</string> <string name="error__36">The Wi-Fi service has been disabled.</string> <string name="error__100">Failed to assign transit server port. Try again</string> <string name="error__101">Failed to connect to the transit server. Check if the server is online.</string> <string name="error__105">Failed to obtain the video service address of the camera</string> <string name="error__108">User authentication failed</string> <string name="error__202">When MLO is enabled, the authentication mode must be WPA2, WPA3, or WPA2/WPA3.</string> <string name="error_001">Duplicate username.</string> <string name="error_002">Passwords don’t match.</string> <string name="error_003">Incorrect username or password.</string> <string name="error_005">The length of the password does not meet requirements.</string> <string name="error_007">The username cannot be empty.</string> <string name="error_008">Duplicate nickname.</string> <string name="error_013">Incorrect username or password.</string> <string name="error_014">Exceeded the maximum number of terminals bound to the current account.</string> <string name="error_015">Exceeded the maximum number of accounts bound to this terminal.</string> <string name="error_016">No smart ONT has been bound</string> <string name="error_020">The gateway is offline.</string> <string name="error_021">You do not have the permission to access the gateway.</string> <string name="error_022">The gateway is not registered.</string> <string name="error_023">The username does not exist.</string> <string name="error_029">No terminal is bound to this account.</string> <string name="error_039">The mobile number has not been bound to an account.</string> <string name="error_041">Failed to modify the password: The old password is entered incorrectly.</string> <string name="error_043">The gateway connection timed out. Try again later or check whether the gateway network is connected.</string> <string name="error_045">Operation failed. Please try later.</string> <string name="error_046">Operation failed. Please try later.</string> <string name="error_047">Failed to obtain the device control list.</string> <string name="error_049">Exceeded the maximum number of controllable devices.</string> <string name="error_052">The gateway is not registered.</string> <string name="error_053">Device control is not supported.</string> <string name="error_054">Operation failed. Please try later.</string> <string name="error_055">Unknown error occurred on the device control template.</string> <string name="error_065">Problem description cannot be empty.</string> <string name="error_071">Not a smart gateway.</string> <string name="error_079">Operation failed: the gateway has been unbound.</string> <string name="error_080">Operation failed: the current account has not joined.</string> <string name="error_083">Operation failed. Please try later.</string> <string name="error_084">A non-invite user cannot modify the remarks.</string> <string name="error_085">Unbinding failed. Please try again later.</string> <string name="error_086">Devices exist in the room.</string> <string name="error_088">This app does not support non-smart gateways.</string> <string name="error_089">Binding failed. Please try again later.</string> <string name="error_090">Binding failed. Please try again later.</string> <string name="error_091">Binding failed. Please try again later.</string> <string name="error_092">The number of invited users has exceeded the upper limit.</string> <string name="error_095">Deletion failed. The last user cannot be deleted.</string> <string name="error_096">The list of network users to be deleted is empty.</string> <string name="error_102">The new password cannot be the same as any previous password.</string> <string name="error_104">The password has expired.</string> <string name="error_109">The greeting message is empty.</string> <string name="error_119">The room name cannot be empty.</string> <string name="error_120">The room ID cannot be empty.</string> <string name="error_125">The username does not meet the complexity requirements. Enter a correct one.</string> <string name="error_126">The username cannot be empty.</string> <string name="error_127">The username does not meet the complexity requirements. Enter a correct one.</string> <string name="error_128">No mobile number is bound.</string> <string name="error_129">This mobile number is not a administrator account.</string> <string name="error_130">The mobile number must be a Bahraini number.</string> <string name="error_131">The mobile number has been bound.</string> <string name="error_132">No phone number is bound to the current account.</string> <string name="error_134">Administrators cannot leave.</string> <string name="error_135">The mobile number is not bound to any account.</string> <string name="error_136">The login has expired.</string> <string name="error_140">The device has been updated to the latest version.</string> <string name="error_141">No new version is available.</string> <string name="error_143">Incorrect log file format.</string> <string name="error_147">The gateway is being upgraded.</string> <string name="error_148">The phone number has already been registered once, please use another number or use this number to login.</string> <string name="error_149">Duplicate room name.</string> <string name="error_167">Operation failed. Please try later.</string> <string name="error_168">Starting the plug-in…</string> <string name="error_169">Stopping the plug-in…</string> <string name="error_170">Uninstalling the plug-in…</string> <string name="error_188">The gateway does not exist.</string> <string name="error_190">You do not have access to this gateway.</string> <string name="error_191">The message push type is empty or of an incorrect format.</string> <string name="error_194">Operation failed. Please try later.</string> <string name="error_195">You cannot invite other network members to join.</string> <string name="error_LHConsumerService_login_accountRoleMismatch">Members from other enterprises are not allowed.</string> <string name="error_LHConsumerService_bindGroup_exceedMaxBindGroupNum">Members from other enterprises are not allowed.</string> <string name="error_201">Failed to check the remaining balance.</string> <string name="error_202">Failed to change the mobile number.</string> <string name="error_203">Failed to change the email address.</string> <string name="error_214">Incorrect addedDeviceList format.</string> <string name="error_219">The password cannot be the same as the username or the username in reverse.</string> <string name="error_220">You do not have the administrative permission.</string> <string name="error_221">Failed to uninstall all the plug-ins of the home gateway.</string> <string name="error_224">The new gateway is not registered.</string> <string name="error_225">The new home gateway has been bound.</string> <string name="error_238">Your account has not been bound with a mobile number or email address. The password cannot be retrieved through self service. You are advised to contact your administrator to retrieve the password.</string> <string name="error_239">The mobile number is bound to multiple accounts.</string> <string name="error_240">The email address is bound to multiple accounts.</string> <string name="error_247">Anonymous binding information cannot be queried by using a mobile number or an email address.</string> <string name="error_255">The account has been bound to a gateway, and cannot be bound to another one.</string> <string name="error_272">Incorrect username or password.</string> <string name="error_1002">The interval between requests for sending verification codes is too short.</string> <string name="error_30000117">The home gateway MAC address does not exist.</string> <string name="error_30000118">The home gateway is offline.</string> <string name="error_30000119">The home gateway plug-in does not exist.</string> <string name="error_30000120">The plug-in is not installed or not upgraded on the home gateway.</string> <string name="error__1013">The MAC address (XXX) of your gateway does not exist on the server.</string> <string name="error_2001">The input parameter is empty.</string> <string name="error_40000001">The parameter contains unsupported special characters.</string> <string name="error_40000003">The length is less than the minimum limit.</string> <string name="error_40000004">The parameter is not a numeric type.</string> <string name="error_40000007">Invalid IP address.</string> <string name="net_conn_failed">Connection failed.</string> <string name="error__3">Connection failed.</string> <string name="error__4">The gateway is busy and cannot process the current request. Try again later.</string> <string name="error__5">Operation failed. Please try later.</string> <string name="error__7">Operation failed. Please try later.</string> <string name="error__8">Not supported by the gateway.</string> <string name="error__9">Operation failed. Please try later.</string> <string name="error__10">Your login has expired. Please log in again.</string> <string name="error_280">Failed to send the SMS message. Please try again later.</string> <string name="error_300">The current server version does not support user name registration.</string> <string name="error__102">Camera offline or camera connection failed. Check if the camera is powered on.</string> <string name="error__104">Camera video service address illegal, please report impaired</string> <string name="error__106">Gateway cannot connect to the transit server. Check if the server is online.</string> <string name="error__200">Reached the upper limit.</string> <string name="error__201">When MLO is enabled, the working mode must be 802.11be.</string> <string name="error__203">Saving Wi-Fi settings. Please wait.</string> <string name="error__204">Incorrect request parameter.</string> <string name="error__205">The Wi-Fi frequency band is not enabled. Enable it first.</string> <string name="error__301">Fails to play the real-time video of the camera. Failed to connect to the gateway locally.</string> <string name="error__330">Application control is not enabled. Please enable it first.</string> <string name="error__331">The number of application control policies has reached the upper limit.</string> <string name="error__332">The app control rule does not exist.</string> <string name="error__622">The rate limit periods cannot overlap with each other.</string> <string name="error_028">Your account has been used for login on another device. If this was done without your knowledge, your account and password may have been compromised. Choose Settings > Account And Security to change your account password.</string> <string name="error_2009">Failed to query the package status.</string> <string name="error__99999">Operation failed. Please try later.</string> <string name="error_1017">The MAC address cannot be empty.</string> <string name="error_licence_expire">Licence expired, please contact service provider.</string> <string name="LHConsumerService.bindLocalAccount.hasFamily">The account is already in a family.</string> <string name="LHConsumerService.bindLocalAccount.bound">Already bound to another account.</string> <string name="LHConsumerService.weakvalue.error">The password is too simple.</string> <string name="error_LHConsumerService_feedback_daylimit">The number of problems you reported has reached the upper limit. Try again 24 hours later.</string> <string name="error_306">Failed to send the verification code.The possible cause is that the mobile number format is incorrect or the mobile number has been bound.</string> <string name="error_307">Failed to send the verification code.The possible cause is that the email address format is incorrect or the email address has been bound.</string> <string name="error_308">Failed to send the verification code.The possible cause is that the mobile number format is incorrect or the mobile number is not bound.</string> <string name="error_309">Failed to send the verification code.The possible cause is that the email address format is incorrect or the email address is not bound.</string> <string name="error_310">The client IP address is locked,please try again later.</string> <string name="error_311">The current version does not support multi-factor authentication. Contact the administrator to disable multi-factor authentication.</string> <string name="error__340">The portal function has been enabled. The speed limit cannot be configured. To set the rate limit, disable Portal authentication on the web management page of the gateway.</string> <string name="error_AppSdk_notInitialized">Failed to initialize the app. Please log in again.</string> <string name="error_log_collect_offline">Device is offline</string> <string name="error_log_collect_conflict">Another collection task of the device is in progress.</string> <string name="error_log_collect_failed">Log collection failed</string> <string name="LHConsumerService.domainMigration.notSupportBinding">The server has been switched. Please switch to the corresponding region and register again.</string> <string name="error__41">Failed to set the 5G Wi-Fi because it has been locked. Contact your carrier to enable it first.</string> <string name="error__14">The same Wi-Fi SSID already exists in the current frequency band.</string> <string name="BindGateway_101">You have joined a family. Please refresh the home page and view it.</string> <string name="error_third_platform_user">Third-party users exist, unbinding failed.</string> </resources>
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值