earlyai / app.py
kevin1911's picture
Update app.py
dcf7837 verified
import gradio as gr
import re
# Global storage: user-defined rule + classification history
positive_keywords = []
classification_history = []
def parse_rule(rule_text):
"""
Parse the comma-separated string of positive words, e.g. "amazing, good".
Store them in a global list as lowercase.
"""
global positive_keywords
if rule_text.strip():
words = [w.strip().lower() for w in rule_text.split(',')]
positive_keywords = words
else:
positive_keywords = []
def rule_based_classify(text, positive_words):
"""
If the text contains ANY of the words in positive_words,
classify as Positive; otherwise Negative.
"""
lowered = text.lower()
for word in positive_words:
if word in lowered:
return "Positive"
return "Negative"
def classify_with_rule(rule_input, statement):
"""
1) Parse the user-defined rule (comma-separated keywords).
2) Classify the statement with the updated rule.
3) Append to classification history and return an HTML table.
"""
global classification_history
# 1) Update our global 'positive_keywords'
parse_rule(rule_input)
# 2) Classify the user's statement
if statement.strip():
label = rule_based_classify(statement, positive_keywords)
classification_history.append((statement, label))
else:
# If no statement was provided, do nothing new
label = None
# Build an HTML table of the classification history
html_table = """
<table style="border-collapse: collapse;">
<tr>
<th style="border:1px solid #ccc; padding:8px;">Statement</th>
<th style="border:1px solid #ccc; padding:8px;">Classification</th>
</tr>
"""
for stmt, cls in classification_history:
color = "green" if cls == "Positive" else "red"
html_table += f"""
<tr>
<td style="border:1px solid #ccc; padding:8px;">{stmt}</td>
<td style="border:1px solid #ccc; padding:8px; color:{color};"><b>{cls}</b></td>
</tr>
"""
html_table += "</table>"
explanation = """
<br>
<h4>Discussion (Rule-Based AI):</h4>
<ul>
<li><b>Pros:</b> You decide the keywords. If they're present, it's "Positive." Otherwise "Negative."</li>
<li><b>Cons:</b> If your sentence doesn't contain <i>exactly</i> those keywords, it gets classified incorrectly.
Real-world language has many synonyms and nuances that this rule won't catch.</li>
</ul>
"""
# Return the combined HTML
return html_table + explanation
# Create a Gradio interface
demo = gr.Interface(
fn=classify_with_rule, # function to call
inputs=[
gr.Textbox(label="Define Rule (comma-separated positive words)", lines=1),
gr.Textbox(label="Statement to Classify", lines=2)
],
outputs=gr.HTML(label="Classification History"),
title="Traditional Rule-Based AI Demo",
css="footer{display:none !important}",
description=(
"1) In the first box, type comma-separated words you consider 'positive'.\n"
"2) In the second box, type a statement to classify.\n"
"Click 'Submit' to see how the statement is labeled.\n\n"
"You'll see a growing table of all statements you've classified so far."
)
)
# Launch the Gradio app
demo.launch()