TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #241 · 5 мај

Можно ли в Python создавать бинарные файлы? Конечно можно. Для этого в Python есть следующие инструменты: ▫️ тип данных bytes и bytearray ▫️ открытие файла в режиме wb (write binary) или rb (read binary) ▫️ модуль struct Про модуль struct поговорим в первую очередь. Файл в формате JSON или Yaml внутри себя содержит разметку данных. Всегда можно определить где список начался а где закончился. Где записана строка а где словарь. То есть формат записи данных содержит в себе элементы разметки данных. В binary-файле данные не имеют визуальной разметки. Это просто байты, записанные один за другим. Правила записи и чтения находятся вне файла. Модуль struct как раз и помогает с организацией данных в таком файле с помощью определения форматов записи для разных частей файла. Модуль struct преобразует Python-объекты в массив байт, готовый к записи в файл и имеющий определённый вид. Для этого всегда следует указывать формат преобразования (или, как оно здесь называется - запаковки). Формат нужен для того, чтобы выделить достаточное количество байт для записи конкретного типа объекта. В последствии с помощью того же формата будет производиться чтение. При этом следует помнить что мы говорим о типах языка С а не Python. Именно формат определяет, что записано в конкретном месте файла, число, строка или что-то еще. Вот какие токены формата у нас есть. Помимо этого, первым символом можно указать порядок байтов. На разных системах одни и те же типы данных могут записываться по-разному, поэтому желательно указать конкретный способ из доступных. Если этого не сделать, то используется символ '@', то есть нативный для текущей системы. В строке формата мы пишем в каком порядке и какие типы собираемся преобразовать в байты. Запакуем в байты простое число, токен "i". >>> import struct >>> struct.pack('=i', 10) b'\n\x00\x00\x00' Теперь несколько float, при этом нужно передавать элементы не массивом а последовательностью аргументов. >>> struct.pack('=fff', 1.0, 2.5, 4.1) b'\x00\x00\x80?\x00\x00 @33\x83@' Вместо нескольких токенов можно просто указать нужное количество элементов перед одним токеном, результат будет тот же. >>> struct.pack('=3f', 1.0, 2.5, 4.1) b'\x00\x00\x80?\x00\x00 @33\x83@' Теперь запакуем разные типы >>> data = struct.pack('=fiQ', 1.0, 4, 100500) я запаковал типы float, int и unsigned long long (очень большой int, на 8 байт) b'\x00\x00\x80?\x04\x00\x00...' Распаковка происходит аналогично, но нужно указать тот же формат, который использовался при запаковке. Результат возвращается всегда в виде кортежа. >>> struct.unpack('=fiQ', data) (1.0, 4, 100500) Как видите, ничего страшного! #lib#basic

Hashtags

Резултати

Пронајдени 6 слични објави

Пребарај: #aiandart

当前筛选 #aiandart清除筛选
AI & Law

@ai_and_law · Post #77 · 07.08.2023 г., 07:04

Copyright in the Age of AI: Artists Take a Stand Hey there, AI & Law community! Have you ever wondered about the complex interplay between art and artificial intelligence? A recent legal battle is shedding light on how AI-generated content intersects with copyright law. Imagine discovering that your artwork has been used to train an AI system without your consent. That's exactly what happened to Kelly McKernan, a talented watercolor and acrylic illustrator. She found her creations uploaded to the LAION dataset, fueling AI image generators. This revelation transformed her relationship with her art, raising concerns about her career and the rights of countless creators. Kelly McKernan isn't alone in her struggle. Alongside cartoonist Sarah Anderson and illustrator Karla Ortiz, she's taking a stand against AI firm Stability AI, the company behind Stable Diffusion, Midjourney, and DeviantArt. These artists are filing a lawsuit, questioning the use of their work to train AI systems. This legal challenge adds to a growing list of cases that highlight the copyright complexities brought about by AI. Artists worldwide are coming together to address the concerns surrounding AI's impact on their creations. The European Guild of Artificial Intelligence Regulation is a prime example, aiming to create legislation that safeguards artists from predatory AI practices. The lack of protective measures and the potential for AI-generated art to replace human creativity is a pressing issue that demands attention. The case brings to the forefront the need for updated copyright laws in the face of AI advancements. The current framework often falls short in addressing the challenges posed by generative AI. #AIandArt#CopyrightProtection#ArtificialIntelligence#AIinLaw

AI & Law

@ai_and_law · Post #161 · 10.11.2023 г., 08:04

Artist Lawsuit Over AI Image Generators Faces Challenges Hello, dear subscribers! In the ongoing lawsuit against AI image generators by artists, several claims were dismissed by US district Judge William H. Orrick. Notably, two of the three plaintiffs in the case had not registered their disputed works with the Copyright Office, leading to the dismissal of their claims. However, the lead plaintiff, Sarah Andersen, has 30 days to amend her complaint and continue the copyright dispute. The artists allege that AI image generators infringe on their copyrights, claiming direct and vicarious infringement, violations of the Digital Millennium Copyright Act, and California laws related to unfair competition and rights to publicity. They argue that AI-generated images should be considered derivative works based on copyrighted content. While the case proceeds, the judge has called for clarification on how image generators work, especially regarding "compressed copies" of images and the operation of AI systems like Stable Diffusion. The lawsuit remains complex, with the core claim of direct copyright infringement proceeding against Stability AI but not against DeviantArt and Midjourney. The artists will need to address the many issues identified in their claims, including specifics regarding copyright management information and rights of publicity. #AIImageGenerators#CopyrightLawsuit#AIandArt#LegalAction

The Digi Doodles

@Digi_doodles · Post #596 · 15.06.2025 г., 12:20

#ЦифровойКонтекст sónar+D 2025: как ИИ учат быть человечным 💐 С 12 по 14 июня в Барселоне прошёл фестиваль sónar+D — пространство, где технологии и культура перестают спорить, а начинают сотрудничать 🖼 Что было? — сенсорные перформансы и звук на уровне кожи — «разговоры» с растениями через датчики — квантовая музыка и генеративный звук Главный посыл ИИ — не угроза, а медиатор. Технологии — не инструмент, а соавтор ✉️ sónar+D предлагает не страх, а эмпатию к цифровому. #Sonar2025#AIandArt#DigitalEmpathy#новости

The Digi Doodles

@Digi_doodles · Post #594 · 13.06.2025 г., 20:24

#ЦифровойКонтекст Цифровое возвращение: в Базеле стартовала Digital Art Mile ❤️ С 16 по 22 июня, параллельно с Art Basel, в Швейцарии проходит первая Digital Art Mile, организованная платформой ArtMeta 💐 👌Что на повестке? — художники, работающие с ИИ, NFT и нейросетями — робототехника как перформанс — попытка вернуть цифровое искусство в контекст искусства, а не просто блокчейна 👫Ключевой фокус Историзация цифрового. ИИ и NFT — не временный хайп, а часть художественной традиции XXI века. #DigitalArtMile#ArtMeta#AIandArt#новости

The Digi Doodles

@Digi_doodles · Post #595 · 14.06.2025 г., 12:20

#ЦифровойКонтекст ИИ, цветы и фотоплёнка: названы цифровые художники года 💐 Arab Bank Switzerland назвал победителей Digital Art Prize 2025: 🧝Анна Ридлер и София Креспо — Artists of the Year за проект "Snapshots: Orchids" (гибрид аналоговой фотографии и генеративной визуализации, где ИИ выращивает орхидеи памяти) 👼Чезар Мокану — Emerging Artist of the Year за ¡World Upstream! (антиутопический дипфейк-фильм о климате, сделанный на грани эстетики и симуляции). AI здесь — не модный фильтр. Это язык, на котором художники разговаривают с будущим 🌸 #DigitalArt#AnnaRidler#SofiaCrespo#AIandArt#новости

AI & Law

@ai_and_law · Post #151 · 29.10.2023 г., 09:48

🌟 AI Sunday Wonders: New Tool Empowers Artists in the Fight Against Unauthorized AI Training Hello everyone! This Sunday Here's the latest from the world of AI and art. Meet "Nightshade," a groundbreaking tool enabling artists to safeguard their work from being used in AI model training without their consent. By subtly altering the pixels in their artwork before posting it online, artists can introduce invisible changes that, when incorporated into AI training data, can cause unpredictable distortions in the AI-generated output. This tool is designed to challenge AI companies that exploit artists' creations without authorization to train their models. The result? Future iterations of image-generating AI models may produce bizarre results: dogs might become cats, cars could transform into cows, and so on. Nightshade aims to shift the balance of power back to artists. It serves as a potent deterrent against AI companies that disregard artists' copyrights and intellectual property. #AIandArt#ArtProtection#AIInnovation#NightshadeTool#AIandCopyright