Spaces:
Running
Running
import json | |
import requests | |
import gradio as gr | |
from utils import is_valid_url, HEADER, EN_US | |
ZH2EN = { | |
"输入长链接": "Input a long URL", | |
"选择 API 提供商": "Select an API provider", | |
"输出短链接": "Output short URL", | |
"预览短链接": "Preview short URL", | |
"将长链接转换为短的、易于共享的链接": "Convert long urls into short, easy-to-share links", | |
"状态栏": "Status", | |
} | |
def _L(zh_txt: str): | |
return ZH2EN[zh_txt] if EN_US else zh_txt | |
def noxlink(longUrl: str, domain="https://noxlink.net"): | |
api = f"{domain}/zh-CN/shorten" | |
response = requests.post(api, json={"longUrl": longUrl}, headers=HEADER) | |
if response.status_code == 200: | |
retcode = json.loads(response.text) | |
if retcode["success"]: | |
return f"{domain}/" + retcode["message"] | |
raise ConnectionError(response.text) | |
def monojson(longUrl: str): | |
response = requests.post( | |
"https://monojson.com/api/short-link", | |
json={"url": longUrl}, | |
headers=HEADER, | |
) | |
if response.status_code == 200: | |
return json.loads(response.text)["shortUrl"] | |
else: | |
raise ConnectionError(response.text) | |
# outer func | |
def infer(longUrl: str, tool: str): | |
status = "Success" | |
shortUrl = preview = None | |
try: | |
if tool == "monojson": | |
shortUrl = monojson(longUrl) | |
elif tool == "noxlink": | |
shortUrl = noxlink(longUrl) | |
else: | |
raise ValueError("请选择一个 API 提供商!") | |
if is_valid_url(shortUrl): | |
preview = f'<a href="{shortUrl}" target="_blank">{shortUrl}</a>' | |
except Exception as e: | |
status = f"{e}" | |
return status, shortUrl, preview | |
def url_shortner(): | |
return gr.Interface( | |
fn=infer, | |
inputs=[ | |
gr.Textbox( | |
label=_L("输入长链接"), | |
placeholder=_L("将长链接转换为短的、易于共享的链接"), | |
), | |
gr.Dropdown( | |
choices=["noxlink", "monojson"], | |
label=_L("选择 API 提供商"), | |
value="noxlink", | |
), | |
], | |
outputs=[ | |
gr.Textbox(label=_L("状态栏"), show_copy_button=True), | |
gr.Textbox(label=_L("输出短链接"), show_copy_button=True), | |
gr.HTML( | |
container=True, | |
show_label=True, | |
label=_L("预览短链接"), | |
), | |
], | |
flagging_mode="never", | |
examples=[ | |
["https://www.bing.com", "noxlink"], | |
["https://www.baidu.com", "monojson"], | |
], | |
cache_examples=False, | |
) | |