Mohammed Thameem commited on
Commit
7ae423d
·
1 Parent(s): 49e9e54

modified test script

Browse files
Files changed (1) hide show
  1. app.py +96 -118
app.py CHANGED
@@ -2,23 +2,12 @@ import os
2
  import gradio as gr
3
  from huggingface_hub import InferenceClient
4
 
5
- HF_TOKEN = os.getenv("HF_TOKEN")
6
-
7
  EMISSIONS_FACTORS = {
8
- "transportation": {
9
- "car": 2.3,
10
- "bus": 0.1,
11
- "train": 0.04,
12
- "plane": 0.25,
13
- },
14
- "food": {
15
- "meat": 6.0,
16
- "vegetarian": 1.5,
17
- "vegan": 1.0,
18
- }
19
  }
20
 
21
-
22
  def calculate_footprint(car_km, bus_km, train_km, air_km,
23
  meat_meals, vegetarian_meals, vegan_meals):
24
  transport_emissions = (
@@ -27,28 +16,33 @@ def calculate_footprint(car_km, bus_km, train_km, air_km,
27
  train_km * EMISSIONS_FACTORS["transportation"]["train"] +
28
  air_km * EMISSIONS_FACTORS["transportation"]["plane"]
29
  )
30
-
31
  food_emissions = (
32
  meat_meals * EMISSIONS_FACTORS["food"]["meat"] +
33
  vegetarian_meals * EMISSIONS_FACTORS["food"]["vegetarian"] +
34
  vegan_meals * EMISSIONS_FACTORS["food"]["vegan"]
35
  )
36
-
37
  total_emissions = transport_emissions + food_emissions
38
-
39
  stats = {
40
- "trees": round(total_emissions / 21),
41
- "flights": round(total_emissions / 500),
42
- "driving100km": round(total_emissions / 230),
43
  }
44
-
45
  return total_emissions, stats
46
 
 
 
 
 
 
 
 
47
 
 
48
  def respond(
49
  message,
50
  history: list[dict[str, str]],
51
- system_message,
 
52
  car_km,
53
  bus_km,
54
  train_km,
@@ -57,110 +51,94 @@ def respond(
57
  vegetarian_meals,
58
  vegan_meals,
59
  ):
60
- client = InferenceClient(token=HF_TOKEN, model="openai/gpt-oss-20b")
61
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  footprint, stats = calculate_footprint(
63
  car_km, bus_km, train_km, air_km,
64
  meat_meals, vegetarian_meals, vegan_meals
65
  )
66
 
67
- custom_prompt = f"""
68
- This user’s estimated weekly footprint is **{footprint:.1f} kg CO2**.
69
- That’s equivalent to planting about {stats['trees']} trees 🌳 or taking {stats['flights']} short flights ✈️.
70
- Their breakdown includes both transportation and food habits.
71
- Your job is to guide them with practical, encouraging suggestions to lower this footprint.
72
- {system_message}
73
- """
74
-
75
- max_tokens = 512
76
- temperature = 0.7
77
- top_p = 0.95
78
 
 
79
  messages = [{"role": "system", "content": custom_prompt}]
80
- messages.extend(history)
81
  messages.append({"role": "user", "content": message})
82
 
83
- response = ""
84
- for message in client.chat_completion(
85
- messages,
86
- max_tokens=max_tokens,
87
- stream=True,
88
- temperature=temperature,
89
- top_p=top_p,
90
- ):
91
- choices = message.choices
92
- token = ""
93
- if len(choices) and choices[0].delta.content:
94
- token = choices[0].delta.content
95
- response += token
96
- yield response
97
-
98
-
99
- system_prompt = """
100
- You are Sustainable.ai, a friendly, encouraging, and knowledgeable AI assistant...
101
- (omit full content for brevity – use your full prompt here)
102
- """
103
-
104
-
105
- with gr.Blocks(css="""
106
- body {
107
- background: linear-gradient(135deg, #e0f7fa, #f1f8e9);
108
- }
109
- .section-card {
110
- background: white;
111
- padding: 20px;
112
- border-radius: 15px;
113
- box-shadow: 0px 4px 12px rgba(0,0,0,0.1);
114
- margin-bottom: 20px;
115
- }
116
- .title-text {
117
- text-align: center;
118
- font-size: 28px;
119
- font-weight: bold;
120
- color: #2e7d32;
121
- }
122
- .subtitle-text {
123
- text-align: center;
124
- font-size: 16px;
125
- color: #555;
126
- margin-bottom: 20px;
127
- }
128
- """) as demo:
129
-
130
- with gr.Column():
131
- gr.HTML("<div class='title-text'>🌍 Eco Wise AI</div>")
132
- gr.HTML("<div class='subtitle-text'>Track your weekly habits and chat with your personal sustainability coach 🌱</div>")
133
-
134
- with gr.Group(elem_classes="section-card"):
135
- gr.Markdown("### 🚗 Transportation (per week)")
136
- with gr.Row():
137
- car_input = gr.Number(label="🚘 Car Travel (km)", value=0)
138
- bus_input = gr.Number(label="🚌 Bus Travel (km)", value=0)
139
- with gr.Row():
140
- train_input = gr.Number(label="🚆 Train Travel (km)", value=0)
141
- air_input = gr.Number(label="✈️ Air Travel (km/month)", value=0)
142
-
143
- with gr.Group(elem_classes="section-card"):
144
- gr.Markdown("### 🍽️ Food Habits (per week)")
145
- with gr.Row():
146
- meat_input = gr.Number(label="🥩 Meat Meals", value=0)
147
- vegetarian_input = gr.Number(label="🥗 Vegetarian Meals", value=0)
148
- vegan_input = gr.Number(label="🌱 Vegan Meals", value=0)
149
-
150
- chatbot = gr.ChatInterface(
151
- respond,
152
- type="messages",
153
- additional_inputs=[
154
- gr.Textbox(value=system_prompt, visible=False),
155
- car_input,
156
- bus_input,
157
- train_input,
158
- air_input,
159
- meat_input,
160
- vegetarian_input,
161
- vegan_input,
162
- ],
163
- )
164
 
165
  if __name__ == "__main__":
166
- demo.launch()
 
2
  import gradio as gr
3
  from huggingface_hub import InferenceClient
4
 
5
+ # --- Emissions factors --------------------------------------------------------
 
6
  EMISSIONS_FACTORS = {
7
+ "transportation": {"car": 2.3, "bus": 0.1, "train": 0.04, "plane": 0.25},
8
+ "food": {"meat": 6.0, "vegetarian": 1.5, "vegan": 1.0},
 
 
 
 
 
 
 
 
 
9
  }
10
 
 
11
  def calculate_footprint(car_km, bus_km, train_km, air_km,
12
  meat_meals, vegetarian_meals, vegan_meals):
13
  transport_emissions = (
 
16
  train_km * EMISSIONS_FACTORS["transportation"]["train"] +
17
  air_km * EMISSIONS_FACTORS["transportation"]["plane"]
18
  )
 
19
  food_emissions = (
20
  meat_meals * EMISSIONS_FACTORS["food"]["meat"] +
21
  vegetarian_meals * EMISSIONS_FACTORS["food"]["vegetarian"] +
22
  vegan_meals * EMISSIONS_FACTORS["food"]["vegan"]
23
  )
 
24
  total_emissions = transport_emissions + food_emissions
 
25
  stats = {
26
+ "trees": round(total_emissions / 21),
27
+ "flights": round(total_emissions / 500),
28
+ "driving100km": round(total_emissions / 230)
29
  }
 
30
  return total_emissions, stats
31
 
32
+ # --- Default system prompt ----------------------------------------------------
33
+ DEFAULT_SYSTEM_PROMPT = """
34
+ You are Sustainable.ai, a friendly, encouraging, and knowledgeable AI assistant.
35
+ Always provide practical sustainability suggestions that are easy to adopt,
36
+ while keeping a supportive and positive tone. Prefer actionable steps over theory.
37
+ Reasoning: medium
38
+ """
39
 
40
+ # --- Chat callback ------------------------------------------------------------
41
  def respond(
42
  message,
43
  history: list[dict[str, str]],
44
+ hf_token_ui, # from password textbox (optional)
45
+ system_message, # from textbox
46
  car_km,
47
  bus_km,
48
  train_km,
 
51
  vegetarian_meals,
52
  vegan_meals,
53
  ):
54
+ """
55
+ Streams a response from openai/gpt-oss-20b via Hugging Face Inference API.
56
+ Token priority: UI textbox > HF_TOKEN env var.
57
+ """
58
+ # Resolve token from UI or env
59
+ token = (hf_token_ui or "").strip() or (os.getenv("HF_TOKEN") or "").strip()
60
+ if not token:
61
+ yield "⚠️ Please provide a valid Hugging Face token in the 'HF Token' box or set HF_TOKEN in the environment."
62
+ return
63
+
64
+ # Correct, namespaced repo id
65
+ model_id = "openai/gpt-oss-20b"
66
+
67
+ # Build client
68
+ try:
69
+ client = InferenceClient(model=model_id, token=token)
70
+ except Exception as e:
71
+ yield f"Failed to initialize InferenceClient: {e}"
72
+ return
73
+
74
+ # Compute personalized footprint summary
75
  footprint, stats = calculate_footprint(
76
  car_km, bus_km, train_km, air_km,
77
  meat_meals, vegetarian_meals, vegan_meals
78
  )
79
 
80
+ custom_prompt = (
81
+ f"This user’s estimated weekly footprint is **{footprint:.1f} kg CO2**.\n"
82
+ f"That’s roughly planting {stats['trees']} trees 🌳 or taking {stats['flights']} short flights ✈️.\n"
83
+ f"Breakdown includes transportation and food choices.\n"
84
+ f"Your job is to give practical, friendly suggestions to lower this footprint.\n"
85
+ f"{system_message}"
86
+ )
 
 
 
 
87
 
88
+ # Construct messages in OpenAI-style format; providers map this to the model's chat template.
89
  messages = [{"role": "system", "content": custom_prompt}]
90
+ messages.extend(history or [])
91
  messages.append({"role": "user", "content": message})
92
 
93
+ # Stream from HF Inference API
94
+ try:
95
+ response = ""
96
+ for chunk in client.chat_completion(
97
+ messages,
98
+ max_tokens=3000,
99
+ temperature=0.7,
100
+ top_p=0.95,
101
+ stream=True,
102
+ ):
103
+ try:
104
+ # Some providers return choices[0].delta.content during streaming
105
+ if chunk.choices and getattr(chunk.choices[0], "delta", None):
106
+ token_piece = chunk.choices[0].delta.content or ""
107
+ else:
108
+ # Fallback: some providers may use 'message' at the end
109
+ token_piece = getattr(chunk, "message", {}).get("content", "") or ""
110
+ except Exception:
111
+ token_piece = ""
112
+
113
+ if token_piece:
114
+ response += token_piece
115
+ yield response
116
+ except Exception as e:
117
+ # Common causes: 401 (bad token), 404 (wrong repo id), provider downtime
118
+ yield f"Inference error with '{model_id}': {e}\n"
119
+ return
120
+
121
+ # --- UI -----------------------------------------------------------------------
122
+ demo = gr.ChatInterface(
123
+ fn=respond,
124
+ type="messages", # fixes 'tuples' deprecation warning
125
+ additional_inputs=[
126
+ gr.Textbox(label="HF Token (prefer env var HF_TOKEN)", type="password", placeholder="hf_..."),
127
+ gr.Textbox(value=DEFAULT_SYSTEM_PROMPT, label="System Prompt"),
128
+ gr.Slider(0, 500, value=50, step=10, label="Car km/week"),
129
+ gr.Slider(0, 500, value=20, step=10, label="Bus km/week"),
130
+ gr.Slider(0, 500, value=20, step=10, label="Train km/week"),
131
+ gr.Slider(0, 5000, value=200, step=50, label="Air km/week"),
132
+ gr.Slider(0, 21, value=7, step=1, label="Meat meals/week"),
133
+ gr.Slider(0, 21, value=7, step=1, label="Vegetarian meals/week"),
134
+ gr.Slider(0, 21, value=7, step=1, label="Vegan meals/week"),
135
+ ],
136
+ title="🌱 Sustainable.ai (gpt-oss-20b)",
137
+ description=(
138
+ "Chat with an AI that helps you understand and reduce your carbon footprint. "
139
+ "Provide a Hugging Face token in the UI or via HF_TOKEN. Uses openai/gpt-oss-20b."
140
+ ),
141
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
  if __name__ == "__main__":
144
+ demo.launch()