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

TGINSIGHT SIMILAR POSTS

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

Изворен канал @pythonotes · Post #121 · 20 јул.

Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для URL, имени файла, имени объекта в каком-то софте и тд. Требования совместимости простые: в тексте должны быть только допустимые символы. Обычно это a-z, 0-9 и "_" или "-". То есть, только прописные буквы латинского алфавита и цифры (как пример). Допустим, нам нужно название статьи в блоге преобразовать в slug для добавления его в URL этой статьи. Как это лучше всего сделать? В Django по умолчанию есть готовая функция slugify для таких случаев. Но я её никогда не использую. Почему? Потому что её недостаточно! Приведём пример >>> from django.utils.text import slugify >>> slugify('This is a Title') 'this-is-a-title' Пока всё отлично >>> slugify('This is a "Title!"') 'this-is-a-title' Спец символы удалились, всё хорошо. >>> slugify('Это заголовок статьи') '' Вот и приехали 😢. Если текст не английский то буквы просто игнорируются. Можно это поправить >>> slugify('Это заголовок статьи', allow_unicode=True) 'это-заголовок-статьи' Но тогда мы не вписываемся в условие. У нас появилась кириллица в тексте. Так как я часто пишу сайты для русскоязычных пользователей эта проблема весьма актуальна. Я не использую стандартную функцию и всегда пишу свою. Оригинал я не беру в расчёт и пишу полностью свою функцию. И так, по порядку: 🔸1. Исходный текст: >>> text = 'Мой заголовок №10 😁!' Взял специально посложней со специальными символами. 🔸2. Транслит Необходимо сделать транслит всех символов в латиницу. Здесь очень выручает библиотека unidecode. Помимо простого транслита кириллицы в латиницу она умеет преобразовывать спец символы и иероглифы в текстовые аналоги. from unidecode import unidecode >>> unidecode("Ñ Σ ® µ ¶ ¼ 月 山") 'N S (r) u P 1/4 Yue Shan' Очень крутая библиотека, советую👍 В нашем случае получаем такое преобразование: >>> text = unidecode(text) >>> print(text) 'Moi zagolovok No. 10 !' Отличный транслит. Смайл просто удалился, хотя я ждал что-то вроде :). Ну и ладно, всë равно невалидные символы. А еще наш код уже поддерживает любой язык, будь то хинди или корейский. 🔸4. Фильтр символов Unidecode не занимается фильтрацией по недопустимым символам. Это мы делаем в следующем шаге через regex. Просто заменим все символы на "_" если они вне указанного диапазона. >>> text = re.sub(r'[^a-zA-Z0-9]+', '_', text) >>> print(text) 'Moi_zagolovok_No_10_' Символ "+" в паттерне выручает когда несколько недопустимых символов идут рядом. Все они заменяются на один символ "_". 🔸5. Slugify Осталось удалить лишние символы по краям и сделать нижний регистр >>> text = text.strip('_').lower() >>> print(text) 'moi_zagolovok_no_10' Получаем отличный slug! 😎 🌎 Полный код в виде функции. ______________ PS. Проверку что в строке остался хоть один допустимый символ я бы вынес в отдельную функцию. #libs#tricks#django

Резултати

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

Пребарај: #trainingdata

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

@ai_and_law · Post #750 · 26.01.2026 г., 08:04

🇺🇸TRAIN Act: U.S. Congress Moves Toward Mandatory AI Training Transparency Bipartisan lawmakers have introduced the Transparency and Responsibility for Artificial Intelligence Networks (TRAIN) Act in the U.S. House, aiming to give copyright holders access to AI training records to determine whether their works were used to train generative AI models without consent or compensation. The bill, led by Rep. Madeleine Dean (PA-04) and Rep. Nathaniel Moran (TX-01), follows a Senate version reintroduced by Senators Peter Welch, Marsha Blackburn, Adam Schiff, and Josh Hawley. This is the first time the TRAIN Act has been introduced in the House. The proposal is modeled on enforcement mechanisms used in online piracy cases and responds to the current lack of any clear process for creators to verify whether their content was ingested into training datasets. The bill has support from major creator and rights-holder organizations, including the Recording Industry Association of America (RIAA) and SAG-AFTRA, alongside groups representing musicians, publishers, and copyright licensing. If enacted, the TRAIN Act would shift AI copyright disputes from speculation to evidence by establishing a legal path to training-data disclosure. It would also add pressure on AI companies that do not currently reveal how their models are trained. #AIandLaw#Copyright#TrainingData#Transparency

AI & Law

@ai_and_law · Post #785 · 16.03.2026 г., 07:04

🇪🇺📖Study Finds Limited Availability of AI Training Data Disclosures Under EU AI Act Researchers from Trinity College Dublin report that information about AI training data required under the AI Act is often missing and difficult to locate. The law requires developers to publish summaries explaining how their models were trained, using a disclosure template designed to help copyright holders enforce their rights regarding the use of copyrighted material in AI training. A pre-print study funded by Mozilla found that only a small number of such summaries could be identified. The researchers also found structural issues in accessing the disclosures. The AI Act does not specify where companies must publish the summaries, leaving the decision to developers. As a result, no common publication mechanism exists and practices vary widely. The template created by the European Commission AI Office has led to heterogeneous implementations, making it difficult to determine whether the available documents meet EU transparency requirements. Most of the identified disclosures were produced by smaller organizations, including documentation for Switzerland’s Apertus national model. A document published by Microsoft for one of its open-source models was also reviewed, but the study found that it lacked several required details. Researchers recommend creating a centralized portal for publishing transparency summaries to improve accessibility and support enforcement once the AI Act obligations become applicable in August. #AIAct#AITransparency#TrainingData#Copyright#AIGovernance#AIRegulation#EULaw

Venture Village Wall 🦄

@venturevillagewall · Post #3551 · 20.12.2024 г., 09:32

Fraction AI Raises $6M Fraction AI successfully secured $6M in funding for its groundbreaking project aimed at democratizing access to high-quality training data for artificial intelligence using Web3 technology. The funding round concluded on December 18, 2024. #FractionAI#Funding#AI#Web3#TrainingData#TechInvestment#Innovation#DataDemocratization

AI & Law

@ai_and_law · Post #783 · 12.03.2026 г., 07:04

🇺🇸Court Allows Enforcement of California AI Training Data Disclosure Law A US federal court has denied a request by Elon Musk’s AI company xAI to block enforcement of California Assembly Bill 2013. The law requires AI developers whose models are accessible in California to publicly disclose key information about training datasets, including dataset sources, collection timelines, whether collection is ongoing, and whether datasets contain copyrighted, trademarked, patented, or personal data. Companies must also indicate whether training data was licensed or purchased and the extent of synthetic data used. xAI argued the law would force disclosure of trade secrets, including dataset sources, dataset sizes, and data-cleaning methods. According to the company, such transparency could allow competitors to infer what datasets it uses and replicate its approach. The company warned that compliance could be “economically devastating” and reduce the value of its proprietary data practices. However, US District Judge Jesus Bernal ruled that xAI failed to demonstrate that the law requires disclosure of protected trade secrets. The court found the company’s claims too general and based largely on hypotheticals. The motion for a preliminary injunction was denied, allowing the law—which took effect in January—to remain in force while the lawsuit continues. #AIRegulation#AITransparency#TrainingData#TradeSecrets#AIAct#AIGovernance#TechLaw