# encoding=utf-8
import os, json,re

def has_chinese(text: str) -> bool:
    # \u4e00‑\u9fff 汉字区间
    pattern = re.compile(r'[\u4e00-\u9fff]')
    return bool(pattern.search(text))

def read_movie_txt_files(root_dir):
    """
    遍历指定目录下的子文件夹，读取所有TXT文件内容并返回字典

    参数:
        root_dir: 根目录路径（这里是"/home/ray/www/public/moruienglish/movies"）

    返回:
        字典结构: {"子文件夹名": {"txt文件名": "txt内容"}}
    """
    result = []
    # 遍历根目录下的所有子项
    for item in os.listdir(root_dir):
        item_path = os.path.join(root_dir, item)
        # 只处理子文件夹（跳过文件）
        if os.path.isdir(item_path):
            subfolder_name = item  # 子文件夹名称
            #result[subfolder_name] = {}  # 初始化子文件夹对应的字典

            # 遍历子文件夹中的所有文件
            for file in os.listdir(item_path):
                file_path=os.path.join(item_path, file)
                if os.path.isfile(file_path) and file.lower().endswith('.txt'):
                    #print(file_path)
                    id=file.split(".")[0]
                    if "ZJLN" in id:
                        continue
                    # 读取TXT文件内容（使用utf-8编码，遇到错误忽略）
                    with open(file_path, 'r') as f:
                        content = f.read()
                    if "♪" in content:
                        continue
                    if has_chinese(content):
                        continue
                    img_path=file_path.replace(".txt",".gif").replace("/home/ray/www/public/moruienglish","")
                    audio_path=file_path.replace(".txt",".mp3").replace("/home/ray/www/public/moruienglish","")
                    result.append({"id":id,"img_path":img_path,"audio_path":audio_path,"text":content})
                    #print(id,diff,content)
    print("记录词条数：",len(result))
    return result

# 调用函数（指定目标根目录）
root_directory = "/home/ray/www/public/moruienglish/movies"
content_dict = read_movie_txt_files(root_directory)
with open("data.json", "w") as f:
    # 注意参数顺序：第一个是要写入的数据，第二个是文件对象
    # 加上 ensure_ascii=False 确保中文等非ASCII字符正常显示
    json.dump({"data":content_dict}, f, ensure_ascii=False, indent=2)