jesusvilela commited on
Commit
7ec2562
·
verified ·
1 Parent(s): 253ad37

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -69
app.py CHANGED
@@ -1,76 +1,111 @@
1
- import os
2
- from typing import List, Optional
3
- from web_ui import WebUI
4
- from qwen_agent.agents import Assistant
5
- import spaces
6
 
7
- @spaces.GPU
8
- def create_ev_prompt(electricity_consumption, car_type, vehicle_choice, range_km, daily_mileage, travel_mileage):
9
- """
10
- Create the prompt for the EV Advisor based on user inputs.
11
- """
12
- return (
13
- f"Analyze the advantages of a {car_type} with the following parameters:\n"
14
- f"- Electricity consumption: {electricity_consumption} kWh/100km\n"
15
- f"- Range: {range_km} km\n"
16
- f"- Daily mileage: {daily_mileage} km\n"
17
- f"- Annual travel mileage: {travel_mileage} km\n"
18
- f"- Vehicle type: {vehicle_choice}\n\n"
19
- "Please calculate potential fuel cost savings, CO2 emissions reductions, "
20
- "and highlight other advantages like maintenance costs and driving experience. "
21
- "Use these assumptions:\n"
22
- "- Electricity cost: 0.13 EUR/kWh\n"
23
- "- Gasoline cost: 1.6 EUR/liter\n"
24
- "- Average fuel economy for conventional vehicles: 25 mpg\n"
25
- "- Average fuel economy for hybrids: 50 mpg\n\n"
26
- "Provide a detailed report with calculations and actionable insights."
27
- )
28
 
29
- @spaces.GPU
30
- def app_gui():
31
- """
32
- Define and run the EV Advisor application GUI.
33
- """
34
 
35
- # Define the assistant
36
- bot = Assistant(
37
- llm={
38
- 'model': os.environ.get("MODELNAME", "DevQuasar/Qwen.QwQ-32B-Preview-GGUF"),
39
- 'model_type': 'qwen_dashscope',
40
- 'generate_cfg': {
41
- 'max_input_tokens': 32768,
42
- 'max_retries': 10,
43
- 'temperature': 0.7,
44
- 'repetition_penalty': 1.0,
45
- 'top_k': 20,
46
- 'top_p': 0.9,
47
- },
48
- },
49
- name="EV Advisor",
50
- description="The assistant explains the advantages of electric or hybrid vehicles, provides cost and CO2 savings, and other benefits.",
51
- system_message=(
52
- "You are an assistant specializing in electric and hybrid vehicles. You will ask the user "
53
- "for necessary details like electricity consumption, car type, and travel mileage, then calculate "
54
- "and explain the benefits of EVs with detailed insights and actionable advice."
55
- ),
56
- rag_cfg={'max_ref_token': 32768, 'rag_searchers': []},
57
- )
 
 
58
 
59
- chatbot_config = {
60
- 'input.placeholder': "Ask about electric vehicles, or type '/start' to begin the questionnaire.",
61
- 'verbose': True,
62
- 'prompt.suggestions': [
63
- {'text': "What are the benefits of switching to an electric car?"},
64
- {'text': "How do hybrid vehicles compare to conventional ones in terms of emissions?"},
65
- {'text': "/start"},
66
- ],
67
- }
68
 
69
- # WebUI Integration
70
- WebUI(bot, chatbot_config=chatbot_config).run(
71
- concurrency_limit=80,
72
- enable_mention=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- if __name__ == "__main__":
76
- app_gui()
 
1
+ import gradio as gr
2
+ import logging
3
+ import torch
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ from huggingface_hub import spaces # Import spaces module
6
 
7
+ # Configure logging
8
+ logging.basicConfig(level=logging.INFO)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ # Model configuration
11
+ model_name_or_path = "Qwen/QwQ-32B-Preview"
 
 
 
12
 
13
+ # Initialize tokenizer and model variables
14
+ tokenizer = None
15
+ model = None
16
+
17
+ # Define the function to load the model with the @spaces.GPU decorator
18
+ @spaces.GPU()
19
+ def load_model():
20
+ global tokenizer, model
21
+ try:
22
+ tokenizer = AutoTokenizer.from_pretrained(
23
+ model_name_or_path, use_fast=False, trust_remote_code=True
24
+ )
25
+ model = AutoModelForCausalLM.from_pretrained(
26
+ model_name_or_path,
27
+ torch_dtype=torch.float16,
28
+ device_map="auto",
29
+ trust_remote_code=True
30
+ )
31
+ logging.info("Model loaded successfully.")
32
+ except Exception as e:
33
+ logging.error(f"Failed to load model: {e}")
34
+ raise e
35
+
36
+ # Call the load_model function to load the model
37
+ load_model()
38
 
39
+ def explain_advantages(electricity_consumption, car_type, vehicle_choice, range_km, daily_mileage, travel_mileage):
40
+ logging.info("Function 'explain_advantages' called with inputs:")
41
+ logging.info(f"Electricity Consumption: {electricity_consumption}")
42
+ logging.info(f"Car Type: {car_type}")
43
+ logging.info(f"Vehicle Choice: {vehicle_choice}")
44
+ logging.info(f"Range (km): {range_km}")
45
+ logging.info(f"Daily Mileage (km): {daily_mileage}")
46
+ logging.info(f"Travel Mileage (km/year): {travel_mileage}")
 
47
 
48
+ # Input validation
49
+ try:
50
+ electricity_consumption = float(electricity_consumption)
51
+ range_km = float(range_km)
52
+ daily_mileage = float(daily_mileage)
53
+ travel_mileage = float(travel_mileage)
54
+ logging.info("Input conversion successful.")
55
+ except ValueError as ve:
56
+ logging.error(f"Input conversion error: {ve}")
57
+ return "Invalid input: Please enter numeric values for consumption, range, and mileage."
58
+
59
+ # Construct the prompt
60
+ prompt = (
61
+ f"Given a {car_type} with electricity consumption of {electricity_consumption} kWh/100km, "
62
+ f"a range of {range_km} km, daily mileage of {daily_mileage} km, and annual mileage of {travel_mileage} km, "
63
+ f"compare the benefits of choosing a {vehicle_choice} vehicle over a conventional vehicle. "
64
+ f"Calculate potential fuel cost savings, CO2 emissions savings, and highlight additional benefits such as maintenance costs and driving experience. "
65
+ f"Assume the average electricity cost is 0.13 EUR per kWh and gasoline cost is 1.6 EUR per liter. "
66
+ f"Consider the average fuel economy for conventional vehicles to be 25 mpg and for hybrids to be 50 mpg. "
67
+ f"Provide a convincing argument with derived figures to illustrate the advantages. "
68
+ f"Provide advice to optimize the benefits of the chosen vehicle based on the input figures."
69
  )
70
+ logging.info("Prompt constructed successfully.")
71
+
72
+ # Prepare the input for the model
73
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
74
+
75
+ # Generate the response
76
+ try:
77
+ outputs = model.generate(
78
+ **inputs,
79
+ max_new_tokens=500,
80
+ temperature=0.7,
81
+ top_p=0.95,
82
+ repetition_penalty=1.0,
83
+ do_sample=True,
84
+ )
85
+ logging.info("Model generation successful.")
86
+ # Decode and post-process the generated text
87
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
88
+ response = generated_text[len(prompt):].strip()
89
+ return response
90
+ except Exception as e:
91
+ logging.error(f"Error during model generation: {e}")
92
+ return f"An error occurred while generating the response: {e}"
93
+
94
+ # Define the Gradio interface
95
+ iface = gr.Interface(
96
+ fn=explain_advantages,
97
+ inputs=[
98
+ gr.Number(label="Electricity Consumption (kWh/100km)", value=15.0),
99
+ gr.Textbox(label="Type of Car", value="Electric"),
100
+ gr.Radio(choices=["Hybrid", "Electric"], label="Hybrid/Electric"),
101
+ gr.Number(label="Range (km)", value=300.0),
102
+ gr.Number(label="Estimated Daily Mileage (km)", value=50.0),
103
+ gr.Number(label="Mileage from Travels (km/year)", value=1000.0),
104
+ ],
105
+ outputs=gr.Textbox(label="Advantages of Going Fully Electric"),
106
+ title="Explaining the Advantages of Going Fully Electric",
107
+ description="Enter your vehicle's parameters to understand the benefits of switching to a fully electric vehicle.",
108
+ )
109
 
110
+ # Launch the app
111
+ iface.launch()