GithubHelp home page GithubHelp logo

fagan2888 / function-bike-rider Goto Github PK

View Code? Open in Web Editor NEW

This project forked from noahgift/function-bike-rider

0.0 0.0 0.0 26 KB

This is a repo for showing what you can do with a function

Makefile 11.27% Python 88.73%

function-bike-rider's Introduction

function-bike-rider

This is a repo for showing what you can do with a function

You can watch a Video Walkthrough here:

The Power of Functions in Python

Setup Cloud Environment (AWS Cloud9)

python3 -m venv ~/.function-bike-rider source ~/.function-bike-rider/bin/activate

SSH Keys

ssh-keygen -t rsa

upload to github

Create Scaffold (with Marco Polo function)

  • Makefile
  • hello.py
  • requirements.txt

Continuous Integration with Github Actions

  • test_hello.py
  • installed pylint, pytest, black

Building a command-line tool

  • use click to build a cli

https://github.com/noahgift/function-bike-rider/blob/master/cvcli.py

Explored AWS Lambda

def lambda_handler(event, context):
    if event["name"] == "Marco":
        return "Polo"
    return "No!"

Use Boto3

  • install boto3 and use ipython

Build a computer vision cli

Build a trigger that automatically runs a Lambda Function

import boto3
from urllib.parse import unquote_plus

def label_function(bucket, name):
    """This takes an S3 bucket and a image name!"""
    print(f"This is the bucketname {bucket} !")
    print(f"This is the imagename {name} !")
    rekognition = boto3.client("rekognition")
    response = rekognition.detect_labels(
        Image={"S3Object": {"Bucket": bucket, "Name": name,}},
    )
    labels = response["Labels"]
    print(f"I found these labels {labels}")
    return labels


def lambda_handler(event, context):
    """This is a computer vision lambda handler"""

    print(f"This is my S3 event {event}")
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        print(f"This is my bucket {bucket}")
        key = unquote_plus(record['s3']['object']['key'])
        print(f"This is my key {key}")
        
    my_labels = label_function(bucket=bucket, 
        name=key)
    return my_labels

GCP Cloud Function that Translates

import wikipedia

from google.cloud import translate

def sample_translate_text(text="YOUR_TEXT_TO_TRANSLATE", 
    project_id="YOUR_PROJECT_ID", language="fr"):
    """Translating Text."""

    client = translate.TranslationServiceClient()

    parent = client.location_path(project_id, "global")

    # Detail on supported types can be found here:
    # https://cloud.google.com/translate/docs/supported-formats
    response = client.translate_text(
        parent=parent,
        contents=[text],
        mime_type="text/plain",  # mime types: text/plain, text/html
        source_language_code="en-US",
        target_language_code=language,
    )
    print(f"You passed in this language {language}")
    # Display the translation for each input text provided
    for translation in response.translations:
        print(u"Translated text: {}".format(translation.translated_text))
    return u"Translated text: {}".format(translation.translated_text)

def translate_test(request):
    """Takes JSON Payload {"entity": "google"}
    """
    request_json = request.get_json()
    print(f"This is my payload: {request_json}")
    if request_json and 'entity' in request_json:
        entity = request_json['entity']
        language = request_json['language']
        sentences = request_json['sentences']
        print(entity)
        res = wikipedia.summary(entity, sentences=sentences)
        trans=sample_translate_text(text=res, project_id="cloudai-194723",
            language=language )
        return trans
    else:
        return f'No Payload'

Example Output of GCP Cloud Function

Send payload in:

{
        "entity":"google",
        "language":"es",
        "sentences":"3"
}

The result below:

Translated text: Google LLC es una empresa de tecnología multinacional estadounidense que se especializa en servicios y productos relacionados con Internet, que incluyen tecnologías de publicidad en línea, un motor de búsqueda, computación en la nube, software y hardware. Se considera una de las cuatro grandes empresas de tecnología junto con Amazon, Apple y Microsoft. Google fue fundada en septiembre de 1998 por Larry Page y Sergey Brin mientras eran Ph.D. estudiantes de la Universidad de Stanford en California. Juntos poseen alrededor del 14 por ciento de sus acciones y controlan el 56 por ciento del poder de voto de los accionistas a través de acciones de supervotación.

Finally, you can call from the CLI:

gcloud functions call translate-wikipedia --data '{"entity":"google", "sentences
": "20", "language":"es"}'

function-bike-rider's People

Contributors

noahgift avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.