Lit-llama: Implementation of the LLaMA language model based on nanoGPT

⚡ Lit-LLaMA ️

Lit-LLaMA and pineapple pizza

⚡ Lit-LLaMA ️

Independent implementation of LLaMA that is fully open source under the Apache 2.0 license.

This implementation builds on nanoGPT.

Why?

We believe that AI should be fully open source and part of the collective knowledge.

The original LLaMA code is GPL licensed which means any project using it must also be released under GPL.

This "taints" any other code and prevents meaningful academic and commercial use.

Lit-LLaMA solves that for good.

Design principles

Lit-LLaMA is:

  • Simple: Single-file implementation without boilerplate.
  • Correct: Numerically equivalent to the original model.
  • Optimized: Runs on consumer hardware or at scale.
  • Open-source: No strings attached.

Get involved!

Join our Discord to build high-performance, truly open-source models for the common benefit of the community.

Setup

Clone the repo

git clone https://github.com/Lightning-AI/lit-llama
cd lit-llama

install dependencies

pip install -r requirements.txt

You are all set! 🎉

Use the model

To generate text predictions, download the model weights following the instructions on the official LLaMA repository. Note that currently the weights are still under a research-only license, there's no change to that (yet 🤓).

Once downloaded, you should have a folder like this:

checkpoints/llama
├── 7B
│   ├── checklist.chk
│   ├── consolidated.00.pth
│   └── params.json
├── 13B
│   ...
├── tokenizer_checklist.chk
└── tokenizer.model

Convert the weights to the Lit-LLaMA format:

python scripts/convert_checkpoint.py \
    --output_dir checkpoints/lit-llama \
    --ckpt_dir checkpoints/llama \
    --tokenizer_path checkpoints/llama/tokenizer.model \
    --model_size 7B

Run inference:

python generate.py --prompt "Hello, my name is"

This will run the 7B model and require ~26 GB of GPU memory (A100 GPU).

Run Lit-LLaMA on consumer devices

For GPUs with less memory, enable quantization (--quantize true). This will take longer to load but require ~8GB of memory. This can run on any consumer GPU.

python generate.py --quantize true --prompt "Hello, my name is"

See python generate.py --help for more options.

Finetune the model

We provide a simple training script in finetune.py that instruction-tunes a pretrained model on the Alpaca dataset and also integrates LoRA.

Download the data and generate a instruction tuning dataset:

python scripts/prepare_alpaca.py

Run the finetuning script

python finetune.py

It is expected that you have downloaded the pretrained weights as described above. The finetuning requires a GPU with 40 GB memory (A100). Coming soon: LoRA + quantization for training on a consumer-grade GPU!

Get involved!

We're in a quest towards fully open source AI.

Lit-LLaMA

Join us and start contributing, especially on the following areas:

Look at train.py for a starting point towards pre-training / fine-tuning using Lightning Fabric.

Don't forget to join our Discord!

Acknowledgements

Download Details:

Author: Lightning-AI
Source Code: https://github.com/Lightning-AI/lit-llama 
License: Apache-2.0 license

#llama #gpt #ai #python 

Lit-llama: Implementation of the LLaMA language model based on nanoGPT

Проверка и рефакторинг кода с помощью GPT-4

Пришло время улучшить процесс кодирования с помощью улучшения кода на основе ИИ. Семейство моделей GPT от OpenAI предлагает разработчикам множество возможностей для улучшения, проверки, исправления и даже аутсорсинга написания кода. Знание того, как использовать эти большие языковые модели в процессе разработки, скоро станет важным инструментом в наборе инструментов разработчика.

Вы когда-нибудь задумывались, как ИИ может изменить ваш процесс кодирования? В этом руководстве мы продемонстрируем методы использования ChatGPT или GPT-4 для проверки и рефакторинга кода, а также обсудим некоторые ограничения и предоставим полезные ресурсы для использования этих LLM в рабочем процессе программирования.

Мы начнем с способов проверки и рефакторинга, и для каждого из них вы можете поэкспериментировать с различными подсказками и предоставленными методами, чтобы раскрыть весь потенциал улучшения кода с помощью ИИ.

Примечание. Я буду использовать термин GPT4 во время содержания, так как это текущая модель, запрашиваемая для содержащихся примеров. ChatGPT (GPT3.5) работает аналогичным образом и может использоваться взаимозаменяемо.

Рефакторинг кода с помощью GPT-4 и ChatGPT

Рефакторинг кода имеет решающее значение по нескольким причинам: он повышает удобочитаемость и удобство сопровождения, облегчая разработчикам понимание и изменение кода. Это также помогает предотвратить возможные ошибки и гарантирует, что ваш код соответствует установленным рекомендациям. В конечном итоге рефакторинг может привести к созданию более эффективного, надежного и надежного программного обеспечения.

ГПТ-4 может внести существенный вклад в этот процесс. Используя GPT-4 для просмотра и оценки вашего кода, вы можете быстро определить области для улучшения и создать более чистый и эффективный код. Использование возможностей GPT-4 может сэкономить время и уменьшить количество человеческих ошибок в процессе, что приведет к более последовательному соблюдению стандартов кодирования.

Модернизация старого кода

Вы можете быстро модернизировать свой код, предоставив свою старую функцию GPT-4 и попросив ее реорганизовать ее в соответствии с современными методами кодирования.

Быстрый:Refactor the following code to modern es6 programming standards

До:

function tempConvert(temp, scale) { // Vague function name
  var result = 0; // 'var' is so es2015
  if (scale == "C") { // Is this the correct way to compare strings?
    result = (temp - 32) * (5 / 9); // Magic numbers
  } else {
    result = (temp * (9 / 5)) + 32;
  }
  return result.toFixed(1) + "°" + (scale == "C" ? "F" : "C"); // This line feels a bit cluttered...
}

После:

/**
 * Converts a temperature between Celsius and Fahrenheit.
 * @param {number} temp - The temperature value to convert.
 * @param {string} scale - The temperature scale ('C' or 'F') to convert from.
 * @return {string} The converted temperature value, formatted with one decimal place and the appropriate unit.
 */
const tempConvert = (temp, scale) => {
  const isValidScale = scale === "C" || scale === "F";
  if (!isValidScale) {
    throw new Error("Invalid scale: must be 'C' or 'F'.");
  }

  const conversionFactor = 5 / 9;
  const result = scale === "C"
    ? (temp - 32) * conversionFactor
    : (temp * conversionFactor) + 32;

  const resultUnit = scale === "C" ? "F" : "C";
  return `${result.toFixed(1)}°${resultUnit}`;
}

В этой рефакторинговой версии GPT4 быстро были внесены следующие улучшения:

  1. Добавлены комментарии JSDoc
  2. Преобразовал tempConvertфункцию в функцию стрелки.
  3. Заменено varна constнеизменяемые переменные.
  4. Используются строгие проверки на равенство ( ===) для сравнения строк.
  5. Введена константа для устранения магических чисел.
  6. Упрощен оператор возврата с помощью литералов шаблонов.

Добавление лучших практик или принципов кодирования

Ваша организация или кодовая база могут использовать определенные приемы и стили кодирования, которые вы хотите сохранить. В подобных ситуациях предоставьте GPT4 инструкции о том, на какой конкретной практике кодирования или стиле вы хотите сосредоточиться.

Быстрый: Review the following code and refactor it to make it more DRY and adopt the SOLID programming principles.

Обратите внимание, что с тем же вводом он принял принцип SOLID программирования с единой ответственностью и разделил функцию на 3. В отличие от шага «Модернизация» ранее, он не преобразовал функцию в функцию стрелки.

«Выделив логику преобразования в отдельные функции, мы улучшили соответствие кода принципу единой ответственности (часть SOLID), поскольку теперь у каждой функции есть четкая, целенаправленная цель».

function tempConvert(temp, scale) {
  const isValidScale = scale === "C" || scale === "F";
  if (!isValidScale) {
    throw new Error("Invalid scale: must be 'C' or 'F'.");
  }

  const result = scale === "C" ? celsiusToFahrenheit(temp) : fahrenheitToCelsius(temp);
  const resultUnit = scale === "C" ? "F" : "C";
  return `${result.toFixed(1)}°${resultUnit}`;
}

function celsiusToFahrenheit(temp) {
  const conversionFactor = 9 / 5;
  return (temp * conversionFactor) + 32;
}

function fahrenheitToCelsius(temp) {
  const conversionFactor = 5 / 9;
  return (temp - 32) * conversionFactor;
}

Обнаружение и исправление ошибок

Иногда мы не замечаем уязвимостей или потенциальных проблем, которые может создать наш код. Получение GPT-4 для просмотра и устранения проблем с кодом может сэкономить вам больше, чем просто время.

Быстрый: Review this code for errors and refactor to fix any issues...

Входная (дефектная) функция:

function updateTotalPrice(items, discountPercentage) {
  let totalPrice = 0;

  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    totalPrice += item.price * item.quantity;
  }

  // Potential error: discountPercentage is not validated or checked for boundary conditions
  const discount = totalPrice * (discountPercentage / 100);
  totalPrice -= discount;

  return totalPrice;
}

Выход:

function updateTotalPrice(items, discountPercentage) {
  // Fix 1: Validate input parameters
  if (!Array.isArray(items) || typeof discountPercentage !== 'number') {
    throw new Error('Invalid input parameters');
  }

  // Fix 2: Check for boundary conditions of discountPercentage
  if (discountPercentage < 0 || discountPercentage > 100) {
    throw new Error('Invalid discount percentage value. It should be between 0 and 100');
  }

  let totalPrice = 0;

  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    
    // Fix 3: Validate item properties and types
    if (!item.hasOwnProperty('price') || !item.hasOwnProperty('quantity') || 
        typeof item.price !== 'number' || typeof item.quantity !== 'number') {
      throw new Error('Invalid item properties');
    }

    totalPrice += item.price * item.quantity;
  }

  const discount = totalPrice * (discountPercentage / 100);
  totalPrice -= discount;

  return totalPrice;
}

Изменения, внесенные GPT-4:

  1. Добавлена ​​проверка входного параметра, чтобы убедиться, что элементы являются массивом, а DiscountPercentage — числом.
  2. Проверены граничные условия для DiscountPercentage, чтобы убедиться, что он находится в диапазоне от 0 до 100.
  3. Добавлена ​​проверка свойств предметов и их типов, чтобы убедиться, что цена и количество являются числами.

Создать шаблонный код (*мой любимый)

Начало новых проектов может быть болезненным. GPT-4 не знает вашей бизнес-логики, но с его помощью можно запустить скучный шаблонный код в первый же день. Технически это не рефакторинг, но он потрясающий и может быть частью процесса в жизненном цикле программирования.

Быстрый: Write me a boilerplate Node.js function that will take a variable of type User, validate that the user has the right permissions, fetch an array of item type Posts from a postgres database and return them. Leave comments for business logic.

Транспиляция кода

Есть много причин, по которым вам может понадобиться преобразовать код с одного языка на другой. Вы нашли репозиторий с кодом для одного языка, который вам нужен на другом, вы перемещаете базы кода, или, может быть, ваш начальник прочитал статью о последнем фреймворке внешнего интерфейса, и теперь вы переходите на {разделяющую новую библиотеку}.

В любом случае GPT-4 может оказать помощь простой подсказкой.

Быстрый: Rewrite the following code in Rust: ...

Добавляйте комментарии к коду

Если ваш код говорит сам за себя, но требует комментариев, это может значительно сэкономить время.

Быстрый: Add comments to the following code ...

Советы по улучшению рефакторинга

Как и многие другие вещи в жизни, с GPT-4 вы получаете то, что вкладываете. В этом случае предоставление большего количества контекста, инструкций и рекомендаций обычно дает лучшие результаты.

Вот краткий список советов и приемов по улучшению рефакторинга кода:

  • Разделите подсказки: попробуйте разбить подсказки и желаемый результат на несколько шагов. Было показано, что сохранение подсказок с одним результатом дает лучшие результаты, чем комбинированные подсказки. Например, запросите обзор, а затем запросите рефакторинг на основе ответа на обзор. Со временем это может стать менее важным, поскольку LLM увеличат свой лимит токенов.
  • Приведите примеры: предоставьте ожидаемые входные данные, данные и выходные данные для повышения качества точности.
  • Будьте конкретны: не бойтесь точно перечислить, что вы хотите, что вы знаете, что необходимо и что не следует включать.
  • Попросите его подумать: было показано , что метод, называемый рефлексией , повышает точность GPT4. В основном спросите его: «Почему вы были неправы?» или заставить его задуматься и пересмотреть свой собственный ответ.

Ограничения

Эта статья посвящена искусственному интеллекту, однако эти модели не идеальны и не могут (пока) точно воспроизвести бизнес-логику, среди прочего. Вот список того, на что следует обратить внимание и чего следует избегать при использовании GPT-4 для проверки или рефакторинга кода:

  • Это может быть (уверенно) неправильно: GPT4 обучен звучать убедительно, но это не значит, что он всегда прав. В другой отличной статье о рефакторинге Golang с помощью ChatGPT сообщается : «Он избавился от проверок типов с уверенным объяснением, что утверждение типа не-int для типа int вернет нулевое значение для типа int, но это неверно и будет паника» .
  • Предварительная экономия времени может оказаться бесполезной в долгосрочной перспективе: конечно, GPT4 может генерировать вам 50 строк кода в минуту, но в конечном итоге вам может потребоваться 45 минут на отладку и настройку, если он не подходит для вашей кодовой базы. Вы бы лучше сами написали.
  • Это может быть устаревшим: мир технологий движется быстро. «GPT-4 обычно не знает о событиях, которые произошли после того, как подавляющее большинство его данных отключилось (сентябрь 2021 года) » . Вы можете столкнуться с проблемами с любой недавно обновленной библиотекой, платформой или технологией.

Заключение

Программирование на базе искусственного интеллекта — это всего лишь новинка, но она никуда не денется. При правильном использовании это может сэкономить время и помочь нам писать лучший код. Надеюсь, вам понравилась эта статья, и вы усвоили некоторые новые навыки, которые помогут вам повысить производительность программирования или обработку ошибок.

Оригинальный источник статьи: https://www.sitepoint.com/

#gpt4 #chatgpt #ai #openai 

Проверка и рефакторинг кода с помощью GPT-4

使用 GPT-4 审查和重构代码

是时候通过 AI 驱动的代码改进来增强您的编码过程了。OpenAI 的 GPT 模型系列为开发人员提供了大量改进、审查、修复甚至外包代码编写的机会。了解如何在开发过程中使用这些大型语言模型将很快成为开发人员工具包中必不可少的工具。

有没有想过人工智能如何改变你的编码过程?在本指南中,我们将演示使用 ChatGPT 或 GPT-4 审查和重构代码的技术,并讨论一些限制并提供在编程工作流程中使用这些 LLM 的便利资源。

我们将从我们可以审查和重构的方式开始,对于每一种方式,您可能想要尝试不同的提示和提供的技术来释放 AI 驱动的代码改进的全部潜力。

注意:我将在内容中使用术语 GPT4,因为这是提示包含示例的当前模型。ChatGPT (GPT3.5) 的工作方式类似,可以互换使用。

使用 GPT-4 和 ChatGPT 重构代码

重构代码之所以至关重要,有几个原因:它增强了可读性和可维护性,使开发人员更容易理解和修改代码。它还有助于防止潜在的错误并确保您的代码符合既定的最佳实践。最终,重构可以带来更高效、可靠和健壮的软件。

GPT-4 可以为这一过程做出重大贡献。通过使用 GPT-4 审查和评估您的代码,您可以快速确定需要改进的地方并创建更简洁、更高效的代码。利用 GPT-4 的功能可以节省时间并减少流程中的人为错误,从而更加一致地遵守编码标准。

旧代码现代化

您可以通过向 GPT-4 提供旧功能并要求其重构为现代编码实践来快速实现代码现代化。

迅速的:Refactor the following code to modern es6 programming standards

前:

function tempConvert(temp, scale) { // Vague function name
  var result = 0; // 'var' is so es2015
  if (scale == "C") { // Is this the correct way to compare strings?
    result = (temp - 32) * (5 / 9); // Magic numbers
  } else {
    result = (temp * (9 / 5)) + 32;
  }
  return result.toFixed(1) + "°" + (scale == "C" ? "F" : "C"); // This line feels a bit cluttered...
}

后:

/**
 * Converts a temperature between Celsius and Fahrenheit.
 * @param {number} temp - The temperature value to convert.
 * @param {string} scale - The temperature scale ('C' or 'F') to convert from.
 * @return {string} The converted temperature value, formatted with one decimal place and the appropriate unit.
 */
const tempConvert = (temp, scale) => {
  const isValidScale = scale === "C" || scale === "F";
  if (!isValidScale) {
    throw new Error("Invalid scale: must be 'C' or 'F'.");
  }

  const conversionFactor = 5 / 9;
  const result = scale === "C"
    ? (temp - 32) * conversionFactor
    : (temp * conversionFactor) + 32;

  const resultUnit = scale === "C" ? "F" : "C";
  return `${result.toFixed(1)}°${resultUnit}`;
}

在这次重构的版本中,GPT4 很快做出了以下改进:

  1. 添加了 JSDoc 注释
  2. 将函数转换tempConvert为箭头函数。
  3. 替换varconst不可变变量。
  4. 使用严格的相等性检查 ( ===) 进行字符串比较。
  5. 引入了一个常量来消除幻数。
  6. 使用模板文字简化了返回语句。

添加编码最佳实践或原则

您的组织或代码库可能使用您希望保留的某些编码实践和风格。对于这种情况,请向 GPT4 提供有关您希望其关注的特定编码实践或风格的说明。

迅速的: Review the following code and refactor it to make it more DRY and adopt the SOLID programming principles.

请注意,对于相同的输入,它采用了单一职责的 SOLID 编程原则,并将函数拆分为 3 个。与前面的“现代化”步骤不同,它没有将函数转换为箭头函数。

“通过将转换逻辑提取到单独的函数中,我们改进了代码对单一职责原则(SOLID 的一部分)的遵守,因为每个函数现在都有一个明确、集中的目的。”

function tempConvert(temp, scale) {
  const isValidScale = scale === "C" || scale === "F";
  if (!isValidScale) {
    throw new Error("Invalid scale: must be 'C' or 'F'.");
  }

  const result = scale === "C" ? celsiusToFahrenheit(temp) : fahrenheitToCelsius(temp);
  const resultUnit = scale === "C" ? "F" : "C";
  return `${result.toFixed(1)}°${resultUnit}`;
}

function celsiusToFahrenheit(temp) {
  const conversionFactor = 9 / 5;
  return (temp * conversionFactor) + 32;
}

function fahrenheitToCelsius(temp) {
  const conversionFactor = 5 / 9;
  return (temp - 32) * conversionFactor;
}

检测和修复错误

有时我们对我们的代码可能造成的漏洞或潜在问题视而不见。让 GPT-4 审查和解决代码问题可以为您节省的不仅仅是时间。

迅速的: Review this code for errors and refactor to fix any issues...

输入(有缺陷的)功能:

function updateTotalPrice(items, discountPercentage) {
  let totalPrice = 0;

  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    totalPrice += item.price * item.quantity;
  }

  // Potential error: discountPercentage is not validated or checked for boundary conditions
  const discount = totalPrice * (discountPercentage / 100);
  totalPrice -= discount;

  return totalPrice;
}

输出:

function updateTotalPrice(items, discountPercentage) {
  // Fix 1: Validate input parameters
  if (!Array.isArray(items) || typeof discountPercentage !== 'number') {
    throw new Error('Invalid input parameters');
  }

  // Fix 2: Check for boundary conditions of discountPercentage
  if (discountPercentage < 0 || discountPercentage > 100) {
    throw new Error('Invalid discount percentage value. It should be between 0 and 100');
  }

  let totalPrice = 0;

  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    
    // Fix 3: Validate item properties and types
    if (!item.hasOwnProperty('price') || !item.hasOwnProperty('quantity') || 
        typeof item.price !== 'number' || typeof item.quantity !== 'number') {
      throw new Error('Invalid item properties');
    }

    totalPrice += item.price * item.quantity;
  }

  const discount = totalPrice * (discountPercentage / 100);
  totalPrice -= discount;

  return totalPrice;
}

GPT-4 所做的更改:

  1. 添加了输入参数验证以确保 items 是一个数组并且 discountPercentage 是一个数字。
  2. 检查 discountPercentage 的边界条件以确保它在 0-100 范围内。
  3. 添加了对项目属性及其类型的验证,以确保价格和数量是数字。

创建样板代码(*我的最爱)

开始新项目可能会很痛苦。GPT-4 不知道您的业务逻辑,但它可用于在第一天启动无聊的样板代码。这不是技术上的重构,但它很了不起,并且可以成为编程生命周期中流程的一部分。

迅速的: Write me a boilerplate Node.js function that will take a variable of type User, validate that the user has the right permissions, fetch an array of item type Posts from a postgres database and return them. Leave comments for business logic.

转译代码

您可能需要将代码从一种语言转换为另一种语言的原因有很多。您找到了一个存储库,其中包含您需要的另一种语言的代码,您正在移动代码库,或者您的老板可能阅读了一篇关于最新前端框架的文章,现在您正在转向{分裂的新库}。

在任何情况下,GPT-4 都可以通过简单的提示提供帮助。

迅速的: Rewrite the following code in Rust: ...

给代码添加注释

如果您的代码不言自明但需要注释,这可以节省大量时间。

迅速的: Add comments to the following code ...

更好重构的技巧

就像生活中的许多事情一样,使用 GPT-4,你会得到你投入的东西。在这种情况下,提供更多的背景、说明和指导通常会产生更好的结果。

以下是改进代码重构的技巧和技巧的简短列表:

  • 拆分您的提示:尝试在多个步骤中分解您的提示和期望的结果。保持提示以获得单一结果已证明比组合提示产生更好的结果。例如,要求审查,然后根据审查响应要求重构。随着 LLM 增加其令牌限制,这可能会随着时间的推移变得不那么重要。
  • 举例:提供预期的输入、数据和输出以提高准确性质量。
  • 要具体:不要害怕准确地列出你想要什么、你知道什么、需要什么以及不包括什么。
  • 要求它反映:一种称为反射的技术已被证明可以提高 GPT4 的准确性。基本上问它“你为什么错了?” 或者让它反思和审查自己的回应。

限制

这篇文章非常支持 AI,但是这些模型并不完美,并且不能(还)准确地复制业务逻辑等。以下是使用 GPT-4 审查或重构代码时需要注意和避免的事项列表:

  • 它可能(自信地)错了: GPT4 经过训练听起来很有说服力,但这并不意味着它总是正确的。另一篇关于使用 ChatGPT 重构 Golang 的精彩文章报告说“它摆脱了类型检查,并自信地解释说将非 int 值类型断言为 int 类型将返回 int 类型的零值,但这是不正确的,并且会恐慌'
  • 从长远来看,预先节省时间可能不值得:当然,GPT4 可以在一分钟内为您生成 50 行代码,但如果它不适合您的代码库,最终可能需要 45 分钟来调试和调整它。你最好自己写。
  • 它可能已经过时:技术世界发展迅速。“GPT-4 通常缺乏对绝大多数数据中断后发生的事件的了解(2021 年 9 月) ”。您可能会遇到任何新更新的库、框架或技术的问题。

结论

人工智能驱动的编程只是一个新事物,但它会一直存在。如果使用得当,它可以节省时间并帮助我们编写更好的代码。我希望您喜欢这篇文章并掌握了一些新技能来提高您的编程效率或错误处理能力。

文章原文出处:https: //www.sitepoint.com/

#gpt4 #chatgpt #ai #openai 

使用 GPT-4 审查和重构代码
Gordon  Matlala

Gordon Matlala

1680234447

Review and Refactor Code with GPT-4

It’s time to enhance your coding process with AI-driven code improvement. The GPT family of models from OpenAI offers developers a wealth of opportunities to improve, review, fix, and even outsource code writing. Knowing how to use these large language models during the development process will soon become an essential tool in the developer toolkit.

Ever wondered how AI could transform your coding process? In this guide, we’ll demonstrate techniques for using ChatGPT or GPT-4 to review and refactor code, as well as discuss some limitations and provide handy resources for using these LLMs in your programming workflow.

We’ll start with ways we can review and refactor, and for each of these, you may want to experiment with different prompts and the provided techniques to unlock the full potential of AI-driven code improvement.

Note: I will use the term GPT4 during the content as this is the current model prompted for the containted examples. ChatGPT (GPT3.5) works in a similar way and can be used interchangeably.

Refactoring Code with GPT-4 and ChatGPT

Refactoring code is crucial for several reasons: it enhances readability and maintainability, making it easier for developers to understand and modify the code. It also helps prevent potential bugs and ensures that your code adheres to established best practices. Ultimately, refactoring can lead to more efficient, reliable, and robust software.

GPT-4 can significantly contribute to this process. By using GPT-4 to review and assess your code, you can quickly identify areas for improvement and create cleaner, more efficient code. Leveraging GPT-4’s capabilities can save time and reduce human errors in the process, resulting in more consistent adherence to coding standards.

Modernizing Old Code

You can quickly modernize your code by providing your old function to GPT-4 and ask it to refactor it to modern coding practices.

Prompt: Refactor the following code to modern es6 programming standards

Before:

function tempConvert(temp, scale) { // Vague function name
  var result = 0; // 'var' is so es2015
  if (scale == "C") { // Is this the correct way to compare strings?
    result = (temp - 32) * (5 / 9); // Magic numbers
  } else {
    result = (temp * (9 / 5)) + 32;
  }
  return result.toFixed(1) + "°" + (scale == "C" ? "F" : "C"); // This line feels a bit cluttered...
}

After:

/**
 * Converts a temperature between Celsius and Fahrenheit.
 * @param {number} temp - The temperature value to convert.
 * @param {string} scale - The temperature scale ('C' or 'F') to convert from.
 * @return {string} The converted temperature value, formatted with one decimal place and the appropriate unit.
 */
const tempConvert = (temp, scale) => {
  const isValidScale = scale === "C" || scale === "F";
  if (!isValidScale) {
    throw new Error("Invalid scale: must be 'C' or 'F'.");
  }

  const conversionFactor = 5 / 9;
  const result = scale === "C"
    ? (temp - 32) * conversionFactor
    : (temp * conversionFactor) + 32;

  const resultUnit = scale === "C" ? "F" : "C";
  return `${result.toFixed(1)}°${resultUnit}`;
}

In this refactored version, GPT4 quickly made the following improvements:

  1. Added JSDoc comments
  2. Converted the tempConvert function to an arrow function.
  3. Replaced var with const for immutable variables.
  4. Used strict equality checks (===) for string comparisons.
  5. Introduced a constant to eliminate magic numbers.
  6. Simplified the return statement with template literals.

Adding Coding Best Practices or Principles

Your organisation or code base might use certain coding practices and styles that you want to keep. For situations like this, provide instructions to GPT4 on what particular coding practice, or style you’d like it to focus on.

Prompt: Review the following code and refactor it to make it more DRY and adopt the SOLID programming principles.

Note with the same input it has adopted the SOLID programming principle of Single Responsibility and split the function into 3. Unlike the ‘Modernize’ step earlier, it did not convert the function to an arrow function.

“By extracting the conversion logic into separate functions, we’ve improved the code’s adherence to the Single Responsibility Principle (part of SOLID), as each function now has a clear, focused purpose.”

function tempConvert(temp, scale) {
  const isValidScale = scale === "C" || scale === "F";
  if (!isValidScale) {
    throw new Error("Invalid scale: must be 'C' or 'F'.");
  }

  const result = scale === "C" ? celsiusToFahrenheit(temp) : fahrenheitToCelsius(temp);
  const resultUnit = scale === "C" ? "F" : "C";
  return `${result.toFixed(1)}°${resultUnit}`;
}

function celsiusToFahrenheit(temp) {
  const conversionFactor = 9 / 5;
  return (temp * conversionFactor) + 32;
}

function fahrenheitToCelsius(temp) {
  const conversionFactor = 5 / 9;
  return (temp - 32) * conversionFactor;
}

Detecting and Fixing Errors

Sometimes we are blind to the vulnerabilities or potential issues our code can create. Getting GPT-4 to review and address code issues can save you more than just time.

Prompt: Review this code for errors and refactor to fix any issues...

Input (Flawed) Function:

function updateTotalPrice(items, discountPercentage) {
  let totalPrice = 0;

  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    totalPrice += item.price * item.quantity;
  }

  // Potential error: discountPercentage is not validated or checked for boundary conditions
  const discount = totalPrice * (discountPercentage / 100);
  totalPrice -= discount;

  return totalPrice;
}

Output:

function updateTotalPrice(items, discountPercentage) {
  // Fix 1: Validate input parameters
  if (!Array.isArray(items) || typeof discountPercentage !== 'number') {
    throw new Error('Invalid input parameters');
  }

  // Fix 2: Check for boundary conditions of discountPercentage
  if (discountPercentage < 0 || discountPercentage > 100) {
    throw new Error('Invalid discount percentage value. It should be between 0 and 100');
  }

  let totalPrice = 0;

  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    
    // Fix 3: Validate item properties and types
    if (!item.hasOwnProperty('price') || !item.hasOwnProperty('quantity') || 
        typeof item.price !== 'number' || typeof item.quantity !== 'number') {
      throw new Error('Invalid item properties');
    }

    totalPrice += item.price * item.quantity;
  }

  const discount = totalPrice * (discountPercentage / 100);
  totalPrice -= discount;

  return totalPrice;
}

Changes that GPT-4 made:

  1. Added input parameter validation to ensure items is an array and discountPercentage is a number.
  2. Checked boundary conditions for discountPercentage to ensure it’s within the 0-100 range.
  3. Added validation for item properties and their types to ensure price and quantity are numbers.

Create Boilerplate Code (*my favourite)

Starting new projects can be a painful. GPT-4 doesn’t know your business logic but it can be used to kick off the boring boilerplate code on day 1. This isn’t technically refactoring but it’s amazing and can be part of an process in the programming lifecycle.

Prompt: Write me a boilerplate Node.js function that will take a variable of type User, validate that the user has the right permissions, fetch an array of item type Posts from a postgres database and return them. Leave comments for business logic.

Transpiling Code

There are many reasons you may need to convert code from one language to another. You’ve found a repo with code for one language that you need in another, you’re moving code bases, or maybe your boss read an article on the latest front end framework and now you’re moving to {divisive new library}.

In any case, GPT-4 can provide assistance with a simple prompt.

Prompt: Rewrite the following code in Rust: ...

Add comments to code

If your code is self-explanatory but requires commenting, this can be a huge time-saver.

Prompt: Add comments to the following code ...

Tips for Better Refactoring

Like many things in life, with GPT-4, you get out what you put in. In this case, providing more context, instructions, and guidance will usually produce better results.

Here’s a short list of tips and techniques to improve your code refactoring:

  • Split your prompts: Try breaking your prompts and desired outcome across multiple steps. Keeping prompts to have a single outcome has shown to produce better results than combined prompts. For example, ask for a review, then ask for a refactor based on the review response. This may become less important in time as LLMs increase their token limit.
  • Give Examples: Provide expected inputs, data and outputs to improve accuracy quality.
  • Be Specific: Don’t be afraid to list exactly what you want, what you know, what is needed, and what not to include.
  • Ask it to Reflect: A technique called reflexion has been shown to increase GPT4’s accuracy. Basically ask it ‘Why were you wrong?’ or get it to reflect and review its own response.

Limitations

This article is very pro-AI, however these models are not perfect and cannot (yet) accurately replicate business logic, among other things. Here’s a list of things to look out for and avoid when using GPT-4 to review or refactor your code:

  • It can be (confidently) wrong: GPT4 is trained to sound convincing but that doesn’t mean its always right. Another great article on refactoring Golang with ChatGPT reported ‘It got rid of the type checks with the confident explanation that type-asserting a non-int value to an int type will return the zero value for the int type, but this is not correct and will panic‘.
  • Saving time upfront may not be worth it in the long run: Sure, GPT4 can generate you 50 lines of code in a minute but it may end up taking you 45 minutes to debug and tweak it if it is not fit for your codebase. You would have been better off writing it yourself.
  • It can be out of date: The technology world moves fast. “GPT-4 generally lacks knowledge of events that have occurred after the vast majority of its data cuts off (September 2021). You may encounter issues with any newly updated library, framework, or technology.

Conclusion

AI-powered programming is only new but it is here to stay. When used correctly it can save time and help us write better code. I hope you’ve enjoyed this article and have taken away some new skills to boost your programming productivity or error handling.

Original article source at: https://www.sitepoint.com/

#gpt4 #chatgpt #ai #openai 

Review and Refactor Code with GPT-4
Felix Kling

Felix Kling

1680167168

Generate a Custom Pokémon in Next.js App with ChatGPT and DALL-E

How to Use AI to Generate a Custom Pokémon with OpenAI ChatGPT & DALL-E

Learn how to Use AI to Generate a Custom Pokémon in Next.js App with OpenAI ChatGPT & DALL-E. Pokémon Generator with ChatGPT & DALL-E API in Next.js

Pokémon Generator with ChatGPT & DALL-E API in Next.js. Use ChatGPT and DALL-E to generate a custom Pokémon in a Next.js app.

We'll walk through setting up API routes in a Next.js app that use the OpenAI API and SDK to generate custom Pokémon attributes and an image based on that generated appearance.

🧐 What's Inside

00:00 - Intro
00:21 - Tool we'll use
01:30 - Setting up an OpenAI API Key and installing the SDK
03:00 - Creating a new Create API Route
03:52 - Using the OpenAI Chat API with GPT to generate a new Pokémon
06:19 - Adding prompt modifiers for better results
10:24 - Generating a new Pokémon on button click
14:11 - Using the OpenAI Image API with DALL-E to generate a Pokémon image
16:27 - POSTing the appearance to the API route to generate an image based on the existing Pokémon
21:18 - Outro

AI is here and as developers, we need to use it to empower us in our work. How can we use tools like the OpenAI SDK with generative images and language models to create a completely custom person or character?

What's Inside

  • What is OpenAI?
  • AI? Is the future really here?
  • What are we going to build?
  • Step 0: Creating a new Next.js app
  • Step 1: Installing and configuring the OpenAI SDK
  • Step 2: Generating a new Pokémon with the ChatGPT API in a Next.js serverless function
  • Step 3: Generating a new Pokémon card on button click
  • Step 4: Generating a Pokémon’s image with OpenAI DALL-E
  • What else can we do?

What is OpenAI?

OpenAI is a currently non-profit organization focused on AI research.

They’ve made huge splashes in the tech community with it’s popular releases like DALL-E which gives the ability to create an image from some basic text and GPT which let’s people have real conversations with human-like responses based on language models.

Pokemon character images generated from DALL-E based on a fire-type description

Flamikyu generated images

They’re rapidly making progress, constantly releasing new versions of the models, which make huge strides each time.

AI? Is the future really here?

Pretty much! While it’s likely we’re in a little bit of a “hype wave”, some of the technology we’re seeing is gamechanging.

In my previous article, I explored using GitHub Copilot CLI which let’s you generate commands using AI in the terminal. For a terminal noob like me, that’s incredibly helpful.

Screenshot of video from exploring GitHub Copilot

Exploring GitHub Copilot

But this extends to things like accessibility where it gives us more tools like voice to text to help those i neeed or other industries that can use features like the new ChatGPT Plugins to bring realworld problem-solving into a simple chat interface.

Again, while there’s certainly some hype, I’m excited about the future!

What are we going to build?

We’re going to build a Pokémon generator that creates a new, custom Pokémon using AI.

Generated Pokémon added to card in app

Pokémon generator app

We’ll do this by using the OpenAI SDK in a Next.js serverless function to make our requests.

Once created, we’ll add the Pokémon data to a Card template that we’ll get as part of a Next.js Starter template.

Step 0: Creating a new Next.js app

If you want to follow along with my example, let’s start off by creating a new Next.js app from a Starter template I created that will give us a basic Pokémon card UI.

In your terminal run:

npx create-next-app -e https://github.com/colbyfayock/demo-pokemon-generator-starter my-pokemon-generator

Once complete, navigate to your new directory

  cd my-pokemon-generator

Then start your development server with:

npm run dev

Your server will spin up at http://localhost:3000 and you should be ready to go with your new Next.js app!

App showing empty Pokémon card with generate button

New Pokemon generator app

Step 1: Installing and configuring the OpenAI SDK

Digging in, we’ll start off by installing the OpenAI SDK.

In your terminal, install openai with:

npm install openai

To use the OpenAI SDK, we’ll need an API key that is connected to our account.

If you don’t already have an account, head over to openai.com/product and click Get Started to sign up, or go directly to the signup page, where you can create your free account.

Note: If this is the first time using OpenAI (or you haven’t used much), you should have access to a limited trial. If that’s expired, you’ll need to enter your billing information. For pricing perspective, playing around and setting up the demo for this cost me less than $0.50 USD.

Once in your account, navigate to API Keys by either selecting it from the left sidebar or by clicking your profile avatar on the top right of the navigation.

Let’s create a new key so that we can store it to use in our project.

Note: this is a secret key, be sure not to commit this key openly or share it with anyone or it will get abused.

Inside of your project, create a new file .env.local and inside add:

OPENAI_API_KEY="<Your API Key>"

In the next step, we’ll use this key for initializing the SDK!

Follow along with the commit!

Step 2: Generating a new Pokémon with the ChatGPT API in a Next.js serverless function

Starting off, we want to build a profile for our Pokémon.

To do that, we’re going to use ChatGPT API, particularly the gpt-3.5-turbo model, inside of a Next.js serverless function.

Note: Before we dive in, the ChatGPT API takes a little long to process a request. This combined with the standard Free Tier timeout of 10s from tools like Vercel and Netlify means the API may fail when deployed. You can use Edge Functions which have no limit or upgrade to the Pro plan to get higher limits.

Create a new file inside the directory src/pages/api/pokemon called create.js.

Inside src/pages/api/pokemon/create.js add:

const { Configuration, OpenAIApi } = require('openai');

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

export default async function handler(req, res) {
  res.status(200).json({
    attributes: {}
  })
}

Here we’re:

  • Scaffolding a new async API endpoint
  • Importing Configuration and OpenAIApi from the OpenAI SDK
  • Creating a new configuration with our API Key
  • Creating a new OpenAIApi instance with that configuration
  • Returning an empty object for attributes

We can test out our new endpoint by visiting it in our browser at http://localhost:3000/api/pokemon/create.

Tip: We can visit it in the browser because we’re only using it as a GET request for now. If you start to accept a request body, you would no longer be able to do so.

With that OpenAI configuration, we really have access to any model we specify, so we can dive right in.

Add the following above the response inside of the function to use the createChatCompletion method:

const results = await openai.createChatCompletion({
  model: 'gpt-3.5-turbo',
  messages: [],
});

This whole thing really revolves around this simple method.

Here we’re:

  • Invoking createChatCompletion
  • Stating we want to use the model gpt-3.5-turbo
  • Currently sending an empty message

If we try testing this, which don’t bother, we’ll get an error. The whole point is we want to pass in a message to tell or ask ChatGPT what to do.

This is the prompt of the request, where in our case, we want to generate a new Pokémon.

Let’s first try something like this:

Create a new Pokemon character

Where in the code we would want to add:

messages: [{
  role: 'user',
  content: 'Create a new Pokemon character'
}]

Here we’re defining our message as a user message with the content of the message.

If we add a console log to view the results at:

console.log(results.data.choices);

We’ll be able to see in the terminal when hitting out endpoint that we start to see some real results!

Terminal showing results of a newly generated Pokémon

New Pokémon!

Now before we move on, let’s just take a moment to think about how little code we required and how little of a prompt we needed to gather that bit of information. It blows my mind!

But moving on, we have a particular set of information we need for each Pokémon.

So let’s update our prompt to include bullet points for each one:

messages: [{
  role: 'user',
  content: `
    Create a new Pokemon character with the following unique attributes:
    - Name
    - Short description less than 80 characters
    - The type of Pokemon
    - The category of Pokemon it is
    - Number of Hit Points or health
    - The Pokemon's length in inches
    - The Pokemon's weight in pounds
    - The Pokemon's power name and description
    - The Pokemon's attack name with description and Hit Points it would cause in damage
    - The type of Pokemon it is weak against
    - The type of Pokemon it is resistant against
    - The retreat cost of the Pokemon
    - The Pokemon's appearance in less than 600 characters
    - The Pokemon's backstory in less than 600 characters
  `
}]

And as you’d expect, we get our results.

Terminal showing all attributes requested

All Pokémon attributes

But there’s one issue with this, I don’t want to have to write a RegEx to parse all of this (or ask ChatGPT to write one for me).

Instead, we can simply tell ChatGPT we want the response formatted as JSON!

Format the response in the following JSON objectmessages: [{
  role: 'user',
  content: `
    Create a new Pokemon character with the following unique attributes:
    - Name
    - Short description less than 80 characters
    - The type of Pokemon
    - The category of Pokemon it is
    - Number of Hit Points or health
    - The Pokemon's length in inches
    - The Pokemon's weight in pounds
    - The Pokemon's power name and description
    - The Pokemon's attack name with description and Hit Points it would cause in damage
    - The type of Pokemon it is weak against
    - The type of Pokemon it is resistant against
    - The retreat cost of the Pokemon
    - The Pokemon's appearance in less than 600 characters
    - The Pokemon's backstory in less than 600 characters
    Format the response as a JSON object
  `
}]

And our results.

Terminal showing new Pokémon data as a JSON string

Pokémon data as JSON

We’ll notice that it’s being return as a string, as the content field is a stirng, but we can easily parse that in our endpoint.

Now as one last thing, if you make this request several times, you might notice you get inconsistent keys, which is bad for predicting the data.

What we can do is even tell ChatGPT exactly how we want our data formatted, such as passing in an example object.

I went ahead and prepared this bit for you, so first import the sample data:

const { POKEMON_ATTRIBUTES } = require('@/data/pokemon');

Then update the prompt one last time:

messages: [{
  role: 'user',
  content: `
    Create a new Pokemon character with the following unique attributes:
    - Name
    - Short description less than 80 characters
    - The type of Pokemon
    - The category of Pokemon it is
    - Number of Hit Points or health
    - The Pokemon's length in inches
    - The Pokemon's weight in pounds
    - The Pokemon's power name and description
    - The Pokemon's attack name with description and Hit Points it would cause in damage
    - The type of Pokemon it is weak against
    - The type of Pokemon it is resistant against
    - The retreat cost of the Pokemon
    - The Pokemon's appearance in less than 600 characters
    - The Pokemon's backstory in less than 600 characters
    Format the response in the following JSON object ${JSON.stringify(POKEMON_ATTRIBUTES)}.
  `
}]

And now every time we request our Pokémon, we’ll get our data consistently!

Finally we want to return this data to the endpoint so we can use it in the app.

We’re only going to get one “choice” from our results, so we can hard code the first item in the array, and return our attributes parsed:

const attributes = JSON.parse(completion.data.choices[0].message.content);

res.status(200).json({
  attributes
});

And now when we hit our endpoint in the browser, we’ll see our attributes returned and ready to use!

Follow along with the commit!

Step 3: Generating a new Pokémon card on button click

Heading to the UI, let’s get this thing working so we can see the results on our Pokémon card.

Inside src/pages/index.js, we want to add a click event handler so that any time the Generate button is clicked, we make a request to our endpoint, and fill out the card.

On the Button component (which is just a standard button wrapped), add an onClick handler with:

<Button onClick={handleOnGenerate}>Generate</Button>

Next let’s define that handleOnGenerate function at the top of our page component:

function handleOnGenerate(e) {
  e.preventDefault();
}

Here we’re simply defining the function and preventing the default actions from taking place in the browser on click.

Now, we want to kick off the process of creating our new Pokémon.

First we need a mechanism to store that information.

Let’s import the useState hook with:

import { useState } from 'react';

Then set up a new instance of state:

const [attributes, setAttributes] = useState();

And then, let’s actually set up our generation request:

setAttributes(undefined);
const data = await fetch('/api/pokemon/create/attributes').then(res => res.json());
setAttributes(data.attributes);

Here we’re:

  • First resetting the attributes state in the event we generate multiple
  • Use Fetch to make a request to our create endpoint
  • Set our results into state

At this point you can try to log out the results, but I’m moving right along to wiring this up to the existing UI.

The existing Card component takes in a prop of attributes which knows exactly what this data looks like, so update Card to:

<Card attributes={attributes} />

And now, if you click the Generate button and wait a few seconds (be patient, check the Network tab in your developer tools!), we’ll see our card UI populate with information and even change color based on the type!

Note: If the card didn’t populate right, you may have not added the POKEMON_ATTRIBUTES object into the prompt in Step 2.

We can even update the backstory at the bottom with:

<h2>Backstory</h2>
{attributes?.backstory && <p>{ attributes.backstory }</p>}

Which gives us a new look at our new Pokémon!

App UI showing filled out attributes on card with Network tab from developer tools open showing data

Who’s that Pokémon? It’s Sparkem!

Next, we’ll add a new endpoint to generate an image!

Follow along with the commit!

Step 4: Generating a Pokémon’s image with OpenAI DALL-E

Creating our image endpoint will look pretty similar to the create endpoint only one difference, we’re going to update the prompt based on the previous step.

But we’re not going to jump right to that, first, let’s scaffold our new endpoint.

Create a new file image.js inside of src/pages/api/pokemon.

Inside src/pages/api/pokemon/image.js add:

const { Configuration, OpenAIApi } = require('openai');

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

export default async function handler(req, res) {
  res.status(200).json({
    image: {}
  });
}

Like before, we’re setting up our new endpoint and initializing the OpenAI SDK.

This time though, we’re going to use the createImage method, which uses DALL-E models.

Add the following to the function:

const results = await openai.createImage({
  prompt: `Create an image of a new Pokemon with a plain colored background that has no text or objects`,
  n: 2,
  size: '1024x1024',
});

If we add a console log statment and open up our new endpoint in the browser, we’ll be able to see some new results.

Terminal showing two image URL results

Two image results

Open one of those (or both) up in your browser and you’ll see a new Pokémon!

Browser showing image of generated Pokémon

New generated Pokémon character image

The only issue, is that’s not OUR Pokémon, so we want to be able to define a paramter in the body of our endpoint so that we can pass it to the prompt.

First let’s parse the body and grab a description value:

const body = req.body && JSON.parse(req.body);
const { description } = body || {};

And then pass it to our prompt:

const results = await openai.createImage({
  prompt: `Create an image of a new Pokemon with a plain colored background that has no text or objects from the description: ${description}`,
  n: 2,
  size: '1024x1024',
});

Now at this point, we won’t be able to simply test our endpoint in the browser because we require a body for the request, but we’ll be able to see it when we wire up the UI.

So finally, let’s return those results, where because we’re currently only using one image, I’m going to return only the first image:

res.status(200).json({
  image: results.data.data[0]
});

To test this out, let’s head back to our UI.

Inside of src/pages/index.js, first set up a new state instance:

const [image, setImage] = useState();

And once our create endpoint is complete, let’s fire off a second request to get our image:

setImage(undefined);
const { image } = await fetch('/api/pokemon/image', {
  method: 'POST',
  body: JSON.stringify({
    description: data.attributes.appearance
  })
}).then(res => res.json());
setImage(image);

And finally update the Card UI to magically update:

<Card attributes={attributes} image={image} />

And once you now open it up in your browser and click Generate (again be patient), you’ll first see the attributes load in, then you’ll see the image!

App showing new generated Pokémon with image

Epic Pokémon card with an image!

Follow along with the commit!

What else can we do?

ADD MORE SECURITY TO YOUR ENDPOINT

People will be wanting to abuse your API! While here we’re just generating a Pokémon, you wouldn’t want someone to be able to use the web console on your site and use the endpoint as much as you’d like.

Add some sort of security such as authentication with Clerk or other auth tools.

ADD THE ABILITY TO PASS IN OPTIONS TO THE GENERATOR ENDPOINT

We’re currently passing in a static prompt to OpenAI, but we can fine tune this to give more personalized results to the person genrating a Pokémon.

For instance, we can pass in the type as a parameter in the body of the Attributes request and specify that we want a Pokémon of that type.

USE A FIXED LIST SUCH AS TYPE

There’s only a finite about of Pokémon types, is it possible ChatGPT will make one up?

We can be sure that we only get a Type of the ones we support, so we can tell ChatGPT to create a type out of a given list, similar to how we passed in the JSON object as a string.

🧰 Resources

Starter: https://github.com/colbyfayock/demo-pokemon-generator-starter 
Code: https://github.com/colbyfayock/my-pokemon-generator 
Demo: https://my-pokemon-generator.vercel.app/ 

Tutorial: https://spacejelly.dev/posts/how-to-use-ai-to-generate-a-custom-pokemon-with-openai-chatgpt-dall-e/ 
OpenAI API: https://platform.openai.com/overview 
Vercel: https://vercel.com/ambassadors/colbyfayock 

#openai #nextjs #dalle #chatgpt #gpt #ai #webdevelopment

Generate a Custom Pokémon in Next.js App with ChatGPT and DALL-E
Nigel  Uys

Nigel Uys

1680150660

Opencommit: GPT CLI to Auto-generate Impressive Commits in 1 Second

OpenCommit

GPT CLI to auto-generate impressive commits in 1 second

Killing lame commits with AI 🤯🔫


OpenCommit example

All the commits in this repo are done with OpenCommit — look into the commits to see how OpenCommit works. Emoji and long commit description text is configurable.

Setup

Install OpenCommit globally to use in any repository:

npm install -g opencommit

Get your API key from OpenAI. Make sure you add payment details, so API works.

Set the key to OpenCommit config:

opencommit config set OPENAI_API_KEY=<your_api_key>

Your api key is stored locally in ~/.opencommit config file.

Usage

You can call OpenCommit directly to generate a commit message for your staged changes:

git add <files...>
opencommit

You can also use the oc shortcut:

git add <files...>
oc

Features

Preface commits with emoji 🤠

GitMoji convention is used.

To add emoji:

oc config set emoji=true

To remove emoji:

oc config set emoji=false

Postface commits with descriptions of changes

To add descriptions:

oc config set description=true

To remove description:

oc config set description=false

Internationalization support

To specify the language used to generate commit messages:

# de, German ,Deutsch
oc config set language=de
oc config set language=German
oc config set language=Deutsch

# fr, French, française
oc config set language=fr
oc config set language=French
oc config set language=française

The default language set is English
All available languages are currently listed in the i18n folder

Git flags

The opencommit or oc commands can be used in place of the git commit -m "${generatedMessage}" command. This means that any regular flags that are used with the git commit command will also be applied when using opencommit or oc.

oc --no-verify

is translated to :

git commit -m "${generatedMessage}" --no-verify

Ignore files

You can ignore files from submission to OpenAI by creating a .opencommitignore file. For example:

path/to/large-asset.zip
**/*.jpg

This is useful for preventing opencommit from uploading artifacts and large files.

By default, opencommit ignores files matching: *-lock.* and *.lock

Git hook

You can set OpenCommit as Git prepare-commit-msg hook. Hook integrates with you IDE Source Control and allows you edit the message before commit.

To set the hook:

oc hook set

To unset the hook:

oc hook unset

To use the hook:

git add <files...>
git commit

Or follow the process of your IDE Source Control feature, when it calls git commit command — OpenCommit will integrate into the flow.

Payments

You pay for your own requests to OpenAI API. OpenCommit uses ChatGPT official model, that is ~10x times cheaper than GPT-3 and ~6x times cheaper than GPT-4.


Download Details:

Author: Di-sukharev
Source Code: https://github.com/di-sukharev/opencommit 
License: MIT license

#chatgpt #git #productivity #ai #artificialintelligence #gpt 

Opencommit: GPT CLI to Auto-generate Impressive Commits in 1 Second

Как автоматизировать скучные вещи с помощью ChatGPT и Python

Ускорьте свои повседневные рабочие процессы, заставив ИИ писать код Python за считанные секунды.

14 марта 2023 года OpenAI запустила GPT-4, новейшую и самую мощную версию своей языковой модели. 

Всего через несколько часов после своего запуска GPT-4 ошеломил людей, превратив нарисованный от руки эскиз в функциональный веб-сайт , сдав экзамен на адвоката и создав точные резюме статей в Википедии

Он также превосходит своего предшественника, GPT-3.5, в решении математических задач и ответах на вопросы, основанные на логике и рассуждениях.

ChatGPT, чат-бот, созданный на основе GPT-3.5 и выпущенный для широкой публики, был известен своими «галлюцинациями». Он генерировал ответы, которые казались правильными, и защищал свои ответы «фактами», хотя они были полны ошибок.

Один пользователь обратился в Twitter после того, как модель настояла на том, что слоновьи яйца были самыми большими из всех наземных животных:

Автоматизируйте скучные вещи с помощью ChatGPT и Python
Изображение из FioraAeterna

И это не остановилось на достигнутом. Алгоритм продолжал подтверждать свой ответ выдуманными фактами, которые на мгновение почти убедили меня.

GPT-4, с другой стороны, был обучен реже «галлюцинировать». Последнюю модель OpenAI сложнее обмануть, и она не так часто уверенно генерирует ложные сведения.

Зачем автоматизировать рабочие процессы с помощью GPT-4?

Моя работа как специалиста по данным требует от меня поиска релевантных источников данных, предварительной обработки больших наборов данных и создания высокоточных моделей машинного обучения, которые повышают ценность бизнеса. 

Я провожу огромную часть своего дня, извлекая данные из файлов разных форматов и объединяя их в одном месте. 

После того, как ChatGPT был впервые запущен в ноябре 2022 года, я обратился к чат-боту за некоторыми рекомендациями по моим повседневным рабочим процессам. Я использовал этот инструмент, чтобы сэкономить время, затрачиваемое на черную работу, чтобы вместо этого сосредоточиться на придумывании новых идей и создании лучших моделей.

Когда GPT-4 был выпущен, мне стало любопытно, изменит ли это мою работу. Были ли какие-либо существенные преимущества использования GPT-4 по сравнению с его предшественниками? Поможет ли это мне сэкономить больше времени, чем с GPT-3.5?

В этой статье я покажу вам, как я использую ChatGPT для автоматизации рабочих процессов обработки данных. 

Я создам одинаковые подсказки и отправлю их как в GPT-4, так и в GPT-3.5, чтобы увидеть, действительно ли первый работает лучше и приводит к большей экономии времени.

Как получить доступ к ChatGPT?

Если вы хотите следовать всему, что я делаю в этой статье, вам необходим доступ к GPT-4 и GPT-3.5.

ГПТ-3,5

GPT-3.5 находится в открытом доступе на веб-сайте OpenAI. Просто перейдите на https://chat.openai.com/auth/login , заполните необходимые данные, и вы получите доступ к языковой модели:

Автоматизируйте скучные вещи с помощью ChatGPT и Python
Изображение из ChatGPT 

ГПТ-4

С другой стороны, GPT-4 в настоящее время скрыт за платным доступом. Чтобы получить доступ к модели, вам необходимо перейти на ChatGPTPlus, нажав «Обновить до Plus». 

Существует ежемесячная абонентская плата в размере 20 долларов США в месяц, которую можно отменить в любое время:

Автоматизируйте скучные вещи с помощью ChatGPT и Python
Изображение из ChatGPT

Если вы не хотите платить ежемесячную абонентскую плату, вы также можете присоединиться к списку ожидания API для GPT-4. Получив доступ к API, вы можете следовать этому руководству, чтобы использовать его в Python. 

Ничего страшного, если у вас сейчас нет доступа к GPT-4.

Вы по-прежнему можете следовать этому руководству с бесплатной версией ChatGPT, которая использует GPT-3.5 в серверной части.

3 способа автоматизации рабочих процессов обработки данных с помощью GPT-4 и Python

1. Визуализация данных

При выполнении исследовательского анализа данных создание быстрой визуализации в Python часто помогает мне лучше понять набор данных. 

К сожалению, эта задача может занять невероятно много времени, особенно если вы не знаете правильный синтаксис, который можно использовать для получения желаемого результата. 

Я часто просматриваю обширную документацию Seaborn и использую StackOverflow для создания одного графика Python.

Посмотрим, поможет ли ChatGPT решить эту проблему.

В этом разделе мы будем использовать набор данных о диабете индейцев пима . Вы можете скачать набор данных, если хотите следить за результатами, созданными ChatGPT.

После загрузки набора данных давайте загрузим его в Python с помощью библиотеки Pandas и напечатаем заголовок фрейма данных:

import pandas as pd

df = pd.read_csv('diabetes.csv')
df.head()

 

 

Автоматизируйте скучные вещи с помощью ChatGPT и Python
 
В этом наборе данных девять переменных. Один из них, «Исход», является целевой переменной, которая сообщает нам, будет ли у человека развиваться диабет. Остальные являются независимыми переменными, используемыми для прогнозирования результата.

Хорошо! Поэтому я хочу посмотреть, какие из этих переменных влияют на то, разовьется ли у человека диабет.

Для этого мы можем создать гистограмму с кластерами, чтобы визуализировать переменную «Диабет» по всем зависимым переменным в наборе данных.

На самом деле это довольно легко закодировать, но давайте начнем с простого. По ходу статьи мы перейдем к более сложным подсказкам.

Визуализация данных с помощью GPT-3.5

Поскольку у меня есть платная подписка на ChatGPT, этот инструмент позволяет мне выбирать базовую модель, которую я хотел бы использовать, каждый раз, когда я обращаюсь к нему.

Я собираюсь выбрать GPT-3.5:
 

Автоматизируйте скучные вещи с помощью ChatGPT и Python


Изображение из ChatGPT Plus

Если у вас нет подписки, вы можете использовать бесплатную версию ChatGPT, так как чат-бот по умолчанию использует GPT-3.5.

Теперь давайте введем следующую подсказку, чтобы создать визуализацию с использованием набора данных о диабете:

У меня есть набор данных с 8 независимыми переменными и 1 зависимой переменной. Зависимая переменная «Результат» сообщает нам, будет ли у человека развиваться диабет. 
 
Независимые переменные «Беременность», «Глюкоза», «Кровяное давление», «Толщина кожи», «Инсулин», «ИМТ», «Функция родословной диабета» и «Возраст» используются для прогнозирования этого результата.
 
Можете ли вы сгенерировать код Python для визуализации всех этих независимых переменных по результату? На выходе должна быть одна гистограмма с кластерами, окрашенная переменной «Результат». Всего должно быть 16 баров, по 2 на каждую независимую переменную.

Вот ответ модели на приведенную выше подсказку:

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Сразу бросается в глаза то, что модель предполагала, что мы хотим импортировать набор данных из Seaborn. Вероятно, он сделал это предположение, поскольку мы попросили его использовать библиотеку Seaborn.

Это не большая проблема, нам просто нужно изменить одну строку перед запуском кода.

Вот полный фрагмент кода, сгенерированный GPT-3.5:

import seaborn as sns
import matplotlib.pyplot as plt

# Load the dataset
dataset = pd.read_csv("diabetes.csv")

# Create the bar chart
sns.barplot(
    x="variable",
    y="value",
    hue="Outcome",
    data=pd.melt(dataset, id_vars=["Outcome"]),
    ci=None,
)

# Set the title and labels
plt.title("Dependent Variables by Outcome")
plt.xlabel("Independent Variables")
plt.ylabel("Value")

# Show the chart
plt.show()

Вы можете скопировать и вставить это в свою Python IDE.

Вот результат, полученный после запуска приведенного выше кода:
 

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Эта диаграмма выглядит идеально! Именно так я себе это представлял, вводя приглашение в ChatGPT.

Однако выделяется одна проблема: текст на этой диаграмме перекрывается. Я собираюсь спросить модель, может ли она помочь нам исправить это, введя следующую подсказку:
 

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Алгоритм объяснил, что мы можем предотвратить это перекрытие, либо повернув метки диаграммы, либо отрегулировав размер фигуры. Он также сгенерировал новый код, чтобы помочь нам достичь этого.

Давайте запустим этот код, чтобы увидеть, дает ли он нам желаемые результаты:

import seaborn as sns
import matplotlib.pyplot as plt

# Load the dataset
dataset = pd.read_csv("diabetes.csv")

# Create the bar chart
sns.barplot(
    x="variable",
    y="value",
    hue="Outcome",
    data=pd.melt(dataset, id_vars=["Outcome"]),
    ci=None,
)

# Set the title and labels
plt.title("Dependent Variables by Outcome")
plt.xlabel("Independent Variables")
plt.ylabel("Value")

# Rotate the x-axis labels by 45 degrees and set horizontal alignment to right
plt.xticks(rotation=45, ha="right")

# Show the chart
plt.show()

Приведенные выше строки кода должны генерировать следующий вывод:

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Это выглядит великолепно! 

Теперь я намного лучше понимаю набор данных, просто взглянув на эту диаграмму. Похоже, что люди с более высоким уровнем глюкозы и инсулина более склонны к развитию диабета.

Также обратите внимание, что переменная DiabetesPedigreeFunction не дает нам никакой информации на этой диаграмме. Это связано с тем, что функция имеет меньший масштаб (от 0 до 2,4). Если вы хотите поэкспериментировать с ChatGPT, вы можете попросить его создать несколько подграфиков на одной диаграмме, чтобы решить эту проблему.

Визуализация данных с помощью GPT-4

Теперь давайте отправим те же подсказки в GPT-4, чтобы посмотреть, получим ли мы другой ответ. Я собираюсь выбрать модель GPT-4 в ChatGPT и ввести ту же подсказку, что и раньше:
 

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Обратите внимание, что GPT-4 не предполагает, что мы будем использовать фрейм данных, встроенный в Seaborn. 

Он сообщает нам, что будет использовать фрейм данных с именем «df» для построения визуализации, что является улучшением по сравнению с ответом, сгенерированным GPT-3.5.

Вот полный код, сгенерированный этим алгоритмом:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Assuming your DataFrame is called df
# First, you need to melt the DataFrame to make 
# it suitable for creating a clustered bar chart
melted_df = pd.melt(
    df,
    id_vars=["Outcome"],
    var_name="Independent Variable",
    value_name="Value",
)

# Create the clustered bar chart
plt.figure(figsize=(12, 6))
sns.barplot(
    data=melted_df,
    x="Independent Variable",
    y="Value",
    hue="Outcome",
    ci=None,
)

# Customize the plot
plt.title("Independent Variables by Outcome")
plt.ylabel("Average Value")
plt.xlabel("Independent Variables")
plt.legend(title="Outcome", loc="upper right")

# Show the plot
plt.show()

Приведенный выше код должен генерировать следующий график:

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Это потрясающе! 

Несмотря на то, что мы не просили об этом, GPT-4 включает строку кода для увеличения размера графика. Все метки на этой диаграмме хорошо видны, поэтому нам не нужно возвращаться назад и исправлять код, как мы делали ранее. 

Это на шаг выше ответа, генерируемого GPT-3.5.

Однако в целом создается впечатление, что GPT-3.5 и GPT-4 эффективно генерируют код для выполнения таких задач, как визуализация и анализ данных. 

Важно отметить, что, поскольку вы не можете загружать данные в интерфейс ChatGPT, вы должны предоставить модели точное описание вашего набора данных для получения оптимальных результатов.

2. Работа с PDF-документами

Хотя это не распространенный вариант использования в науке о данных, мне однажды пришлось извлекать текстовые данные из сотен PDF-файлов, чтобы построить модель анализа тональности. Данные были неструктурированы, и я потратил много времени на их извлечение и предварительную обработку.

Я также часто работаю с исследователями, которые читают и создают контент о текущих событиях, происходящих в конкретных отраслях. Им нужно быть в курсе новостей, анализировать отчеты компаний и читать о потенциальных тенденциях в отрасли. 

Вместо того, чтобы читать 100 страниц отчета компании, не проще ли просто извлечь интересующие вас слова и прочитать только те предложения, которые содержат эти ключевые слова? 

Или, если вас интересуют тенденции, вы можете создать автоматизированный рабочий процесс, демонстрирующий рост ключевых слов с течением времени, вместо того, чтобы просматривать каждый отчет вручную.

В этом разделе мы будем использовать ChatGPT для анализа файлов PDF в Python. Мы попросим чат-бота извлечь содержимое файла PDF и записать его в текстовый файл.

Опять же, это будет сделано с использованием как GPT-3.5, так и GPT-4, чтобы увидеть, есть ли существенная разница в сгенерированном коде.

Чтение файлов PDF с помощью GPT-3.5

В этом разделе мы будем анализировать общедоступный PDF-документ под названием « Краткое введение в машинное обучение для инженеров ». Обязательно загрузите этот файл, если вы хотите кодировать в этом разделе.

Во-первых, давайте попросим алгоритм сгенерировать код Python для извлечения данных из этого PDF-документа и сохранения их в текстовый файл:

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Вот полный код, предоставленный алгоритмом:

import PyPDF2

# Open the PDF file in read-binary mode
with open("Intro_to_ML.pdf", "rb") as pdf_file:
    # Create a PDF reader object
    pdf_reader = PyPDF2.PdfFileReader(pdf_file)

    # Get the total number of pages in the PDF file
    num_pages = pdf_reader.getNumPages()

    # Create a new text file
    with open("output_file.txt", "w") as txt_file:
        # Loop through each page in the PDF file
        for page_num in range(num_pages):
            # Get the text from the current page
            page_text = pdf_reader.getPage(page_num).extractText()

            # Write the text to the text file
            txt_file.write(page_text)

(Примечание: обязательно измените имя файла PDF на то, которое вы сохранили перед запуском этого кода.)

К сожалению, после запуска кода, сгенерированного GPT-3.5, я столкнулся со следующей ошибкой юникода:

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Вернемся к GPT-3.5 и посмотрим, сможет ли модель исправить это:

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Я вставил ошибку в ChatGPT, и модель ответила, что ее можно исправить, изменив используемую кодировку на «utf-8». Это также дало мне модифицированный код, отражающий это изменение:

import PyPDF2

# Open the PDF file in read-binary mode
with open("Intro_to_ML.pdf", "rb") as pdf_file:
    # Create a PDF reader object
    pdf_reader = PyPDF2.PdfFileReader(pdf_file)

    # Get the total number of pages in the PDF file
    num_pages = pdf_reader.getNumPages()

    # Create a new text file with utf-8 encoding
    with open("output_file.txt", "w", encoding="utf-8") as txt_file:
        # Loop through each page in the PDF file
        for page_num in range(num_pages):
            # Get the text from the current page
            page_text = pdf_reader.getPage(page_num).extractText()

            # Write the text to the text file
            txt_file.write(page_text)

Этот код успешно выполнился и создал текстовый файл с именем «output_file.txt». Все содержимое документа PDF было записано в файл:
 

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Чтение файлов PDF с помощью GPT-4

Теперь я собираюсь вставить ту же подсказку в GPT-4, чтобы посмотреть, что предлагает модель:
 

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Вот полный код, сгенерированный GPT-4:

import PyPDF2


def pdf_to_text(input_pdf, output_txt):
    with open(input_pdf, "rb") as pdf_file:
        pdf_reader = PyPDF2.PdfFileReader(pdf_file)
        num_pages = pdf_reader.numPages

        text = ""
        for page_num in range(num_pages):
            page = pdf_reader.getPage(page_num)
            text += page.extractText()
    with open(output_txt, "w", encoding="utf-8") as text_file:
        text_file.write(text)


input_pdf = "Intro_to_ML.pdf"
output_txt = "output_gpt4.txt"
pdf_to_text(input_pdf, output_txt)

Посмотри на это!

В отличие от GPT-3.5, в GPT-4 уже указано, что для открытия текстового файла следует использовать кодировку «utf-8». Нам не нужно возвращаться и исправлять код, как мы это делали раньше.

Код, предоставленный GPT-4, должен успешно выполниться, и вы должны увидеть содержимое документа PDF в созданном текстовом файле.

Есть много других методов, которые вы можете использовать для автоматизации PDF-документов с помощью Python. Если вы хотите изучить это подробнее, вот несколько других подсказок, которые вы можете ввести в ChatGPT:

  • Можете ли вы написать код Python для объединения двух файлов PDF?
  • Как я могу подсчитать количество вхождений определенного слова или фразы в PDF-документе с помощью Python?
  • Можете ли вы написать код Python для извлечения таблиц из PDF-файлов и записи их в Excel?

Я предлагаю попробовать некоторые из них в свободное время — вы будете удивлены тем, как быстро GPT-4 может помочь вам выполнить черную работу, на выполнение которой обычно уходят часы.

3. Отправка автоматических писем

Я провожу часы своей рабочей недели, читая электронные письма и отвечая на них. Это не только отнимает много времени, но и может быть невероятно напряженным, чтобы оставаться в курсе электронной почты, когда вы гонитесь за сжатыми сроками.

И хотя вы не можете заставить ChatGPT писать все ваши электронные письма за вас (я бы хотел), вы все равно можете использовать его для написания программ, которые отправляют электронные письма по расписанию в определенное время или модифицируют один шаблон электронной почты, который можно отправить нескольким людям. .

В этом разделе мы получим GPT-3.5 и GPT-4, которые помогут нам написать скрипт Python для автоматической отправки электронных писем.

Отправка автоматических писем с помощью GPT-3.5

Во-первых, давайте введем следующую подсказку, чтобы сгенерировать коды для автоматической отправки электронной почты:

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Вот полный код, сгенерированный GPT-3.5 (не забудьте изменить адреса электронной почты и пароль перед запуском этого кода):

import smtplib

# Set up SMTP connection
smtp_server = "smtp.gmail.com"
smtp_port = 587
sender_email = "your_email@gmail.com"
sender_password = "your_password"
receiver_email = "receiver_email@example.com"

with smtplib.SMTP(smtp_server, smtp_port) as smtp:
    # Start TLS encryption
    smtp.starttls()

    # Log in to your Gmail account
    smtp.login(sender_email, sender_password)

    # Compose your email message
    subject = "Automated email"
    body = "Hello,\n\nThis is an automated email sent from Python."
    message = f"Subject: {subject}\n\n{body}"

    # Send the email
    smtp.sendmail(sender_email, receiver_email, message)

К сожалению, этот код не выполнился успешно для меня. Это вызвало следующую ошибку:
 

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Давайте вставим эту ошибку в ChatGPT и посмотрим, поможет ли модель решить ее:

Автоматизируйте скучные вещи с помощью ChatGPT и Python



 

 

Итак, алгоритм указал на несколько причин, по которым мы можем столкнуться с этой ошибкой.

Я точно знаю, что мои учетные данные и адреса электронной почты были действительными и что в коде не было опечаток. Так что эти причины можно исключить.

GPT-3.5 также предполагает, что разрешение менее безопасных приложений может решить эту проблему.

Однако, если вы попробуете это сделать, вы не найдете в своей учетной записи Google возможность разрешить доступ к менее безопасным приложениям.

Это связано с тем, что Google больше не позволяет пользователям разрешать менее безопасные приложения из соображений безопасности.

Наконец, в GPT-3.5 также упоминается, что пароль приложения должен быть сгенерирован, если включена двухфакторная аутентификация.

У меня не включена двухфакторная аутентификация, поэтому я собираюсь (временно) отказаться от этой модели и посмотреть, есть ли решение GPT-4.

Отправка автоматических писем с помощью GPT-4

Итак, если вы введете ту же подсказку в GPT-4, вы обнаружите, что алгоритм генерирует код, очень похожий на тот, что дал нам GPT-3.5. Это вызовет ту же ошибку, с которой мы столкнулись ранее.

Давайте посмотрим, поможет ли GPT-4 исправить эту ошибку:

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Предложения GPT-4 очень похожи на то, что мы видели ранее.

Однако на этот раз он дает нам пошаговую разбивку того, как выполнить каждый шаг.

GPT-4 также предлагает создать пароль приложения, так что давайте попробуем.

Сначала зайдите в свою учетную запись Google, перейдите в «Безопасность» и включите двухфакторную аутентификацию. Затем в том же разделе вы должны увидеть опцию «Пароли приложений».

Нажмите на нее, и появится следующий экран:

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Вы можете ввести любое имя, которое вам нравится, и нажать «Создать».

Появится новый пароль приложения.

Замените существующий пароль в коде Python на этот пароль приложения и снова запустите код:

import smtplib

# Set up SMTP connection
smtp_server = "smtp.gmail.com"
smtp_port = 587
sender_email = "your_email@gmail.com"
sender_password = "YOUR_APP_PASSWORD"
receiver_email = "receiver_email@example.com"

with smtplib.SMTP(smtp_server, smtp_port) as smtp:
    # Start TLS encryption
    smtp.starttls()

    # Log in to your Gmail account
    smtp.login(sender_email, sender_password)

    # Compose your email message
    subject = "Automated email"
    body = "Hello,\n\nThis is an automated email sent from Python."
    message = f"Subject: {subject}\n\n{body}"

    # Send the email
    smtp.sendmail(sender_email, receiver_email, message)

На этот раз он должен пройти успешно, и ваш получатель получит электронное письмо, которое выглядит следующим образом:
 

Автоматизируйте скучные вещи с помощью ChatGPT и Python

Идеальный!

Благодаря ChatGPT мы успешно отправили автоматическое электронное письмо с помощью Python.

Если вы хотите пойти дальше, я предлагаю создать подсказки, которые позволят вам:

  1. Отправляйте массовые электронные письма нескольким получателям одновременно
  2. Отправляйте запланированные электронные письма на предопределенный список адресов электронной почты
  3. Отправляйте получателям индивидуальное электронное письмо с учетом их возраста, пола и местоположения.

Оригинальный источник статьи: https://www.kdnuggets.com/

#chatgpt #python #automate #ai 

Как автоматизировать скучные вещи с помощью ChatGPT и Python
木村  直子

木村 直子

1680079169

如何使用 ChatGPT 和 Python 自动化无聊的事情

让 AI 在几秒钟内编写 Python 代码,从而加快您的日常工作流程。

2023 年 3 月 14 日,OpenAI 发布了 GPT-4,这是其语言模型的最新、最强大的版本。 

在发布后的短短几个小时内,GPT-4 通过将手绘草图变成功能性网站通过司法考试生成维基百科文章的准确摘要而震惊了人们。 

在基于逻辑和推理解决数学问题和回答问题方面,它也优于其前身 GPT-3.5。

ChatGPT 是建立在 GPT-3.5 之上并向公众发布的聊天机器人,它因“产生幻觉”而臭名昭著。它会生成看似正确的响应,并会用“事实”来捍卫它的答案,尽管它们充满了错误。

在模型坚持认为象蛋是所有陆生动物中最大的之后,一位用户上了 Twitter:

使用 ChatGPT 和 Python 自动化无聊的事情
图片来自FioraAeterna

它并没有就此停止。该算法继续用编造的事实来证实它的反应,这几乎让我相信了一会儿。

另一方面,GPT-4 接受的训练较少出现“幻觉”。OpenAI 的最新模型更难被欺骗,并且不会自信地频繁地产生虚假信息。

为什么使用 GPT-4 自动化工作流程?

作为一名数据科学家,我的工作要求我找到相关的数据源、预处理大型数据集并构建可推动业务价值的高度准确的机器学习模型。 

我一天中的大部分时间都在从不同的文件格式中提取数据并将其整合到一个地方。 

ChatGPT 于 2022 年 11 月首次推出后,我向聊天机器人寻求日常工作流程的一些指导。我使用该工具节省了花在琐碎工作上的时间 - 这样我就可以专注于提出新想法并创建更好的模型。

GPT-4 发布后,我很好奇它是否会对我所做的工作产生影响。使用 GPT-4 与其前身相比有什么显着的好处吗?与使用 GPT-3.5 相比,它会帮助我节省更多时间吗?

在本文中,我将向您展示我如何使用 ChatGPT 来自动化数据科学工作流程。 

我将创建相同的提示并将它们提供给 GPT-4 和 GPT-3.5,看看前者是否确实表现更好并节省更多时间。

如何访问 ChatGPT?

如果您想按照我在本文中所做的一切进行操作,则需要能够访问 GPT-4 和 GPT-3.5。

GPT-3.5

GPT-3.5 在 OpenAI 的网站上公开可用。只需导航到https://chat.openai.com/auth/login,填写所需的详细信息,您就可以访问语言模型:

使用 ChatGPT 和 Python 自动化无聊的事情
图片来自ChatGPT 

GPT-4

另一方面,GPT-4 目前隐藏在付费专区后面。要访问该模型,您需要通过单击“升级到 Plus”来升级到 ChatGPTPlus。 

每月订阅费为 20 美元,可以随时取消:

使用 ChatGPT 和 Python 自动化无聊的事情
图片来自ChatGPT

如果你不想支付每月的订阅费,你也可以加入GPT-4 的API 候补名单。获得 API 的访问权限后,您可以按照指南在 Python 中使用它。 

如果您目前无法访问 GPT-4 也没关系。

您仍然可以使用在后端使用 GPT-3.5 的免费版 ChatGPT 来学习本教程。

使用 GPT-4 和 Python 自动化数据科学工作流程的 3 种方法

1. 数据可视化

在执行探索性数据分析时,用 Python 生成快速可视化通常可以帮助我更好地理解数据集。 

不幸的是,这项任务可能会变得非常耗时——尤其是当您不知道使用正确的语法来获得所需结果时。 

我经常发现自己在搜索 Seaborn 的大量文档并使用 StackOverflow 生成单个 Python 图。

让我们看看 ChatGPT 是否可以帮助解决这个问题。

我们将在本节中使用Pima Indians Diabetes数据集。如果您想了解 ChatGPT 生成的结果,可以下载数据集。

下载数据集后,让我们使用 Pandas 库将其加载到 Python 中并打印数据帧的头部:

import pandas as pd

df = pd.read_csv('diabetes.csv')
df.head()

 

 

使用 ChatGPT 和 Python 自动化无聊的事情
 
该数据集中有九个变量。其中之一,“结果”,是告诉我们一个人是否会患上糖尿病的目标变量。其余的是用于预测结果的自变量。

好的!所以我想看看这些变量中的哪些变量会影响一个人是否会患上糖尿病。

为实现这一点,我们可以创建一个聚类条形图来可视化数据集中所有因变量的变量“糖尿病”。

这实际上很容易编写出来,但让我们从简单的开始。随着文章的进展,我们将转向更复杂的提示。

使用 GPT-3.5 进行数据可视化

由于我付费订阅了 ChatGPT,该工具允许我在每次访问它时选择我想使用的基础模型。

我要选择 GPT-3.5:
 

使用 ChatGPT 和 Python 自动化无聊的事情


图片来自 ChatGPT Plus

如果您没有订阅,您可以使用 ChatGPT 的免费版本,因为聊天机器人默认使用 GPT-3.5。

现在,让我们输入以下提示以使用糖尿病数据集生成可视化:

我有一个包含 8 个自变量和 1 个因变量的数据集。因变量“结果”告诉我们一个人是否会患上糖尿病。 
 
自变量“Pregnancies”、“Glucose”、“BloodPressure”、“SkinThickness”、“Insulin”、“BMI”、“DiabetesPedigreeFunction”和“Age”用于预测此结果。
 
您能否生成 Python 代码以按结果可视化所有这些自变量?输出应该是一个由“结果”变量着色的聚类条形图。总共应该有 16 个条,每个自变量 2 个。

以下是模型对上述提示的响应:

使用 ChatGPT 和 Python 自动化无聊的事情

立即突出的一件事是该模型假定我们想要从 Seaborn 导入数据集。它可能做出了这个假设,因为我们要求它使用 Seaborn 库。

这不是一个大问题,我们只需要在运行代码之前更改一行。

下面是 GPT-3.5 生成的完整代码片段:

import seaborn as sns
import matplotlib.pyplot as plt

# Load the dataset
dataset = pd.read_csv("diabetes.csv")

# Create the bar chart
sns.barplot(
    x="variable",
    y="value",
    hue="Outcome",
    data=pd.melt(dataset, id_vars=["Outcome"]),
    ci=None,
)

# Set the title and labels
plt.title("Dependent Variables by Outcome")
plt.xlabel("Independent Variables")
plt.ylabel("Value")

# Show the chart
plt.show()

您可以将其复制并粘贴到您的 Python IDE 中。

以下是运行上述代码后生成的结果:
 

使用 ChatGPT 和 Python 自动化无聊的事情

这张图表看起来很完美!这正是我在 ChatGPT 中输入提示时的设想。

然而,一个突出的问题是该图表上的文本重叠。我将通过键入以下提示询问模型是否可以帮助我们解决此问题:
 

使用 ChatGPT 和 Python 自动化无聊的事情

该算法解释说,我们可以通过旋转图表标签或调整图形大小来防止这种重叠。它还生成了新代码来帮助我们实现这一目标。

让我们运行这段代码,看看它是否给了我们想要的结果:

import seaborn as sns
import matplotlib.pyplot as plt

# Load the dataset
dataset = pd.read_csv("diabetes.csv")

# Create the bar chart
sns.barplot(
    x="variable",
    y="value",
    hue="Outcome",
    data=pd.melt(dataset, id_vars=["Outcome"]),
    ci=None,
)

# Set the title and labels
plt.title("Dependent Variables by Outcome")
plt.xlabel("Independent Variables")
plt.ylabel("Value")

# Rotate the x-axis labels by 45 degrees and set horizontal alignment to right
plt.xticks(rotation=45, ha="right")

# Show the chart
plt.show()

上面的代码行应该生成以下输出:

使用 ChatGPT 和 Python 自动化无聊的事情

这看起来很棒! 

通过简单地查看此图表,我现在可以更好地理解数据集。似乎葡萄糖和胰岛素水平较高的人更容易患上糖尿病。

另请注意,“DiabetesPedigreeFunction”变量并未在此图表中提供任何信息。这是因为该特征的比例较小(介于 0 和 2.4 之间)。如果您想进一步试验 ChatGPT,您可以提示它在单个图表中生成多个子图来解决这个问题。

使用 GPT-4 进行数据可视化

现在,让我们将相同的提示输入 GPT-4,看看是否会得到不同的响应。我将在 ChatGPT 中选择 GPT-4 模型并输入与之前相同的提示:
 

使用 ChatGPT 和 Python 自动化无聊的事情

请注意 GPT-4 如何不假设我们将使用 Seaborn 内置的数据框。 

它告诉我们它将使用名为“df”的数据框来构建可视化,这是对 GPT-3.5 生成的响应的改进。

下面是这个算法生成的完整代码:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Assuming your DataFrame is called df
# First, you need to melt the DataFrame to make 
# it suitable for creating a clustered bar chart
melted_df = pd.melt(
    df,
    id_vars=["Outcome"],
    var_name="Independent Variable",
    value_name="Value",
)

# Create the clustered bar chart
plt.figure(figsize=(12, 6))
sns.barplot(
    data=melted_df,
    x="Independent Variable",
    y="Value",
    hue="Outcome",
    ci=None,
)

# Customize the plot
plt.title("Independent Variables by Outcome")
plt.ylabel("Average Value")
plt.xlabel("Independent Variables")
plt.legend(title="Outcome", loc="upper right")

# Show the plot
plt.show()

上面的代码应该生成以下图:

使用 ChatGPT 和 Python 自动化无聊的事情

太棒了! 

即使我们没有要求,GPT-4 也包含了一行代码来增加绘图大小。这张图表上的标签都清晰可见,所以我们不必像之前那样回头修改代码。 

这是 GPT-3.5 生成的响应之上的一步。

然而,总的来说,GPT-3.5 和 GPT-4 似乎都能有效地生成代码来执行数据可视化和分析等任务。 

请务必注意,由于您无法将数据上传到 ChatGPT 的界面,因此您应该为模型提供数据集的准确描述以获得最佳结果。

2. 使用 PDF 文档

虽然这不是常见的数据科学用例,但我不得不从数百个 PDF 文件中提取文本数据来构建情绪分析模型一次。数据是非结构化的,我花了很多时间来提取和预处理它。

我还经常与研究人员合作,他们阅读和创建有关特定行业发生的时事的内容。他们需要紧跟新闻,分析公司报告,并了解行业的潜在趋势。 

与其阅读 100 页的公司报告,简单地提取您感兴趣的词并只阅读包含这些关键词的句子不是更容易吗? 

或者,如果您对趋势感兴趣,您可以创建一个自动化的工作流程来展示关键字随时间的增长,而不是手动查看每个报告。

在本节中,我们将使用 ChatGPT 在 Python 中分析 PDF 文件。我们将要求聊天机器人提取 PDF 文件的内容并将其写入文本文件。

同样,这将使用 GPT-3.5 和 GPT-4 来完成,以查看生成的代码是否存在显着差异。

使用 GPT-3.5 阅读 PDF 文件

在本节中,我们将分析一份公开可用的 PDF 文档,标题为工程师机器学习简介。如果您想按照此部分进行编码,请务必下载此文件。

首先,让算法生成 Python 代码以从此 PDF 文档中提取数据并将其保存到文本文件中:

使用 ChatGPT 和 Python 自动化无聊的事情

下面是算法提供的完整代码:

import PyPDF2

# Open the PDF file in read-binary mode
with open("Intro_to_ML.pdf", "rb") as pdf_file:
    # Create a PDF reader object
    pdf_reader = PyPDF2.PdfFileReader(pdf_file)

    # Get the total number of pages in the PDF file
    num_pages = pdf_reader.getNumPages()

    # Create a new text file
    with open("output_file.txt", "w") as txt_file:
        # Loop through each page in the PDF file
        for page_num in range(num_pages):
            # Get the text from the current page
            page_text = pdf_reader.getPage(page_num).extractText()

            # Write the text to the text file
            txt_file.write(page_text)

(注意:确保将 PDF 文件名更改为您在运行此代码之前保存的文件名。)

不幸的是,在运行 GPT-3.5 生成的代码后,我遇到了以下 unicode 错误:

使用 ChatGPT 和 Python 自动化无聊的事情

让我们回到 GPT-3.5,看看模型是否可以解决这个问题:

使用 ChatGPT 和 Python 自动化无聊的事情

我将错误粘贴到 ChatGPT 中,模型回应说可以通过将使用的编码更改为“utf-8”来修复它。它还为我提供了一些反映此更改的修改代码:

import PyPDF2

# Open the PDF file in read-binary mode
with open("Intro_to_ML.pdf", "rb") as pdf_file:
    # Create a PDF reader object
    pdf_reader = PyPDF2.PdfFileReader(pdf_file)

    # Get the total number of pages in the PDF file
    num_pages = pdf_reader.getNumPages()

    # Create a new text file with utf-8 encoding
    with open("output_file.txt", "w", encoding="utf-8") as txt_file:
        # Loop through each page in the PDF file
        for page_num in range(num_pages):
            # Get the text from the current page
            page_text = pdf_reader.getPage(page_num).extractText()

            # Write the text to the text file
            txt_file.write(page_text)

此代码成功执行并创建了一个名为“output_file.txt”的文本文件。PDF文档中的所有内容已经写入文件:
 

使用 ChatGPT 和 Python 自动化无聊的事情

使用 GPT-4 阅读 PDF 文件

现在,我将把相同的提示粘贴到 GPT-4 中,看看模型会产生什么:
 

使用 ChatGPT 和 Python 自动化无聊的事情

以下是 GPT-4 生成的完整代码:

import PyPDF2


def pdf_to_text(input_pdf, output_txt):
    with open(input_pdf, "rb") as pdf_file:
        pdf_reader = PyPDF2.PdfFileReader(pdf_file)
        num_pages = pdf_reader.numPages

        text = ""
        for page_num in range(num_pages):
            page = pdf_reader.getPage(page_num)
            text += page.extractText()
    with open(output_txt, "w", encoding="utf-8") as text_file:
        text_file.write(text)


input_pdf = "Intro_to_ML.pdf"
output_txt = "output_gpt4.txt"
pdf_to_text(input_pdf, output_txt)

看那个!

与 GPT-3.5 不同,GPT-4 已经规定打开文本文件应使用“utf-8”编码。我们不需要像以前那样返回并修改代码。

GPT-4 提供的代码应该可以成功执行,您应该可以在创建的文本文件中看到 PDF 文档的内容。

您可以使用许多其他技术通过 Python 自动化 PDF 文档。如果您想进一步探索这一点,您可以在 ChatGPT 中输入以下一些其他提示:

  • 你能写 Python 代码来合并两个 PDF 文件吗?
  • 如何使用 Python 计算 PDF 文档中特定单词或短语的出现次数?
  • 您可以编写 Python 代码从 PDF 中提取表格并将其写入 Excel 中吗?

我建议您在空闲时间尝试其中的一些 - 您会惊讶于 GPT-4 可以多快地帮助您完成通常需要数小时才能完成的琐碎任务。

3. 发送自动邮件

我每周都会花几个小时阅读和回复电子邮件。这不仅耗时,而且在紧迫的截止日期前处理电子邮件也会让人倍感压力。

虽然你不能让 ChatGPT 为你写所有的电子邮件(我希望),但你仍然可以用它来编写在特定时间发送预定电子邮件的程序,或者修改可以发送给多人的单个电子邮件模板.

在本节中,我们将获得 GPT-3.5 和 GPT-4 来帮助我们编写一个 Python 脚本来发送自动电子邮件。

使用 GPT-3.5 发送自动电子邮件

首先,让我们输入以下提示以生成代码以发送自动电子邮件:

使用 ChatGPT 和 Python 自动化无聊的事情

这是 GPT-3.5 生成的完整代码(确保在运行此代码之前更改电子邮件地址和密码):

import smtplib

# Set up SMTP connection
smtp_server = "smtp.gmail.com"
smtp_port = 587
sender_email = "your_email@gmail.com"
sender_password = "your_password"
receiver_email = "receiver_email@example.com"

with smtplib.SMTP(smtp_server, smtp_port) as smtp:
    # Start TLS encryption
    smtp.starttls()

    # Log in to your Gmail account
    smtp.login(sender_email, sender_password)

    # Compose your email message
    subject = "Automated email"
    body = "Hello,\n\nThis is an automated email sent from Python."
    message = f"Subject: {subject}\n\n{body}"

    # Send the email
    smtp.sendmail(sender_email, receiver_email, message)

不幸的是,这段代码没有为我成功执行。它产生了以下错误:
 

使用 ChatGPT 和 Python 自动化无聊的事情

让我们将这个错误粘贴到 ChatGPT 中,看看模型是否可以帮助我们解决它:

使用 ChatGPT 和 Python 自动化无聊的事情



 

 

好的,算法指出了我们可能会遇到此错误的几个原因。

我知道我的登录凭据和电子邮件地址是有效的,并且代码中没有拼写错误。所以可以排除这些原因。

GPT-3.5 还建议允许安全性较低的应用程序可能会解决此问题。

但是,如果您尝试这样做,您将不会在您的 Google 帐户中找到允许访问安全性较低的应用程序的选项。

这是因为出于安全考虑,谷歌不再允许用户允许安全性较低的应用程序。

最后,GPT-3.5 还提到如果启用了双因素身份验证,则应生成应用程序密码。

我没有启用双因素身份验证,所以我打算(暂时)放弃这个模型,看看 GPT-4 是否有解决方案。

使用 GPT-4 发送自动电子邮件

好的,所以如果你在 GPT-4 中输入相同的提示,你会发现该算法生成的代码与 GPT-3.5 给我们的非常相似。这将导致我们之前遇到的相同错误。

让我们看看 GPT-4 是否可以帮助我们修复这个错误:

使用 ChatGPT 和 Python 自动化无聊的事情

GPT-4 的建议与我们之前看到的非常相似。

然而,这一次,它为我们提供了如何完成每个步骤的分步分解。

GPT-4 还建议创建一个应用程序密码,所以让我们试一试。

首先,访问您的 Google 帐户,导航至“安全”,然后启用双因素身份验证。然后,在同一部分中,您应该会看到一个显示“App Passwords”的选项。

单击它,将出现以下屏幕:

使用 ChatGPT 和 Python 自动化无聊的事情

您可以输入您喜欢的任何名称,然后单击“生成”。

将出现一个新的应用程序密码。

用此应用程序密码替换 Python 代码中的现有密码,然后再次运行代码:

import smtplib

# Set up SMTP connection
smtp_server = "smtp.gmail.com"
smtp_port = 587
sender_email = "your_email@gmail.com"
sender_password = "YOUR_APP_PASSWORD"
receiver_email = "receiver_email@example.com"

with smtplib.SMTP(smtp_server, smtp_port) as smtp:
    # Start TLS encryption
    smtp.starttls()

    # Log in to your Gmail account
    smtp.login(sender_email, sender_password)

    # Compose your email message
    subject = "Automated email"
    body = "Hello,\n\nThis is an automated email sent from Python."
    message = f"Subject: {subject}\n\n{body}"

    # Send the email
    smtp.sendmail(sender_email, receiver_email, message)

这次它应该会成功运行,您的收件人将收到一封如下所示的电子邮件:
 

使用 ChatGPT 和 Python 自动化无聊的事情

完美的!

感谢 ChatGPT,我们已经成功地使用 Python 发送了一封自动电子邮件。

如果您想更进一步,我建议生成允许您执行以下操作的提示:

  1. 同时向多个收件人发送批量电子邮件
  2. 将预定的电子邮件发送到预定义的电子邮件地址列表
  3. 向收件人发送一封根据他们的年龄、性别和位置量身定制的电子邮件。

文章原文出处:https: //www.kdnuggets.com/

#chatgpt #python #automate #ai 

如何使用 ChatGPT 和 Python 自动化无聊的事情
Gordon  Murray

Gordon Murray

1680075133

How to Automate The Boring Stuff with ChatGPT & Python

Speed up your daily workflows by getting AI to write Python code in seconds.

On March 14, 2023, OpenAI launched GPT-4, the newest and most powerful version of their language model. 

Within just hours of its launch, GPT-4 stunned people by turning a hand-drawn sketch into a functional website, passing the bar exam, and generating accurate summaries of Wikipedia articles

It also outperforms its predecessor, GPT-3.5, in solving math problems and answering questions based on logic and reasoning.

ChatGPT, the chatbot which was built on top of GPT-3.5 and released to the public, was notorious for “hallucinating.” It would generate responses that were seemingly correct and would defend its answers with “facts”, although they were laden with errors.

One user took to Twitter after the model insisted that elephant eggs were the largest of all land animals:

Automate the Boring Stuff with ChatGPT and Python
Image from FioraAeterna

And it didn’t stop there. The algorithm went on to corroborate its response with made-up facts that almost had me convinced for a moment.

GPT-4, on the other hand, was trained to “hallucinate” less often. OpenAI’s latest model is harder to trick and does not confidently generate falsehoods as frequently.

Why Automate Workflows with GPT-4?

As a data scientist, my job requires me to find relevant data sources, preprocess large datasets, and build highly accurate machine learning models that drive business value. 

I spend a huge portion of my day extracting data from different file formats and consolidating it in one place. 

After ChatGPT was first launched in November 2022, I looked to the chatbot for some guidance with my daily workflows. I used the tool to save the amount of time spent on menial work - so that I could focus on coming up with new ideas and creating better models instead.

Once GPT-4 was released, I was curious about whether it would make a difference in the work I was doing. Were there any significant benefits to using GPT-4 over its predecessors? Would it help me save more time than I already was with GPT-3.5?

In this article, I will show you how I use ChatGPT to automate data science workflows. 

I will create the same prompts and feed them into both GPT-4 and GPT-3.5, to see if the former indeed does perform better and result in more time savings.

How to Access ChatGPT?

If you’d like to follow along with everything I do in this article, you need to have access to GPT-4 and GPT-3.5.

GPT-3.5

GPT-3.5 is publicly available on OpenAI’s website. Simply navigate to https://chat.openai.com/auth/login, fill out the required details, and you will have access to the language model:

Automate the Boring Stuff with ChatGPT and Python
Image from ChatGPT 

GPT-4

GPT-4, on the other hand, is currently hidden behind a paywall. To access the model, you need to upgrade to ChatGPTPlus by clicking on “Upgrade to Plus.” 

There is a monthly subscription fee of $20/month that can be canceled anytime:

Automate the Boring Stuff with ChatGPT and Python
Image from ChatGPT

If you don’t want to pay the monthly subscription fee, you can also join the API waitlist for GPT-4. Once you get access to the API, you can follow this guide to use it in Python. 

It’s okay if you don’t currently have access to GPT-4.

You can still follow this tutorial with the free version of ChatGPT that uses GPT-3.5 in the backend.

3 Ways to Automate Data Science Workflows with GPT-4 and Python

1. Data Visualization

When performing exploratory data analysis, generating a quick visualization in Python often helps me better understand the dataset. 

Unfortunately, this task can become incredibly time-consuming - especially when you don’t know the right syntax to use to get the desired result. 

I often find myself searching through Seaborn’s extensive documentation and using StackOverflow to generate a single Python plot.

Let’s see if ChatGPT can help solve this problem.

We will be using the Pima Indians Diabetes dataset in this section. You can download the dataset if you’d like to follow along with the results generated by ChatGPT.

After downloading the dataset, let’s load it into Python using the Pandas library and print the head of the dataframe:

import pandas as pd

df = pd.read_csv('diabetes.csv')
df.head()

 

 

Automate the Boring Stuff with ChatGPT and Python
 
There are nine variables in this dataset. One of them, “Outcome”, is the target variable that tells us whether a person will develop diabetes. The remaining are independent variables used to predict the outcome.

Okay! So I want to see which of these variables have an impact on whether a person will develop diabetes.

To achieve this, we can create a clustered bar chart to visualize the variable “Diabetes” across all the dependent variables in the dataset.

This is actually pretty easy to code out, but let’s start simple. We will move on to more complicated prompts as we progress through the article.

Data Visualization with GPT-3.5

Since I have a paid subscription to ChatGPT, the tool allows me to select the underlying model I’d like to use every time I access it.

I am going to select GPT-3.5:
 

Automate the Boring Stuff with ChatGPT and Python


Image from ChatGPT Plus

If you don’t have a subscription, you can use the free version of ChatGPT since the chatbot uses GPT-3.5 by default.

Now, let’s type the following prompt to generate a visualization using the diabetes dataset:

I have a dataset with 8 independent variables and 1 dependent variable. The dependent variable, "Outcome", tells us whether a person will develop diabetes. 
 
The independent variables, "Pregnancies", "Glucose", "BloodPressure", "SkinThickness", "Insulin", "BMI", "DiabetesPedigreeFunction", and "Age" are used to predict this outcome.
 
Can you generate Python code to visualize all these independent variables by outcome? The output should be one clustered bar chart that is colored by the "Outcome" variable. There should be 16 bars in total, 2 for each independent variable.

Here is the model’s response to the above prompt:

Automate the Boring Stuff with ChatGPT and Python

One thing that stands out immediately is that the model assumed we wanted to import a dataset from Seaborn. It probably made this assumption since we asked it to use the Seaborn library.

This isn’t a huge issue, we just need to change one line before running the codes.

Here’s the complete code snippet generated by GPT-3.5:

import seaborn as sns
import matplotlib.pyplot as plt

# Load the dataset
dataset = pd.read_csv("diabetes.csv")

# Create the bar chart
sns.barplot(
    x="variable",
    y="value",
    hue="Outcome",
    data=pd.melt(dataset, id_vars=["Outcome"]),
    ci=None,
)

# Set the title and labels
plt.title("Dependent Variables by Outcome")
plt.xlabel("Independent Variables")
plt.ylabel("Value")

# Show the chart
plt.show()

You can copy and paste this into your Python IDE.

Here is the outcome generated after running the above code:
 

Automate the Boring Stuff with ChatGPT and Python

This chart looks perfect! It’s exactly how I envisioned it when typing the prompt into ChatGPT.

One issue that stands out, however, is that the text on this chart is overlapping. I am going to ask the model if it can help us fix this, by typing the following prompt:
 

Automate the Boring Stuff with ChatGPT and Python

The algorithm explained that we could prevent this overlap by either rotating the chart labels or adjusting the figure size. It also generated new code to help us achieve this.

Let’s run this code to see if it gives us the desired results:

import seaborn as sns
import matplotlib.pyplot as plt

# Load the dataset
dataset = pd.read_csv("diabetes.csv")

# Create the bar chart
sns.barplot(
    x="variable",
    y="value",
    hue="Outcome",
    data=pd.melt(dataset, id_vars=["Outcome"]),
    ci=None,
)

# Set the title and labels
plt.title("Dependent Variables by Outcome")
plt.xlabel("Independent Variables")
plt.ylabel("Value")

# Rotate the x-axis labels by 45 degrees and set horizontal alignment to right
plt.xticks(rotation=45, ha="right")

# Show the chart
plt.show()

The above lines of code should generate the following output:

Automate the Boring Stuff with ChatGPT and Python

This looks great! 

I understand the dataset a lot better now by simply looking at this chart. It appears as though people with higher glucose and insulin levels are more likely to develop diabetes.

Also, notice that the “DiabetesPedigreeFunction” variable doesn’t give us any information in this chart. This is because the feature is on a smaller scale (between 0 and 2.4). If you’d like to further experiment with ChatGPT, you can prompt it to generate multiple subplots within a single chart to solve this problem.

Data Visualization with GPT-4

Now, let’s feed the same prompts into GPT-4 to see if we get a different response. I am going to select the GPT-4 model within ChatGPT and type in the same prompt as before:
 

Automate the Boring Stuff with ChatGPT and Python

Notice how GPT-4 does not assume that we will be using a dataframe that is built into Seaborn. 

It tells us that it will use a dataframe called “df” to build the visualization, which is an improvement from the response generated by GPT-3.5.

Here is the complete code generated by this algorithm:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Assuming your DataFrame is called df
# First, you need to melt the DataFrame to make 
# it suitable for creating a clustered bar chart
melted_df = pd.melt(
    df,
    id_vars=["Outcome"],
    var_name="Independent Variable",
    value_name="Value",
)

# Create the clustered bar chart
plt.figure(figsize=(12, 6))
sns.barplot(
    data=melted_df,
    x="Independent Variable",
    y="Value",
    hue="Outcome",
    ci=None,
)

# Customize the plot
plt.title("Independent Variables by Outcome")
plt.ylabel("Average Value")
plt.xlabel("Independent Variables")
plt.legend(title="Outcome", loc="upper right")

# Show the plot
plt.show()

The above code should generate the following plot:

Automate the Boring Stuff with ChatGPT and Python

This is perfect! 

Even though we didn’t ask it to, GPT-4 has included a line of code to increase the plot size. The labels on this chart are all clearly visible, so we don’t have to go back and amend the code as we did earlier. 

This is a step above the response generated by GPT-3.5.

Overall, however, it appears as though GPT-3.5 and GPT-4 are both effective at generating code to perform tasks like data visualization and analysis. 

It is important to note that since you cannot upload data into ChatGPT’s interface, you should provide the model with an accurate description of your dataset for optimum results.

2. Working with PDF Documents

While this isn’t a common data science use-case, I have had to extract text data from hundreds of PDF files to build a sentiment analysis model once. The data was unstructured, and I spent a lot of time extracting and preprocessing it.

I also often work with researchers who read and create content about current events taking place in specific industries. They need to stay on top of the news, parse through company reports, and read about potential trends in the industry. 

Instead of reading 100 pages of a company’s report, isn’t it easier to simply extract words you are interested in and only read through sentences that contain those keywords? 

Or if you’re interested in trends, you can create an automated workflow that showcases keyword growth over time instead of going through each report manually.

In this section, we will be using ChatGPT to analyze PDF files in Python. We will ask the chatbot to extract the contents of a PDF file and write it into a text file.

Again, this will be done using both GPT-3.5 and GPT-4 to see if there is a significant difference in the code generated.

Reading PDF Files with GPT-3.5

In this section, we will be analyzing a publicly available PDF document titled A Brief Introduction to Machine Learning for Engineers. Make sure to download this file if you’d like to code along to this section.

First, let’s ask the algorithm to generate Python code to extract data from this PDF document and save it to a text file:

Automate the Boring Stuff with ChatGPT and Python

Here is the complete code provided by the algorithm:

import PyPDF2

# Open the PDF file in read-binary mode
with open("Intro_to_ML.pdf", "rb") as pdf_file:
    # Create a PDF reader object
    pdf_reader = PyPDF2.PdfFileReader(pdf_file)

    # Get the total number of pages in the PDF file
    num_pages = pdf_reader.getNumPages()

    # Create a new text file
    with open("output_file.txt", "w") as txt_file:
        # Loop through each page in the PDF file
        for page_num in range(num_pages):
            # Get the text from the current page
            page_text = pdf_reader.getPage(page_num).extractText()

            # Write the text to the text file
            txt_file.write(page_text)

(Note: Make sure to change the PDF file name to the one you saved before running this code.)

Unfortunately, after running the code generated by GPT-3.5, I encountered the following unicode error:

Automate the Boring Stuff with ChatGPT and Python

Let’s go back to GPT-3.5 and see if the model can fix this:

Automate the Boring Stuff with ChatGPT and Python

I pasted the error into ChatGPT, and the model responded that it could be fixed by changing the encoding used to “utf-8.” It also gave me some modified code that reflected this change:

import PyPDF2

# Open the PDF file in read-binary mode
with open("Intro_to_ML.pdf", "rb") as pdf_file:
    # Create a PDF reader object
    pdf_reader = PyPDF2.PdfFileReader(pdf_file)

    # Get the total number of pages in the PDF file
    num_pages = pdf_reader.getNumPages()

    # Create a new text file with utf-8 encoding
    with open("output_file.txt", "w", encoding="utf-8") as txt_file:
        # Loop through each page in the PDF file
        for page_num in range(num_pages):
            # Get the text from the current page
            page_text = pdf_reader.getPage(page_num).extractText()

            # Write the text to the text file
            txt_file.write(page_text)

This code executed successfully and created a text file called “output_file.txt.” All the content in the PDF document have been written to the file:
 

Automate the Boring Stuff with ChatGPT and Python

Reading PDF Files with GPT-4

Now, I am going to paste the same prompt into GPT-4 to see what the model comes up with:
 

Automate the Boring Stuff with ChatGPT and Python

Here is the complete code generated by GPT-4:

import PyPDF2


def pdf_to_text(input_pdf, output_txt):
    with open(input_pdf, "rb") as pdf_file:
        pdf_reader = PyPDF2.PdfFileReader(pdf_file)
        num_pages = pdf_reader.numPages

        text = ""
        for page_num in range(num_pages):
            page = pdf_reader.getPage(page_num)
            text += page.extractText()
    with open(output_txt, "w", encoding="utf-8") as text_file:
        text_file.write(text)


input_pdf = "Intro_to_ML.pdf"
output_txt = "output_gpt4.txt"
pdf_to_text(input_pdf, output_txt)

Look at that!

Unlike GPT-3.5, GPT-4 has already specified that “utf-8” encoding should be used to open the text file. We don’t need to go back and amend the code like we did previously.

The code provided by GPT-4 should execute successfully, and you should see the contents of the PDF document in the text file that was created.

There are many other techniques you can use to automate PDF documents with Python. If you’d like to explore this further, here are some other prompts you can type into ChatGPT:

  • Can you write Python code to merge two PDF files?
  • How can I count the occurrences of a specific word or phrase in a PDF document with Python?
  • Can you write Python code to extract tables from PDFs and write them in Excel?

I suggest trying some of these during your free time - you’d be surprised at how quickly GPT-4 can help you accomplish menial tasks that usually take hours to perform.

3. Sending Automated Emails

I spend hours of my workweek reading and responding to emails. Not only is this time-consuming, but it can also be incredibly stressful to stay on top of emails when you are chasing tight deadlines.

And although you can’t get ChatGPT to write all your emails for you (I wish), you can still use it to write programs that send scheduled emails at a specific time or modify a single email template that can be sent out to multiple people.

In this section, we will get GPT-3.5 and GPT-4 to help us write a Python script to send automated emails.

Sending Automated Emails with GPT-3.5

First, let’s type the following prompt to generate codes to send an automated email:

Automate the Boring Stuff with ChatGPT and Python

Here is the complete code generated by GPT-3.5 (Make sure to change the email addresses and password before running this code):

import smtplib

# Set up SMTP connection
smtp_server = "smtp.gmail.com"
smtp_port = 587
sender_email = "your_email@gmail.com"
sender_password = "your_password"
receiver_email = "receiver_email@example.com"

with smtplib.SMTP(smtp_server, smtp_port) as smtp:
    # Start TLS encryption
    smtp.starttls()

    # Log in to your Gmail account
    smtp.login(sender_email, sender_password)

    # Compose your email message
    subject = "Automated email"
    body = "Hello,\n\nThis is an automated email sent from Python."
    message = f"Subject: {subject}\n\n{body}"

    # Send the email
    smtp.sendmail(sender_email, receiver_email, message)

Unfortunately, this code did not execute successfully for me. It generated the following error:
 

Automate the Boring Stuff with ChatGPT and Python

Let’s paste this error into ChatGPT and see if the model can help us solve it:

Automate the Boring Stuff with ChatGPT and Python



 

 

Okay, so the algorithm pointed out a few reasons as to why we might be running into this error.

I know for a fact that my login credentials and email addresses were valid, and that there were no typos in the code. So these reasons can be ruled out.

GPT-3.5 also suggests that allowing less secure apps might solve this problem.

If you try this, however, you will not find an option in your Google account to allow access to less secure apps.

This is because Google no longer lets users allow less secure apps due to security concerns.

Finally, GPT-3.5 also mentions that an app password should be generated if two-factor authentication was enabled.

I don’t have two-factor authentication enabled, so I’m going to (temporarily) give up on this model and see if GPT-4 has a solution.

Sending Automated Emails with GPT-4

Okay, so if you type the same prompt into GPT-4, you will find that the algorithm generates code that is very similar to what GPT-3.5 gave us. This will cause the same error that we ran into previously.

Let’s see if GPT-4 can help us fix this error:

Automate the Boring Stuff with ChatGPT and Python

GPT-4’s suggestions are very similar to what we saw previously.

However, this time, it gives us a step-by-step breakdown of how to accomplish each step.

GPT-4 also suggests creating an app password, so let’s give it a try.

First, visit your Google Account, navigate to “Security”, and enable two-factor authentication. Then, in the same section, you should see an option that says “App Passwords.”

Click on it and the following screen will appear:

Automate the Boring Stuff with ChatGPT and Python

You can enter any name you like, and click on “Generate.”

A new app password will appear.

Replace your existing password in the Python code with this app password and run the code again:

import smtplib

# Set up SMTP connection
smtp_server = "smtp.gmail.com"
smtp_port = 587
sender_email = "your_email@gmail.com"
sender_password = "YOUR_APP_PASSWORD"
receiver_email = "receiver_email@example.com"

with smtplib.SMTP(smtp_server, smtp_port) as smtp:
    # Start TLS encryption
    smtp.starttls()

    # Log in to your Gmail account
    smtp.login(sender_email, sender_password)

    # Compose your email message
    subject = "Automated email"
    body = "Hello,\n\nThis is an automated email sent from Python."
    message = f"Subject: {subject}\n\n{body}"

    # Send the email
    smtp.sendmail(sender_email, receiver_email, message)

It should run successfully this time, and your recipient will receive an email that looks like this:
 

Automate the Boring Stuff with ChatGPT and Python

Perfect!

Thanks to ChatGPT, we have successfully sent out an automated email with Python.

If you’d like to take this a step further, I suggest generating prompts that allow you to:

  1. Send bulk emails to multiple recipients at the same time
  2. Send scheduled emails to a predefined list of email addresses
  3. Send recipients a customized email that is tailored to their age, gender, and location.

Original article source at: https://www.kdnuggets.com/

#chatgpt #python #automate #ai 

How to Automate The Boring Stuff with ChatGPT & Python
Archie  Clayton

Archie Clayton

1679993100

GPT4 API and ChatGPT 3.5 API for Beginners - Crash Course

Beginners Guide to GPT4 API & ChatGPT 3.5 Turbo API Tutorial. Crash Course GPT4 API and ChatGPT 3.5 API for Beginners. 

The documentation for the Chat Completion API for GPT-3.5-Turbo and GPT4 are identical, so this video should serve as a way to implement new Chat API into your next product!

I cover how to use the latest GPT3.5 Turbo API (which is also the same Chat API that OpenAI uses for GPT4). If you're looking to use OpenAI API this video should cover the whole process. In it, we will integrate Open AI API for GPT and add it to a simple application to interact with the artificial intelligence models.

00:00 - Introduction
00:37 - OpenAI Account Setup
01:31 - NodeJS and VSCode Setup
02:16 - Setup Project Environment
02:58 - OpenAI Initialisation
03:55 - GPT4 Chat Completion
05:44 - Express REST Setup
06:50 - ChatGPT 3.5 Chat Message
07:10 - Frontend ChatGPT API
08:06 - Frontend JavaScript Setup
09:16 - Frontend Fetch Request to OpenAI Backend
10:20 - OpenAI Chat Competitions API Configuration
11:05 - Backend GPT Message History Setup
11:39 - Frontend GPT Message History Setup
13:02 - Testing Local GPT3.5 API Chat Bot Setup
13:45 - Microsoft Azure Function Initialisation
14:30 - VS Code Azure Extension
15:00 - Create Azure Serverless Function
16:00 - Prepare Test Local Azure Function
17:04 - Deploy Azure Function to the Cloud
18:04 - Integrate OpenAI Chat GPT into Azure Function
20:13 - Deploy ChatGPT API Function into Cloud
21:18 - Conclusion

Learn more about OpenAI and GPT4 and GPT 3.5 Turbo below
https://openai.com/

#gpt4 #ai #openai

GPT4 API and ChatGPT 3.5 API for Beginners - Crash Course
Hermann  Frami

Hermann Frami

1679931197

Text-to-Image Diffusion Models are Zero-Shot Video Generators

Text2Video-Zero

This repository is the official implementation of Text2Video-Zero.

Text2Video-Zero: Text-to-Image Diffusion Models are Zero-Shot Video Generators 
Levon Khachatryan, Andranik Movsisyan, Vahram Tadevosyan, Roberto Henschel, Zhangyang Wang, Shant Navasardyan, Humphrey Shi 

 
Our method Text2Video-Zero enables zero-shot video generation using (i) a textual prompt (see rows 1, 2), (ii) a prompt combined with guidance from poses or edges (see lower right), and (iii) Video Instruct-Pix2Pix, i.e., instruction-guided video editing (see lower left). Results are temporally consistent and follow closely the guidance and textual prompts.

News

  • [03/23/2023] Paper Text2Video-Zero released!
  • [03/25/2023] The first version of our huggingface demo (zero-shot text-to-video generation, Video Instruct Pix2Pix) released!

Code

Will be released soon!

Results

Text-To-Video

cat_running.gifplaying.gifrunning.gifskii.gif
"A cat is running on the grass""A panda is playing guitar on times square"A man is running in the snow""An astronaut is skiing down the hill"
panda_surfing.gifbear_dancing.gifbicycle.gifhorse_galloping.gif
"A panda surfing on a wakeboard""A bear dancing on times square"A man is riding a bicycle in the sunshine""A horse galloping on a street"
tiger_walking.gifpanda_surfing_2.gifhorse_galloping_2.gifcat_walking.gif
"A tiger walking alone down the street""A panda surfing on a wakeboard"A horse galloping on a street""A cute cat running in a beatiful meadow"
horse_galloping_3.gifpanda_walking.gifdog_walking.gifastronaut.gif
"A horse galloping on a street""A panda walking alone down the street"A dog is walking down the street""An astronaut is waving his hands on the moon"

Text-To-Video with Pose Guidance

img_bot_left.gifpose_bot_left.gifimg_bot_right.gifpose_bot_right.gifimg_top_left.gifpose_top_left.gifimg_top_right.gifpose_top_right.gif
"A bear dancing on the concrete""An alien dancing under a flying saucer"A panda dancing in Antarctica""An astronaut dancing in the outer space"

Text-To-Video with Edge Guidance

butterfly.gifbutterfly_edge.gifhead.gifhead_edge.gifjelly.gifjelly_edge.gifmask.gifmask_edge.gif
"White butterfly""Beautiful girl"A jellyfish""beautiful girl halloween style"
fox.giffix_edge.gifhead_2.gifhead_2_edge.gifsanta.gifsanta_edge.gifdear.gifdear_edge.gif
"Wild fox is walking""Oil painting of a beautiful girl close-up"A santa claus""A deer"

Text-To-Video with Edge Guidance and Dreambooth specialization

anime_style.gifanime_edge.gifarcane_style.gifarcane_edge.gifgta-5_man_style.gifgta-5_man_edge.gifimg_bot_right.gifedge_bot_right.gif
"anime style""arcane style"gta-5 man""avar style"

Video Instruct Pix2Pix

up_left.gifbot_left.gifup_mid.gifbot_mid.gifup_right.gifbot_right.gif
"Replace man with chimpanze""Make it Van Gogh Starry Night style""Make it Picasso style"
up_left.gifbot_left.gifup_mid.gifbot_mid.gifup_right.gifbot_right.gif
"Make it Expressionism style""Make it night""Make it autumn"

BibTeX

If you use our work in your research, please cite our publication:

@article{text2video-zero,
    title={Text2Video-Zero: Text-to-Image Diffusion Models are Zero-Shot Video Generators},
    author={Khachatryan, Levon and Movsisyan, Andranik and Tadevosyan, Vahram and Henschel, Roberto and Wang, Zhangyang and Navasardyan, Shant and Shi, Humphrey},
    journal={arXiv preprint arXiv:2303.13439},
    year={2023}
}

Download Details:

Author: Picsart-AI-Research
Source Code: https://github.com/Picsart-AI-Research/Text2Video-Zero 
License: 

#text #image #models #video #ai 

Text-to-Image Diffusion Models are Zero-Shot Video Generators

How to Create Your Own AI Assistant with Python

Let's learn to build and improve our own voice-controlled AI assistant using Python.

Python is a computer programming language often used to build websites and software, automate tasks, and conduct data analysis. Python is a general purpose language, meaning it can be used to create a variety of different programs and isn’t specialized for any specific problems. This versatility, along with its beginner-friendliness, has made it one of the most-used programming languages today.

00:00 Intro
02:30 Initial Setup
14:45 Web navigation
17:30 Wikipedia
22:30 Wolfram Alpha
35:00 Recording notes
38:10 Conclusion

Full code:
https://pastebin.com/WPPtgiAn 
https://github.com/Mikael-Codes/ai-assistant 

Subscribe: https://www.youtube.com/@mikaelcodes/featured 

#python #ai 

How to Create Your Own AI Assistant with Python
go home

go home

1679814084

Top 100 AI Technology Websites

  1. OpenAI - https://openai.com/
  2. Google AI - https://ai.google/
  3. Microsoft AI - https://www.microsoft.com/en-us/ai
  4. IBM Watson - https://www.ibm.com/watson
  5. NVIDIA AI - https://www.nvidia.com/en-us/ai/
  6. TensorFlow - https://www.tensorflow.org/
  7. PyTorch - https://pytorch.org/
  8. Keras - https://keras.io/
  9. Caffe - http://caffe.berkeleyvision.org/
  10. Torch - http://torch.ch/
  11. Theano - http://deeplearning.net/software/theano/
  12. Apache MXNet - https://mxnet.apache.org/
  13. Amazon Web Services (AWS) AI - https://aws.amazon.com/ai/
  14. Facebook AI - https://ai.facebook.com/
  15. Baidu AI - https://ai.baidu.com/
  16. Alibaba AI - https://www.alibabacloud.com/ai
  17. Tencent AI - https://ai.tencent.com/
  18. Intel AI - https://www.intel.ai/
  19. Accenture Applied Intelligence - https://www.accenture.com/us-en/applied-intelligence-index
  20. Hugging Face - https://huggingface.co/
  21. NVIDIA Deep Learning Institute - https://www.nvidia.com/en-us/deep-learning-ai/education/
  22. Fast.ai - https://www.fast.ai/
  23. AI Business - https://aibusiness.com/
  24. AI News - https://www.ainewsletter.com/
  25. AI Trends - https://www.aitrends.com/
  26. VentureBeat AI - https://venturebeat.com/category/ai/
  27. The Verge AI - https://www.theverge.com/ai
  28. Wired AI - https://www.wired.com/tag/ai/
  29. TechCrunch AI - https://techcrunch.com/tag/ai/
  30. Forbes AI - https://www.forbes.com/ai/
  31. Harvard Business Review AI - https://hbr.org/topic/artificial-intelligence
  32. MIT Technology Review AI - https://www.technologyreview.com/topic/artificial-intelligence/
  33. Stanford AI Lab - https://ai.stanford.edu/
  34. UC Berkeley AI Research - https://bair.berkeley.edu/
  35. Carnegie Mellon University AI - https://www.cs.cmu.edu/research/ai
  36. Oxford AI - https://www.cs.ox.ac.uk/activities/ai/
  37. Cambridge AI - https://www.cst.cam.ac.uk/research/themes/ai
  38. University of Toronto AI - https://vectorinstitute.ai/
  39. DeepMind - https://deepmind.com/
  40. OpenCV - https://opencv.org/
  41. Robot Operating System (ROS) - https://www.ros.org/
  42. MATLAB AI - https://www.mathworks.com/solutions/artificial-intelligence.html
  43. Scikit-learn - https://scikit-learn.org/
  44. Pandas - https://pandas.pydata.org/
  45. NumPy - https://numpy.org/
  46. SciPy - https://www.scipy.org/
  47. Matplotlib - https://matplotlib.org/
  48. Seaborn - https://seaborn.pydata.org/
  49. Plotly - https://plotly.com/
  50. Streamlit - https://streamlit.io/
  51. Flask - https://flask.palletsprojects.com/en/2.1.x/
  52. Django - https://www.djangoproject.com/
  53. AWS Lambda - https://aws.amazon.com/lambda/
  54. Google Cloud - https://cloud.google.com/
  55. Microsoft Azure Functions - https://azure.microsoft.com/en-us/services/functions/
  56. IBM Cloud Functions - https://www.ibm.com/cloud/functions
  57. Apache Spark - https://spark.apache.org/
  58. Apache Hadoop - https://hadoop.apache.org/
  59. Apache Flink - https://flink.apache.org/
  60. Apache Kafka - https://kafka.apache.org/
  61. Databricks - https://databricks.com/
  62. Cloudera - https://www.cloudera.com/
  63. Hortonworks - https://hortonworks.com/
  64. Dataiku - https://www.dataiku.com/
  65. RapidMiner - https://rapidminer.com/
  66. Alteryx - https://www.alteryx.com/
  67. KNIME - https://www.knime.com/
  68. Google Cloud AI Platform - https://cloud.google.com/ai-platform
  69. IBM Watson Studio - https://www.ibm.com/cloud/watson-studio
  70. Amazon SageMaker - https://aws.amazon.com/sagemaker/
  71. H2O.ai - https://www.h2o.ai/
  72. DataRobot - https://www.datarobot.com/
  73. TensorFlow Hub - https://tfhub.dev/
  74. NVIDIA GPU Cloud (NGC) - https://www.nvidia.com/en-us/gpu-cloud/
  75. NVIDIA DeepStream SDK - https://developer.nvidia.com/deepstream-sdk
  76. NVIDIA JetPack - https://developer.nvidia.com/embedded/jetpack
  77. PyTorch Lightning - https://www.pytorchlightning.ai/
  78. ONNX - https://onnx.ai/
  79. TensorFlow Lite - https://www.tensorflow.org/lite
  80. NVIDIA TensorRT - https://developer.nvidia.com/tensorrt
  81. PyTorch Mobile - https://pytorch.org/mobile/
  82. KubeFlow - https://www.kubeflow.org/
  83. MLflow - https://mlflow.org/
  84. TensorFlow Extended (TFX) - https://www.tensorflow.org/tfx
  85. Kubeflow Pipelines - https://www.kubeflow.org/docs/pipelines/
  86. TensorFlow Probability - https://www.tensorflow.org/probability
  87. OpenAI Gym - https://gym.openai.com/
  88. Keras RL - https://keras-rl.readthedocs.io/en/latest/
  89. TensorFlow Agents - https://www.tensorflow.org/agents
  90. Intel Nervana AI Academy - https://www.intelnervana.com/academia/
  91. Intel OpenVINO Toolkit - https://software.intel.com/content/www/us/en/develop/tools/openvino-toolkit.html
  92. NVIDIA Isaac SDK - https://developer.nvidia.com/isaac-sdk
  93. TensorFlow.js - https://www.tensorflow.org/js/
  94. Keras.js - https://transcranial.github.io/keras-js/
  95. PyTorch.js - https://pytorch.org/js/
  96. AWS DeepLens - https://aws.amazon.com/deeplens/
  97. Google Coral - https://coral.ai/
  98. NVIDIA Jetson - https://developer.nvidia.com/embedded/jetson
  99. IBM Watson IoT - https://www.ibm.com/internet-of-things
  100. . Azure IoT - https://azure.microsoft.com/en-us/services/iot-central/

#ai #AI 

Top 100 AI Technology Websites

MyGPTReader: A Slack Bot That Can Read any Webpage

myGPTReader

myGPTReader is a slack bot that can read any webpage, ebook or document and summarize it with chatGPT. It can also talk to you via voice using the content in the channel.

For now it is in development, but you can try it out by join this channel.

The exciting part is that the development of this project is also paired with chatGPT. I document the development process in this CDDR file.

Features

  •  Integrated with slack bot
    •  Bot replies messages in the same thread
  •  Support web page reading with chatGPT
  •  Support RSS reading with chatGPT
    • RSS is a bunch of links, so it is equivalent to reading a web page to get the content.
  •  Support newsletter reading with chatGPT
    • Most newsletters are public and can be accessed online, so we can just give the url to the slack bot.
  • Prompt fine-tue
    •  Support for custom prompt
    •  Show prompt templates by slack app slash commands
    •  Auto collect the good prompt to #gpt-prompt channel by message shortcut
  • Cost saving
    •  by caching the web page llama index
      • Consider to use sqlite-vss to store and search the text embeddings
      • Use chromadb to store and search the text embeddings
      • Use the llama index file to restore the index
    •  Consider to use sentence-transformers or txtai to generate embeddings (vectors)
      • Not good as the embeddings of OpenAI, rollback to use the OpenAI embeddings, and if enable to use the custom embeddings, the minimum of server's memory is 2GB which still increase the cost.
    •  Consider to fine-tue the chunk size of index node and prompt to save the cost
      • If the chunk size is too big, it will cause the index node to be too large and the cost will be high.
  •  Bot can read historical messages from the same thread, thus providing context to chatGPT
  • Index fine-tune
    •  Use the GPTListIndex to summarize multiple URLs
    •  Use the GPTTreeIndex with summarize mode to summarize a single web page
  • Bot regularly send hot summarizes(expensive cost) news in the slack channel (#daily-news)
    •  Use chatGPT to summarize the hot news
    • Refer to this approach
      • World News
        •  Zhihu daily hot answers
        •  V2EX daily hot topics
        •  1point3acres daily hot topics
        •  Reddit world hot news
      • Dev News
        •  Hacker News daily hot topics
        •  Product Hunt daily hot topics
      • Invest News
        •  Xueqiu daily hot topics
        •  Jisilu daily hot topics
  • Support file reading and analysis 💥
    • Considering the expensive billing, it needs to use the slack userID whitelist to restrict the access this feature
    • Need to cache the file Documents to save extract cost
    •  EPUB
    •  DOCX
    •  MD
    •  TEXT
    •  PDF
    •  Image
      • may use GPT4
  •  Support voice reading with self-hosting whisper
    • (whisper -> chatGPT -> azure text2speech) to play language speaking practices 💥
    • Support language
      • Chinese
      • English
        • 🇺🇸
        • 🇬🇧
        • 🇦🇺
        • 🇮🇳
      • Japanese
      • German
  •  Integrated with Azure OpenAI Service
  •  User access limit
    • Limit the number of requests to bot per user per day to save the cost
  •  Support discord bot ❓
  •  Rewrite the code in Typescript ❓
  •  Upgrade chat model (gpt-3.5-turbo) to GPT4 (gpt-4-0314) 💥
  •  Documentation
  • Publish bot to make it can be used in other workspaces
    •  Slack marketplace

Star History

Star History Chart


Download Details:

Author: Madawei2699
Source Code: https://github.com/madawei2699/myGPTReader 
License: MIT license

#python #crawler #ai #slackbot #gpt 

MyGPTReader: A Slack Bot That Can Read any Webpage

ML-Notebooks: Machine Learning Notebooks

🐙 Machine Learning Notebooks

This repo contains machine learning notebooks for different tasks and applications. The notebooks are meant to be minimal, easily reusable, and extendable. You are free to use them for educational and research purposes.

This repo supports Codespaces!

  • Spin up a new instance by clicking on the green "<> Code" button followed by the "Configure and create codespace" option. Make sure to select the dev container config provided with this repo. This setups an environment with all the dependencies installed and ready to go.
  • Once the codespace is fully running, you can install all the libraries you will need to run the notebooks under the /notebooks folder. Open up a terminal and simply run conda create --name myenv --file spec-file.txt to install all the Python libraries including PyTorch.
  • Activate your environment conda activate myenv. You might need to run conda init zsh or whatever shell you are using... and then close + reopen terminal.
  • Finally you can try out if everything is working by opening a notebook such as /notebooks/bow.ipynb.

Getting Started

NameDescriptionNotebook
Introduction to Computational GraphsA basic tutorial to learn about computational graphs
PyTorch Hello World!Build a simple neural network and train it
A Gentle Introduction to PyTorchA detailed explanation introducing PyTorch concepts
Counterfactual ExplanationsA basic tutorial to learn about counterfactual explanations for explainable AI
Linear Regression from ScratchAn implementation of linear regression from scratch using stochastic gradient descent
Logistic Regression from ScratchAn implementation of logistic regression from scratch
Concise Logistic RegressionConcise implementation of logistic regression model for binary image classification.
First Neural Network - Image ClassifierBuild a minimal image classifier using MNIST
Neural Network from ScratchAn implementation of simple neural network from scratch
Introduction to GNNsIntroduction to Graph Neural Networks. Applies basic GCN to Cora dataset for node classification.

NLP

NameDescriptionNotebook
Bag of Words Text ClassifierBuild a simple bag of words text classifier.
Continuous Bag of Words (CBOW) Text ClassifierBuild a continuous bag of words text classifier.
Deep Continuous Bag of Words (Deep CBOW) Text ClassifierBuild a deep continuous bag of words text classifier.
Text Data AugmentationAn introduction to the most commonly used data augmentation techniques for text and their implementation
Emotion Classification with Fine-tuned BERTEmotion classification using fine-tuned BERT model

Transformers

NameDescriptionNotebook
Text Classification using TransformerAn implementation of Attention Mechanism and Positional Embeddings on a text classification task 
Kaggle
Neural Machine Translation using TransformerAn implementation of Transformer to translate human readable dates in any format to YYYY-MM-DD format. 
Kaggle
Feature Tokenizer TransformerAn implementation of Feature Tokenizer Transformer on a classification task 
Kaggle
Named Entity Recognition using TransformerAn implementation of Transformer to perform token classification and identify species in PubMed abstracts 
Kaggle
Extractive Question Answering using TransformerAn implementation of Transformer to perform extractive question answering 
Kaggle

Computer Vision

NameDescriptionNotebook
Siamese NetworkAn implementation of Siamese Network for finding Image Similarity 
Kaggle
Variational Auto EncoderAn implementation of Variational Auto Encoder to generate Augmentations for MNIST Handwritten Digits 
Kaggle
Object Detection using Sliding Window and Image PyramidA basic object detection implementation using sliding window and image pyramid on top of an image classifier 
Kaggle
Object Detection using Selective SearchA basic object detection implementation using selective search on top of an image classifier 
Kaggle

Generative Adversarial Network

NameDescriptionNotebook
Deep Convolutional GANAn Implementation of Deep Convolutional GAN to generate MNIST digits 
Kaggle
Wasserstein GAN with Gradient PenaltyAn Implementation of Wasserstein GAN with Gradient Penalty to generate MNIST digits 
Kaggle
Conditional GANAn Implementation of Conditional GAN to generate MNIST digits 
Kaggle

If you find any bugs or have any questions regarding these notebooks, please open an issue. We will address it as soon as we can.

Reach out on Twitter if you have any questions.

Please cite the following if you use the code examples in your research:

@misc{saravia2022ml,
  title={ML Notebooks},
  author={Saravia, Elvis and Rastogi, Ritvik},
  journal={https://github.com/dair-ai/ML-Notebooks},
  year={2022}
}

Download Details:

Author: Dair-ai
Source Code: https://github.com/dair-ai/ML-Notebooks 
License: Apache-2.0 license

#python #machinelearning #ai #deeplearning #pytorch 

ML-Notebooks: Machine Learning Notebooks