Gradio 案例——将文本文件转为词云图

文章目录

  • Gradio 案例——将文本文件转为词云图
    • 界面截图
    • 依赖安装
    • 项目目录结构
    • 代码

Gradio 案例——将文本文件转为词云图

  • 利用 word_cloud 库,将文本文件转为词云图
  • 更完整、丰富的示例项目见 GitHub - AlionSSS/wordcloud-webui: The web UI for word_cloud(text to word cloud picture converter)

界面截图

image.png

依赖安装

  • 新建一个虚拟环境 Python 3.9.16
  • 依赖
    • $ pip install gradio==4.29 -i "https://pypi.doubanio.com/simple/"
    • $ pip install wordcloud==1.9.3 -i "https://pypi.doubanio.com/simple/"
    • $ pip install jieba==0.42.1 -i "https://pypi.doubanio.com/simple/"

项目目录结构

wordcloud-webui         # 目录
--/resources             # 资源目录
--/consts.py             # py文件,常量
--/gradio_interfaces.py  # py文件,Gradio视图
--/jieba_util.py         # py文件,工具库文件
--/lib_word_cloud.py     # py文件,工具库文件
--/main.py               # py文件,入口

代码

  • main.py
from gradio_interfaces import iface

if __name__ == "__main__":
    iface.launch()
  • lib_word_cloud.py
from wordcloud import WordCloud, ImageColorGenerator
import numpy as np
from PIL import Image

from consts import *

def text2wordcount_normal(
    text: str,
    background_color: str = "white",
    margin = 2,
    min_font_size = 4,
    max_font_size = 200,
    font_path = None,
    width: int = 400,
    height: int = 200,
):
    if not background_color or "" == str(background_color).strip():
        background_color = "white"
    if not min_font_size or  min_font_size < 1:
        min_font_size = 4
    if not max_font_size or max_font_size < 4:
        max_font_size = 200    
    if not font_path or "" == str(font_path).strip():
        font_path = DEFAULT_FONT_PATH
    if not width or width < 1:
        width = 400
    if not height or height < 1:
        height = 200 

    # Generate a word cloud image
    wordcloud = WordCloud(
        font_path=font_path,
        width=width, height=height, background_color=background_color, 
        max_words=2000, 
        margin=margin, min_font_size=min_font_size, max_font_size=max_font_size, 
        random_state=42
    ).generate(text)
    return wordcloud.to_image()

def text2wordcount_mask(
    text: str,
    background_color: str = "white",
    margin = 2,
    min_font_size = 4,
    max_font_size = 200,
    font_path = None,
    mask_image = None,
    mask_color = None,
    contour_width=3,
    contour_color="steelblue",
):
    if not background_color or "" == str(background_color).strip():
        background_color = "white"
    if not min_font_size or  min_font_size < 1:
        min_font_size = 4
    if not max_font_size or max_font_size < 4:
        max_font_size = 200   
    if not font_path or "" == str(font_path).strip():
        font_path = DEFAULT_FONT_PATH
    if not contour_width or contour_width < 0:
        contour_width = 3      
    if not contour_color or "" == str(contour_color).strip():
        contour_color = "steelblue"
    
    # mask_color
    if mask_color is not None:
        image_colors = ImageColorGenerator(mask_color, True)
    else:
        image_colors = ImageColorGenerator(mask_image, True)

    # Generate a word cloud image
    wordcloud = WordCloud(
        font_path=font_path,
        mask=mask_image,
        background_color=background_color,
        color_func=image_colors,
        contour_width=contour_width,
        contour_color=contour_color,
        max_words=2000, 
        margin=margin, min_font_size=min_font_size, max_font_size=max_font_size, 
        random_state=42
    ).generate(text)

    return wordcloud.to_image()
  • jieba_util.py
import jieba
# jieba.enable_parallel(4)

from consts import *

# The function for processing text with Jieba
def jieba_processing_txt(text, userdict_list=['阿Q', '孔乙己', '单四嫂子']):
    if userdict_list is not None:
        for word in userdict_list:
            jieba.add_word(word)

    mywordlist = []
    seg_list = jieba.cut(text, cut_all=False)
    liststr = "/ ".join(seg_list)

    with open(STOPWORDS_PATH, encoding='utf-8') as f_stop:
        f_stop_text = f_stop.read()
        f_stop_seg_list = f_stop_text.splitlines()

    for myword in liststr.split('/'):
        if not (myword.strip() in f_stop_seg_list) and len(myword.strip()) > 1:
            mywordlist.append(myword)
    return ' '.join(mywordlist)
  • gradio_interfaces.py
import gradio as gr

import lib_word_cloud
import jieba_util

from consts import *

def service_text2wc(
    text_file,
    text_lang,
    text_dict: str,
    background_color,
    margin,
    max_font_size,
    min_font_size,
    font_file,
    width,
    height,
    mask_image,
    mask_color,
    contour_width,
    contour_color,
):
    if not text_file:
        gr.Warning(f"请传入正确的文本文件!")
        return
    if margin < 0 :
        gr.Warning(f"字体间隔配置不合法!")
        return
    if min_font_size < 0 or max_font_size < 0 or min_font_size > max_font_size:
        gr.Warning(f"字体大小配置不合法!")
        return

    try:
        with open(file=text_file.name, encoding="utf-8") as file:
            text = file.read()
            
        if text_lang == '中文':
            gr.Info(f"选择了中文,将使用Jieba库解析文本!")
            userdict_list = []
            if text_dict is not None:
                # userdict_list = map(lambda w: w.strip(), text_dict.split(", "))
                userdict_list = [w.strip() for w in text_dict.split(",")]
            text = jieba_util.jieba_processing_txt(text, userdict_list)
            
        font_path = font_file.name if font_file else None
        
        if mask_image is not None:
            return lib_word_cloud.text2wordcount_mask(
                text,
                background_color,
                margin,
                min_font_size,
                max_font_size,
                font_path,
                mask_image,
                mask_color,
                contour_width,
                contour_color,
            )
        else:
            return lib_word_cloud.text2wordcount_normal(
                text, 
                background_color, 
                margin,
                min_font_size,
                max_font_size,
                font_path, 
                width, 
                height
            )
    except Exception as e:
        print(e)
        raise gr.Error("文本转词云图时,发生异常:" + str(e))

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 = '欢迎使用“词云转换器”!';
    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 * 200);
        })(i);
    }

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

    return 'Animation created';
}
"""

with gr.Blocks(title="词云转换器", js=js) as iface:
    with gr.Row():
        with gr.Column():
            with gr.Group():
                with gr.Row():
                    input_text_file = gr.File(label="待处理的文本文件(必填)")
                    with gr.Column():
                        gr.Label(label="Tips", value="请传入正常可读的文本文件,如以.txt结尾的文档", color="#fee2e2")
                        gr.File(value=EXAMPLE_TEXT_FILE, label="文本文件的样例")
                        input_text_lang = gr.Radio(label="文本语言模式", choices=["中文", "英文"], value="中文")
                input_text_dict = gr.Textbox(label="自定义分词词典(可选)", info="中文模式使用,多个词之间用英文逗号分隔,例如'阿Q, 孔乙己, 单四嫂子'")
            with gr.Tab("普通模式"):
                with gr.Row():
                    input_width = gr.Number(value=400, label="生成图像的宽", minimum=1)
                    input_height = gr.Number(value=200, label="生成图像的高", minimum=1)
                gr.Label(label="Tips", value="使用该模式时,记得清理掉“Mask模式”下的“Mask图像”", color="#fee2e2")
            with gr.Tab("Mask模式"):
                with gr.Row():
                    input_contour_width = gr.Number(value=3, label="轮廓线的粗细", minimum=0)
                    input_contour_color = gr.Textbox(value="steelblue", label="轮廓线的颜色")
                with gr.Row():
                    input_mask_image = gr.Image(label="Mask图像(决定词云的形状、颜色、宽高)")
                    input_mask_color = gr.Image(label="若传入该图,则词云的颜色由该图决定")
                # gr.Image(value=EXAMPLE_MASK_IMAGE_PATH, label="Mask图像的样例", interactive=False)
                gr.Gallery(value=[EXAMPLE_MASK_IMAGE_PATH, EXAMPLE_MASK_IMAGE_PATH, EXAMPLE_MASK_IMAGE_PATH], label="Mask图像的样例", interactive=False)
        with gr.Column():
            with gr.Group():
                with gr.Row():
                    with gr.Group():
                        input_bg_color = gr.Textbox(value="white", label="词云图的背景色(默认为'white')")
                        input_margin = gr.Number(value=2, label="字体间隔(默认为'2')", minimum=0)
                        with gr.Row():
                            input_min_font_size = gr.Number(value=4, label="字体大小-最小值", minimum=1)
                            input_max_font_size = gr.Number(value=200, label="字体大小-最大值", minimum=4)    
                    input_font_file = gr.File(label="词云图的字体文件(可选,如otf文件)")
                format_radio = gr.Radio(choices=["png", "jpeg", "webp", "bmp", "tiff"], label="词云图像格式", value="png")
            submit_button = gr.Button("开始处理", variant="primary")
            output_image = gr.Image(label="词云图", format="png")

    def fix_format(x):
        output_image.format = x 
        return None

    format_radio.change(fn=fix_format, inputs=format_radio)

    submit_button.click(
        fn=service_text2wc,
        inputs=[
            input_text_file,
            input_text_lang,
            input_text_dict,
            input_bg_color,
            input_margin,
            input_max_font_size,
            input_min_font_size,
            input_font_file,
            input_width,
            input_height,
            input_mask_image,
            input_mask_color,
            input_contour_width,
            input_contour_color,
        ],
        outputs=output_image,
    )

  • consts.py,记得修改下下面文件的地址,和resource目录对应
# 样例文本
EXAMPLE_TEXT_FILE = r".\wordcloud-webui\resources\CalltoArms.txt"
# MASK图像样例
EXAMPLE_MASK_IMAGE_PATH = r".\wordcloud-webui\resources\parrot_mask.png "
# 分词器的 stop word 库
STOPWORDS_PATH = r".\wordcloud-webui\resources\stopwords_cn_en.txt"
# 词云图的默认字体
DEFAULT_FONT_PATH = r".\wordcloud-webui\resources\SourceHanSerifK-Light.otf"

  • resources 目录
    • parrot_mask.png parrot_mask.png
    • CalltoArms.txt https://github.com/amueller/word_cloud/blob/main/examples/wc_cn/CalltoArms.txt
    • SourceHanSerifK-Light.otf https://github.com/amueller/word_cloud/blob/main/examples/fonts/SourceHanSerif/SourceHanSerifK-Light.otf
    • stopwords_cn_en.txt https://github.com/amueller/word_cloud/blob/main/examples/wc_cn/stopwords_cn_en.txt

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/687969.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

AI产品经理岗位需求量大吗?好找工作吗?

前言 在当今这个科技日新月异的时代&#xff0c;人工智能&#xff08;AI&#xff09;已不再仅仅是一个遥远的概念&#xff0c;而是深深嵌入到我们生活的方方面面&#xff0c;从日常的语音助手到复杂的自动驾驶系统&#xff0c;AI的触角无处不在。随着AI技术的广泛应用和持续进…

kettle列转行(行扁平化)的使用

kettle行扁平化节点是将多行数据合并为一行数据如&#xff0c;其行为类似于css中的float排列 将上表格数据转换为下表格数据 namecategorynumjack语文10jack数学20jack英语40rose英语50 name语文数学英语jack102040rose50 使用行扁平化节点配置需要扁平化的字段&#xff0c…

泛微开发修炼之旅--09Ecology作为所有异构系统的待办中心,实现与kafka对接源码及示例

文章链接&#xff1a;泛微开发修炼之旅--09Ecology作为所有异构系统的待办中心&#xff0c;实现与kafka对接源码及示例

龙迅LT6911GX HDMI 2.1桥接到四 PORT MIPI或者LVDS,支持图像处理以及旋转,内置MCU以及LPDDR4

龙迅LT6911GX描述&#xff1a; LT6911GX是一款高性能的HDMI2.1到MIPI或LVDS芯片&#xff0c;用于VR/显示器应用。HDCP RX作为HDCP中继器的上游端&#xff0c;可以与其他芯片的HDCP TX协同工作&#xff0c;实现中继器的功能。对于HDMI2.1输入&#xff0c;LT6911GX可配置为3/4车…

JavaScript的核心语法

JavaScript JavaScript&#xff1a;JavaScript的组成&#xff1a;核心语法&#xff1a;Hello&#xff1a;变量&#xff1a;JS的基本数据类型&#xff1a;特殊点&#xff1a; 数组&#xff1a;流程控制语句&#xff1a;函数&#xff1a;函数的重载&#xff1a;函数的递归:预定义…

python-windows10普通笔记本跑bert mrpc数据样例0.1.001

python-windows10普通笔记本跑bert mrpc数据样例0.1.000 背景参考章节获取数据下载bert模型下载bert代码windows10的cpu执行结果注意事项TODOLIST背景 看了介绍说可以在gpu或者tpu上去微调,当前没环境,所以先在windows10上跑一跑,看是否能顺利进行,目标就是训练的过程中没…

WWDC24即将到来,ios18放大招

苹果公司即将在下周开全球开发者大会(WWDC)&#xff0c;大会上将展示其人工智能技术整合到设备和软件中的重大进展,包括与OpenAI的历史性合作。随着大会的临近,有关iOS 18及其据称采用AI技术支持的应用程序和功能的各种泄露信息已经浮出水面。 据报道,苹果将利用其自主研发的大…

WPF国际化的最佳实践

WPF国际化的最佳实践 1.创建项目资源文件 如果你的项目没有Properties文件夹和Resources.resx文件&#xff0c;可以通过右键项目-资源-常规-添加创建或打开程序集资源 2.添加国际化字符串 打开Resources.resx文件&#xff0c;添加需要翻译的文本字符&#xff0c;并将访问修…

深入了解 Postman 中的变量

在我们进行 API 开发和测试时&#xff0c;使用诸如 Postman 之类的工具可以极大地简化工作流程&#xff0c;提高效率。Postman 的一个强大功能就是变量&#xff08;Variables&#xff09;。利用变量&#xff0c;我们可以使我们的请求变得更加动态和灵活&#xff0c;避免重复输入…

计算机组成实验---Cache的实现

直接映射 先看懂cache的映射原理&#xff0c;根据cache大小与主存大小来计算各个信号线的位数 各个信号线位数 主存地址在逻辑上分为区号、块号、块内地址 Cache结构 Cache访问原理 基本过程 状态机&#xff1a;“三段式”实现 6.3 Verilog 状态机 | 菜鸟教程 (runoob.com) …

问题:当频点数大于载波数时,() #学习方法#知识分享

问题&#xff1a;当频点数大于载波数时&#xff0c;&#xff08;&#xff09; A.基带跳频可以执行&#xff0c;混合跳频可以执行 B.基带跳频不可以执行&#xff0c;混合跳频可以执行 C.基带跳频可以执行&#xff0c;混合跳频不可以执行 D.基带跳频不可以执行&#xff0c;混…

2024-06-07 Unity 编辑器开发之编辑器拓展8 —— Scene 窗口拓展

文章目录 1 Handles 类1.1 Scene 响应函数1.2 自定义窗口中监听 Scene1.3 Handles 常用 API2.2.1 颜色控制2.2.2 文本2.2.3 线段2.2.4 虚线2.2.5 圆弧2.2.6 圆2.2.7 立方体2.2.8 几何体2.2.9 移动、旋转、缩放2.2.10 自由移动 / 旋转 2 Scene 窗口中显示 GUI3 HandleUtility4 G…

React 18

创建 React 18 脚手架项目 全局安装 create-react-app npm install -g create-react-app yarn global add create-react-app . 确认是否已安装 create-react-app npm list -g create-react-app yarn global list | grep create-react-app . 如果安装失败 有时&#xff0…

YOLOv8---seg实例分割(制作数据集,训练模型,预测结果)

YOLOv8----seg实例分割&#xff08;制作数据集&#xff0c;训练模型&#xff0c;预测结果&#xff09; 内容如下&#xff1a;【需要软件及工具&#xff1a;pycharm、labelme、anaconda、云主机&#xff08;跑训练&#xff09;】 1.制作自己的数据集 2.在yolo的预训练模型的基础…

Linux系统下 安装 Nginx

一、下载Nginx安装包 压缩包下载地址&#xff1a;nginx: download 服务器有外网&#xff0c;可直接使用命令下载 wget -c https://nginx.org/download/nginx-1.24.0.tar.gz 二、安装Nginx 1、解压 tar -zxvf nginx-1.24.0.tar.gz 2、安装Nginx所需依赖 yum install -y gc…

顶顶通呼叫中心中间件-asr录音路径修改(mod_cti基于FreeSWITCH)

顶顶通呼叫中心中间件-asr录音路径修改(mod_cti基于FreeSWITCH) 录音路径模板。如果不是绝对路径&#xff0c;会把这个路径追加到FreeSWITCH的recordings后面。支持变量&#xff0c;比如日期 ${strftime(%Y-%m-%d)}。最后一个录音文件路径会保存到变量 ${cti_asr_last_record_…

[职场] 项目实施工程师的工作前景 #笔记#经验分享

项目实施工程师的工作前景 项目实施工程师是负责将软件产品或解决方案实施到客户现场并确保项目成功落地的工作岗位。他们要负责整个项目的规划、组织、执行和控制&#xff0c;确保项目按照预定的进度、质量和预算完成。 一&#xff0e;工作内容 1. 项目规划&#xff1a;确定…

docker部署fastdfs

我的镜像包地址 链接&#xff1a;https://pan.baidu.com/s/1j5E5O1xdyQVfJhsOevXvYg?pwdhcav 提取码&#xff1a;hcav docker load -i gofast.tar.gz拉取gofast docker pull sjqzhang/go-fastdfs启动gofast docker run -d --name fastdfs -p 8080:8080 -v /opt/lijia/lijia…

耐酸碱腐蚀可溶性聚四氟乙烯(PFA)溶样罐

PFA溶样罐也叫PFA溶样瓶&#xff0c;可直接放在加热板上及油浴里加热&#xff0c;也可液氮下长期保存&#xff0c;使用温度-200—260℃。 根据不同实验的需求&#xff0c;PFA溶样罐有U型、V型、平底3种设计。V型底的设计&#xff0c;更加方便少量样品的集中收集。溶样罐广泛用…

Linux-桌面操作系统在服务器上未关闭休眠机制,使其开机半小时左右死机无法远程ssh连接

故障表述 操作系统:ubuntu desktop 18.04 异常描述:开机半小时左右死机 1、登录iBMC查看硬件无异常 2、登录ubuntu desktop 18.04操作系统,导出日志文件syslog、dmesg、lastlog(路径:/var/log),操作系统在11月8号~11月9号之间出现异常 经分析操作系统日志文件,操作系…