Можно ли в 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
Europe's Final AI Act: Key Provisions Unveiled Analysed
Hello everyone! William Fry law summarized the final AI Act draft. The legislation outlines prohibited AI practices, including manipulation for behavior distortion, exploiting vulnerabilities, and unauthorized biometric categorization. Notably, AI systems posing minimal risks won't be deemed high-risk if specific criteria are met.
General-purpose AI models must comply with obligations like documentation maintenance and cooperation with authorities. The Act mandates disclosure of deep fakes, unless legally authorized or part of artistic works. Providers must watermark AI-generated content for transparency, ensuring effective marking and compatibility with technical standards.
#AIACT#EURegulation#AI
🇳🇱Netherlands Issues Practical Guidance on EU AI Act Compliance
The Dutch Ministry of Economic Affairs has released a detailed report outlining how organizations can comply with the EU AI Act. The document clarifies requirements for general-purpose AI models, high-risk AI systems, and the safeguards needed to ensure data protection and transparency.
By breaking down obligations across risk categories, the guidance aims to help companies navigate the EU AI Act’s technical and legal standards more effectively, ensuring that deployment of AI systems aligns with both regulatory and ethical expectations.
#EUAIAct#AIlaw#EUregulation
EU Countries Unanimously Approve AI Act Advancement
Hello everyone! Representatives from European Union member states have unanimously voted to advance the Artificial Intelligence Act, marking a crucial step in shaping the governance of AI within the region and globally.
The approval by the Council of the EU's Committee of Permanent Representatives (COREPER) removes significant obstacles, despite prior reservations from countries like France, Austria, Germany, and Italy.
The next phase involves the European Parliament, with two key committees set to vote on February 13. The full plenary vote is anticipated on either April 10 or 11, with widespread opposition not expected.
Once adopted, the AI Act will come into force 20 days after publication in the official journal, introducing regulations for various AI systems. The European Commission will take a lead role in implementing the Act, including establishing an AI Office.
#EUAIAct#ArtificialIntelligence#AIGovernance#EURegulation
🇪🇺📖Algorithmic Management in the EU: A Structural Shift in Labor Governance
The European Commission’s Directorate-General for Employment has released a study on algorithmic management (AM), offering the most comprehensive analysis to date of how digital systems are transforming workforce governance. Covering everything from recruitment and task allocation to performance evaluation and contract termination, the study shows that around 25% of EU enterprises — especially large private companies — are already using AM tools, with adoption expected to rise by 3–6% annually over the next decade.
This multi-year research project, developed with input from social partners, academics, and industry leaders, highlights both operational efficiencies and significant legal and ethical challenges. Among them: threats to worker privacy, diminished autonomy, lack of transparency, and deskilling. While current EU legislation — including GDPR and anti-discrimination directives — offers partial coverage, the study identifies critical regulatory gaps. As algorithmic oversight becomes embedded in everyday management, the findings make one thing clear: governance must evolve just as fast as the technology it aims to regulate.
#AIandLaw#EURegulation#DigitalGovernance
🚢ЕС утвердил первый немецкий судоремонтный завод в списке разрешённых для конвенционной утилизации.
Европейская комиссия приняла 15-ю редакцию European List of Ship Recycling Facilities, включив в неё первую верфь в Германии (г. Эмден).
Список также продлевает аккредитацию четырёх верфей в Дании, Эстонии, Литве и Испании, а также одной площадки в Турции. Одновременно три предприятия исключены: финская верфь не продлила разрешение, площадка в Северной Ирландии не предоставила требуемые данные, а одна турецкая верфь признана несоответствующей требованиям EU Ship Recycling Regulation (в части защиты береговой линии).
Включение в список позволяет предприятиям утилизировать крупнотоннажные суда под флагом стран ЕС при соблюдении строгих экологических, трудовых и стандартов безопасности. Обновлённый перечень включает 41 площадку: 30 в Европе (ЕС, Норвегия, Великобритания), 10 в Турции и 1 в США.
Для судоходной отрасли решение усиливает роль регулируемой утилизации и поддерживает развитие циркулярной экономики, включая переработку стали и вторичных материалов.
Напомним, что с 31 декабря 2018 года суда под флагом ЕС обязаны проходить утилизацию только на площадках из Европейского списка. При этом европейские судовладельцы контролируют около 30% мирового флота по дедвейту.
📌European Commission — исполнительный орган Европейского союза, созданный в 1958 году, отвечает за разработку и реализацию законодательства ЕС. Финансируется из общего бюджета Европейского союза.
#ShipRecycling#EURegulation#CircularEconomy#MaritimePolicy#Sustainability
Experts Examine AI Office's Key Role in EU Regulation
Hello, dear subscribers! Hadrien Pouget, Associate Fellow at the Carnegie Endowment for International Peace, and Johann Laux, British Academy Postdoctoral Fellow at the University of Oxford, have written an insightful article highlighting the pivotal role of the AI Office within the EU's regulatory framework, especially in the context of implementing the AI Act.
The authors propose a three-fold strategy for the AI Office:
1️⃣ Developing Harmonized Standards: They recommend that the AI Office actively contributes to enhancing the specificity of AI regulations over time. This involves aiding in the determination of normative decisions for consideration and offering insights when normative judgments need to be made.
2️⃣ Amending the AI Act: The AI Office should monitor and navigate the intricate interplay between the AI Act and other laws. Moreover, it should maintain independence while providing recommendations for delegated acts and amendments.
3️⃣ Handling Legal Matters: In court proceedings, the AI Office plays a vital role in identifying gaps in the protection of fundamental rights. It offers insights into distinguishing predictable harms from unpredictable ones by meticulously examining technological evidence.
The AI Office is envisioned as a central agency instrumental in ensuring the ethical and effective implementation of AI regulations.
#AIRegulation#AIStandards#AIAct#EURegulation#AIOffice#FundamentalRights