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

Резултати

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

Пребарај: #sagaftra

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

@ai_and_law · Post #362 · 29.07.2024 г., 07:04

Video Game Performers Strike Over AI Concerns Hollywood’s video game performers have announced a strike, following the breakdown of contract negotiations with major game studios over AI protections. This strike, organized by the Screen Actors Guild-American Federation of Television and Radio Artists (SAG-AFTRA), marks the second work stoppage for video game voice actors and motion capture performers. Despite progress on wages and job safety, SAG-AFTRA negotiators remain at an impasse with gaming giants such as Activision, Warner Bros., and Walt Disney Co. over the regulation of generative AI. Audrey Cooling, a spokesperson for the video game producers, stated that studios have proposed AI protections. However, SAG-AFTRA’s negotiating committee highlights a critical issue: the studios’ narrow definition of “performer,” which excludes many physical performances from protection, treating them instead as mere "data." Ray Rodriguez, SAG-AFTRA’s Chief Contracts Officer, emphasized that the industry’s stance undermines the rights of many performers, reflecting a significant challenge in the evolving landscape of AI in entertainment. #AI#SAGAFTRA#AIRegulation

AI & Law

@ai_and_law · Post #386 · 30.08.2024 г., 07:04

California Takes a Stand: New Bill to Protect Performers from AI Replicas The California Senate has approved AB 2602, a groundbreaking bill requiring explicit consent from performers before creating digital replicas of their likeness across TV, film, video games, audiobooks, and commercials. This legislation represents a significant victory for SAG-AFTRA in its ongoing battle against unauthorized AI use in the entertainment industry. Duncan Crabtree-Ireland, SAG-AFTRA's executive director, hailed the bill as "a huge step forward" in establishing safeguards against potential licensing abuse. While this marks a critical development, the bill still awaits Governor Gavin Newsom’s signature to become law. If enacted, it could set a new standard for AI ethics and performer rights, reflecting California’s leadership in balancing innovation with human protection. #AI#DigitalRights#SAGAFTRA#AIEthics

AI & Law

@ai_and_law · Post #173 · 24.11.2023 г., 08:04

SAG-AFTRA's Post-Strike Contract Raises Alarms on AI Usage Hello, dear subscribers! The tentative agreement between SAG-AFTRA and the Alliance of Motion Picture and Television Producers (AMPTP) that signals the potential end to the ongoing labor strike has taken an unexpected turn. While there's hope for the strike to conclude, concerns are emerging regarding the contract's stance on the use of artificial intelligence and its potential impact on actors. Disagreements over the digital capture, perpetual ownership, and usage of actors' likenesses by Hollywood studios have been key reasons behind the strike. The tentative contract introduces provisions related to generative AI technology, sparking worries about the extent of responsibility placed on studios. The contract's ambiguous wording around "unprecedented provisions for consent and compensation that will protect members from the threat of AI" has raised questions about how effectively it safeguards actors. Notably, nearly 14% of SAG-AFTRA's National Board opposed moving forward, indicating reservations within the union. The agreement introduces new definitions for digital replicas, emphasizing the need for clear and advance consent from actors. However, critics, including former SAG-AFTRA board member Justine Bateman, express concerns about potential loopholes favoring studios. The summary's of tentative agreement mention of actors potentially competing with AI objects for roles is seen as a significant drawback. While the strike officially ended on November 9th, the summary specifies that AMPTP only has to "endeavor to comply" until the contract is ratified. The lack of detail on enforcement mechanisms and the expansive powers given to studios in post-production edits raise concerns about actors' control over their digital replicas. As the union heads toward a ratification vote on December 5th, many questions remain unanswered. The summary's lack of clarity on specific terms for substantial changes triggering contractual mechanisms raises uncertainties about the practicalities of AI usage in the industry. #SAGAFTRA#AI#EntertainmentIndustry#LaborStrike#DigitalReplicas