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

2024-06-02 12:28

本文主要是介绍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 ifaceif __name__ == "__main__":iface.launch()
  • lib_word_cloud.py
from wordcloud import WordCloud, ImageColorGenerator
import numpy as np
from PIL import Imagefrom 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 = 4if 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_PATHif not width or width < 1:width = 400if not height or height < 1:height = 200 # Generate a word cloud imagewordcloud = 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 = 4if 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_PATHif not contour_width or contour_width < 0:contour_width = 3      if not contour_color or "" == str(contour_color).strip():contour_color = "steelblue"# mask_colorif mask_color is not None:image_colors = ImageColorGenerator(mask_color, True)else:image_colors = ImageColorGenerator(mask_image, True)# Generate a word cloud imagewordcloud = 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 grimport lib_word_cloud
import jieba_utilfrom 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"请传入正确的文本文件!")returnif margin < 0 :gr.Warning(f"字体间隔配置不合法!")returnif min_font_size < 0 or max_font_size < 0 or min_font_size > max_font_size:gr.Warning(f"字体大小配置不合法!")returntry: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 Noneif 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 Noneformat_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

这篇关于Gradio 案例——将文本文件转为词云图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1023964

相关文章

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

Python get()函数用法案例详解

《Pythonget()函数用法案例详解》在Python中,get()是字典(dict)类型的内置方法,用于安全地获取字典中指定键对应的值,它的核心作用是避免因访问不存在的键而引发KeyError错... 目录简介基本语法一、用法二、案例:安全访问未知键三、案例:配置参数默认值简介python是一种高级编

MySQL中的索引结构和分类实战案例详解

《MySQL中的索引结构和分类实战案例详解》本文详解MySQL索引结构与分类,涵盖B树、B+树、哈希及全文索引,分析其原理与优劣势,并结合实战案例探讨创建、管理及优化技巧,助力提升查询性能,感兴趣的朋... 目录一、索引概述1.1 索引的定义与作用1.2 索引的基本原理二、索引结构详解2.1 B树索引2.2

从入门到精通MySQL 数据库索引(实战案例)

《从入门到精通MySQL数据库索引(实战案例)》索引是数据库的目录,提升查询速度,主要类型包括BTree、Hash、全文、空间索引,需根据场景选择,建议用于高频查询、关联字段、排序等,避免重复率高或... 目录一、索引是什么?能干嘛?核心作用:二、索引的 4 种主要类型(附通俗例子)1. BTree 索引(

HTML中meta标签的常见使用案例(示例详解)

《HTML中meta标签的常见使用案例(示例详解)》HTMLmeta标签用于提供文档元数据,涵盖字符编码、SEO优化、社交媒体集成、移动设备适配、浏览器控制及安全隐私设置,优化页面显示与搜索引擎索引... 目录html中meta标签的常见使用案例一、基础功能二、搜索引擎优化(seo)三、社交媒体集成四、移动

Springboot3+将ID转为JSON字符串的详细配置方案

《Springboot3+将ID转为JSON字符串的详细配置方案》:本文主要介绍纯后端实现Long/BigIntegerID转为JSON字符串的详细配置方案,s基于SpringBoot3+和Spr... 目录1. 添加依赖2. 全局 Jackson 配置3. 精准控制(可选)4. OpenAPI (Spri

六个案例搞懂mysql间隙锁

《六个案例搞懂mysql间隙锁》MySQL中的间隙是指索引中两个索引键之间的空间,间隙锁用于防止范围查询期间的幻读,本文主要介绍了六个案例搞懂mysql间隙锁,具有一定的参考价值,感兴趣的可以了解一下... 目录概念解释间隙锁详解间隙锁触发条件间隙锁加锁规则案例演示案例一:唯一索引等值锁定存在的数据案例二:

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.

MySQL 表的内外连接案例详解

《MySQL表的内外连接案例详解》本文给大家介绍MySQL表的内外连接,结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录表的内外连接(重点)内连接外连接表的内外连接(重点)内连接内连接实际上就是利用where子句对两种表形成的笛卡儿积进行筛选,我