Sujana85 commited on
Commit
73c2c7e
Β·
verified Β·
1 Parent(s): 19ce028

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -60
app.py CHANGED
@@ -1,64 +1,109 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
3
+ import matplotlib.pyplot as plt
4
+ import seaborn as sns
5
+ import pandas as pd
6
+ import torch
7
+
8
+ # Load model
9
+ model_id = "ibm-granite/granite-3b-code-instruct" # Replace with actual granite model if different
10
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
11
+ model = AutoModelForCausalLM.from_pretrained(
12
+ model_id,
13
+ device_map="auto",
14
+ torch_dtype=torch.float16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  )
16
 
17
+ # Load sentiment analysis model
18
+ sentiment_analyzer = pipeline("sentiment-analysis")
19
+
20
+ # Simulated citizen profiles
21
+ user_profiles = {
22
+ "1001": {"location": "Hyderabad", "issues": ["traffic", "air pollution"]},
23
+ "1002": {"location": "Delhi", "issues": ["waste management", "noise"]},
24
+ }
25
+
26
+ # Store submitted feedback during session
27
+ submitted_data = []
28
+
29
+ # Chat Function (ChatGPT-style)
30
+ def chat_fn(message, history):
31
+ full_prompt = tokenizer.apply_chat_template(
32
+ [{"role": "user", "content": message}],
33
+ tokenize=False,
34
+ add_generation_prompt=True
35
+ )
36
+ inputs = tokenizer(full_prompt, return_tensors="pt").to(model.device)
37
+ outputs = model.generate(**inputs, max_new_tokens=200)
38
+ reply = tokenizer.decode(outputs[0], skip_special_tokens=True).split("assistant")[-1].strip()
39
+ return reply
40
+
41
+ # Sentiment Analysis
42
+ def analyze_sentiment(text):
43
+ result = sentiment_analyzer(text)[0]
44
+ return f"{result['label']} ({result['score']*100:.2f}%)"
45
+
46
+ # Live Feedback β†’ Dashboard
47
+ def collect_and_plot_feedback(comment, category):
48
+ sentiment = sentiment_analyzer(comment)[0]["label"]
49
+ submitted_data.append({"Category": category, "Sentiment": sentiment})
50
+
51
+ df = pd.DataFrame(submitted_data)
52
+ summary = df.groupby(['Category', 'Sentiment']).size().unstack(fill_value=0)
53
+
54
+ fig, ax = plt.subplots(figsize=(8, 5))
55
+ summary.plot(kind='bar', stacked=True, ax=ax, colormap="Set2")
56
+ plt.title("Live Citizen Sentiment by Category")
57
+ plt.ylabel("Count")
58
+ plt.tight_layout()
59
+ return f"Recorded sentiment: {sentiment}", fig
60
+
61
+ # Personalized Contextual Assistant
62
+ def personalized_response(user_id, query):
63
+ profile = user_profiles.get(user_id)
64
+ if not profile:
65
+ return "User profile not found. Please check your user ID."
66
+ context = f"User from {profile['location']} concerned with: {', '.join(profile['issues'])}. Question: {query}"
67
+ input_tokens = tokenizer(context, return_tensors="pt").to(model.device)
68
+ output = model.generate(**input_tokens, max_new_tokens=150)
69
+ return tokenizer.decode(output[0], skip_special_tokens=True)
70
+
71
+ # Build Gradio App
72
+ with gr.Blocks(title="Citizen AI – Intelligent Citizen Engagement Platform") as demo:
73
+ gr.Markdown("## 🧠 Citizen AI – Intelligent Citizen Engagement Platform")
74
+
75
+ with gr.Tab("πŸ€– Chat Assistant"):
76
+ gr.ChatInterface(
77
+ fn=chat_fn,
78
+ title="🧠 Ask Citizen AI",
79
+ theme="soft",
80
+ chatbot=gr.Chatbot(label="Citizen Chat"),
81
+ textbox=gr.Textbox(placeholder="Type your question here...", show_label=False),
82
+ retry_btn="πŸ” Retry",
83
+ clear_btn="πŸ—‘οΈ Clear",
84
+ submit_btn="➀ Send"
85
+ )
86
+
87
+ with gr.Tab("πŸ“Š Sentiment Analysis"):
88
+ sentiment_input = gr.Textbox(label="Enter citizen comment")
89
+ sentiment_output = gr.Textbox(label="Sentiment Result")
90
+ analyze_btn = gr.Button("Analyze")
91
+ analyze_btn.click(analyze_sentiment, inputs=sentiment_input, outputs=sentiment_output)
92
+
93
+ with gr.Tab("πŸ“ˆ Live Dashboard"):
94
+ gr.Markdown("### πŸ“¬ Submit Feedback and Watch Sentiment Grow Live")
95
+ comment_input = gr.Textbox(label="Citizen Feedback")
96
+ category_input = gr.Dropdown(choices=["Healthcare", "Sanitation", "Transport", "Education"], label="Category")
97
+ submit_button = gr.Button("Submit Feedback")
98
+ sentiment_display = gr.Textbox(label="Detected Sentiment")
99
+ live_chart = gr.Plot(label="Live Sentiment Chart")
100
+ submit_button.click(collect_and_plot_feedback, inputs=[comment_input, category_input], outputs=[sentiment_display, live_chart])
101
+
102
+ with gr.Tab("🧬 Personalized AI Response"):
103
+ uid_input = gr.Textbox(label="User ID (e.g., 1001)")
104
+ query_input = gr.Textbox(label="Your query")
105
+ response_output = gr.Textbox(label="AI Response")
106
+ personal_btn = gr.Button("Generate Personalized Response")
107
+ personal_btn.click(personalized_response, inputs=[uid_input, query_input], outputs=response_output)
108
 
109
+ demo.launch(share=True)