### Install user_guided_colorization Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/Image_editing/colorization/user_guided_colorization/README_en.md Install the user_guided_colorization module using the PaddleHub package manager. Refer to the provided links for platform-specific quickstart guides if installation issues arise. ```shell $ hub install user_guided_colorization ``` -------------------------------- ### Install User Guided Colorization 1.0.0 Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/Image_editing/colorization/user_guided_colorization/README_en.md Install the User Guided Colorization module version 1.0.0 using the hub command. ```shell $ hub install user_guided_colorization==1.0.0 ``` -------------------------------- ### Install DeOldify Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/Image_editing/colorization/deoldify/README_en.md Installs the DeOldify module using the paddlehub command-line tool. Refer to the quickstart guides for Windows, Linux, or Mac if installation issues arise. ```shell hub install deoldify ``` -------------------------------- ### Install Disco Diffusion CNCLIP ViTB16 Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/text_to_image/disco_diffusion_cnclip_vitb16/README_en.md Install the Disco Diffusion CNCLIP ViTB16 module using the hub install command. Refer to the quickstart guides for Windows, Linux, or Mac if installation issues arise. ```shell $ hub install disco_diffusion_cnclip_vitb16 ``` -------------------------------- ### Command Line Prediction with Custom Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/text_generation/ernie_gen/README_en.md Example of how to run a custom Ernie-Gen module from the command line after installation. ```bash $ hub run $module_name --input_text="输入文本" --use_gpu True --beam_width 5 ``` -------------------------------- ### Example ~/.bash_profile with Conda Initialization Source: https://github.com/paddlepaddle/paddlehub/blob/develop/docs/docs_en/get_start/linux_quickstart.md Illustrates a typical ~/.bash_profile configuration after Anaconda has been installed and initialized. It includes the PATH export and conda's shell hook for environment management. ```shell export PATH="~/opt/anaconda3/bin:$PATH" # >>> conda initialize >>> # !! Contents within this block are managed by 'conda init' !! __conda_setup="$('/Users/xxx/opt/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)" if [ $? -eq 0 ]; then eval "$__conda_setup" else if [ -f "/Users/xxx/opt/anaconda3/etc/profile.d/conda.sh" ]; then . "/Users/xxx/opt/anaconda3/etc/profile.d/conda.sh" else export PATH="/Users/xxx/opt/anaconda3/bin:$PATH" fi fi unset __conda_setup # <<< conda initialize <<< ``` -------------------------------- ### Install ernie_gen_poetry Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/text_generation/ernie_gen_poetry/README.md Install the ernie_gen_poetry module using the hub command. Ensure paddlepaddle, paddlehub, and paddlenlp are installed. ```shell $ hub install ernie_gen_poetry ``` -------------------------------- ### Install w2v_weibo_target_word-word_dim300 Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/embedding/w2v_weibo_target_word-word_dim300/README.md Install the w2v_weibo_target_word-word_dim300 model using the PaddleHub command-line tool. Ensure paddlepaddle and paddlehub are installed first. ```shell hub install w2v_weibo_target_word-word_dim300 ``` -------------------------------- ### install Source: https://github.com/paddlepaddle/paddlehub/blob/develop/docs/docs_en/api/module_manager.rst Installs a HubModule from various sources like name, directory, archive file, or URL. If a matching module is already installed, the installation is skipped. Installing with parameters other than 'name' will uninstall locally installed modules first. ```APIDOC ## install ### Description Installs a HubModule from various sources like name, directory, archive file, or URL. If a matching module is already installed, the installation is skipped. Installing with parameters other than 'name' will uninstall locally installed modules first. ### Method Signature ```python def install( name: str = None, directory: str = None, archive: str = None, url: str = None, version: str = None, ignore_env_mismatch: bool = False) ``` ### Parameters * **name** (str | optional) - Module name to install. * **directory** (str | optional) - Directory containing module code. * **archive** (str | optional) - Archive file containing module code. * **url** (str | optional) - URL pointing to an archive file containing module code. * **version** (str | optional) - Module version. Use with the `name` parameter. * **ignore_env_mismatch** (bool | optional) - Whether to ignore environment mismatch during installation. ``` -------------------------------- ### Install OpenPose Body Estimation Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/keypoint_detection/openpose_body_estimation/readme.md Install the openpose_body_estimation module using PaddleHub. Ensure you have paddlepaddle and paddlehub installed. ```shell hub install openpose_body_estimation ``` -------------------------------- ### Install spinalnet_vgg16_gemstone Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/spinalnet_vgg16_gemstone/README_en.md Install the module using the PaddleHub command-line tool. Ensure PaddleHub and PaddlePaddle are installed first. ```shell $ hub install spinalnet_vgg16_gemstone ``` -------------------------------- ### Install w2v_baidu_encyclopedia_target_word-ngram_1-3_dim300 Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/embedding/w2v_baidu_encyclopedia_target_word-ngram_1-3_dim300/README.md Install the w2v_baidu_encyclopedia_target_word-ngram_1-3_dim300 model using the PaddleHub CLI. Ensure paddlepaddle and paddlehub are installed first. ```shell hub install w2v_baidu_encyclopedia_target_word-ngram_1-3_dim300 ``` -------------------------------- ### Install ginet_resnet50vd_ade20k Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/semantic_segmentation/ginet_resnet50vd_ade20k/README_en.md Installs the ginet_resnet50vd_ade20k module using the PaddleHub command-line interface. Ensure paddlepaddle and paddlehub are installed. ```shell hub install ginet_resnet50vd_ade20k ``` -------------------------------- ### Install se_hrnet64_imagenet_ssld Model Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/se_hrnet64_imagenet_ssld/README.md Install the se_hrnet64_imagenet_ssld model using the PaddleHub command-line interface. Ensure paddlepaddle and paddlehub are installed. ```shell $ hub install se_hrnet64_imagenet_ssld ``` -------------------------------- ### Install PaddlePaddle and PaddleHub Source: https://github.com/paddlepaddle/paddlehub/blob/develop/README.md Install the necessary components for PaddleHub. Choose the GPU version of PaddlePaddle if you have a compatible GPU, otherwise install the CPU version. Then, install PaddleHub itself. ```python # install paddlepaddle with gpu # !pip install --upgrade paddlepaddle-gpu # or install paddlepaddle with cpu !pip install --upgrade paddlepaddle # install paddlehub !pip install --upgrade paddlehub ``` -------------------------------- ### Run Module via Command Line Source: https://github.com/paddlepaddle/paddlehub/blob/develop/docs/docs_en/tutorial/custom_module.rst Illustrates how to install a module and then execute it directly from the command line using 'hub run', passing input arguments. ```console $ hub install senta_test $ hub run senta_test --input_text "这部电影太差劲了" ``` -------------------------------- ### Install AnimeGANv2 Paprika 97 Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/Image_gan/style_transfer/animegan_v2_paprika_97/README_en.md Install the animegan_v2_paprika_97 module using the PaddleHub package manager. Refer to the quickstart guides for platform-specific installation issues. ```shell $ hub install animegan_v2_paprika_97 ``` -------------------------------- ### Install ResNet-vd Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/resnet50_vd_imagenet_ssld/README_en.md Install the resnet50_vd_imagenet_ssld module using the hub command-line tool. Ensure paddlepaddle and paddlehub are installed. ```shell $ hub install resnet50_vd_imagenet_ssld ``` -------------------------------- ### Command Line Interface Example Source: https://github.com/paddlepaddle/paddlehub/blob/develop/docs/docs_en/tutorial/custom_module.rst Shows how to run a custom module from the command line using the 'hub run' command. This example uses the 'senta_test' module with input text. ```shell hub run senta_test --input_text 这部电影太差劲了 ``` -------------------------------- ### Start Development Server Source: https://github.com/paddlepaddle/paddlehub/blob/develop/demo/serving/bentoml/cloud-native-model-serving-with-bentoml.ipynb Start a local development server to test the BentoService. This allows for quick iteration and debugging before deployment. ```python # Start a dev model server bento_svc.start_dev_server() ``` -------------------------------- ### Install Disco Diffusion CLIP ViTB32 Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/text_to_image/disco_diffusion_clip_vitb32/README_en.md Install the disco_diffusion_clip_vitb32 module using the hub command-line tool. Refer to the quickstart guides for specific operating system instructions if installation issues arise. ```shell $ hub install disco_diffusion_clip_vitb32 ``` -------------------------------- ### Run Installed Module from Command Line Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/demo/README.md Installs the module and then executes it using the 'hub run' command with specific input parameters. ```shell hub install senta_test hub run senta_test --input_text "这部电影太差劲了" ``` -------------------------------- ### Install ResNeXt101_32x4d_ImageNet Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/resnext101_32x4d_imagenet/README_en.md Install the resnext101_32x4d_imagenet module using the hub command-line tool. Ensure paddlepaddle and paddlehub are installed first. ```shell $ hub install resnext101_32x4d_imagenet ``` -------------------------------- ### Install Disco Diffusion CLIP RN50 Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/text_to_image/disco_diffusion_clip_rn50/README_en.md Install the Disco Diffusion CLIP RN50 module using the PaddleHub command-line tool. Refer to the quickstart guides for specific operating systems if installation issues arise. ```shell $ hub install disco_diffusion_clip_rn50 ``` -------------------------------- ### Start PaddleHub Serving with Configuration File Source: https://github.com/paddlepaddle/paddlehub/blob/develop/docs/docs_en/tutorial/serving.md Start the PaddleHub Serving using a JSON configuration file to define modules, ports, and other service parameters. ```shell $ hub serving start --config config.json ``` ```json { "modules_info": { "yolov3_darknet53_coco2017": { "init_args": { "version": "1.0.0" }, "predict_args": { "batch_size": 1, "use_gpu": false } }, "lac": { "init_args": { "version": "1.1.0" }, "predict_args": { "batch_size": 1, "use_gpu": false } } }, "port": 8866, "use_multiprocess": false, "workers": 2, "gpu": "0,1,2" } ``` -------------------------------- ### Installation Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/audio/asr/u2_conformer_aishell/README.md Instructions for installing the U2 Conformer Aishell model, including system dependencies, environment dependencies, and the installation command. ```APIDOC ## Installation ### System Dependencies - **Linux**: `sudo apt-get install libsndfile` or `sudo yum install libsndfile` - **macOS**: `brew install libsndfile` ### Environment Dependencies - `paddlepaddle >= 2.1.0` - `paddlehub >= 2.1.0` ### Installation Command ```shell $ hub install u2_conformer_aishell ``` ``` -------------------------------- ### Install Chinese OCR DB CRNN Mobile Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/text_recognition/chinese_ocr_db_crnn_mobile/README_en.md Install the chinese_ocr_db_crnn_mobile module using the PaddleHub package manager. Refer to the provided links for quick start guides on different operating systems if installation issues arise. ```shell $ hub install chinese_ocr_db_crnn_mobile ``` -------------------------------- ### Prediction Code Example Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/resnet50_vd_10w/README_en.md Example of how to load the module and get the prediction context. ```APIDOC ## Prediction Code Example ```python import paddlehub as hub import cv2 classifier = hub.Module(name="resnet50_vd_10w") input_dict, output_dict, program = classifier.context(trainable=True) ``` ``` -------------------------------- ### Install and Load Module via Name Source: https://github.com/paddlepaddle/paddlehub/blob/develop/docs/docs_en/tutorial/custom_module.rst Demonstrates how to install a custom module using the 'hub install' command and then load it into your Python script using its name. ```console $ hub install senta_test ``` ```python import paddlehub as hub senta_test = hub.Module(name="senta_test") senta_test.sentiment_classify(texts=["这部电影太差劲了"]) ``` -------------------------------- ### Install ernie_skep_sentiment_analysis Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/sentiment_analysis/ernie_skep_sentiment_analysis/README.md Install the ernie_skep_sentiment_analysis module using the hub command. Refer to the provided links for installation guides on different operating systems. ```shell $ hub install ernie_skep_sentiment_analysis ``` -------------------------------- ### Start PaddleHub Serving Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/face_detection/pyramidbox_lite_mobile/README_en.md Starts the PaddleHub Serving with the pyramidbox_lite_mobile model. Ensure CUDA_VISIBLE_DEVICES is set if using GPU. ```shell $ hub serving start -m pyramidbox_lite_mobile ``` -------------------------------- ### Install and Install Pre-commit Hooks Source: https://github.com/paddlepaddle/paddlehub/blob/develop/docs/docs_en/community/contribute_code.md Install the pre-commit tool and set up Git pre-commit hooks for code formatting and checks. ```shell pip install pre-commit pre-commit install ``` -------------------------------- ### Install latin_ocr_db_crnn_mobile Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/text_recognition/latin_ocr_db_crnn_mobile/README.md Install the latin_ocr_db_crnn_mobile module using the hub command. Refer to the provided links for installation guides on different operating systems. ```shell $ hub install latin_ocr_db_crnn_mobile ``` -------------------------------- ### Install fastspeech2_baker Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/audio/tts/fastspeech2_baker/README.md Install the fastspeech2_baker module using PaddleHub. This command is used for initial setup. ```shell $ hub install fastspeech2_baker ``` -------------------------------- ### Start PP-TinyPose Serving Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/keypoint_detection/pp-tinypose/README.md Deploy PP-TinyPose as an online service using PaddleHub Serving. This command starts the service, making the keypoint detection API available. GPU usage requires setting the CUDA_VISIBLE_DEVICES environment variable beforehand. ```shell $ hub serving start -m pp-tinypose ``` -------------------------------- ### Set GPU and Start Training Source: https://github.com/paddlepaddle/paddlehub/blob/develop/demo/text_classification/README.md Configure the visible GPU device and initiate the training process for text classification fine-tuning. ```shell # Set the GPU card number to be used export CUDA_VISIBLE_DEVICES=0 python train.py ``` -------------------------------- ### Install German OCR Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/text_recognition/german_ocr_db_crnn_mobile/README_en.md Install the german_ocr_db_crnn_mobile module using PaddleHub. Refer to the provided links for platform-specific installation guides if issues arise. ```shell $ hub install german_ocr_db_crnn_mobile ``` -------------------------------- ### Start PaddleHub Serving for CPM_LM Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/text_generation/CPM_LM/readme.md Start a PaddleHub Serving instance to deploy the CPM_LM model as a web service. Specify the module name and port. Set CUDA_VISIBLE_DEVICES if using GPU. ```shell $ hub serving start --modules GPT2_CPM_LM -p 8866 ``` -------------------------------- ### Install AnimeGANv2 Paprika Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/Image_gan/style_transfer/animegan_v2_paprika_74/README_en.md Install the animegan_v2_paprika_74 module using PaddleHub. Refer to installation guides for Windows, Linux, or Mac if issues arise. ```shell hub install animegan_v2_paprika_74 ``` -------------------------------- ### Start Fine-tuning the Model Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/se_hrnet64_imagenet_ssld/README.md Initiate the fine-tuning process using the configured trainer and datasets. Specify epochs, batch size, and evaluation dataset. ```python trainer.train(flowers, epochs=100, batch_size=32, eval_dataset=flowers_validate, save_interval=1) ``` -------------------------------- ### Install Specific LSeg Version Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/semantic_segmentation/lseg/README.md Install a specific version of the LSeg model, for example, version 1.0.0. ```shell hub install lseg==1.0.0 ``` -------------------------------- ### Set Up Optimizer and Trainer for Fine-tuning Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/Image_editing/colorization/user_guided_colorization/README_en.md Configure the Adam optimizer with a specified learning rate and model parameters. Initialize the Trainer with the model, optimizer, and checkpoint directory, then start the training process. ```python optimizer = paddle.optimizer.Adam(learning_rate=0.0001, parameters=model.parameters()) trainer = Trainer(model, optimizer, checkpoint_dir='img_colorization_ckpt_cls_1') trainer.train(color_set, epochs=201, batch_size=25, eval_dataset=color_set, log_interval=10, save_interval=10) ``` -------------------------------- ### Prediction Code Example Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/embedding/w2v_people_daily_target_word-char_dim300/README.md Example of how to use the w2v_people_daily_target_word-char_dim300 module to get word embeddings and calculate similarity. ```python import paddlehub as hub embedding = hub.Module(name='w2v_people_daily_target_word-char_dim300') # Get the embedding of a word embedding.search("中国") # Calculate the cosine similarity between two word vectors embedding.cosine_sim("中国", "美国") # Calculate the dot product of two word vectors embedding.dot("中国", "美国") ``` -------------------------------- ### Installation Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/nasnet_imagenet/README_en.md Install the nasnet_imagenet module using PaddleHub. ```APIDOC ## Installation ```shell $ hub install nasnet_imagenet ``` ``` -------------------------------- ### Install japan_ocr_db_crnn_mobile Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/text_recognition/japan_ocr_db_crnn_mobile/README_en.md Installs the japan_ocr_db_crnn_mobile module using the PaddleHub package manager. Refer to the provided links for platform-specific installation guides if issues arise. ```shell hub install japan_ocr_db_crnn_mobile ``` -------------------------------- ### Deploying as a Service Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/face_detection/pyramidbox_lite_server/README.md Instructions for deploying the PyramidBox Lite Server as an online face detection service using PaddleHub Serving. ```APIDOC ## Deploying as a Service ### Step 1: Start PaddleHub Serving Run the following command to start the service: ```shell $ hub serving start -m pyramidbox_lite_server ``` This deploys an online face detection service with a default port of 8866. **NOTE:** If using GPU prediction, set the `CUDA_VISIBLE_DEVICES` environment variable before starting the service. Otherwise, it is not necessary. ### Step 2: Send Prediction Request Use the following Python code to send a prediction request and get results: ```python import requests import json import cv2 import base64 def cv2_to_base64(image): data = cv2.imencode('.jpg', image)[1] return base64.b64encode(data.tostring()).decode('utf8') # Send HTTP request data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]} headers = {"Content-type": "application/json"} url = "http://127.0.0.1:8866/predict/pyramidbox_lite_server" r = requests.post(url=url, headers=headers, data=json.dumps(data)) # Print prediction results print(r.json()["results"]) ``` ``` -------------------------------- ### Install HRNet18 Model Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/hrnet18_imagenet_ssld/README.md Install the hrnet18_imagenet_ssld model using PaddleHub. Refer to the provided links for installation guides on different operating systems if issues arise. ```shell $ hub install hrnet18_imagenet_ssld ``` -------------------------------- ### Predict Code Example Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/embedding/w2v_baidu_encyclopedia_target_bigram-char_dim300/README.md Example demonstrating how to load the module and use its methods for getting word embeddings and calculating similarity. ```APIDOC ## Predict Code Example This section shows how to use the `w2v_baidu_encyclopedia_target_bigram-char_dim300` module to obtain word embeddings and calculate their similarities. ```python import paddlehub as hub embedding = hub.Module(name='w2v_baidu_encyclopedia_target_bigram-char_dim300') # Get the embedding of a word embedding.search("中国") # Calculate the cosine similarity between two word vectors embedding.cosine_sim("中国", "美国") # Calculate the dot product of two word vectors embedding.dot("中国", "美国") ``` ``` -------------------------------- ### Configure Optimizer and Trainer for Fine-tuning Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/se_hrnet64_imagenet_ssld/README.md Set up the optimizer (e.g., Adam) and the Trainer for the fine-tuning process. Specify learning rate, model parameters, and checkpoint directory. ```python optimizer = paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters()) trainer = Trainer(model, optimizer, checkpoint_dir='img_classification_ckpt') ``` -------------------------------- ### Python API Usage Example Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/embedding/w2v_baidu_encyclopedia_target_word-ngram_2-2_dim300/README.md Example demonstrating how to load the embedding module and use its methods to get word embeddings and calculate similarities. ```python import paddlehub as hub embedding = hub.Module(name='w2v_baidu_encyclopedia_target_word-ngram_2-2_dim300') # Get embedding for a word embedding.search("中国") # Calculate cosine similarity between two word embeddings embedding.cosine_sim("中国", "美国") # Calculate dot product between two word embeddings embedding.dot("中国", "美国") ``` -------------------------------- ### Start PaddleHub Serving from Command Line Source: https://github.com/paddlepaddle/paddlehub/blob/develop/docs/docs_en/tutorial/serving.md Use this command to start the PaddleHub Serving directly from the command line, specifying modules, port, and hardware acceleration options. ```shell $ hub serving start --modules [Module1==Version1, Module2==Version2, ...] --port XXXX \ --use_gpu \ --use_multiprocess \ --workers \ --gpu \ ``` -------------------------------- ### Start Lac Serving Service Source: https://github.com/paddlepaddle/paddlehub/blob/develop/docs/docs_en/tutorial/serving.md Use this command to start the Lac word segmentation service. Alternatively, a configuration file can be used for more detailed setup. ```shell $ hub serving start -m lac ``` ```shell $ hub serving start -c serving_config.json ``` -------------------------------- ### Environment Dependency: swig_decoder Setup Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/audio/asr/deepspeech2_aishell/README.md Clones the DeepSpeech repository, resets to a specific commit, and runs the setup script for the swig_decoder. ```shell git clone https://github.com/PaddlePaddle/DeepSpeech.git && cd DeepSpeech && git reset --hard b53171694e7b87abe7ea96870b2f4d8e0e2b1485 && cd deepspeech/decoders/ctcdecoder/swig && sh setup.sh ``` -------------------------------- ### Initialize BentoService and Pack Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/demo/serving/bentoml/cloud-native-model-serving-with-bentoml.ipynb Import the custom BentoService and initialize it. This step prepares the service for local testing and packing. ```python # Import the custom BentoService defined above from paddlehub_service import PaddleHubService import numpy as np import cv2 # Pack it with required artifacts bento_svc = PaddleHubService() ``` -------------------------------- ### Python Prediction Example Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/densenet169_imagenet/README_en.md Use the densenet169_imagenet module in Python for image classification. Ensure PaddleHub and OpenCV are installed. ```python import paddlehub as hub import cv2 classifier = hub.Module(name="densenet169_imagenet") test_img_path = "/PATH/TO/IMAGE" input_dict = {"image": [test_img_path]} result = classifier.classification(data=input_dict) ``` -------------------------------- ### Configure Optimizer and Trainer for Fine-tuning Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/semantic_segmentation/bisenetv2_cityscapes/README.md Set up the learning rate scheduler, optimizer (e.g., Adam), and trainer for the fine-tuning process. Requires PaddlePaddle. ```python scheduler = paddle.optimizer.lr.PolynomialDecay(learning_rate=0.01, decay_steps=1000, power=0.9, end_lr=0.0001) optimizer = paddle.optimizer.Adam(learning_rate=scheduler, parameters=model.parameters()) trainer = Trainer(model, optimizer, checkpoint_dir='test_ckpt_img_ocr', use_gpu=True) ``` -------------------------------- ### Get Module Type Source: https://github.com/paddlepaddle/paddlehub/blob/develop/docs/docs_en/api/module.rst Retrieve the type of the Module. This attribute categorizes the module, for example, as a 'cv' or 'nlp' module. ```python type ``` -------------------------------- ### Install and Load Module via Name Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/demo/README.md Installs the custom module locally and then loads it using its registered name for programmatic access. ```shell hub install senta_test ``` -------------------------------- ### Python API Usage Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/embedding/w2v_baidu_encyclopedia_target_word-character_char1-4_dim300/README.md Example of how to use the w2v_baidu_encyclopedia_target_word-character_char1-4_dim300 model in Python to get word embeddings, calculate cosine similarity, and dot products. ```APIDOC ## Python API Usage This section demonstrates how to use the `w2v_baidu_encyclopedia_target_word-character_char1-4_dim300` module in Python. ### Installation ```shell hub install w2v_baidu_encyclopedia_target_word-character_char1-4_dim300 ``` ### Code Example ```python import paddlehub as hub embedding = hub.Module(name='w2v_baidu_encyclopedia_target_word-character_char1-4_dim300') # Get the embedding for a word embedding.search("中国") # Calculate the cosine similarity between two word embeddings embedding.cosine_sim("中国", "美国") # Calculate the dot product between two word embeddings embedding.dot("中国", "美国") ``` ### API Reference - **`__init__(*args, **kwargs)`**: Initializes the Embedding Module object. Accepts additional list or dictionary arguments for customization, refer to `paddlenlp.embeddings` for details. - **`search(words: Union[List[str], str, int])`**: Retrieves embeddings for one or more words. Input can be a string (single word), a list of strings (multiple words), or an integer (word index). The word index corresponds to the model's vocabulary, accessible via the `vocab` attribute. - **`cosine_sim(word_a: str, word_b: str)`**: Computes the cosine similarity between the embeddings of two words. Both `word_a` and `word_b` must be present in the vocabulary; otherwise, they are treated as Out-Of-Vocabulary (OOV) and replaced with `unknown_token`. - **`dot(word_a: str, word_b: str)`**: Computes the dot product between the embeddings of two words. Handles OOV words similarly to `cosine_sim`. - **`get_vocab_path()`**: Returns the local path to the vocabulary file. - **`get_tokenizer(*args, **kwargs)`**: Returns a JiebaTokenizer instance for the current model, primarily for Chinese embedding models. Accepts additional list or dictionary arguments, refer to `paddlenlp.data.tokenizer.JiebaTokenizer` for details. ``` -------------------------------- ### Start PaddleHub Serving Source: https://github.com/paddlepaddle/paddlehub/blob/develop/docs/docs_en/finetune/image_classification.md Deploy a fine-tuned image classification model as a web service using PaddleHub Serving. This command starts the serving process. ```shell $ hub serving start -m resnet50_vd_imagenet_ssld ``` -------------------------------- ### Install EfficientNetB6 Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/efficientnetb6_imagenet/README_en.md Install the efficientnetb6_imagenet module using the hub command-line tool. ```shell $ hub install efficientnetb6_imagenet ``` -------------------------------- ### Python Prediction Code Example Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/resnet_v2_18_imagenet/README_en.md Loads the resnet_v2_18_imagenet module and performs image classification on a specified image path using Python. Ensure PaddleHub and OpenCV are installed. ```python import paddlehub as hub import cv2 classifier = hub.Module(name="resnet_v2_18_imagenet") test_img_path = "/PATH/TO/IMAGE" input_dict = {"image": [test_img_path]} result = classifier.classification(data=input_dict) ``` -------------------------------- ### Install w2v_baidu_encyclopedia_context_word-wordLR_dim300 Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/embedding/w2v_baidu_encyclopedia_context_word-wordLR_dim300/README.md Install the w2v_baidu_encyclopedia_context_word-wordLR_dim300 module using the PaddleHub command-line tool. ```shell hub install w2v_baidu_encyclopedia_context_word-wordLR_dim300 ``` -------------------------------- ### Python Prediction Example Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/resnext50_64x4d_imagenet/README_en.md Use the ResNeXt50 64x4d ImageNet module in Python for image classification. Ensure PaddleHub and OpenCV are installed. Replace '/PATH/TO/IMAGE' with the actual image path. ```python import paddlehub as hub import cv2 classifier = hub.Module(name="resnext50_64x4d_imagenet") test_img_path = "/PATH/TO/IMAGE" input_dict = {"image": [test_img_path]} result = classifier.classification(data=input_dict) ``` -------------------------------- ### Install EfficientNetB4 Module Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/efficientnetb4_imagenet/README_en.md Install the efficientnetb4_imagenet module using the hub command-line tool. Ensure PaddleHub and PaddlePaddle are installed first. ```shell hub install efficientnetb4_imagenet ``` -------------------------------- ### Configure Optimizer and Trainer for Fine-tuning Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/classification/hrnet18_imagenet_ssld/README.md Set up the optimizer (e.g., Adam) and the Trainer for the fine-tuning process. Specify the model, optimizer, checkpoint directory, and training parameters. ```python optimizer = paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters()) trainer = Trainer(model, optimizer, checkpoint_dir='img_classification_ckpt') trainer.train(flowers, epochs=100, batch_size=32, eval_dataset=flowers_validate, save_interval=1) ``` -------------------------------- ### Python Code for Sentiment Analysis Prediction Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/sentiment_analysis/ernie_skep_sentiment_analysis/README.md Load the ernie_skep_sentiment_analysis module and use its predict_sentiment method to get sentiment labels and probabilities for a list of texts. Ensure PaddleHub is installed. ```python import paddlehub as hub # Load ernie_skep_sentiment_analysis module. module = hub.Module(name="ernie_skep_sentiment_analysis") # Predict sentiment label test_texts = ['你不是不聪明,而是不认真', '虽然小明很努力,但是他还是没有考100分'] results = module.predict_sentiment(test_texts, use_gpu=False) for result in results: print(result['text']) print(result['sentiment_label']) print(result['positive_probs']) print(result['negative_probs']) ``` -------------------------------- ### Send Prediction Request to Senta-LSTM Service Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/sentiment_analysis/senta_lstm/README.md Send a POST request to the deployed PaddleHub Serving endpoint to get sentiment analysis predictions. This example uses the 'requests' library in Python. ```python import requests import json # 待预测数据 text = ["这家餐厅很好吃", "这部电影真的很差劲"] # 设置运行配置 # 对应本地预测senta_lstm.sentiment_classify(texts=text, batch_size=1, use_gpu=True) data = {"texts": text, "batch_size": 1, "use_gpu":True} # 指定预测方法为senta_lstm并发送post请求,content-type类型应指定json方式 # HOST_IP为服务器IP url = "http://HOST_IP:8866/predict/senta_lstm" headers = {"Content-Type": "application/json"} r = requests.post(url=url, headers=headers, data=json.dumps(data)) # 打印预测结果 print(json.dumps(r.json(), indent=4, ensure_ascii=False)) ``` -------------------------------- ### Start PaddleHub Serving for LSeg Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/semantic_segmentation/lseg/README.md Deploy the LSeg model as a web service using PaddleHub Serving. This command starts the serving process for the lseg module. ```shell hub serving start -m lseg ``` -------------------------------- ### Predict Word Embeddings and Similarities Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/text/embedding/w2v_weibo_target_word-word_dim300/README.md Example of how to use the w2v_weibo_target_word-word_dim300 model to get word embeddings, calculate cosine similarity, and dot product between words. The model needs to be loaded first. ```python import paddlehub as hub embedding = hub.Module(name='w2v_weibo_target_word-word_dim300') # 获取单词的embedding embedding.search("中国") # 计算两个词向量的余弦相似度 embedding.cosine_sim("中国", "美国") # 计算两个词向量的内积 embedding.dot("中国", "美国") ``` -------------------------------- ### Server Deployment Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/Image_gan/style_transfer/animegan_v2_paprika_97/README_en.md Instructions on how to deploy the AnimeGAN V2 Paprika 97 module using PaddleHub Serving. This includes the command to start the service and an example of how to send a prediction request to the deployed service. ```APIDOC ## PaddleHub Serving Deployment ### Step 1: Start PaddleHub Serving Run the following command to start the service: ```shell $ hub serving start -m animegan_v2_paprika_97 ``` The service will be deployed on the default port 8866. **Note:** Set the `CUDA_VISIBLE_DEVICES` environment variable if using a GPU for prediction. ### Step 2: Send a Predictive Request Use the following Python code to send a prediction request to the running service: ```python import requests import json import cv2 import base64 def cv2_to_base64(image): data = cv2.imencode('.jpg', image)[1] return base64.b64encode(data.tostring()).decode('utf8') # Send an HTTP request data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]} headers = {"Content-type": "application/json"} url = "http://127.0.0.1:8866/predict/animegan_v2_paprika_97" r = requests.post(url=url, headers=headers, data=json.dumps(data)) # print prediction results print(r.json()["results"]) ``` ``` -------------------------------- ### Install PyramidBox-Lite Server Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/face_detection/pyramidbox_lite_server/README_en.md Install the pyramidbox_lite_server module using PaddleHub. ```shell $ hub install pyramidbox_lite_server ``` -------------------------------- ### Send Prediction Request to PaddleHub Serving Source: https://github.com/paddlepaddle/paddlehub/blob/develop/modules/image/semantic_segmentation/bisenet_lane_segmentation/README_en.md Send a POST request to the deployed PaddleHub Serving endpoint to get lane segmentation predictions. This example includes utility functions for image encoding/decoding. ```python import requests import json import cv2 import base64 import numpy as np def cv2_to_base64(image): data = cv2.imencode('.jpg', image)[1] return base64.b64encode(data.tostring()).decode('utf8') def base64_to_cv2(b64str): data = base64.b64decode(b64str.encode('utf8')) data = np.fromstring(data, np.uint8) data = cv2.imdecode(data, cv2.IMREAD_COLOR) return data org_im = cv2.imread('/PATH/TO/IMAGE') data = {'images':[cv2_to_base64(org_im)]} headers = {"Content-type": "application/json"} url = "http://127.0.0.1:8866/predict/bisenet_lane_segmentation" r = requests.post(url=url, headers=headers, data=json.dumps(data)) #print(r.json()) mask = base64_to_cv2(r.json()["results"]['data'][0]) print(mask) ```