lyx51 commited on
Commit
7cb7593
·
verified ·
1 Parent(s): a028193

Update streaming_api.py

Browse files
Files changed (1) hide show
  1. streaming_api.py +150 -43
streaming_api.py CHANGED
@@ -1,56 +1,168 @@
1
- # streaming_api_single.py
2
  from fastapi import FastAPI
3
- import pandas as pd
4
  import random
5
  import threading
6
  import time
7
- from datetime import datetime
8
 
9
- # ==============================================================
10
- # 🔧 CONFIGURATION FACILE
11
- # ==============================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- GENERATION_INTERVAL = 60 # secondes entre chaque nouvelle ligne
14
- RANGES = {
15
- "mileage": (10_000, 200_000),
16
- "engine_power": (60, 300),
17
- "rental_price_per_day": (50, 300),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  }
19
 
20
- MODEL_KEYS = ["Renault", "Peugeot", "Citroën", "BMW", "Audi", "Mercedes", "Nissan", "Toyota"]
21
- FUELS = ["diesel", "petrol", "hybrid_petrol", "electro"]
22
- CAR_TYPES = ["hatchback", "estate", "sedan", "suv", "convertible", "coupe", "van", "subcompact"]
23
  PAINT_COLORS = ["black", "grey", "white", "silver", "blue", "red", "brown", "green", "beige", "orange"]
24
 
25
- # ==============================================================
26
- # 🧩 INITIALISATION
27
- # ==============================================================
28
 
29
- app = FastAPI(title="Live Car Rental API", version="1.0")
30
- latest_row = None # la dernière ligne générée
 
 
 
 
 
 
 
 
 
 
31
 
32
- # ==============================================================
33
- # 🧠 GÉNÉRATION DE NOUVELLE LIGNE
34
- # ==============================================================
35
 
36
- def generate_random_row():
37
- """Génère une seule ligne de données réaliste"""
 
 
 
 
38
  return {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  "timestamp": datetime.now().isoformat(),
40
- "model_key": random.choice(MODEL_KEYS),
41
- "mileage": random.randint(*RANGES["mileage"]),
42
- "engine_power": random.randint(*RANGES["engine_power"]),
43
- "fuel": random.choices(FUELS, weights=[0.7, 0.25, 0.04, 0.01])[0],
44
- "paint_color": random.choice(PAINT_COLORS),
45
- "car_type": random.choice(CAR_TYPES),
 
46
  "private_parking_available": random.choice([True, False]),
47
- "has_gps": random.choice([True, False]),
48
- "has_air_conditioning": random.choice([True, False]),
49
- "automatic_car": random.choice([True, False]),
50
- "has_speed_regulator": random.choice([True, False]),
51
- "winter_tires": random.choice([True, False]),
52
- "rental_price_per_day": random.randint(*RANGES["rental_price_per_day"])
53
  }
 
 
54
 
55
  def background_generator():
56
  global latest_row
@@ -58,24 +170,19 @@ def background_generator():
58
  latest_row = generate_random_row()
59
  time.sleep(GENERATION_INTERVAL)
60
 
61
- # Lancer la génération en arrière-plan
62
  threading.Thread(target=background_generator, daemon=True).start()
63
 
64
- # ==============================================================
65
- # 🌐 ROUTES API
66
- # ==============================================================
67
-
68
  @app.get("/")
69
  def home():
70
  return {
71
  "message": "Live car rental API running 🚗",
72
  "generation_interval_sec": GENERATION_INTERVAL,
 
73
  "example_endpoint": "/data"
74
  }
75
 
76
  @app.get("/data")
77
  def get_latest_data():
78
- """Renvoie uniquement la dernière ligne générée"""
79
  if latest_row is None:
80
  return {"status": "waiting", "message": "No data generated yet"}
81
- return latest_row
 
 
1
  from fastapi import FastAPI
 
2
  import random
3
  import threading
4
  import time
5
+ from datetime import datetime, timedelta
6
 
7
+ app = FastAPI(title="Live Car Rental API", version="1.0")
8
+
9
+ GENERATION_INTERVAL = 60 # secondes entre chaque nouvelle ligne
10
+ GENERATE_RENT = True # True pour calculer rental_price, False pour 0
11
+
12
+ brands_list = [
13
+ ("Renault", 16.1, 30000, 50, 160, True, True, False),
14
+ ("Peugeot", 13.5, 33000, 50, 325, True, True, False),
15
+ ("Citroen", 6.5, 28000, 75, 230, True, True, False),
16
+ ("Dacia", 8.4, 23000, 45, 100, False, False, False),
17
+ ("Volkswagen", 7.0, 35000, 80, 394, True, True, False),
18
+ ("Toyota", 7.4, 34000, 70, 220, True, True, False),
19
+ ("BMW", 4.2, 54000, 100, 450, True, True, True),
20
+ ("Mercedes-Benz", 3.2, 75000, 100, 600, True, True, True),
21
+ ("Audi", 2.8, 60000, 90, 580, True, True, True),
22
+ ("Ford", 2.6, 30000, 70, 270, True, True, False),
23
+ ("Fiat", 2.1, 27000, 60, 160, False, True, False),
24
+ ("Kia", 2.1, 28000, 65, 260, True, True, False),
25
+ ("SEAT", 1.3, 28000, 70, 270, True, True, False),
26
+ ("Mini", 0.9, 32000, 75, 200, True, False, False),
27
+ ("Porsche", 0.4, 160000, 300, 1020, True, False, True),
28
+ ("Tesla", 2.0, 58000, 250, 1020, True, False, True),
29
+ ("Opel", 1.7, 27000, 60, 160, False, True, False),
30
+ ("Nissan", 1.8, 28000, 70, 220, True, True, False),
31
+ ("Honda", 0.3, 29000, 70, 200, False, True, False),
32
+ ("Mazda", 0.5, 29000, 75, 200, False, True, False),
33
+ ("Suzuki", 0.8, 21000, 45, 140, False, False, False),
34
+ ("Lexus", 0.3, 55000, 150, 450, True, True, True),
35
+ ("Mitsubishi", 0.2, 26000, 70, 160, True, True, False),
36
+ ("Alfa Romeo", 0.2, 40000, 110, 300, False, False, True),
37
+ ("Subaru", 0.1, 28000, 70, 220, False, False, False)
38
+ ]
39
 
40
+ years = list(range(2010, 2025))
41
+ years_weights = [10, 9, 8, 8, 7, 7, 6, 6, 6, 6, 7, 6, 6, 6, 6]
42
+
43
+ fuel_by_year = {
44
+ 2010: {"diesel": 0.67, "petrol": 0.34, "hybrid": 0.005, "electric": 0},
45
+ 2015: {"diesel": 0.60, "petrol": 0.38, "hybrid": 0.02, "electric": 0.004},
46
+ 2020: {"diesel": 0.30, "petrol": 0.48, "hybrid": 0.148, "electric": 0.067},
47
+ 2024: {"diesel": 0.13, "petrol": 0.24, "hybrid": 0.44, "electric": 0.18}
48
+ }
49
+
50
+ CAR_TYPES = ["hatchback", "estate", "sedan", "suv", "convertible", "coupe"]
51
+ CAR_TYPE_WEIGHTS = [0.35, 0.10, 0.15, 0.25, 0.05, 0.10]
52
+
53
+ car_type_price_factors = {
54
+ "hatchback": 1.00,
55
+ "estate": 1.05,
56
+ "sedan": 1.05,
57
+ "suv": 1.15,
58
+ "convertible": 1.10,
59
+ "coupe": 1.10
60
  }
61
 
 
 
 
62
  PAINT_COLORS = ["black", "grey", "white", "silver", "blue", "red", "brown", "green", "beige", "orange"]
63
 
64
+ def yesno(prob):
65
+ return random.random() < prob
 
66
 
67
+ def get_fuel(year, allows_electric, allows_hybrid, is_tesla):
68
+ step = 2010 if year < 2015 else 2015 if year < 2020 else 2020 if year < 2024 else 2024
69
+ dist = fuel_by_year[step].copy()
70
+ if not allows_electric or is_tesla:
71
+ dist.pop("electric", None)
72
+ if not allows_hybrid:
73
+ dist.pop("hybrid", None)
74
+ if is_tesla:
75
+ return "electric"
76
+ total = sum(dist.values())
77
+ fracs = {k: v / total for k, v in dist.items()}
78
+ return random.choices(list(fracs.keys()), weights=list(fracs.values()), k=1)[0]
79
 
80
+ def get_car_type():
81
+ return random.choices(CAR_TYPES, weights=CAR_TYPE_WEIGHTS, k=1)[0]
 
82
 
83
+ def get_paint_color():
84
+ return random.choice(PAINT_COLORS)
85
+
86
+ def get_option_chances(is_premium):
87
+ base = 0.50
88
+ bonus = 0.35 if is_premium else 0.0
89
  return {
90
+ 'has_gps': base + bonus,
91
+ 'has_air_conditioning': 0.85 + 0.12 * is_premium,
92
+ 'automatic': 0.4 + 0.45 * is_premium,
93
+ 'has_speed_regulator': 0.45 + 0.40 * is_premium,
94
+ 'winter_tires': 0.40 + 0.20 * is_premium
95
+ }
96
+
97
+ def gen_price(avg_sale_price, age_years, km, power, options_count, is_premium, car_type):
98
+ price_bracket = (
99
+ 52 if avg_sale_price < 25000 else
100
+ 62 if avg_sale_price < 35000 else
101
+ 78 if avg_sale_price < 50000 else
102
+ 130 if avg_sale_price < 80000 else
103
+ 180
104
+ )
105
+ age_fac = 1.10 - 0.07 * min(age_years, 10)
106
+ km_fac = 1.0 - (km / 250000) * 0.6
107
+ opt_fac = 1.0 + (options_count * 0.07)
108
+ premium_fac = 1.2 if is_premium else 1.0
109
+ car_type_factor = car_type_price_factors.get(car_type, 1.0)
110
+
111
+ base_price = price_bracket * age_fac * km_fac * opt_fac * premium_fac
112
+ management_fee_factor = 1.20
113
+
114
+ final_price = base_price * management_fee_factor * car_type_factor
115
+ return round(max(final_price, 18), 1)
116
+
117
+ latest_row = None
118
+
119
+ def generate_random_row():
120
+ global latest_row
121
+ brand, share, avg_price, power_min, power_max, allows_electric, allows_hybrid, is_premium = random.choices(brands_list, weights=[b[1] for b in brands_list], k=1)[0]
122
+ year = random.choices(years, weights=years_weights, k=1)[0]
123
+ day = random.randint(1, 365)
124
+ date_str = (datetime(year, 1, 1) + timedelta(days=day-1)).strftime("%Y-%m-%d")
125
+ is_tesla = brand.lower() == "tesla"
126
+ fuel = get_fuel(year, allows_electric, allows_hybrid, is_tesla)
127
+ power = random.randint(power_min, power_max)
128
+ car_type = get_car_type()
129
+ paint_color = get_paint_color()
130
+ base_km = (2025 - year) * 13000 + random.randint(-4000, 3000)
131
+ mileage = int(max(5000, base_km * random.uniform(0.7, 1.0)))
132
+
133
+ opt_prob = get_option_chances(is_premium)
134
+ gps = yesno(opt_prob['has_gps'])
135
+ ac = yesno(opt_prob['has_air_conditioning'])
136
+ auto = yesno(opt_prob['automatic'])
137
+ spd = yesno(opt_prob['has_speed_regulator'])
138
+ winter = yesno(opt_prob['winter_tires'])
139
+ opt_count = sum([gps, ac, auto, spd, winter])
140
+
141
+ age_years = 2025 - year
142
+ if GENERATE_RENT:
143
+ rent = gen_price(avg_price, age_years, mileage, power, opt_count, is_premium, car_type)
144
+ else:
145
+ rent = 0
146
+
147
+ row = {
148
  "timestamp": datetime.now().isoformat(),
149
+ "model_key": brand,
150
+ "mileage": mileage,
151
+ "date_of_first_registration": date_str,
152
+ "engine_power": power,
153
+ "fuel": fuel,
154
+ "paint_color": paint_color,
155
+ "car_type": car_type,
156
  "private_parking_available": random.choice([True, False]),
157
+ "has_gps": gps,
158
+ "has_air_conditioning": ac,
159
+ "automatic_car": auto,
160
+ "has_speed_regulator": spd,
161
+ "winter_tires": winter,
162
+ "rental_price_per_day": rent
163
  }
164
+ latest_row = row
165
+ return row
166
 
167
  def background_generator():
168
  global latest_row
 
170
  latest_row = generate_random_row()
171
  time.sleep(GENERATION_INTERVAL)
172
 
 
173
  threading.Thread(target=background_generator, daemon=True).start()
174
 
 
 
 
 
175
  @app.get("/")
176
  def home():
177
  return {
178
  "message": "Live car rental API running 🚗",
179
  "generation_interval_sec": GENERATION_INTERVAL,
180
+ "generate_rent_enabled": GENERATE_RENT,
181
  "example_endpoint": "/data"
182
  }
183
 
184
  @app.get("/data")
185
  def get_latest_data():
 
186
  if latest_row is None:
187
  return {"status": "waiting", "message": "No data generated yet"}
188
+ return latest_row