modelscope 安装 使用实例

目录

安装

图像融合例子:

多卡分配报错:

解决方法:

人像修复增强例子


安装

pip install modelscope

图像融合例子:

import cv2
from modelscope.outputs import OutputKeys
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks

if __name__ == '__main__':

    image_face_fusion = pipeline(Tasks.image_face_fusion,model='damo/cv_unet-image-face-fusion_damo')
    template_path = 'https://modelscope.oss-cn-beijing.aliyuncs.com/test/images/facefusion_template.jpg'
    user_path = 'https://modelscope.oss-cn-beijing.aliyuncs.com/test/images/facefusion_user.jpg'
    result = image_face_fusion(dict(template=template_path, user=user_path))

    cv2.imwrite('result.png', result[OutputKeys.OUTPUT_IMG])
    print('finished!')

多卡分配报错:

Expected all tensors to be on the same device, but found at least two devices, cuda:1 and cuda:0

解决方法:

Lib\site-packages\modelscope\models\cv\image_face_fusion\image_face_fusion.py

中,改之后的代码:

self.device = torch.device('cuda:0')

    def __init__(self, model_dir: str, *args, **kwargs):
        """initialize the image face fusion model from the `model_dir` path.

        Args:
            model_dir (str): the model path.
        """
        super().__init__(model_dir, *args, **kwargs)

        if torch.cuda.is_available():
            self.device = torch.device('cuda:0')
        else:
            self.device = torch.device('cpu')

人像修复增强例子

import importlib
import os
from collections import OrderedDict

import cv2

import  tensorflow

from modelscope import snapshot_download
from modelscope.utils.error import SKLEARN_IMPORT_ERROR

model_dir = snapshot_download('damo/cv_unet_skin-retouching')

from modelscope.outputs import OutputKeys
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks

import importlib_metadata
from packaging import version
_tf_version = 'N/A'

# following code borrows implementation from huggingface/transformers
ENV_VARS_TRUE_VALUES = {'1', 'ON', 'YES', 'TRUE'}
ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({'AUTO'})
USE_TF = os.environ.get('USE_TF', 'AUTO').upper()
USE_TORCH = os.environ.get('USE_TORCH', 'AUTO').upper()

if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
    _tf_available = importlib.util.find_spec('tensorflow') is not None
    if _tf_available:
        candidates = (
            'tensorflow',
            'tensorflow-cpu',
            'tensorflow-gpu',
            'tf-nightly',
            'tf-nightly-cpu',
            'tf-nightly-gpu',
            'intel-tensorflow',
            'intel-tensorflow-avx512',
            'tensorflow-rocm',
            'tensorflow-macos',
        )
        _tf_version = None
        # For the metadata, we have to look for both tensorflow and tensorflow-cpu
        for pkg in candidates:
            try:
                _tf_version = importlib_metadata.version(pkg)
                break
            except importlib_metadata.PackageNotFoundError:
                pass
        _tf_available = _tf_version is not None
    if _tf_available:
        if version.parse(_tf_version) < version.parse('2'):
            pass
        else:
            print(f'TensorFlow version {_tf_version} Found.')
else:
    print('Disabling Tensorflow because USE_TORCH is set')
    _tf_available = False

def is_scipy_available():
    return importlib.util.find_spec('scipy') is not None


def is_sklearn_available():
    if importlib.util.find_spec('sklearn') is None:
        return False
    return is_scipy_available() and importlib.util.find_spec('sklearn.metrics')


def is_sentencepiece_available():
    return importlib.util.find_spec('sentencepiece') is not None


def is_protobuf_available():
    if importlib.util.find_spec('google') is None:
        return False
    return importlib.util.find_spec('google.protobuf') is not None


def is_tokenizers_available():
    return importlib.util.find_spec('tokenizers') is not None


_timm_available = importlib.util.find_spec('timm') is not None
try:
    _timm_version = importlib_metadata.version('timm')
    print(f'Successfully imported timm version {_timm_version}')
except importlib_metadata.PackageNotFoundError:
    _timm_available = False

def is_timm_available():
    return _timm_available




def is_wenetruntime_available():
    return importlib.util.find_spec('wenetruntime') is not None


def is_swift_available():
    return importlib.util.find_spec('swift') is not None


def is_tf_available():
    return _tf_available


def is_opencv_available():
    return importlib.util.find_spec('cv2') is not None


def is_pillow_available():
    return importlib.util.find_spec('PIL.Image') is not None


def _is_package_available_fn(pkg_name):
    return importlib.util.find_spec(pkg_name) is not None


def is_espnet_available(pkg_name):
    return importlib.util.find_spec('espnet2') is not None \
        and importlib.util.find_spec('espnet')

if __name__ == '__main__':

    # skin_retouching = pipeline(Tasks.skin_retouching,model='damo/cv_unet_skin-retouching')

    skin_retouching=pipeline(Tasks.image_portrait_enhancement, model='damo/cv_gpen_image-portrait-enhancement')
    print('---------------1111111111-----------------------')
    result = skin_retouching(r'E:\project\stable-diffusion-webui-master\test\images\skin_retouching_examples_1.jpg')
    print('---------------2222222222-----------------------')
    cv2.imwrite('result.png', result[OutputKeys.OUTPUT_IMG])

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个使用 ModelScope 的应用实例: ``` import tensorflow as tf from modelscope import ModelScope # 定义模型 def my_model(x): x = tf.layers.dense(x, 64, activation=tf.nn.relu) x = tf.layers.dense(x, 32, activation=tf.nn.relu) x = tf.layers.dense(x, 10) return x # 使用 ModelScope 对模型进行包装 with ModelScope('my_model'): # 构建输入占位符和模型 x = tf.placeholder(tf.float32, shape=(None, 784)) y = my_model(x) # 定义损失函数和优化器 y_true = tf.placeholder(tf.float32, shape=(None, 10)) loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_true)) optimizer = tf.train.AdamOptimizer().minimize(loss) # 训练模型 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # 训练循环 for i in range(num_iterations): batch_x, batch_y = get_batch_data() _, loss_val = sess.run([optimizer, loss], feed_dict={x: batch_x, y_true: batch_y}) # 保存模型 ModelScope.save(sess, 'my_model') ``` 在这个例子中,我们首先定义了一个简单的神经网络模型 `my_model`,然后使用 ModelScope 对其进行包装。 在包装内部,我们构建了输入占位符和模型,并定义了损失函数和优化器。在训练循环中,我们使用 `sess.run()` 执行优化器和损失函数,并传入训练数据。最后,我们使用 `ModelScope.save()` 将模型保存到磁盘上。 使用 ModelScope,我们可以轻松地在模型训练中记录和可视化模型的指标和参数,从而更好地了解模型的性能和行为。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法网奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值