简体   繁体   中英

How to execute Python codes from Java code in Android Studio?

I am building an Android application in Android studio with Java. I want to use Speech to text and Text to speech and some Machine Learning based python programs that I had already written. Is it possible to do this? What is the technology stack that I need to accomplish this?

I came across various solutions like using sl4A, Jython, QPython and running the python code on the server.I have also gone through the following but I haven't found a solution yet

Execute python script from android App in Java

How to execute Python script from Java code in Android

Execute python script from android App in Java

Please explain with an example. As an example if I want to use the following python code (Speech to Text conversion using Google Speech recognition API) to run in my android app:

import speech_recognition as sr
r = sr.Recognizer()

with sr.Microphone() as src:
    print("speak....")
    audio = r.listen(src, 2)
    print("over")
try:
    print("you said: "+r.recognize_google(audio))
except:
    print("cannot recognize")

What steps am I supposed to follow? What is the best way to achieve it? Thank you in advance.

EDIT 1: Can it be achieved using azure services ?

I've been using JEP as a bridge between java and python, I've never actually tried this on android apps, only webapps. (in the FAQS of the project they state that it could work)

private RunOutputModel run(RunInputModel model, String path) throws Exception {

    RunOutputModel retVal = new RunOutputModel();

    try (SharedInterpreter jep = new SharedInterpreter()) {
        jep.eval("import sys");
        jep.eval("sys.path.append('" + path + "')");
        jep.eval("import master_main");
        jep.set("well", model.getWell());
        jep.set("startDate", model.getStartDate());
        jep.set("endDate", model.getEndDate());
        //other vars
        jep.eval("objClass = master_main.master()");
        jep.eval("x = objClass.main(path, well, startDate, endDate,/*vars*/)");
        Object result1 = jep.getValue("x");
        //manager result
        }
    } catch (Exception e) {
        retVal.setStatus(e.getMessage());
        Utils.log("error", e.getMessage(), path);
    }
    return retVal;
}

And here's python:

class master:
def __init__(self):
    self.SETVARIABLES = ''

def main(self, path, well, startDate, endDate):
    #stuff

By searching I've found this , they even have project examples of mixed source code app (both python and java).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM