【问题标题】:How to execute Python codes from Java code in Android Studio?如何在 Android Studio 中从 Java 代码执行 Python 代码?
【发布时间】:2019-02-04 14:53:36
【问题描述】:

我正在使用 Java 在 Android Studio 中构建一个 Android 应用程序。我想使用 Speech to text 和 Text to Speech 以及我已经编写的一些基于机器学习的 python 程序。 是否有可能做到这一点?我需要什么技术栈来完成这项工作?

我遇到了各种解决方案,例如使用 sl4A、Jython、QPython 和在服务器上运行 python 代码。我也经历了以下但我还没有找到解决方案

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

请举例说明。例如,如果我想使用以下 python 代码(使用 Google 语音识别 API 进行语音到文本转换)在我的 android 应用程序中运行:

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")

我应该遵循哪些步骤?实现它的最佳方法是什么? 提前谢谢你。

编辑 1:是否可以使用 azure services 来实现?

【问题讨论】:

    标签: java python azure android-studio


    【解决方案1】:

    我一直在使用JEP 作为 java 和 python 之间的桥梁,我从来没有在 Android 应用程序上真正尝试过这个,只有 webapps。 (在项目的常见问题解答中,他们声明它可以工作)

    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;
    }
    

    这里是python:

    class master:
    def __init__(self):
        self.SETVARIABLES = ''
    
    def main(self, path, well, startDate, endDate):
        #stuff
    

    通过搜索我找到了this,他们甚至有混合源代码应用程序(python和java)的项目示例。

    【讨论】:

    • 非常感谢,但您在链接中提到的 chaquopy 未经许可运行仅 5 分钟,之后我们需要重新安装它。
    猜你喜欢
    • 2015-05-09
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 2016-10-12
    • 1970-01-01
    • 2014-02-17
    相关资源
    最近更新 更多