File size: 6,865 Bytes
23dddf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import json
from datetime import datetime
import pytz
import time
import gradio as gr

js = """
function createGradioAnimation() {
    var container = document.createElement('div');
    container.id = 'gradio-animation';
    container.style.fontSize = '2em';
    container.style.fontWeight = 'bold';
    container.style.textAlign = 'center';
    container.style.marginBottom = '20px';

    var text = 'Welcome to Code Tools!';
    for (var i = 0; i < text.length; i++) {
        (function(i){
            setTimeout(function(){
                var letter = document.createElement('span');
                letter.style.opacity = '0';
                letter.style.transition = 'opacity 0.5s';
                letter.innerText = text[i];

                container.appendChild(letter);

                setTimeout(function() {
                    letter.style.opacity = '1';
                }, 50);
            }, i * 250);
        })(i);
    }

    var gradioContainer = document.querySelector('.gradio-container');
    gradioContainer.insertBefore(container, gradioContainer.firstChild);

    return 'Animation created';
}
"""


def json_format(data):
    try:
        data = json.loads(data)
        return data
    except:
        raise gr.Error("Json数据格式不正确!")


def html_format(data):
    return data


def md_format(data):
    return data


# 获取当前 Unix 时间戳
def get_current_timestamp(precision):
    timestamp = int(time.time() * 1000) if precision == "ms" else int(time.time())
    return str(timestamp)


# 时间戳转换为日期
def timestamp_to_date(input_time, target_timezone, precision):
    try:
        if precision == "ms":
            input_time = int(input_time) / 1000  # 毫秒转为秒
        else:
            input_time = int(input_time)  # 秒级时间戳

        # 将输入的 Unix 时间戳转换为 UTC 时间
        utc_time = datetime.utcfromtimestamp(input_time).replace(tzinfo=pytz.utc)

        # 获取目标时区
        target_tz = pytz.timezone(target_timezone)

        # 转换到目标时区
        target_time = utc_time.astimezone(target_tz)

        # 返回格式化后的时间
        return target_time.strftime("%Y-%m-%d %H:%M:%S")
    except Exception as e:
        return f"error: {e}"


# 日期转换为时间戳
def date_to_timestamp(input_date, target_timezone):
    try:
        # 解析日期输入为 datetime 对象
        target_tz = pytz.timezone(target_timezone)
        target_time = datetime.fromisoformat(input_date).astimezone(target_tz)

        # 转换为 UTC 时间戳
        timestamp = int(target_time.astimezone(pytz.utc).timestamp())

        return str(timestamp)
    except Exception as e:
        return f"error: {e}"


# 获取所有时区列表
timezones = pytz.all_timezones

with gr.Blocks(title='Gradio-Tools', theme=gr.themes.Ocean(), js=js) as demo:
    with gr.Tabs():
        with gr.Tab("Json Format"):
            with gr.Row():
                json_input = gr.Textbox(label="Json Data", interactive=True, placeholder="{}", lines=50)
                json_output = gr.Json(label="Json Format")

        json_input.change(fn=json_format, inputs=json_input, outputs=json_output)

        with gr.Tab("Timestamp Conversion"):
            with gr.Row():
                # 时间戳输入框,显示当前时间戳
                timestamp_input = gr.Textbox(
                    label="Timestamp (s/ms)",
                    value=get_current_timestamp("s"),  # 默认显示当前秒级时间戳
                    interactive=True,  # 可编辑
                    elem_id="timestamp_input",
                    placeholder="Please enter a timestamp"
                )

                # 选择精度(秒或毫秒)
                precision = gr.Dropdown(
                    ["s", "ms"],
                    label="Timestamp accuracy",
                    value="s",  # 默认秒
                    elem_id="precision"
                )

                target_timezone = gr.Dropdown(
                    timezones,
                    label="Target time zone",
                    value="Asia/Shanghai",  # 默认设置为北京时间
                    elem_id="target_timezone"
                )

            with gr.Row():
                # 日期输入框,用户输入日期
                date_input = gr.Textbox(
                    label="Date Input (ISO 8601)",
                    placeholder="For example:2025-01-01 12:34:56",
                    elem_id="date_input"
                )

                output = gr.Textbox(label="Conversion results", elem_id="output")

            with gr.Row():
                # 时间戳转日期按钮
                timestamp_to_date_btn = gr.Button("Timestamp to date", elem_id="timestamp_to_date_btn")

                # 日期转时间戳按钮
                date_to_timestamp_btn = gr.Button("Date to timestamp", elem_id="date_to_timestamp_btn")

            # 精度选择改变时,动态更新时间戳显示
            precision.change(
                lambda precision: get_current_timestamp(precision),
                inputs=precision,
                outputs=timestamp_input
            )

            # 时间戳转日期按钮点击事件
            def handle_timestamp_to_date(timestamp_input, target_timezone, precision):
                if timestamp_input:  # 如果时间戳输入框有内容
                    return timestamp_to_date(timestamp_input, target_timezone, precision)
                return "Please enter a valid timestamp"


            timestamp_to_date_btn.click(
                handle_timestamp_to_date,
                inputs=[timestamp_input, target_timezone, precision],
                outputs=output
            )

            # 日期转时间戳按钮点击事件
            def handle_date_to_timestamp(date_input, target_timezone):
                if date_input:  # 如果日期输入框有内容
                    return date_to_timestamp(date_input, target_timezone)
                return "Please enter a valid date"


            date_to_timestamp_btn.click(
                handle_date_to_timestamp,
                inputs=[date_input, target_timezone],
                outputs=output
            )

        with gr.Tab("Html Rendering"):
            with gr.Row():
                html_input = gr.Textbox(label="Html Data", interactive=True, placeholder="<html></html>", lines=50)
                html_output = gr.HTML()

        html_input.change(fn=html_format, inputs=html_input, outputs=html_output)

        with gr.Tab("Markdown Rendering"):
            with gr.Row():
                md_input = gr.Textbox(label="Markdown Data", interactive=True, placeholder="## title", lines=50)
                md_output = gr.Markdown()

        md_input.change(fn=md_format, inputs=md_input, outputs=md_output)

demo.launch()