Remove Pydantic v2 patch from Lite (#8799)

* Remove Pydantic v2 patch as it's now natively provided by Pyodide>=0.26.1 (ref: https://github.com/pyodide/pyodide/pull/4500)

* add changeset

* add changeset

* Fix

* add changeset

---------

Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
This commit is contained in:
Yuichiro Tachibana (Tsuchiya) 2024-07-18 10:39:40 +09:00 committed by GitHub
parent 2cc813a287
commit 61bb5883a2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 12 additions and 76 deletions

View File

@ -0,0 +1,6 @@
---
"@gradio/wasm": patch
"gradio": patch
---
fix:Remove Pydantic v2 patch from Lite

View File

@ -8,81 +8,19 @@ import secrets
import shutil
from abc import ABC, abstractmethod
from enum import Enum, auto
from typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple, TypedDict, Union
from typing import Any, List, Literal, Optional, Tuple, TypedDict, Union
from fastapi import Request
from gradio_client.documentation import document
from gradio_client.utils import traverse
from pydantic import BaseModel, RootModel, ValidationError
from typing_extensions import NotRequired
from . import wasm_utils
if not wasm_utils.IS_WASM or TYPE_CHECKING:
from pydantic import BaseModel, RootModel, ValidationError
try:
from pydantic import JsonValue
except ImportError:
JsonValue = Any
else:
# XXX: Currently Pyodide V2 is not available on Pyodide,
# so we install V1 for the Wasm version.
from typing import Generic, TypeVar
from pydantic import BaseModel as BaseModelV1
from pydantic import ValidationError, schema_of
try:
from pydantic import JsonValue
except ImportError:
JsonValue = Any
# Map V2 method calls to V1 implementations.
# Ref: https://docs.pydantic.dev/latest/migration/#changes-to-pydanticbasemodel
class BaseModelMeta(type(BaseModelV1)):
def __new__(cls, name, bases, dct):
# Override `dct` to dynamically create a `Config` class based on `model_config`.
if "model_config" in dct:
config_class = type("Config", (), {})
for key, value in dct["model_config"].items():
setattr(config_class, key, value)
dct["Config"] = config_class
del dct["model_config"]
model_class = super().__new__(cls, name, bases, dct)
return model_class
class BaseModel(BaseModelV1, metaclass=BaseModelMeta):
pass
BaseModel.model_dump = BaseModel.dict # type: ignore
BaseModel.model_json_schema = BaseModel.schema # type: ignore
# RootModel is not available in V1, so we create a dummy class.
PydanticUndefined = object()
RootModelRootType = TypeVar("RootModelRootType")
class RootModel(BaseModel, Generic[RootModelRootType]):
root: RootModelRootType
def __init__(self, root: RootModelRootType = PydanticUndefined, **data):
if data:
if root is not PydanticUndefined:
raise ValueError(
'"RootModel.__init__" accepts either a single positional argument or arbitrary keyword arguments'
)
root = data # type: ignore
# XXX: No runtime validation is executed.
super().__init__(root=root) # type: ignore
def dict(self, **kwargs):
return super().dict(**kwargs)["root"]
@classmethod
def schema(cls, **_kwargs):
# XXX: kwargs are ignored.
return schema_of(cls.__fields__["root"].type_) # type: ignore
RootModel.model_dump = RootModel.dict # type: ignore
RootModel.model_json_schema = RootModel.schema # type: ignore
class CancelBody(BaseModel):
session_hash: str

View File

@ -1,12 +1,7 @@
from typing import List, Literal, Optional, Union
from gradio_client.utils import ServerMessage
# In the data_classes.py file, the BaseModel class is patched
# so that it can be used in both Pyodide and non-Pyodide environments.
# So we import it from the data_classes.py file
# instead of the original Pydantic BaseModel class.
from gradio.data_classes import BaseModel
from pydantic import BaseModel
class BaseMessage(BaseModel):

View File

@ -80,7 +80,6 @@ async function initializeEnvironment(
updateProgress("Loading Gradio wheels");
await pyodide.loadPackage(["ssl", "setuptools"]);
await micropip.add_mock_package("ffmpy", "0.3.0");
await micropip.add_mock_package("pydantic", "2.4.2"); // PydanticV2 is not supported on Pyodide yet. Mock it here for installing the `gradio` package to pass the version check. Then, install PydanticV1 below.
await micropip.install.callKwargs(
[
"typing-extensions>=4.8.0", // Typing extensions needs to be installed first otherwise the versions from the pyodide lockfile is used which is incompatible with the latest fastapi.
@ -93,8 +92,6 @@ async function initializeEnvironment(
await micropip.install.callKwargs(gradioWheelUrls, {
keep_going: true
});
await micropip.remove_mock_package("pydantic");
await micropip.install(["pydantic==1.*"]); // Pydantic is necessary for `gradio` to run, so install v1 here as a fallback. Some tricks has been introduced in `gradio/data_classes.py` to make it work with v1.
console.debug("Gradio wheels are loaded.");
console.debug("Mocking os module methods.");