Woffee's picture
Fix timestamp
f146ea8
Raw
History Blame Contribute Delete
2.98 kB
import gradio as gr
import pandas as pd
import re
# 提取文件名中的所有数字作为时间戳
def extract_timestamps(file_name):
# 使用正则表达式提取所有的数字
timestamps = re.findall(r'(\d+)', file_name)
# 将这些数字转换为整数,返回列表
return [int(ts) for ts in timestamps]
# 根据提取的时间戳列表排序
def sort_by_timestamps(file_name):
# 提取所有时间戳,并按自然顺序进行排序
timestamps = extract_timestamps(file_name)
# 返回时间戳中的最小值作为排序的主键
return timestamps
def csv_to_dict(df):
df = df.fillna('')
res = {}
for i, row in df.iterrows():
if row['CRN'] not in res:
res[ row['CRN' ] ] = {
'Instructor': row['Instructor'],
'Now': row['Now'],
}
return res
def compare_dicts(dict_a, dict_b):
# 遍历两个字典,查找 Instructor 或 Now 不同的CRN
changed = []
all_crns = set(dict_a.keys()).union(set(dict_b.keys()))
for crn in all_crns:
instructor_a = dict_a.get(crn, {}).get('Instructor', None)
instructor_b = dict_b.get(crn, {}).get('Instructor', None)
max_a = dict_a.get(crn, {}).get('Now', None)
max_b = dict_b.get(crn, {}).get('Now', None)
# 如果Instructor或Max不同,则记录CRN
if instructor_a != instructor_b:
msg = ' * CRN: {}, Instructor change: {} --> {}'.format(crn, instructor_a, instructor_b)
changed.append(msg)
if max_a != max_b:
msg = ' * CRN: {}, Now change: {} --> {}'.format(crn, max_a, max_b)
changed.append(msg)
return changed
def process_files(files):
if len(files) < 2:
return "Please upload at least 2 files."
# 根据文件名中的时间戳进行排序
files_sorted = sorted(files, key=sort_by_timestamps)
result = []
# 对排序后的文件进行两两比较
for i in range(len(files_sorted) - 1):
df_older = pd.read_csv(files_sorted[i].name)
df_newer = pd.read_csv(files_sorted[i + 1].name)
dict_a = csv_to_dict(df_older)
dict_b = csv_to_dict(df_newer)
f1 = files_sorted[i].name.split('/')[-1]
f2 = files_sorted[i+1].name.split('/')[-1]
crns = compare_dicts(dict_a, dict_b)
if crns:
result.append("{} --> {} \n{}".format(f1, f2, "\n".join(crns)))
else:
result.append("{} --> {} \n * No change.".format(f1, f2))
return "\n".join(result)
# 使用Gradio构建界面
gr.Interface(
fn=process_files,
inputs=gr.Files(label="Upload CSV files"),
outputs="text",
title="Course Schedule Tracker",
description="Upload multiple CSV files, sort them based on the timestamp in the filenames, compare two adjacent files at a time, and output the CRNs where the 'Instructor' or 'Now' has changed."
).launch()