Files changed (1) hide show
  1. app.py +32 -25
app.py CHANGED
@@ -7,10 +7,17 @@ API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-b
7
  headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
8
 
9
  def query(payload):
10
- response = requests.post(API_URL, headers=headers, json=payload)
11
- return response.json()
 
 
 
 
12
 
13
  def classify_news(chat_history, user_input):
 
 
 
14
  prompt = (
15
  f"You are a fake news classifier. Respond with 'Answer: Real' or 'Answer: Fake'.\n"
16
  f"Statement: {user_input}"
@@ -23,8 +30,14 @@ def classify_news(chat_history, user_input):
23
  "do_sample": False
24
  }
25
  })
 
26
  try:
27
- result = output[0]["generated_text"].split("Answer:")[-1].strip().split()[0]
 
 
 
 
 
28
  if result.lower().startswith("real"):
29
  result = "🟒 Real"
30
  elif result.lower().startswith("fake"):
@@ -33,45 +46,39 @@ def classify_news(chat_history, user_input):
33
  result = "⚠️ Unclear"
34
  except Exception:
35
  result = "❌ Error: Could not get a response."
36
- chat_history.append((user_input, result))
 
 
 
37
  return chat_history, ""
38
 
39
- with gr.Blocks(theme=gr.themes.Soft(), css="""
40
- .chatbot {background-color: #0d1117; border-radius: 10px; padding: 10px;}
41
- .message.user {background-color: #1f6feb; color: white; padding: 8px; border-radius: 10px;}
42
- .message.bot {background-color: #21262d; color: #c9d1d9; padding: 8px; border-radius: 10px;}
43
- #submit-button {background-color: #2ea043; color: white; font-weight: bold; transition: background-color 0.3s ease-in-out;}
44
- #submit-button:hover {background-color: #239139;}
45
- #clear-button {background-color: #e5534b; color: white; font-weight: bold; transition: background-color 0.3s ease-in-out;}
46
- #clear-button:hover {background-color: #c8433b;}
47
- .toggle-label {color: #c9d1d9; margin-top: 1rem;}
48
- """) as demo:
49
  gr.Markdown("""
50
  # πŸ“° Fake News Detector Chat
51
  _Classify news as **Real** or **Fake** using a GPT-style model._
52
  """)
53
 
54
- chatbot = gr.Chatbot(type="messages",label="🧠 Chatbot", elem_classes=["chatbot"])
55
  with gr.Row():
56
  user_input = gr.Textbox(placeholder="Type or paste a news statement here...", scale=6)
57
  clear_btn = gr.Button("🧹 Clear", elem_id="clear-button")
58
-
59
  submit_btn = gr.Button("πŸš€ Classify", elem_id="submit-button", scale=2)
60
-
61
  with gr.Row():
62
  audio = gr.Audio(type="filepath", label="🎀 Speak News", interactive=True)
63
  export_btn = gr.Button("⬇️ Export Chat")
64
-
65
  toggle_dark_mode = gr.Checkbox(label="πŸŒ— Toggle Dark Mode", value=True)
66
 
67
- def export_chat(chat_history):
68
- export_text = "\n".join([f"User: {u}\nModel: {r}" for u, r in chat_history])
69
- with open("chat_log.txt", "w") as f:
70
- f.write(export_text)
71
- return "chat_log.txt"
72
-
73
  submit_btn.click(classify_news, inputs=[chatbot, user_input], outputs=[chatbot, user_input])
74
- clear_btn.click(lambda: [], None, chatbot)
75
  export_btn.click(export_chat, inputs=[chatbot], outputs=gr.File(label="Download Log"))
76
 
77
  demo.launch()
 
7
  headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
8
 
9
  def query(payload):
10
+ try:
11
+ response = requests.post(API_URL, headers=headers, json=payload)
12
+ response.raise_for_status()
13
+ return response.json()
14
+ except Exception as e:
15
+ return [{"generated_text": f"Error: {str(e)}"}]
16
 
17
  def classify_news(chat_history, user_input):
18
+ if not user_input or not user_input.strip():
19
+ return chat_history, ""
20
+
21
  prompt = (
22
  f"You are a fake news classifier. Respond with 'Answer: Real' or 'Answer: Fake'.\n"
23
  f"Statement: {user_input}"
 
30
  "do_sample": False
31
  }
32
  })
33
+
34
  try:
35
+ model_output = output[0]["generated_text"]
36
+ # Robust parsing -- finds "Answer: Real" or "Answer: Fake"
37
+ if "Answer:" in model_output:
38
+ result = model_output.split("Answer:")[-1].strip().split()[0]
39
+ else:
40
+ result = model_output.strip().split()[0]
41
  if result.lower().startswith("real"):
42
  result = "🟒 Real"
43
  elif result.lower().startswith("fake"):
 
46
  result = "⚠️ Unclear"
47
  except Exception:
48
  result = "❌ Error: Could not get a response."
49
+
50
+ chat_history = chat_history or []
51
+ chat_history.append({"role": "user", "content": user_input})
52
+ chat_history.append({"role": "assistant", "content": result})
53
  return chat_history, ""
54
 
55
+ def export_chat(chat_history):
56
+ export_text = ""
57
+ for message in chat_history:
58
+ role = "User" if message["role"] == "user" else "Model"
59
+ export_text += f"{role}: {message['content']}\n"
60
+ with open("chat_log.txt", "w") as f:
61
+ f.write(export_text.strip())
62
+ return "chat_log.txt"
63
+
64
+ with gr.Blocks(theme=gr.themes.Soft(), css="""...""") as demo:
65
  gr.Markdown("""
66
  # πŸ“° Fake News Detector Chat
67
  _Classify news as **Real** or **Fake** using a GPT-style model._
68
  """)
69
 
70
+ chatbot = gr.Chatbot(type="messages", label="🧠 Chatbot", elem_classes=["chatbot"])
71
  with gr.Row():
72
  user_input = gr.Textbox(placeholder="Type or paste a news statement here...", scale=6)
73
  clear_btn = gr.Button("🧹 Clear", elem_id="clear-button")
 
74
  submit_btn = gr.Button("πŸš€ Classify", elem_id="submit-button", scale=2)
 
75
  with gr.Row():
76
  audio = gr.Audio(type="filepath", label="🎀 Speak News", interactive=True)
77
  export_btn = gr.Button("⬇️ Export Chat")
 
78
  toggle_dark_mode = gr.Checkbox(label="πŸŒ— Toggle Dark Mode", value=True)
79
 
 
 
 
 
 
 
80
  submit_btn.click(classify_news, inputs=[chatbot, user_input], outputs=[chatbot, user_input])
81
+ clear_btn.click(lambda: ([], ""), None, [chatbot, user_input])
82
  export_btn.click(export_chat, inputs=[chatbot], outputs=gr.File(label="Download Log"))
83
 
84
  demo.launch()