howzus/docker-tutorial
0
1from fastapi import FastAPI2from transformers import pipeline3 4# NOTE - we configure docs_url to serve the interactive Docs at the root path5# of the app. This way, we can use the docs as a landing page for the app on Spaces.6app = FastAPI(docs_url="/")7 8# Initialize the text generation pipeline9# This function will be able to generate text10# given an input.11pipe = pipeline("text2text-generation", 12model="google/flan-t5-small")13 14# Define a function to handle the GET request at `/generate`15# The generate() function is defined as a FastAPI route that takes a 16# string parameter called text. The function generates text based on the # input using the pipeline() object, and returns a JSON response 17# containing the generated text under the key "output"18@app.get("/generate")19def generate(text: str):20 """21 Using the text2text-generation pipeline from `transformers`, generate text22 from the given input text. The model used is `google/flan-t5-small`, which23 can be found [here](<https://huggingface.co/google/flan-t5-small>).24 """25 # Use the pipeline to generate text from the given input text26 output = pipe(text)27 28 # Return the generated text in a JSON response29 return {"output": output[0]["generated_text"]}