שימוש בספריות הלקוח ב-Cloud Code
בדף הזה מוסבר איך להתחיל במהירות עם ספריות לקוח של Cloud ו-Cloud Code. תגדירו אפליקציית Kubernetes חדשה באמצעות אפליקציית דוגמה של Hello World, ואז תעדכנו את האפליקציה כדי להשתמש ב-Cloud Translation API לתרגום התגובה לספרדית.
לפני שמתחילים
- נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Google Kubernetes Engine and Cloud Translation APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Google Kubernetes Engine and Cloud Translation APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.- מתקינים את Git כדי ש-Cloud Code יוכל לבצע פעולות של Git, כמו שיבוט של דוגמה.
- אם עוד לא עשיתם זאת, מתקינים את הפלאגין Cloud Code.
יצירת אפליקציה
- מלוח הפקודות (
Cmd/Ctrl+Shift+P), מריצים את הפקודה Cloud Code: New Application, בוחרים באפשרות Kubernetes Application, ואז בוחרים באפליקציית Hello World בשפה הרצויה. לדוגמה, בוחרים באפשרות Node.js: Hello World כדי ליצור אפליקציית Node.js Hello World למתחילים. - שומרים את האפליקציה החדשה. תוצג התראה שמאשרת שהבקשה נוצרה, וחלון חדש עם הבקשה ייפתח.
הגדרת פרטי כניסה
כדי לפתוח טרמינל, לוחצים על Terminal (טרמינל) > New Terminal (טרמינל חדש).
יוצרים חשבון שירות כדי לאמת את בקשות ה-API:
gcloud iam service-accounts create \ translation-quickstart \ --project PROJECT_ID
נותנים לחשבון השירות את התפקיד Cloud Translation API User:
gcloud projects \ add-iam-policy-binding \ PROJECT_ID \ --member='serviceAccount:translation-quickstart@PROJECT_ID.iam.gserviceaccount.com' \ --role='roles/cloudtranslate.user'
יוצרים מַפְתח לחשבון השירות:
gcloud iam service-accounts keys \ create key.json --iam-account \ translation-quickstart@PROJECT_ID.iam.gserviceaccount.com
הגדרת המפתח כפרטי ברירת המחדל:
export \ GOOGLE_APPLICATION_CREDENTIALS=key.json
קריאה ל-Cloud Translation API מהאפליקציה
המשך
מתקינים את ספריות הלקוח של Cloud לשימוש ב-Cloud Translation API:
- כדי לפתוח טרמינל, לוחצים על Terminal (טרמינל) > New Terminal (טרמינל חדש).
מריצים את הפקודה הבאה:
go get cloud.google.com/go/translate/apiv3
יוצרים קובץ
app.go.פותחים את
app.goומוסיפים את שם החבילה, את הייבוא ואת המבנה של האפליקציה:package main import ( "context" "fmt" translate "cloud.google.com/go/translate/apiv3" translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" ) func translateText(w io.Writer, projectID string, sourceLang string, targetLang string, text string) error { } func main() { }בפונקציה
translateText(), מוסיפים את הקוד הבא שמתרגם את הטקסט שצוין. בוחרים באפשרות קובץ > שמירה כדי לעצב מחדש את הקוד:ctx := context.Background() client, err := translate.NewTranslationClient(ctx) if err != nil { return fmt.Errorf("NewTranslationClient: %v", err) } defer client.Close() req := &translatepb.TranslateTextRequest{ Parent: fmt.Sprintf("projects/%s/locations/global", projectID), SourceLanguageCode: sourceLang, TargetLanguageCode: targetLang, MimeType: "text/plain", // Mime types: "text/plain", "text/html" Contents: []string{text}, } resp, err := client.TranslateText(ctx, req) if err != nil { return fmt.Errorf("TranslateText: %v", err) } // Display the translation for each input text provided for _, translation := range resp.GetTranslations() { fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText()) } return nilבפונקציה
main(), קוראים לפונקציהtranslateText(). ערכי הפרמטרים הבאים מתרגמים מאנגלית לספרדית:projectID := "<var>PROJECT_ID</var>" sourceLang := "en-US" targetLang := "es" text := "Text to translate" err := translateText(os.Stdout, projectID, sourceLang, targetLang, text) if err != nil { fmt.Print(err) }מריצים את האפליקציה מהטרמינל.
go run app.go
Java
פותחים את
pom.xmlומוסיפים את קטע הקוד הבא לקטעdependencies:<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-translate</artifactId> </dependency> </dependencies>לאחר מכן, בקובץ
pom.xml, מוסיפים את קטע הקוד הבא לקטעdependencyManagement:<dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>libraries-bom</artifactId> <version>26.39.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>חשוב לוודא שאתם משתמשים בגרסה העדכנית ביותר של Google Cloud ספריות נתמכות. רשימת הגרסאות מופיעה במאמר Google Cloud ספריות נתמכות.
כשמוצגת השאלה אם רוצים לסנכרן את Java classpath/configuration, לוחצים על Always (תמיד).
יוצרים קובץ בשם
app.java.ב-
app.java, מוסיפים את ההצהרות הבאות על ייבוא אחרי הגדרת החבילה:import com.google.cloud.translate.v3.LocationName; import com.google.cloud.translate.v3.TranslateTextRequest; import com.google.cloud.translate.v3.TranslateTextResponse; import com.google.cloud.translate.v3.Translation; import com.google.cloud.translate.v3.TranslationServiceClient; import java.io.IOException;מוסיפים את ה-method
translateText()למחלקהApp. בשיטה הזו מוגדרים משתנים ומועברים לשיטתtranslateText()בעומס יתר. הערכים הבאים מתרגמים מאנגלית לספרדית:public static void translateText() throws IOException { String projectId = "<walkthrough-project-id/>"; String targetLanguage = "es"; String text = "Hello world!"; translateText(projectId, targetLanguage, text); }מוסיפים שיטת
translateText()עם עומס יתר. השיטה הזו מקבלת טקסט ומתרגמת אותו לשפת היעד.public static void translateText(String projectId, String targetLanguage, String text) throws IOException { try (TranslationServiceClient client = TranslationServiceClient.create()) { LocationName parent = LocationName.of(projectId, "global"); TranslateTextRequest request = TranslateTextRequest.newBuilder() .setParent(parent.toString()) .setMimeType("text/plain") .setTargetLanguageCode(targetLanguage) .addContents(text) .build(); TranslateTextResponse response = client.translateText(request); // Display the translation for each input text provided for (Translation translation : response.getTranslationsList()) { System.out.printf("Translated text: %s\n", translation.getTranslatedText()); } } }מחליפים את הצהרת ההדפסה ב-
mainבקריאה ל-translateText():try { translateText(); } catch (IOException e) { e.printStackTrace(); }
Node.js
מתקינים את ספריות הלקוח של Cloud לשימוש ב-Cloud Translation API:
- לוחצים על
Cloud Code ואז מרחיבים את Cloud APIs Explorer.
- מרחיבים את Cloud AI ואז לוחצים על Cloud Translation API.
- כדי להתקין את ספריית הלקוח, לוחצים על NodeJS ואז על play_arrow
Run in terminal (הפעלה במסוף).
- לוחצים על
יוצרים קובץ
app.jsבפרויקט.פותחים את הקובץ
app.jsומייבאים את ספריית הלקוח של Translation בתחילת הקובץ:const {TranslationServiceClient} = require('@google-cloud/translate');יוצרים לקוח API של Translation API ומוסיפים משתנים למזהה הפרויקט, למיקום ולטקסט שרוצים לתרגם:
// Instantiates a client const translationClient = new TranslationServiceClient(); const projectId = 'PROJECT_ID'; const location = 'global'; const text = 'Hello, world!';
מוסיפים את הפונקציה הבאה
asyncשמזהה את השפה של הטקסטHello, world!ומתרגמת אותו לספרדית:async function translateText() { // Construct request const request = { parent: `projects/PROJECT_ID/locations/LOCATION`, contents: [text], mimeType: 'text/plain', // mime types: text/plain, text/html sourceLanguageCode: 'en', targetLanguageCode: 'es', }; // Run request const [response] = await translationClient.translateText(request); for (const translation of response.translations) { console.log(`Translation: ${translation.translatedText}`); } }בסוף קובץ
app.js, קוראים לפונקציהtranslateText():translateText();כדי להריץ את האפליקציה, פותחים את לוח הפקודות (לוחצים על
Ctrl/Cmd+Shift+P) ומריצים את Cloud Code: Run on Kubernetes.אחרי פריסת האפליקציה, פותחים את כתובת ה-URL שמוצגת בתצוגת האינטרנט כדי לראות את השירות הפועל.
Python
מתקינים את ספריות הלקוח של Cloud לשימוש ב-Cloud Translation API:
- לוחצים על
Cloud Code ואז מרחיבים את Cloud APIs Explorer.
- מרחיבים את Cloud AI ואז לוחצים על Cloud Translation API.
- כדי להתקין את ספריית הלקוח, לוחצים על Python ואז על play_arrow
Run in terminal (הפעלה במסוף).
הערה: אם אתם משתמשים במערכת הפעלה מבוססת-Linux, כולל Chromebook, צריך לשנות את הפקודה כך שתשתמש ב-pip3במקום ב-pip. אם משתמשים ב-Mac, משנים את הפקודה ל-pip3ומוסיפים את הדגל--user.
- לוחצים על
יוצרים קובץ
app.pyבפרויקט.ב-
app.py, מייבאים את ספריית הלקוח בתחילת הקובץ:from google.cloud import translate
מוסיפים את הפונקציה
translate_text. הפעולה הזו יוצרת לקוח כדי לעבוד עם Cloud Translation API.def translate_text(text="Hello, world!", project_id="PROJECT_ID"): client = translate.TranslationServiceClient() location = "global" parent = "projects/PROJECT_ID/locations/LOCATION"
כדי לתרגם טקסט מאנגלית לספרדית ולהדפיס את התוצאה, מוסיפים את הקריאה הבאה ל-Cloud Translation API Cloud Client Libraries בפונקציה
translate_text:response = client.translate_text( request={ "parent": parent, "contents": [text], "mime_type": "text/plain", "source_language_code": "en-US", "target_language_code": "es", } ) for translation in response.translations: print("Translated text: {}".format(translation.translated_text))בסוף
app.py, תתקשר אלtranslate_text().translate_text()כדי להריץ את האפליקציה, פותחים את לוח הפקודות (לוחצים על
Ctrl/Cmd+Shift+P) ומריצים את Cloud Code: Run on Kubernetes.אחרי פריסת האפליקציה, פותחים את כתובת ה-URL שמוצגת בתצוגת האינטרנט כדי לראות את השירות הפועל.
הסרת המשאבים
אחרי שמפסיקים את האפליקציה, כל משאבי Kubernetes שנפרסו במהלך ההרצה נמחקים אוטומטית.
כדי להימנע מחיובים בחשבון על משאבים אחרים שבהם השתמשתם בתחילת העבודה המהירה הזו, הקפידו למחוק את הפרויקט או את האשכול שיצרתם אם אתם רוצים להשתמש שוב בפרויקט.
כדי למחוק את האשכול:
- ב-Kubernetes Explorer, עוצרים עם העכבר מעל שם האשכול ולוחצים על open_in_new Open in Google Cloud console.
- לוחצים על מחיקה ואז על מחיקה.
כדי למחוק את הפרויקט (ואת המשאבים שמשויכים אליו, כולל אשכולות):
- במסוף Google Cloud , נכנסים לדף Manage resources.
- ברשימת הפרויקטים, בוחרים את הפרויקט שרוצים למחוק ולוחצים על Delete.
- כדי למחוק את הפרויקט, כותבים את מזהה הפרויקט בתיבת הדו-שיח ולוחצים על Shut down.