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 = """ """ for stmt, cls in classification_history: color = "green" if cls == "Positive" else "red" html_table += f""" """ html_table += "
Statement Classification
{stmt} {cls}
" explanation = """

Discussion (Rule-Based AI):

""" # 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()