rusticai-huggingface 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rusticai_huggingface-0.0.1/PKG-INFO +50 -0
- rusticai_huggingface-0.0.1/README.md +17 -0
- rusticai_huggingface-0.0.1/pyproject.toml +82 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/__init__.py +0 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/__init__.py +0 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/diffusion/__init__.py +0 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/diffusion/pix2pix.py +95 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/diffusion/stable_diffusion_agent.py +97 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/llm/__init__.py +0 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/llm/phi_agent.py +47 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/models.py +43 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/nlp/__init__.py +0 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/nlp/squad_agent.py +52 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/text_to_speech/__init__.py +0 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/text_to_speech/speecht5_tts_agent.py +74 -0
- rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/inference_mixin.py +36 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: rusticai-huggingface
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Rustic AI module with huggingface integrations
|
|
5
|
+
Home-page: https://www.rustic.ai/
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Author: Dragonscale Industries Inc.
|
|
8
|
+
Author-email: dev@dragonscale.ai
|
|
9
|
+
Requires-Python: >=3.12,<4.0
|
|
10
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Provides-Extra: all
|
|
15
|
+
Provides-Extra: audio
|
|
16
|
+
Provides-Extra: image
|
|
17
|
+
Provides-Extra: llm
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: accelerate (>=1.6.0,<2.0.0)
|
|
20
|
+
Requires-Dist: datasets (>=3.5.0,<4.0.0) ; extra == "audio" or extra == "all"
|
|
21
|
+
Requires-Dist: diffusers (>=0.33.1,<0.34.0) ; extra == "image" or extra == "all"
|
|
22
|
+
Requires-Dist: pillow (>=11.2.1,<12.0.0) ; extra == "image" or extra == "all"
|
|
23
|
+
Requires-Dist: protobuf (>=6.30.2,<7.0.0) ; extra == "image" or extra == "all"
|
|
24
|
+
Requires-Dist: rusticai-core (>=0.0.5,<0.1.0)
|
|
25
|
+
Requires-Dist: sentencepiece (>=0.2.0,<0.3.0) ; extra == "audio" or extra == "all"
|
|
26
|
+
Requires-Dist: soundfile (>=0.13.1,<0.14.0) ; extra == "audio" or extra == "all"
|
|
27
|
+
Requires-Dist: torch (>=2.4.0,<3.0.0) ; extra == "llm" or extra == "audio" or extra == "image" or extra == "all"
|
|
28
|
+
Requires-Dist: transformers (>=4.51.2,<5.0.0) ; extra == "llm" or extra == "all"
|
|
29
|
+
Project-URL: Repository, https://github.com/rustic-ai/python-framework
|
|
30
|
+
Project-URL: Rustic AI Core, https://pypi.org/project/rusticai-core/
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# Rustic AI Hugging Face
|
|
34
|
+
|
|
35
|
+
[Rustic AI](https://www.rustic.ai/) module which provides agents and mixin leveraging [Hugging Face](https://huggingface.co/).
|
|
36
|
+
|
|
37
|
+
## Installing
|
|
38
|
+
|
|
39
|
+
```shell
|
|
40
|
+
pip install rusticai-huggingface
|
|
41
|
+
```
|
|
42
|
+
**Note:** It depends on [rusticai-core](https://pypi.org/project/rusticai-core/).
|
|
43
|
+
|
|
44
|
+
## Building from Source
|
|
45
|
+
|
|
46
|
+
```shell
|
|
47
|
+
poetry install --with dev --all-extras
|
|
48
|
+
poetry build
|
|
49
|
+
```
|
|
50
|
+
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Rustic AI Hugging Face
|
|
2
|
+
|
|
3
|
+
[Rustic AI](https://www.rustic.ai/) module which provides agents and mixin leveraging [Hugging Face](https://huggingface.co/).
|
|
4
|
+
|
|
5
|
+
## Installing
|
|
6
|
+
|
|
7
|
+
```shell
|
|
8
|
+
pip install rusticai-huggingface
|
|
9
|
+
```
|
|
10
|
+
**Note:** It depends on [rusticai-core](https://pypi.org/project/rusticai-core/).
|
|
11
|
+
|
|
12
|
+
## Building from Source
|
|
13
|
+
|
|
14
|
+
```shell
|
|
15
|
+
poetry install --with dev --all-extras
|
|
16
|
+
poetry build
|
|
17
|
+
```
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["poetry-core"]
|
|
3
|
+
build-backend = "poetry.core.masonry.api"
|
|
4
|
+
|
|
5
|
+
[tool.poetry]
|
|
6
|
+
name = "rusticai-huggingface"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
description = "Rustic AI module with huggingface integrations"
|
|
9
|
+
authors = ["Dragonscale Industries Inc. <dev@dragonscale.ai>"]
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
readme = "README.md"
|
|
12
|
+
homepage = "https://www.rustic.ai/"
|
|
13
|
+
repository = "https://github.com/rustic-ai/python-framework"
|
|
14
|
+
packages = [{ include = "rustic_ai", from = "src" }]
|
|
15
|
+
|
|
16
|
+
[tool.poetry.urls]
|
|
17
|
+
"Rustic AI Core" = "https://pypi.org/project/rusticai-core/"
|
|
18
|
+
|
|
19
|
+
[tool.poetry.dependencies]
|
|
20
|
+
python = "^3.12"
|
|
21
|
+
rusticai-core = { version = "0.0.5"}
|
|
22
|
+
accelerate = "^1.6.0"
|
|
23
|
+
transformers = { version = "^4.51.2", optional = true }
|
|
24
|
+
torch = { version = "^2.4.0", optional = true }
|
|
25
|
+
datasets = { version = "^3.5.0", optional = true }
|
|
26
|
+
soundfile = { version = "^0.13.1", optional = true }
|
|
27
|
+
sentencepiece = { version = "^0.2.0", optional = true }
|
|
28
|
+
diffusers = { version = "^0.33.1", optional = true }
|
|
29
|
+
protobuf = { version = "^6.30.2", optional = true }
|
|
30
|
+
pillow = { version = "^11.2.1", optional = true }
|
|
31
|
+
|
|
32
|
+
[tool.poetry-monorepo.deps]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
[tool.poetry.group.dev]
|
|
36
|
+
optional = true
|
|
37
|
+
|
|
38
|
+
[tool.poetry.group.dev.dependencies]
|
|
39
|
+
pytest = "^8.3.4"
|
|
40
|
+
black = { version = "^24.2.0", extras = ["jupyter"] }
|
|
41
|
+
flake8 = "^7.1.2"
|
|
42
|
+
tox = "^4.24.1"
|
|
43
|
+
isort = "^6.0.0"
|
|
44
|
+
mypy = "^1.15.0"
|
|
45
|
+
|
|
46
|
+
[tool.poetry.extras]
|
|
47
|
+
test = ["pytest"]
|
|
48
|
+
llm = ["torch", "transformers"]
|
|
49
|
+
audio = ["torch", "soundfile", "sentencepiece", "datasets"]
|
|
50
|
+
image = ["torch", "diffusers", "pillow", "protobuf"]
|
|
51
|
+
all = ["torch", "soundfile", "sentencepiece", "datasets", "diffusers", "pillow", "protobuf", "transformers"]
|
|
52
|
+
|
|
53
|
+
[tool.black]
|
|
54
|
+
line-length = 120
|
|
55
|
+
target-version = ['py312']
|
|
56
|
+
include = '\.pyi?$'
|
|
57
|
+
exclude = '''
|
|
58
|
+
/(
|
|
59
|
+
\.git
|
|
60
|
+
| \.mypy_cache
|
|
61
|
+
| \.tox
|
|
62
|
+
| \.venv
|
|
63
|
+
| _build
|
|
64
|
+
| buck-out
|
|
65
|
+
| build
|
|
66
|
+
| dist
|
|
67
|
+
)/
|
|
68
|
+
'''
|
|
69
|
+
|
|
70
|
+
[tool.mypy]
|
|
71
|
+
python_version = "3.12"
|
|
72
|
+
ignore_missing_imports = true
|
|
73
|
+
check_untyped_defs = true
|
|
74
|
+
plugins = "pydantic.mypy"
|
|
75
|
+
explicit_package_bases = true
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
[tool.isort]
|
|
79
|
+
profile = "black"
|
|
80
|
+
known_third_party = ["pydantic"]
|
|
81
|
+
known_first_party = ["rustic_ai.core", "rustic_ai.huggingface"]
|
|
82
|
+
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import mimetypes
|
|
2
|
+
import uuid
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
from diffusers import (
|
|
6
|
+
EulerAncestralDiscreteScheduler,
|
|
7
|
+
StableDiffusionInstructPix2PixPipeline,
|
|
8
|
+
)
|
|
9
|
+
from PIL import Image, ImageOps
|
|
10
|
+
|
|
11
|
+
from rustic_ai.core.agents.commons.media import MediaLink
|
|
12
|
+
from rustic_ai.core.agents.commons.message_formats import ErrorMessage
|
|
13
|
+
from rustic_ai.core.guild import agent
|
|
14
|
+
from rustic_ai.core.guild.agent import Agent, ProcessContext
|
|
15
|
+
from rustic_ai.core.guild.agent_ext.depends.filesystem import FileSystem
|
|
16
|
+
from rustic_ai.core.guild.dsl import AgentSpec
|
|
17
|
+
from rustic_ai.huggingface.agents.models import (
|
|
18
|
+
ImageGenerationRequest,
|
|
19
|
+
ImageGenerationResponse,
|
|
20
|
+
PyTorchAgentProps,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ImageQuery(ImageGenerationRequest):
|
|
25
|
+
image_path: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Pix2PixProps(PyTorchAgentProps):
|
|
29
|
+
model_id: str = "timbrooks/instruct-pix2pix"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Image2ImageAgent(Agent[Pix2PixProps]):
|
|
33
|
+
"""
|
|
34
|
+
Generate image from a given image and a query
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, agent_spec: AgentSpec[Pix2PixProps]):
|
|
38
|
+
super().__init__(agent_spec)
|
|
39
|
+
if agent_spec.properties is None:
|
|
40
|
+
agent_spec.properties = Pix2PixProps()
|
|
41
|
+
self.torch_device = agent_spec.properties.torch_device
|
|
42
|
+
model_id = agent_spec.properties.model_id
|
|
43
|
+
|
|
44
|
+
self._pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained(model_id, safety_checker=None)
|
|
45
|
+
self._pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(self._pipeline.scheduler.config)
|
|
46
|
+
self._pipeline.to(torch.device(self.torch_device))
|
|
47
|
+
|
|
48
|
+
@agent.processor(ImageQuery, depends_on=["filesystem:guild_fs:True"])
|
|
49
|
+
def process_user_query(self, ctx: ProcessContext[ImageQuery], guild_fs: FileSystem) -> None:
|
|
50
|
+
"""
|
|
51
|
+
Process the users query
|
|
52
|
+
"""
|
|
53
|
+
image_gen_request = ctx.payload
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
with guild_fs.open(image_gen_request.image_path, "rb") as f:
|
|
57
|
+
loaded_image = Image.open(f)
|
|
58
|
+
image = ImageOps.exif_transpose(loaded_image)
|
|
59
|
+
if image is not None:
|
|
60
|
+
image = image.convert("RGB")
|
|
61
|
+
else:
|
|
62
|
+
raise ValueError("Image cannot be none")
|
|
63
|
+
|
|
64
|
+
prompt = [image_gen_request.generation_prompt] * image_gen_request.num_images
|
|
65
|
+
image_input = [image] * image_gen_request.num_images
|
|
66
|
+
output_images = self._pipeline(
|
|
67
|
+
prompt,
|
|
68
|
+
image=image_input,
|
|
69
|
+
num_inference_steps=image_gen_request.num_inference_steps,
|
|
70
|
+
guidance_scale=image_gen_request.guidance_scale,
|
|
71
|
+
height=image_gen_request.height,
|
|
72
|
+
width=image_gen_request.width,
|
|
73
|
+
).images
|
|
74
|
+
|
|
75
|
+
result = ImageGenerationResponse(files=[], errors=[], request=image_gen_request.model_dump_json())
|
|
76
|
+
for output_image in output_images:
|
|
77
|
+
filename = f"{uuid.uuid4()}.{image_gen_request.image_format}"
|
|
78
|
+
try:
|
|
79
|
+
with guild_fs.open(filename, "wb") as f:
|
|
80
|
+
output_image.save(f)
|
|
81
|
+
media_link = MediaLink(
|
|
82
|
+
url=filename, name=filename, mimetype=mimetypes.guess_type(filename)[0], on_filesystem=True
|
|
83
|
+
)
|
|
84
|
+
result.files.append(media_link)
|
|
85
|
+
except Exception as e:
|
|
86
|
+
result.errors.append(f"Failed to write image file {filename}:{e}")
|
|
87
|
+
ctx.send(result)
|
|
88
|
+
except Exception as ex:
|
|
89
|
+
ctx.send(
|
|
90
|
+
ErrorMessage(
|
|
91
|
+
agent_type=self.get_qualified_class_name(),
|
|
92
|
+
error_type="ImageGenerationError",
|
|
93
|
+
error_message=str(ex),
|
|
94
|
+
)
|
|
95
|
+
)
|
rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/diffusion/stable_diffusion_agent.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import mimetypes
|
|
2
|
+
import uuid
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
from diffusers import StableDiffusion3Pipeline
|
|
6
|
+
|
|
7
|
+
from rustic_ai.core.agents.commons.media import MediaLink
|
|
8
|
+
from rustic_ai.core.agents.commons.message_formats import ErrorMessage
|
|
9
|
+
from rustic_ai.core.guild import (
|
|
10
|
+
Agent,
|
|
11
|
+
AgentMode,
|
|
12
|
+
AgentSpec,
|
|
13
|
+
AgentType,
|
|
14
|
+
agent,
|
|
15
|
+
)
|
|
16
|
+
from rustic_ai.core.guild.agent_ext.depends.filesystem import FileSystem
|
|
17
|
+
from rustic_ai.huggingface.agents.models import (
|
|
18
|
+
ImageGenerationRequest,
|
|
19
|
+
ImageGenerationResponse,
|
|
20
|
+
PyTorchAgentProps,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RunwaymlStableDiffusionProps(PyTorchAgentProps):
|
|
25
|
+
model_id: str = "stabilityai/stable-diffusion-3.5-medium"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class RunwaymlStableDiffusionAgent(Agent[RunwaymlStableDiffusionProps]):
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
agent_spec: AgentSpec[RunwaymlStableDiffusionProps],
|
|
32
|
+
) -> None:
|
|
33
|
+
"""
|
|
34
|
+
Initializes the RunwaymlStableDiffusionAgent with the specified agent specification and sets up the Stable Diffusion pipeline.
|
|
35
|
+
|
|
36
|
+
Note:
|
|
37
|
+
If you run into a "Fatal Python error: Bus error", try passing `safety_checker=None` to the `from_pretrained` method.
|
|
38
|
+
Reference: https://huggingface.co/docs/diffusers/en/using-diffusers/loading#safety-checker
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
agent_spec (AgentSpec[RunwaymlStableDiffusionProps]): The agent specification containing the properties for the Stable Diffusion agent.
|
|
42
|
+
"""
|
|
43
|
+
super().__init__(
|
|
44
|
+
agent_spec=agent_spec,
|
|
45
|
+
agent_type=AgentType.BOT,
|
|
46
|
+
agent_mode=AgentMode.LOCAL,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
if agent_spec.properties is None:
|
|
50
|
+
agent_spec.properties = RunwaymlStableDiffusionProps()
|
|
51
|
+
self.torch_device = agent_spec.properties.torch_device
|
|
52
|
+
model_id = agent_spec.properties.model_id
|
|
53
|
+
|
|
54
|
+
self._pipeline = StableDiffusion3Pipeline.from_pretrained(
|
|
55
|
+
model_id, torch_dtype=torch.float32, use_safetensors=True
|
|
56
|
+
)
|
|
57
|
+
self._pipeline.to(torch.device(self.torch_device))
|
|
58
|
+
|
|
59
|
+
@agent.processor(ImageGenerationRequest, depends_on=["filesystem:guild_fs:True"])
|
|
60
|
+
def generate_image(self, ctx: agent.ProcessContext[ImageGenerationRequest], guild_fs: FileSystem) -> None:
|
|
61
|
+
"""
|
|
62
|
+
Generates an image from the given prompt using the stable diffusion model.
|
|
63
|
+
The underlying model takes the generation prompt as input and returns a list of images.
|
|
64
|
+
The generated image format is "png".
|
|
65
|
+
Note: This method leverages the filesystem dependency to save the generated images.
|
|
66
|
+
"""
|
|
67
|
+
image_gen_request = ctx.payload
|
|
68
|
+
|
|
69
|
+
prompt = [image_gen_request.generation_prompt] * image_gen_request.num_images
|
|
70
|
+
try:
|
|
71
|
+
output_images = self._pipeline(
|
|
72
|
+
prompt,
|
|
73
|
+
guidance_scale=image_gen_request.guidance_scale,
|
|
74
|
+
num_inference_steps=image_gen_request.num_inference_steps,
|
|
75
|
+
height=image_gen_request.height,
|
|
76
|
+
width=image_gen_request.width,
|
|
77
|
+
).images
|
|
78
|
+
result = ImageGenerationResponse(files=[], errors=[], request=image_gen_request.model_dump_json())
|
|
79
|
+
for i, image in enumerate(output_images):
|
|
80
|
+
filename = f"{uuid.uuid4()}.{image_gen_request.image_format}"
|
|
81
|
+
try:
|
|
82
|
+
with guild_fs.open(filename, "wb") as f:
|
|
83
|
+
image.save(f)
|
|
84
|
+
# Create a MediaLink object for the image
|
|
85
|
+
media_link = MediaLink(
|
|
86
|
+
url=filename, name=filename, mimetype=mimetypes.guess_type(filename)[0], on_filesystem=True
|
|
87
|
+
)
|
|
88
|
+
result.files.append(media_link)
|
|
89
|
+
except Exception as e:
|
|
90
|
+
result.errors.append(f"Failed to write image file {filename}:{e}")
|
|
91
|
+
ctx.send(result)
|
|
92
|
+
except Exception as e:
|
|
93
|
+
ctx.send_error(
|
|
94
|
+
ErrorMessage(
|
|
95
|
+
agent_type=self.get_qualified_class_name(), error_type="ImageGenerationError", error_message=str(e)
|
|
96
|
+
)
|
|
97
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
2
|
+
|
|
3
|
+
from rustic_ai.core.agents.commons.message_formats import (
|
|
4
|
+
GenerationPromptRequest,
|
|
5
|
+
GenerationPromptResponse,
|
|
6
|
+
)
|
|
7
|
+
from rustic_ai.core.guild import agent
|
|
8
|
+
from rustic_ai.core.guild.agent import Agent, AgentMode, AgentSpec, AgentType
|
|
9
|
+
from rustic_ai.huggingface.agents.models import PyTorchAgentProps
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PhiAgentProps(PyTorchAgentProps):
|
|
13
|
+
model_id: str = "microsoft/phi-2"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LLMPhiAgent(Agent[PhiAgentProps]):
|
|
17
|
+
"""An Agent that generates a response to the given generation prompt using Phi 2."""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
agent_spec: AgentSpec[PhiAgentProps],
|
|
22
|
+
) -> None:
|
|
23
|
+
super().__init__(
|
|
24
|
+
agent_spec=agent_spec,
|
|
25
|
+
agent_type=AgentType.BOT,
|
|
26
|
+
agent_mode=AgentMode.LOCAL,
|
|
27
|
+
)
|
|
28
|
+
if agent_spec.properties is None:
|
|
29
|
+
agent_spec.properties = PhiAgentProps()
|
|
30
|
+
|
|
31
|
+
self._device = agent_spec.properties.torch_device
|
|
32
|
+
model_id = agent_spec.properties.model_id
|
|
33
|
+
self.model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True).to(self._device).eval()
|
|
34
|
+
self.tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True, torch_dtype="auto")
|
|
35
|
+
|
|
36
|
+
@agent.processor(GenerationPromptRequest)
|
|
37
|
+
def generate_prompt(self, ctx: agent.ProcessContext[GenerationPromptRequest]) -> None:
|
|
38
|
+
"""
|
|
39
|
+
Generates a response to the given generation prompt.
|
|
40
|
+
"""
|
|
41
|
+
generation_prompt = ctx.payload.generation_prompt
|
|
42
|
+
inputs = self.tokenizer(generation_prompt, return_tensors="pt", return_attention_mask=False).to(self._device)
|
|
43
|
+
|
|
44
|
+
outputs = self.model.generate(**inputs, max_length=200)
|
|
45
|
+
text = self.tokenizer.batch_decode(outputs)[0]
|
|
46
|
+
|
|
47
|
+
ctx.send(GenerationPromptResponse(generation_prompt=generation_prompt, generated_response=text))
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, Field
|
|
4
|
+
|
|
5
|
+
from rustic_ai.core.agents.commons import GenerationPromptRequest
|
|
6
|
+
from rustic_ai.core.agents.commons.media import MediaLink
|
|
7
|
+
from rustic_ai.core.guild import BaseAgentProps
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PyTorchAgentProps(BaseAgentProps):
|
|
11
|
+
"""
|
|
12
|
+
Properties for the HuggingFace PyTorch agent.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
torch_device: str = Field(default="cpu", title="Torch device to use for inference")
|
|
16
|
+
model_id: str = Field(title="HuggingFace Model ID to use")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ImageGenerationRequest(GenerationPromptRequest):
|
|
20
|
+
"""
|
|
21
|
+
Represents a request for generating images using a given generation model.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
num_images: The number of images to generate. Default is 1.
|
|
25
|
+
height: The height of the generated images. Default is 512.
|
|
26
|
+
width: The width of the generated images. Default is 512.
|
|
27
|
+
num_inference_steps: The number of inference steps for generating the images. Default is 50.
|
|
28
|
+
image_format: The format of the generated images. Default is "png".
|
|
29
|
+
guidance_scale: The scale used for guiding the image generation. Default is 7.5.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
num_images: int = Field(default=1)
|
|
33
|
+
height: int = Field(default=512)
|
|
34
|
+
width: int = Field(default=512)
|
|
35
|
+
num_inference_steps: int = Field(default=50)
|
|
36
|
+
image_format: str = Field(default="png")
|
|
37
|
+
guidance_scale: float = Field(default=7.5)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ImageGenerationResponse(BaseModel):
|
|
41
|
+
files: List[MediaLink] = Field(default_factory=list)
|
|
42
|
+
errors: List[str] = Field(default_factory=list)
|
|
43
|
+
request: str = Field(default_factory=str)
|
|
File without changes
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from pydantic import BaseModel
|
|
2
|
+
|
|
3
|
+
from rustic_ai.core.agents.commons.message_formats import ErrorMessage
|
|
4
|
+
from rustic_ai.core.guild import agent
|
|
5
|
+
from rustic_ai.core.guild.agent import Agent, AgentMode, AgentSpec, AgentType
|
|
6
|
+
from rustic_ai.huggingface.inference_mixin import (
|
|
7
|
+
HuggingfaceInferenceMixin,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class QuestionWithContext(BaseModel):
|
|
12
|
+
context: str
|
|
13
|
+
question: str
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SquadAnswer(BaseModel):
|
|
17
|
+
text: str
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SquadAgent(Agent, HuggingfaceInferenceMixin):
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
agent_spec: AgentSpec,
|
|
24
|
+
) -> None:
|
|
25
|
+
super().__init__(
|
|
26
|
+
agent_spec,
|
|
27
|
+
AgentType.BOT,
|
|
28
|
+
AgentMode.REMOTE,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
@agent.processor(QuestionWithContext)
|
|
32
|
+
async def find_answer(self, ctx: agent.ProcessContext[QuestionWithContext]):
|
|
33
|
+
"""
|
|
34
|
+
Uses the Huggingface model (deepset/roberta-base-squad2) to find the answer to the question in the context.
|
|
35
|
+
"""
|
|
36
|
+
question_with_context = ctx.payload
|
|
37
|
+
payload = self.generate_input_prompt(question_with_context.model_dump())
|
|
38
|
+
response = await self.run_inference("deepset/roberta-base-squad2", payload)
|
|
39
|
+
|
|
40
|
+
if response:
|
|
41
|
+
result = SquadAnswer(text=response["answer"])
|
|
42
|
+
|
|
43
|
+
ctx.send(result)
|
|
44
|
+
|
|
45
|
+
else:
|
|
46
|
+
ctx.send(
|
|
47
|
+
ErrorMessage(
|
|
48
|
+
agent_type=self.get_qualified_class_name(),
|
|
49
|
+
error_type="InferenceError",
|
|
50
|
+
error_message="No answer received from the model.",
|
|
51
|
+
)
|
|
52
|
+
) # pragma: no cover
|
|
File without changes
|
rusticai_huggingface-0.0.1/src/rustic_ai/huggingface/agents/text_to_speech/speecht5_tts_agent.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import mimetypes
|
|
2
|
+
import uuid
|
|
3
|
+
|
|
4
|
+
import soundfile as sf
|
|
5
|
+
import torch
|
|
6
|
+
from datasets import load_dataset
|
|
7
|
+
from transformers import pipeline
|
|
8
|
+
|
|
9
|
+
from rustic_ai.core.agents.commons.media import MediaLink
|
|
10
|
+
from rustic_ai.core.agents.commons.message_formats import (
|
|
11
|
+
ErrorMessage,
|
|
12
|
+
GenerationPromptRequest,
|
|
13
|
+
)
|
|
14
|
+
from rustic_ai.core.guild import agent
|
|
15
|
+
from rustic_ai.core.guild.agent import Agent, AgentMode, AgentType
|
|
16
|
+
from rustic_ai.core.guild.agent_ext.depends.filesystem import FileSystem
|
|
17
|
+
from rustic_ai.core.guild.dsl import AgentSpec
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SpeechT5TTSAgent(Agent):
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
agent_spec: AgentSpec,
|
|
25
|
+
) -> None:
|
|
26
|
+
super().__init__(
|
|
27
|
+
agent_spec,
|
|
28
|
+
AgentType.BOT,
|
|
29
|
+
AgentMode.LOCAL,
|
|
30
|
+
)
|
|
31
|
+
self._synthesiser = pipeline("text-to-speech", "microsoft/speecht5_tts")
|
|
32
|
+
|
|
33
|
+
embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
|
|
34
|
+
self._speaker_embedding = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)
|
|
35
|
+
|
|
36
|
+
@agent.processor(GenerationPromptRequest, depends_on=["filesystem:guild_fs:True"])
|
|
37
|
+
def convert(self, ctx: agent.ProcessContext[GenerationPromptRequest], guild_fs: FileSystem) -> None:
|
|
38
|
+
"""
|
|
39
|
+
Handles the received message.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
message (Message): The received message.
|
|
43
|
+
"""
|
|
44
|
+
data = ctx.payload
|
|
45
|
+
try:
|
|
46
|
+
speech = self._synthesiser(
|
|
47
|
+
data.generation_prompt, forward_params={"speaker_embeddings": self._speaker_embedding}
|
|
48
|
+
)
|
|
49
|
+
filename = f"{uuid.uuid4()}.wav"
|
|
50
|
+
try:
|
|
51
|
+
with guild_fs.open(filename, "wb") as f:
|
|
52
|
+
sf.write(f, speech["audio"], samplerate=speech["sampling_rate"])
|
|
53
|
+
output = MediaLink(
|
|
54
|
+
url=filename,
|
|
55
|
+
name=filename,
|
|
56
|
+
metadata={"sampling_rate": speech["sampling_rate"]},
|
|
57
|
+
on_filesystem=True,
|
|
58
|
+
mimetype=mimetypes.guess_type(filename)[0],
|
|
59
|
+
)
|
|
60
|
+
ctx.send(output)
|
|
61
|
+
except Exception as e:
|
|
62
|
+
ctx.send(
|
|
63
|
+
ErrorMessage(
|
|
64
|
+
agent_type=self.get_qualified_class_name(), error_type="FileWriteError", error_message=str(e)
|
|
65
|
+
)
|
|
66
|
+
)
|
|
67
|
+
except Exception as ex:
|
|
68
|
+
ctx.send(
|
|
69
|
+
ErrorMessage(
|
|
70
|
+
agent_type=self.get_qualified_class_name(),
|
|
71
|
+
error_type="SpeechGenerationError",
|
|
72
|
+
error_message=str(ex),
|
|
73
|
+
)
|
|
74
|
+
)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
from urllib.parse import urljoin
|
|
5
|
+
|
|
6
|
+
from rustic_ai.core.agents.utils.http_client import HttpClientMixin
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class HuggingfaceInferenceMixin(HttpClientMixin):
|
|
10
|
+
|
|
11
|
+
async def run_inference(
|
|
12
|
+
self, model: str, prompt_payload: str, inference_endpoint: str = "https://api-inference.huggingface.co/models/"
|
|
13
|
+
):
|
|
14
|
+
api_url = urljoin(inference_endpoint, model)
|
|
15
|
+
|
|
16
|
+
headers = {}
|
|
17
|
+
if not model or not isinstance(model, str):
|
|
18
|
+
logging.info("model not provided") # pragma: no cover
|
|
19
|
+
return
|
|
20
|
+
if not prompt_payload or not isinstance(prompt_payload, str):
|
|
21
|
+
logging.info("prompt not provided") # pragma: no cover
|
|
22
|
+
return
|
|
23
|
+
|
|
24
|
+
huggingface_api_key = os.getenv("HUGGINGFACE_API_KEY", "")
|
|
25
|
+
if huggingface_api_key:
|
|
26
|
+
headers["Authorization"] = f"Bearer {huggingface_api_key}"
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
response = await self.send_json(api_url, extra_headers=headers, json_data=prompt_payload)
|
|
30
|
+
return response
|
|
31
|
+
except Exception as e:
|
|
32
|
+
logging.error(f"Error running inference: {e}")
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
def generate_input_prompt(self, data: dict) -> str:
|
|
36
|
+
return json.dumps({"inputs": data, "options": {"wait_for_model": True}})
|