OwO-Network / DeepLX

Powerful Free DeepL API, No Token Required
https://ssa.sx/deeplx
MIT License
6.64k stars 532 forks source link

Multiple line translation #108

Closed littleblack111 closed 6 months ago

littleblack111 commented 6 months ago

When I try to translate something with multiple lines(\n) like "Hello World" it will respond {"code":404,"message":"No text to translate}. Although "Hello World" works

missuo commented 6 months ago

Show me Screenshot Pls.

littleblack111 commented 6 months ago
截屏2024-04-24 下午2 18 02

Show me Screenshot Pls.

the commands are from README. At first I thought it was my code's issue. So I tested the command with multiple lines. Which didn't work

missuo commented 6 months ago

In JSON, strings cannot be written directly across lines. You should use newline characters.

curl -X POST http://localhost:1188/translate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your_access_token" \
-d '{
    "text": "Hello\nworld!",
    "source_lang": "EN",
    "target_lang": "DE"
}'
missuo commented 6 months ago
image

If you use this type of API debugging tool, you'll notice that when you paste something that contains line breaks, it's automatically converted to \n.

littleblack111 commented 6 months ago

so what should I do if I want to make it able to do multiple lines. Or is it just not possible?

missuo commented 6 months ago

so what should I do if I want to make it able to do multiple lines. Or is it just not possible?

Is my expression not clear enough? I have already given you quite clear examples above.

missuo commented 6 months ago

I hope you have some basic knowledge of coding, at least to the extent that you understand what \n represents. Otherwise, I think you will not be able to use DeepLX properly.

littleblack111 commented 6 months ago

understand, i need to convert it to \n then reconvert it back to lines

missuo commented 6 months ago

understand, i need to convert it to \n then reconvert it back to lines

image

It seems you still haven't understood what I meant. If you extract the data from the Response, printing it will automatically line break because it contains \n.

littleblack111 commented 6 months ago

I need to convert it as well right?(like var=var.replace('\n', '\n') oh, I'm not printing it. I'm displaying it like a widget so, i convert it back (var=var.replace('\n', '\n'))

missuo commented 6 months ago

I need to convert it as well right?(like var=var.replace('\n', '\n') oh, I'm not printing it. I'm displaying it like a widget so, i convert it back (var=var.replace('\n', '\n'))

Show me your full code.

littleblack111 commented 6 months ago

    text = data["q"]
    target_lang = data["target"]

    if "source" in data:
        source_lang = data["source"]

    deeplx_base_url = os.environ.get("DEEPLX_BASE_URL")

    if not deeplx_base_url:
        return Response(
            status_code=500,
            content=json.dumps(
                {
                    "error": {
                        "message": "No DEEPLX_BASE_URL provided",
                    }
                }
            ),
        )
    print(text)
    text = text.replace('\n', '\\n')
    print(text)
    body = {
        "text": text,
        "target_lang": target_lang,
    }
    if "source" in data:
        body["source_lang"] = source_lang

    try:
        req = ProxyRequest(
            deeplx_base_url, "POST", '', json.dumps(body), query_params={}
#             deeplx_base_url, "POST", headers, json.dumps(body), query_params={}
        )
        resp = await pass_through_request(http_client, req, nohttps=True, noheaders=True)
        resp = json.loads(resp.content.decode("utf-8"))
        try:
            translated_text = resp["alternatives"][0]
            print(translated_text)
            translated_text = translated_text.replace('\\nn', '\n')
            print(translated_text)
            res = {"data": {"translations": [{"translatedText": translated_text}]}}
        except TypeError:
            # res = {"error": {"message": "Failed to translate"}}
            # res = {"data": {"translations": [{"translatedText": "Failed to translate"}]}}
            res = {"data": {"translations": [{"translatedText": text}]}}

        if "source" not in raycast_data:
            res["data"]["translations"][0]["detectedSourceLanguage"] = resp[
                "source_lang"
            ].lower()

        return Response(status_code=200, content=json.dumps(res))
    except Exception as e:
        logger.error(f"DEEPLX error: {e}")
        return Response(
            status_code=500,
            content=json.dumps(
                {
                    "error": {
                        "message": "Unknown error",
                    }
                }
            ),
        )
missuo commented 6 months ago

replace('\n', '\\n')

Why do this?

littleblack111 commented 6 months ago

because otherwise it will return {"code":404,"message":"No text to translate}