{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### How to generate the dataset\n", "\n", "1. Use PyGen.AI with prompt: \"Generate code to read dataset bstraehle/airbnb-san-francisco-202403 from Hugging Face. Process line by line to embed field 'description' using OpenAI model 'text-embedding-3-small', then append the line and embedded field 'description_embedding' to file 'c:\\temp\\airbnb-san-francisco-202403-embed.jsonl'.\n", "2. Replace hard-coded OpenAI API key with getpass\n", "3. Fix embedding code, see https://platform.openai.com/docs/guides/embeddings/how-to-get-embeddings" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install openai transformers" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Execution time: ~34 minutes\n", "\n", "from datasets import load_dataset\n", "from openai import OpenAI\n", "import json, getpass\n", "\n", "dataset = load_dataset(\"bstraehle/airbnb-san-francisco-202403\")\n", "\n", "client = OpenAI(api_key = getpass.getpass(\"OpenAI API Key\"))\n", "\n", "def embed_text(text):\n", " \"\"\"Function to embed text using OpenAI's text-embedding-3-small model.\"\"\"\n", " response = client.embeddings.create(\n", " input=text,\n", " model=\"text-embedding-3-small\"\n", " )\n", " return response.data[0].embedding\n", "\n", "def process_dataset(dataset):\n", " \"\"\"Process each row in the dataset, embed 'description', and write to a new file.\"\"\"\n", " with open(\"c:\\\\temp\\\\airbnb-san-francisco-202403-embed.jsonl\", \"w\") as f:\n", " for item in dataset:\n", " description = item[\"description\"]\n", "\n", " if description:\n", " embedding = embed_text(description)\n", " new_item = {**item, \"description_embedding\": embedding}\n", " f.write(json.dumps(new_item) + '\\n')\n", "\n", "process_dataset(dataset['train'])\n", "\n", "print(\"Processing completed.\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13" } }, "nbformat": 4, "nbformat_minor": 2 }