Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines4567891011121314151617181920213 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980812 unmodified lines848586878889903 unmodified linesimport threadingimport time# Session状态初始化if 'download' not in st.session_state:st.session_state.download = {'progress': 0,'is_downloading': False,'complete': False,'file_path': None,'status': ""}def download_torrent(magnet_link, save_path):try:ses = lt.session()params = {'save_path': save_path,3 unmodified lineshandle = lt.add_magnet_uri(ses, magnet_link, params)# 获取元数据st.session_state.download['status'] = "正在获取元数据..."while not handle.has_metadata():time.sleep(1)# 获取文件信息torrent_info = handle.get_torrent_info()files = []for i in range(torrent_info.num_files()):files.append(torrent_info.file_at(i).path)# 开始下载st.session_state.download['status'] = "开始下载..."st.session_state.download['is_downloading'] = Truewhile handle.status().state != lt.torrent_status.seeding:status = handle.status()progress = status.progress * 100st.session_state.download['progress'] = progresstime.sleep(1)# 下载完成st.session_state.download['is_downloading'] = Falsest.session_state.download['complete'] = Truest.session_state.download['file_path'] = save_pathst.session_state.download['status'] = f"下载完成!保存路径:{save_path}"except Exception as e:st.session_state.download['status'] = f"错误:{str(e)}"st.session_state.download['is_downloading'] = False# 界面布局st.title("🎯 磁力链接下载器")st.write("输入磁力链接开始下载(仅支持单个文件)")magnet_link = st.text_input("磁力链接:", placeholder="magnet:?xt=urn:btih:...")col1, col2 = st.columns([1, 3])with col1:if st.button("🚀 开始下载", disabled=st.session_state.download['is_downloading']):if not magnet_link.startswith("magnet:"):st.error("请输入有效的磁力链接!")else:save_dir = "./downloads"os.makedirs(save_dir, exist_ok=True)threading.Thread(target=download_torrent,args=(magnet_link, save_dir),daemon=True).start()# 下载状态显示if st.session_state.download['is_downloading']:st.progress(int(st.session_state.download['progress']))st.write(f"🔍 进度:{st.session_state.download['progress']:.1f}%")2 unmodified linesif st.session_state.download['complete']:st.success("✅ 下载完成!")# 显示下载文件download_dir = st.session_state.download['file_path']files = [f for f in os.listdir(download_dir) if os.path.isfile(os.path.join(download_dir, f))]3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960613 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271282 unmodified lines1311321331341351361373 unmodified linesimport threadingimport time# 线程安全的下载状态管理class DownloadState:_instance = None_lock = threading.Lock()def __new__(cls):with cls._lock:if cls._instance is None:cls._instance = super().__new__(cls)cls._instance.progress = 0cls._instance.is_downloading = Falsecls._instance.complete = Falsecls._instance.file_path = Nonecls._instance.status = ""return cls._instancedef init_session_state():"""初始化session_state"""if 'download_initialized' not in st.session_state:state = DownloadState()st.session_state.download = {'progress': state.progress,'is_downloading': state.is_downloading,'complete': state.complete,'file_path': state.file_path,'status': state.status}st.session_state.download_initialized = Truedef sync_session_state():"""同步状态到session_state"""state = DownloadState()st.session_state.download = {'progress': state.progress,'is_downloading': state.is_downloading,'complete': state.complete,'file_path': state.file_path,'status': state.status}def download_torrent(magnet_link, save_path):try:state = DownloadState()# 初始化下载状态with threading.Lock():state.progress = 0state.is_downloading = Truestate.complete = Falsestate.file_path = Nonestate.status = "正在初始化..."ses = lt.session()params = {'save_path': save_path,3 unmodified lineshandle = lt.add_magnet_uri(ses, magnet_link, params)# 获取元数据with threading.Lock():state.status = "正在获取元数据..."while not handle.has_metadata():time.sleep(1)# 获取文件信息torrent_info = handle.get_torrent_info()files = [torrent_info.file_at(i).path for i in range(torrent_info.num_files())]# 开始下载with threading.Lock():state.status = "开始下载..."while handle.status().state != lt.torrent_status.seeding:status = handle.status()with threading.Lock():state.progress = status.progress * 100time.sleep(1)# 下载完成with threading.Lock():state.is_downloading = Falsestate.complete = Truestate.file_path = save_pathstate.status = f"下载完成!保存路径:{save_path}"except Exception as e:with threading.Lock():state.status = f"错误:{str(e)}"state.is_downloading = Falsefinally:sync_session_state()# 初始化session状态init_session_state()# 界面布局st.title("🎯 磁力链接下载器")st.write("输入磁力链接开始下载(仅支持单个文件)")magnet_link = st.text_input("磁力链接:", placeholder="magnet:?xt=urn:btih:...")if st.button("🚀 开始下载", disabled=st.session_state.download['is_downloading']):if not magnet_link.startswith("magnet:"):st.error("请输入有效的磁力链接!")else:save_dir = "./downloads"os.makedirs(save_dir, exist_ok=True)threading.Thread(target=download_torrent,args=(magnet_link, save_dir),daemon=True).start()# 实时更新状态sync_session_state()# 显示下载状态if st.session_state.download['is_downloading']:st.progress(int(st.session_state.download['progress']))st.write(f"🔍 进度:{st.session_state.download['progress']:.1f}%")2 unmodified linesif st.session_state.download['complete']:st.success("✅ 下载完成!")# 文件下载部分download_dir = st.session_state.download['file_path']files = [f for f in os.listdir(download_dir) if os.path.isfile(os.path.join(download_dir, f))]
app.py+83-36