|
import gradio as gr |
|
from collections import Counter |
|
import string |
|
import csv |
|
import io |
|
|
|
|
|
|
|
def process_text(text, sorting_option): |
|
|
|
translator = str.maketrans('', '', string.punctuation) |
|
text = text.translate(translator) |
|
|
|
words = text.split() |
|
|
|
|
|
word_counts = Counter(words) |
|
|
|
|
|
if sorting_option == 'alphabetically': |
|
sorted_words = sorted(word_counts.items(), key=lambda x: x[0]) |
|
elif sorting_option == 'by_frequency': |
|
sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True) |
|
else: |
|
sorted_words = word_counts.items() |
|
|
|
|
|
top_5_words = sorted_words |
|
|
|
|
|
table_html = "<table style='width:100%'><tr><th>Index</th><th>Word</th><th>Frequency</th></tr>" |
|
for index, (word, freq) in enumerate(top_5_words, start=1): |
|
table_html += f"<tr><td>{index}</td><td>{word}</td><td>{freq}</td></tr>" |
|
table_html += "</table>" |
|
|
|
|
|
csv_data = [["Index", "Word", "Frequency"]] |
|
for index, (word, freq) in enumerate(top_5_words, start=1): |
|
csv_data.append([index, word, freq]) |
|
|
|
|
|
csv_buffer = io.StringIO() |
|
csv_writer = csv.writer(csv_buffer) |
|
csv_writer.writerows(csv_data) |
|
csv_buffer.seek(0) |
|
|
|
|
|
csv_download_link = f"<a href='data:application/csv;charset=utf-8,{csv_buffer.getvalue()}' download='word_frequencies.csv'>Download CSV</a>" |
|
|
|
|
|
div_with_scroll = f"<div style='height: 200px; overflow-y: scroll;'>{table_html}</div>" |
|
|
|
return div_with_scroll, csv_download_link |
|
|
|
iface = gr.Interface( |
|
fn=process_text, |
|
inputs=[gr.Textbox("text", label="Paste Text Here"), |
|
gr.Radio(["alphabetically", "by_frequency", "none"], label="Select Sorting Option")], |
|
outputs=[gr.HTML(label="Top 5 Words with Frequencies"), gr.HTML(label="Download CSV")] |
|
) |
|
|
|
iface.launch(share=True) |
|
|