Skip to content

Commit 6b7928b

Browse files
author
Jens Kürten
committed
improve translation example
1 parent 1ae92e2 commit 6b7928b

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

docs/examples/field_calculation.md

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,9 @@ def calculate_part_number(metadata: MetaData, event: PartFieldCalculationEvent,
5151
You can check `event.data.action` to decide for which operations (*copy*, *create*, *index*, and *modify*) you want your field calculation to return a new value.
5252
Some fields, like part number (*teilenummer*), can only be set during the initial creation.
5353

54-
## Translate a field with DeepL
54+
## Translate a part name with DeepL
5555

56-
Inside Functions, you can fetch data from external systems and fill out fields based on that data. This is something that would not be possible with the field calculations in the datasheet editor. For example, you could use this to fetch new part numbers from an ERP system.
57-
58-
This example uses the API from [DeepL](https://www.deepl.com){:target="_blank"} to translate a field from German to English. The example uses the additional attributes 1 and 2 on parts, but you can of course change that to any attributes that fit your use case.
56+
This example uses the [DeepL API](https://www.deepl.com){:target="_blank"} to translate the part name of newly created parts from German to English or vice versa, depending on which name is already provided. You can easily adapt this example to translate other fields or use a different translation API if needed.
5957

6058
```python
6159
import os
@@ -72,10 +70,18 @@ def part_field_calculation(metadata, event: PartFieldCalculationEvent, service):
7270
# Only translate on creation
7371
return
7472

75-
if event.data.part.cssaas_frame_add_attr_1:
73+
if event.data.part.eng_benennung and not event.data.part.benennung:
74+
# English part name is set but German name is missing
75+
# -> translate English name to German
76+
translated_text = translate_text(
77+
event.data.part.eng_benennung, target_lang="DE", source_lang="EN")
78+
return DataResponse(data={"benennung": translated_text})
79+
elif event.data.part.benennung and not event.data.part.eng_benennung:
80+
# German name is set but English name is missing
81+
# -> translate German name to English
7682
translated_text = translate_text(
77-
event.data.part.cssaas_frame_add_attr_1, "EN", "DE")
78-
return DataResponse(data={"cssaas_frame_add_attr_2": translated_text})
83+
event.data.part.benennung, target_lang="EN", source_lang="DE")
84+
return DataResponse(data={"eng_benennung": translated_text})
7985

8086
def translate_text(text, target_lang, source_lang=None):
8187
url = "https://api-free.deepl.com/v2/translate"

0 commit comments

Comments
 (0)