python calls java services

Posted by sabatier on Sat, 30 Nov 2019 19:25:11 +0100

Background

Python is famous for its fast development, flexibility and strong compatibility. In some cases, python needs to call code in other languages, such as a service that does not provide Python SDK, or the efficiency of Cpython's parsing and operation fails to meet the requirements, or other languages or frameworks are better at a certain field. This article records a real-world experience of Python calling java services. The core reason is that Alibaba cloud's real-time voice to text interface does not provide the python SDK.

Python Preparation

The common java calls from python include jpype, pyjnius, py4j, etc. jpype and py4j have the same core developers. The latter is because the developers think that the underlying architecture of jpype is not good enough, so this paper uses py4j as a tool to implement.
Install py4j first

$ pip install py4j

Then prepare python's interface function for Alibaba cloud real-time voice to text

import json
from aliyunsdkcore.client import AcsClient  # Ali cloud
from aliyunsdkcore.request import CommonRequest  # Ali cloud
from werkzeug.exceptions import BadRequest  # exception handling
from py4j.java_gateway import JavaGateway  # Introducing java gateway from py4j

# The global variables to be set are obtained from the Alibaba cloud account
APP_KEY = 'xxx'
ACCESS_KEY_SECRET = 'xxx'
ONLINE_DOMAIN = 'xxx'
ONLINE_API = 'xxx'
URI_PATTERN = 'xxx'

def create_token(method):
    """
    //Create alicloud connection token
    """
    # create request
    common_request = CommonRequest(domain=ONLINE_DOMAIN, version=ONLINE_API, uri_pattern=URI_PATTERN)
    common_request.set_method(method)

    # create AcsClient
    my_client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, 'cn-shanghai')

    response = my_client.do_action_with_exception(common_request)

    return response
    
def get_online_transcribe():
    """
    //Connect java service to get Alibaba cloud real-time voice to text response
    """
    # create token
    token_response = eval(create_token('POST').decode('utf-8'))
    token = token_response.get('Token', None)
    if not token:
        raise BadRequest('internal error')
    token_id = token.get('Id', None)
    if not token_id:
        raise BadRequest('internal error')

    # create client
    gateway = JavaGateway()
    gateway.entry_point.run(APP_KEY, token_id)  # Related to java service configuration

Java Preparation

First, add py4j dependency in maven and dependency in pom.xml

<dependencies>
    <dependency>
        <groupId>net.sf.py4j</groupId>
        <artifactId>py4j</artifactId>
        <version>0.10.8</version>
    </dependency>
</dependencies>

Then configure java Alibaba cloud real time voice to text The main function code is shown in the link attached above.
Then configure the py4j access code.

package com.alibaba.nls.client.example;

import py4j.GatewayServer;  // Introducing pyfj

import com.alibaba.nls.client.example.SpeechTranscriberWithMicrophoneDemo;

public class SpeechTranscriberWithMicrophoneDemoEntryPoint {
    // Starting function
    public void run(String appKey, String token) {
        SpeechTranscriberWithMicrophoneDemo demo =
                new SpeechTranscriberWithMicrophoneDemo(appKey, token);
        demo.process();
        demo.shutdown();
    }

    public static void main(String[] args) {

        SpeechTranscriberWithMicrophoneDemoEntryPoint app = new SpeechTranscriberWithMicrophoneDemoEntryPoint();
        // py4j services
        GatewayServer gatewayServer = new GatewayServer(app);
        gatewayServer.start();
        System.out.println("Gateway Server Started");
    }
}

Conclusion

Finally, java and python related services are started to complete the related functions.

Topics: Python Java SDK pip