quick / app.py
shvchenko's picture
Update app.py
e042ee3 verified
raw
history blame
4.72 kB
import re
import json
import random
import string
import gradio as gr
from difflib import get_close_matches
CHANNELS_JSON = "channels_fixed.json"
def normalize(name):
name = name.lower()
name = re.sub(r'[^a-z0-9]', '', name)
name = re.sub(r'0+', '', name)
return name
def fuzzy_match(name, json_keys, cutoff=0.8):
matches = get_close_matches(normalize(name), [normalize(k) for k in json_keys], n=1, cutoff=cutoff)
if matches:
for k in json_keys:
if normalize(k) == matches[0]:
return k
return None
def generate_filename(upper=False):
chars = ''.join(random.choices(string.ascii_uppercase if upper else string.ascii_lowercase, k=3))
return f"{chars}.m3u"
def process_playlist(m3u_content):
m3u_lines = m3u_content.splitlines()
try:
with open(CHANNELS_JSON, 'r', encoding='utf-8') as f:
channels_ref = json.load(f)
except Exception as e:
return f"Error reading JSON: {e}", None, None
m3u_24_7 = []
m3u_events = []
current_section = None
for line in m3u_lines:
if line.startswith('#EXTINF'):
if 'group-title="24/7 CHANNELS' in line:
current_section = '24_7'
elif 'EVENTS|' in line:
current_section = 'events'
else:
current_section = None
if current_section == '24_7':
m3u_24_7.append(line)
elif current_section == 'events':
# Remove 24/7 group-title if mistakenly present
line = re.sub(r'group-title="24/7 CHANNELS[^"]*"', '', line)
m3u_events.append(line)
else:
m3u_24_7.append(line)
m3u_events.append(line)
log_lines = []
def update_tvg_id(lines, is_event=False):
updated = []
for line in lines:
if line.startswith('#EXTINF'):
parts = line.split(',')
ch_name = parts[-1].strip()
if is_event:
match_brackets = re.search(r'\[(.*?)\]', ch_name)
ch_name_to_match = match_brackets.group(1) if match_brackets else ch_name
ch_name_norm = normalize(ch_name_to_match)
json_keys_norm = {k: normalize(k) for k in channels_ref.keys()}
match_key = None
matches = get_close_matches(ch_name_norm, list(json_keys_norm.values()), n=1, cutoff=0.7)
if matches:
for k, v in json_keys_norm.items():
if v == matches[0]:
match_key = k
break
new_tvg_id = channels_ref[match_key]['tvg_id'] if match_key else 'Live.Event.us'
# Replace any tvg-id="test" with Live.Event.us
if 'tvg-id="test"' in line:
new_tvg_id = 'Live.Event.us'
else:
match_key = fuzzy_match(ch_name, channels_ref.keys())
new_tvg_id = channels_ref[match_key]['tvg_id'] if match_key else 'Info.Guide.Dummy.us'
if 'tvg-id="test"' in line:
new_tvg_id = 'Info.Guide.Dummy.us'
if 'tvg-id=' in line:
line = re.sub(r'tvg-id=".*?"', f'tvg-id="{new_tvg_id}"', line)
else:
line = line.replace('#EXTINF:', f'#EXTINF:-1 tvg-id="{new_tvg_id}",')
log_lines.append(f"{'✅' if (match_key or not is_event) else '⚠️'} {ch_name}{new_tvg_id}")
updated.append(line)
return updated
updated_24_7 = update_tvg_id(m3u_24_7, is_event=False)
updated_events = update_tvg_id(m3u_events, is_event=True)
filename_24_7 = generate_filename(upper=True)
filename_events = generate_filename(upper=False)
with open(filename_24_7, 'w', encoding='utf-8') as f:
f.write('\n'.join(updated_24_7))
with open(filename_events, 'w', encoding='utf-8') as f:
f.write('\n'.join(updated_events))
log_text = '\n'.join(log_lines)
return log_text, filename_24_7, filename_events
# --- Gradio UI ---
demo = gr.Interface(
fn=process_playlist,
inputs=[gr.Textbox(label="Paste M3U8 Playlist Here", lines=25)],
outputs=[
gr.Textbox(label="Update Log", lines=25),
gr.File(label="Download 24/7 Channels M3U"),
gr.File(label="Download Events M3U")
],
title="Project 1 Playlist Updater - Smart Events",
description="Paste the M3U8 playlist content. Updates 24/7 and Events channels tvg-id using channels_fixed.json with smart Events matching."
)
demo.launch()