B4A Library Translate

Hello all ,

https://github.com/xdjm/Translate in B4A

@DependsOn(values={"translate-release.aar","okhttp-3.9.1","okio-2.2.2","kotlin-stdlib-1.3.20","gson-2.8.5"})

https://drive.google.com/drive/folders/1HidohCzYR31KoF5aj0AQWRxb_lGkXz01?usp=sharing


Translate
Author:
SMM
Version: 0.01
  • Translate
    Events:
    • _result (text As String)
    Methods:
    • YoudaoTranslate (AppId As java.lang.String, text As java.lang.String, fromLanguage As java.lang.String, toLanguage As java.lang.String) As void
    • GoogleTranslate (text As java.lang.String, fromLanguage As java.lang.String, toLanguage As java.lang.String) As void
    • BaiduTranslate (AppId As java.lang.String, text As java.lang.String, fromLanguage As java.lang.String, toLanguage As java.lang.String) As void
    • Initialize (ba As anywheresoftware.b4a.BA, EventName As java.lang.String) As void
    Permissions:
    • android.permission.INTERNET


Sample :
B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim trns As Translate
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    trns.Initialize("trans")
    trns.BaiduTranslate("","Hello","en","it")
    
End Sub
Sub trans_result(text As String)
    Log(text)
End Sub
 

Attachments

  • Translate.zip
    24.1 KB · Views: 486

GeoT

Active Member
Licensed User
Hi.

Good job. It works for me, but now all these jar files must be inside the folder C:\Program Files (x86)\Anywhere Software\Basic4android\Libraries:

kotlin-stdlib-1.3.20.jar
okhttp-3.5.0.jar
okhttp-3.9.1.jar
okio-1.11.0.jar
okio-2.2.2.jar

You can download them from mvnrepository.com for example.

In addition to your Translate.jar

Regards.
 
Last edited:

somed3v3loper

Well-Known Member
Licensed User
Longtime User
but now all these jar files must be inside the folder C:\Program Files (x86)\Anywhere Software\Basic4android\Libraries:

kotlin-stdlib-1.3.20.jar
okhttp-3.5.0.jar
okhttp-3.9.1.jar
okio-1.11.0.jar
okio-2.2.2.jar
Yes sorry for that these are Translate dependencies
If there is any other way that can help reduce them , please tell me how
 

DonManfred

Expert
Licensed User
Longtime User
I don't think so
Why? I just look at the github source. For example BaiduTrans.java
B4X:
 public void into( final OnTransSuccess onTransSuccess) {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("q", context)
                .add("from", from)
                .add("to", to)
                .add("appid", appId)
                .add("salt", salt)
                .add("sign", Md5.md5(appId + context + salt + securityKey))
                .build();
       String url = "http://api.fanyi.baidu.com/api/trans/vip/translate";
       Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, final Response response){
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            assert response.body() != null;
                            onTransSuccess.out(new Gson().fromJson(response.body().string(), Trans.class).getTrans_result().get(0).getDst());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }
It can be easily done with b4a using okhttputils2. You need to build the correct request for sure. But i don´t see a reason why it should not work.
 

somed3v3loper

Well-Known Member
Licensed User
Longtime User
im getting this

B4X:
B4A Version: 8.50
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lokhttp3/Address;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lokhttp3/Authenticator;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lokhttp3/Authenticator$1;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lokhttp3/Cache;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lokhttp3/Cache$1;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lokhttp3/Cache$2;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lokhttp3/Cache$CacheRequestImpl;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lokhttp3/Cache$CacheRequestImpl$1;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lokhttp3/Cache$CacheResponseBody;
It must be because this library depends on another okhttp .jar
I will see what I can do
Did you try to untick okhttp from libraries tab
 

somed3v3loper

Well-Known Member
Licensed User
Longtime User
he is probably using okhttputils2 lib... The problem is in the library. It should NOT use another reference to okhttp jars.
Better rewite the lib as b4a class....
You are right .
I started writing a class :) I wish my time will help me to publish it soon
 

somed3v3loper

Well-Known Member
Licensed User
Longtime User
Google Translate worked but the other two are still NOT WORKING
BaiduTranslate returns {"error_code":"52003","error_msg":"UNAUTHORIZED USER"}
YoudoaTranslate returns a similar message with some nulls
If someone can signup for an appid , they can test and feedback
Also you can fix my mistakes :D
B4X:
       Dim trns As GoogleTrans
    trns.Initialize(Me,"trans")
    trns.fromLanguage("en").ToLanguage("ar").with("hello guys").doTranslate

B4X:
Sub trans_result(text As String)
    Log(text)
End Sub
 

Attachments

  • BaiduTrans.zip
    1.3 KB · Views: 244
  • YoudaoTrans.zip
    967 bytes · Views: 241
  • GoogleTrans.zip
    1.3 KB · Views: 350

DonManfred

Expert
Licensed User
Longtime User
can you share logs ?
not really. I just compared the java code with your class code.
The java source is using a Requestbuilder and setting values to it. My thought is that a multipartpost is probably more suitable/compareable than a json poststring...
 

somed3v3loper

Well-Known Member
Licensed User
Longtime User
not really. I just compared the java code with your class code.
The java source is using a Requestbuilder and setting values to it. My thought is that a multipartpost is probably more suitable/compareable than a json poststring...
I tried using requestbuilder through JavaObject but I got the same result
I will try MultiPartpost and see
 

somed3v3loper

Well-Known Member
Licensed User
Longtime User
I tried MultiPartpost and now I am getting
B4X:
{"error_code":"54001","error_msg":"Invalid Sign"}
It seems I need an appId but the strange thing is that it worked earlier with github author's appid so it might be a different issue

B4X:
private Sub Class_Globals
    Private  salt As String
    Private  Tol As String= "zh"
    Private from As String  = "en"
    Private appId As String = "20160424000019521"
    Private  securityKey As String= "Hv8XkkCeQTn5xGBPDYgj"
    Private call_back As Object
    Private event_Name As String
    Private context As String
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize(callback As Object,eventName As String)
    
    call_back=callback
    event_Name=eventName
End Sub

Public Sub SetAppId(App_Id As String) As BaiduTrans
    appId=App_Id
    Return Me
End Sub


Public Sub SetSecurityKey( security_Key As String) As BaiduTrans
    securityKey=security_Key
    Return Me
End Sub


Public Sub ToLanguage( toLang As String) As BaiduTrans
    Tol=toLang
    Return Me
End Sub

Public Sub fromLanguage( fromLang As String) As BaiduTrans
    Return Me
End Sub

Public Sub  with(text As String)As BaiduTrans
    context=text
    
    Return Me
End Sub

Public Sub doTranslate
    salt = DateTime.Now
    Dim url As String  = "http://api.fanyi.baidu.com/api/trans/vip/translate"
    Dim transJob As HttpJob
    transJob.Initialize("transJob",Me)
    
'    Dim bodyformbuilder As JavaObject
'    bodyformbuilder.InitializeNewInstance("okhttp3.FormBody.Builder",Null)
'    bodyformbuilder.RunMethodjo("add",Array("q",trtext))
'    bodyformbuilder.RunMethodjo("add",Array("from",from))
'    bodyformbuilder.RunMethodjo("add",Array("to",Tol))
'    bodyformbuilder.RunMethodjo("add",Array("appid",appId))
'    bodyformbuilder.RunMethodjo("add",Array("salt",salt))
'    bodyformbuilder.RunMethodjo("add",Array("sign",MD5(appId&trtext&salt&securityKey)) )
    
'    Log(bodyformbuilder)
'    Dim s As String=bodyformbuilder.RunMethod("build",Null )
'    Log(s)

    Dim bodymap As Map
    bodymap.Initialize
    bodymap.Put("q",context)
    bodymap.Put("from",from)
    bodymap.Put("to",Tol)
    bodymap.Put("appid",appId)
    bodymap.Put("salt",salt)
    bodymap.Put("sign",MD5(appId&context&salt&securityKey))
    Dim jg As JSONGenerator
    jg.Initialize(bodymap)
    Dim s As String=jg.ToString
    Log(s)
    transJob.PostMultipart(url, bodymap,Null)   
'    Public void into( final OnTransSuccess onTransSuccess) {
'    OkHttpClient client = new OkHttpClient();
'    RequestBody body = new FormBody.Builder()
'    .add("q", context)
'    .add("from", from)
'    .add("to", To)
'    .add("appid", appId)
'    .add("salt", salt)
'    .add("sign", MD5.md5(appId + context + salt + securityKey))
'    .build();
'    String url = "http://api.fanyi.baidu.com/api/trans/vip/translate";
'    Request request = new Request.Builder()
'    .url(url)
'    .post(body)
'    .build();
'   
End Sub
Private Sub jobdone(okjob As HttpJob)
    If okjob.Success Then
        
            
            
        Log(okjob.GetString)
        
        
        
    Else
        Log("error with "&okjob.JobName& " " &okjob.ErrorMessage)
    End If
    
    okjob.Release
End Sub
Private Sub MD5(obj As String) As String
    Dim md As MessageDigest
    Dim ByteCon As ByteConverter
    Dim passwordhash() As Byte

    passwordhash = md.GetMessageDigest( obj.GetBytes("UTF8"),"MD5")


    Return ByteCon.HexFromBytes( passwordhash )

    
End Sub
 

StephenRM

Member
I get the error, when I add the Translate library and compile,
Error in C:\Android\tools\..\extras\b4a_local\unpacked-okhttp-3.9.1-63689043584000\dex_v1\okhttp-3.9.1.zip:classes.dex:
Type okhttp3.Address is defined multiple times: C:\Android\tools\..\extras\b4a_local\unpacked-okhttp-3.9.1-63689043584000\dex_v1\okhttp-3.9.1.zip:classes.dex, C:\Android\tools\..\extras\b4a_local\unpacked-okhttp-4.9.0-63783486950000\dex_v1\okhttp-4.9.0.zip:classes.dex
Compilation failed
 

Attachments

  • error1.jpg
    error1.jpg
    77.9 KB · Views: 88

somed3v3loper

Well-Known Member
Licensed User
Longtime User
Try class code instead of compiled library?
 
Top