Hands-On Gen AI: Chapter 1
Initial Setup
The following is an export from a Jupyter Notebook run. To set up the environment using uv:
- In a project directory,
uv init - Edit
pyproject.tomlto set the Python version to>=3.10 - Pin the Python version to 3.10 (as used in the book),
uv python pin 3.10 - Install the
genaibookpackage,uv add genaibook - Install Jupyter for notebook support,
uv add jupyter
from genaibook.core import get_device
device = get_device()
print(device)
cuda
import torch
from diffusers import StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5",
torch_dtype=torch.float16,
variant="fp16",
).to(device)
prompt = "a photograph of an astronaut riding a horse"
pipe(prompt).images[0]

from transformers import pipeline
classifier = pipeline("text-classification", device=device)
classifier("This movie is disgustingly good!")
[{'label': 'POSITIVE', 'score': 0.9998536109924316}]
from transformers import set_seed
# Settings the seed ensures we get the same results every time we run this code
set_seed(10)
generator = pipeline("text-generation", device=device)
prompt = "It was a dark and stormy"
generator(prompt)[0]["generated_text"]
'It was a dark and stormy night, the kind where the rain comes down in sheets and the thunder booms like a freight train. The kind of night that makes you think of horror movies and the kind of night that you don\'t want to be out in. But for some reason, I was out in it.\n\nI had been walking for hours, trying to get to my friend\'s house, but the storm had gotten worse and worse. The streets were empty, except for the occasional car that sped by, lights flashing. I had been walking through alleys and side streets, trying to find my way. But I had gotten lost.\n\nI was starting to get really scared. The wind was howling and the rain was stinging my face. I had to find my way out of here, but I didn\'t know where I was. I started to run, trying to get to a main road.\n\nThat\'s when I saw it. A figure standing in the middle of the street, waving at me. It was my friend, Emily.\n\n"Sarah! I\'ve been looking all over for you!" she called out, her voice carrying over the storm.\n\nI ran towards her, my heart racing. "Emily! I\'m so glad you found me!"\n\nShe took my hands and pulled me into'
pipe = pipeline("text-to-audio", model="facebook/musicgen-small", device=device)
data = pipe("electric rock solo, very intense")
print(data)
import IPython.display as ipd
display(ipd.Audio(data["audio"], rate=data["sampling_rate"]))