Engenharia de software e documentação
A program is like a poem: you cannot write a poem without writing it.
Dijkstra
Arquitetura do sistema
Coesão, acoplamento, inversão e injeção de dependência
Como não destruir seu repositório com PRs
I named Linux after myself. It's only natural that I did the same with Git.
Linus Torvalds
Retirado de fonte
Retirado de fonte
Design patterns e requisitos de software
Insanity is doing the exact same fucking thing over and over again, expecting shit to change.
Vaas Montenegro
Motivações e exemplos
Coesão
Acoplamento
Reutilização
+
Escalabilidade
+
Retirado de fonte
Inversão de dependência
Retirado de fonte
Retirado de fonte
class ROSMaster:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super(ROSMaster, cls).__new__(cls)
cls._instance.publishers = {}
return cls._instance
def register_publisher(self, topic_name, publisher):
self.publishers[topic_name] = publisher
def subscribe(self, subscriber, topic_name):
publisher = self.publishers.get(topic_name)
if publisher:
publisher.add_subscriber(subscriber)
# Testando o Singleton:
master1 = ROSMaster()
master2 = ROSMaster()
# Deve retornar True, já que ambos devem ser a mesma instância
print(master1 == master2)
Crie um script em Python capaz de ler as notas de alunos e calcular a média para cada um deles. O programa deve ser capaz de ler as notas tanto de um arquivo csv quanto de um arquivo yml. A sua saíde pode ser tanto uma atualização do arquivo csv/yml quanto por stdout (terminal). Exemplo:
./gera-notas.py -i notas.csv -o notas.yml
>> Arquivo atualizado com sucesso
./gera-notas.py -i notas.yml
Betinho: 5.5
Elisa: 7.5
João: 8.5
Dicas: bibliotecas pyyaml, csv, argparse
Como criá-los? Como medí-los
Revisão de ROS e Quatérnios
Quaternions came from Hamilton after his really good work had been done, and though beautifully ingenious, have been an unmixed evil to those who have touched them in any way.
Lord Kelvin
Nós e tópicos. Publishers e subscribers
Use o pacote turtlesim para rodar um nó de simulação e outro de teleoperação.
rqt_graph
Crie um subscriber simples capaz de consumir informações do tópico de pose do turtlesim e exibir no terminal.
Crie um publisher capaz de publicar mensagens no tópico que rege a movimentação do turtlesim.
A forma mais simples de se trabalhar com projetos em ROS
Utilizando o tutorial fornecido no material auxiliar, transforme os dois scripts feitos anteriormente em um pacote e crie um launchfile para rodá-los ao mesmo tempo (o launchfile deve fazer parte do pacote).
ROS_DOMAIN_ID e Tchau, brigado pro WSL!
export ROS_DOMAIN_ID=<valor>
#Valores seguros: 0-101 e 215-232
Em duplas ou trios, criem um script capaz de fazer um desenho. Configurem para que o ROS_DOMAIN_ID seja o mesmo e alternem entre um fazer um desenho no turtlesim do outro.
Pure evil
Retirado de fonte
Retirado de fonte
Gazebo e nav2
...and yet though I know beforehand that he won’t, I set off to him. Why? Well, when one has no one, nowhere else one can go! For every man must have somewhere to go. Since there are times when one absolutely must go somewhere!
Marmeladov (Crime and Punishment)
Server - Client
Retirado de fonte
Dois serviços e um tópico
Retirado de fonte
Mapeando e navegando
Retirado de fonte
Retirado de fonte
Execute o lançador do turtlebot_world e mova o robô no mundo simulado com o turtlebot_teleop.
ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
ros2 run turtlebot3_teleop teleop_keyboard
Usando o turtlebot cartographer, mapeie o mundo do turtlebot3. Para isso, use o teleop para mover-se pelo mapa enquanto mapeia.
ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
ros2 launch turtlebot3_cartographer cartographer.launch.py use_sim_time:=True
ros2 run turtlebot3_teleop teleop_keyboard
ros2 run nav2_map_saver map_saver_cli -f <nome-do-mapa>
Agora que já temos um mapa, vamos carregá-lo e navegar usando o Rviz + nav2
ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
# Substitua o arquivo-do-mapa pelo local onde está o seu mapa
ros2 launch turtlebot3_navigation2 navigation2.launch.py use_sim_time:=True
map:=<arquivo-do-mapa>.yaml
Vamos agora fazer tudo isso, só que programáticamente?
ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
# Substitua o arquivo-do-mapa pelo local onde está o seu mapa
ros2 launch turtlebot3_navigation2 navigation2.launch.py use_sim_time:=True
map:=<arquivo-do-mapa>.yaml
Webots e chatbot simples
Chatbots baseados em regras são como papagaios tecnológicos, repetem o que é programado, mas não entendem o bate-papo. Eu, por outro lado, sou mais como um romancista em uma mesa de bar, criando histórias com cada palavra digitada. Eles seguem o script, eu jogo xadrez com as palavras.
Gepeto, Chat
Tchau, brigado gazebo
/^.*regex.*:\)$/
Dois dicionários e muito regex
Agora que já temos um mapa, vamos carregá-lo e navegar usando o Rviz + nav2
ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
# Substitua o arquivo-do-mapa pelo local onde está o seu mapa
ros2 launch turtlebot3_navigation2 navigation2.launch.py use_sim_time:=True
map:=<arquivo-do-mapa>.yaml
Vamos agora fazer tudo isso, só que programáticamente?
ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
# Substitua o arquivo-do-mapa pelo local onde está o seu mapa
ros2 launch turtlebot3_navigation2 navigation2.launch.py use_sim_time:=True
map:=<arquivo-do-mapa>.yaml
Langchain pt 2, LCEL, RAG
Sou o milhor. Posso não ser o milhor, mas na minha cabeça sou o milhor
Chat CR7
Quanto overengineering vocês querem?
- Sim
Retirado de fonte
from langchain.prompts import PromptTemplate
prompt_template = PromptTemplate.from_template(
"Tell me a {adjective} joke about {content}."
)
prompt_template.format(adjective="funny", content="chickens")
Conciso, mas com 500 abstrações para cada coisinha
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
model = ChatOpenAI(model="gpt-3.5-turbo")
prompt = ChatPromptTemplate.from_template(
"""
You are now my personal travel agent. Act as someone who has immense travel
experience and knows the best places in the world to do certain activities. I
want to know where I should go to {activity}. Give the answers as a list of
items, no bigger than 5 items. For each item, create a simple sentence
justifying this choice.
"""
)
chain = prompt | model
for s in chain.stream({"activity": "eat live fish"}):
print(s.content, end="", flush=True)
Vamos implementar uma cadeia simples?
Como evitar que um LLM alucine?
Retirado de fonte
Retirado de fonte
Retirado de fonte
Retirado de fonte
Retirado de fonte
Retirado de fonte
Retirado de fonte
from langchain.chat_models import ChatOpenAI
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import ChatPromptTemplate
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import RunnableLambda, RunnablePassthrough
from langchain.vectorstores import FAISS
vectorstore = FAISS.from_texts(
["Bread - (0.0, 1.0, 2.0)\nMilk - (1.0, 2.0, 0.0)"],
embedding=OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever()
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
model = ChatOpenAI(model="gpt-3.5-turbo")
chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| model
)
for s in chain.stream("Where is the bread?"):
print(s.content, end="", flush=True)
Bora de RAG? Baixem o arquivo texto aqui
Introdução à redes neurais
AI winters were not due to imagination traps, but due to lack of imaginations. Imaginations bring order out of chaos. Deep learning with deep imagination is the road map to AI springs and AI autumns.
Amit Ray
class Perceptron:
def __init__(self, weights, threshold):
self.weights = np.array(weights)
self.threshold = threshold
self.bias = 0
def activation_function(self, x):
return 1 if x >= self.threshold else 0
def predict(self, inputs):
# Calcula a soma ponderada das entradas
linear_output = np.dot(inputs, self.weights) + self.bias
# Aplica a função degrau para determinar a saída
y_predicted = self.activation_function(linear_output)
return y_predicted
Vamos implementar um perceptron? Do livro "Neural networks and deep learning":
Suppose the weekend is coming up, and you've heard that there's going to be a cheese festival in your city. You like cheese, and are trying to decide whether or not to go to the festival. You might make your decision by weighing up three factors:
We can represent these three factors by corresponding binary variables x1,x2, and x3. For instance, we'd have x1=1 if the weather is good, and x1=0 if the weather is bad. Similarly, x2=1 if your boyfriend or girlfriend wants to go, and x2=0 if not. And similarly again for x3 and public transit.
Vamos fazer o perceptron aprender? Crie um método de treinamento e, usando-o, faça com que o perceptron aprenda a reproduzir o comportamento das seguintes portas lógicas:
Forward propagation
Redes neurais convolucionais
You've got it from here.
Nanamin
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
x = np.array([[0,0], [0,1], [1,0], [1,1]])
y = np.array([[0], [1], [1], [0]])
# Creating the MLP model
model = Sequential()
model.add(Dense(4, input_dim=2, activation='relu')) # First hidden layer
model.add(Dense(1, activation='sigmoid')) # Output layer
# Compile the model
model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])
# Train the model
model.fit(x, y, epochs=10, batch_size=1)
MLP c/ Keras
Ponderada 7 - Classificação MNIST utilizando redes neurais convolucionais.
Ferramentas TTS e STT
Honored bun
Utilizando o whisper, crie um programa simples que transcreva um arquivo de áudio contendo uma frase e exiba-o no terminal
pip install -U openai-whisper
Utilizando o JETS TTS, crie um script que receba um input do usuário e converta-o em áudio
pip install txtai[pipeline-audio]
pip install soundfile
Ponderada 8 - Criando o seu próprio tradutor
Redes neurais recorrentes
Aoi Todo (GOAT)
Feedforward
Utilizando LSTM para gerar músicas.
Encoder-Decoder Transformer
You're right, [REDACTED]. I'm you. I wanted to reject you, convince myself that you were wrong. But that doesn't matter now. I'm gonna kill you. Even if you come back as another curse, I'll kill you. Change your name. Change your form. I'll kill you again. I don't need to find meaning or a reason. Maybe in a hundred years after my death, the meaning behind my actions will become apparent. In the grand scheme of things... I'm probably nothing more than a cog.
HIMtadori, Yuji
Gyobu Masataka Oniwa
Vetor de contexto
Tokens
Ficou perfeito agora??
Fabricação digital
[Jensen] sent out an email on Friday evening saying everything is going to deep learning, and that we were no longer a graphics company. By Monday morning, we were an AI company. Literally, it was that fast.
Greg Estes (VP Marketing - NVidia)
The “classical stack” of Software 1.0 is what we’re all familiar with — it consists of explicit instructions to the computer written by a programmer. In contrast, Software 2.0 is written in much more abstract, human unfriendly language, such as the weights of a neural network.
Andrej Karpathy (Tesla, OpenAI)