Callmebowoo-22 commited on
Commit
7c127d4
·
verified ·
1 Parent(s): 581242d

Update utils/models.py

Browse files
Files changed (1) hide show
  1. utils/models.py +28 -29
utils/models.py CHANGED
@@ -1,58 +1,57 @@
1
  import torch
2
  import numpy as np
3
- from tsfm_public.toolkit.get_model import get_model
4
  from transformers import pipeline
 
5
 
6
- def predict_umkm(data, prediction_length=7, confidence=0.85):
7
  device = "cuda" if torch.cuda.is_available() else "cpu"
8
 
9
  try:
10
- # ===== 1. GRANITE-TTM Forecasting =====
11
- model = get_model(
12
- model_path="ibm-granite/granite-timeseries-ttm-r2",
13
- context_length=min(512, len(data)),
14
- prediction_length=prediction_length,
15
- device=device
16
- )
17
-
18
- # Format input
19
- inputs = torch.tensor(data['demand'].values, dtype=torch.float32)
20
- inputs = inputs.unsqueeze(0).to(device) # Shape: [1, seq_len]
21
 
22
- # Prediksi
23
- with torch.no_grad():
24
- preds = model.generate(inputs).cpu().numpy().flatten()
25
-
26
- # ===== 2. Chronos-T5 Decision =====
27
  chronos = pipeline(
28
  "text-generation",
29
  model="amazon/chronos-t5-small",
30
  device=device
31
  )
32
 
 
33
  prompt = f"""
34
  [INSTRUCTION]
35
- Berikan rekomendasi untuk manajemen inventory dengan:
36
- - Prediksi {prediction_length} hari: {preds.tolist()}
37
  - Stok saat ini: {data['supply'].iloc[-1]}
38
- - Tingkat kepercayaan: {confidence*100}%
39
 
40
  [FORMAT]
41
- 1 kalimat dalam Bahasa Indonesia dengan angka spesifik.
42
- Estimasi ROI dalam range persentase.
43
  [/FORMAT]
44
  """
45
 
46
- response = chronos(prompt, max_length=150)[0]['generated_text']
 
 
 
 
 
47
 
48
  # Ekstrak teks rekomendasi
49
- rec_text = response.split("[/FORMAT]")[-1].strip()
 
 
 
 
50
 
51
  return {
52
- "text": rec_text,
53
- "predictions": preds.tolist(),
54
- "roi": confidence * 0.8, # Simulasi ROI
55
- "confidence": confidence
 
56
  }
57
 
58
  except Exception as e:
 
1
  import torch
2
  import numpy as np
 
3
  from transformers import pipeline
4
+ from sklearn.preprocessing import MinMaxScaler
5
 
6
+ def predict_umkm(data, prediction_length=7, safety_stock=10):
7
  device = "cuda" if torch.cuda.is_available() else "cpu"
8
 
9
  try:
10
+ # ===== 1. Persiapan Data =====
11
+ scaler = MinMaxScaler()
12
+ scaled_demand = scaler.fit_transform(data[['demand']]).flatten().tolist()
 
 
 
 
 
 
 
 
13
 
14
+ # ===== 2. Prediksi dengan Chronos-T5 =====
 
 
 
 
15
  chronos = pipeline(
16
  "text-generation",
17
  model="amazon/chronos-t5-small",
18
  device=device
19
  )
20
 
21
+ # Format prompt khusus time series
22
  prompt = f"""
23
  [INSTRUCTION]
24
+ Berikan rekomendasi manajemen inventori untuk {prediction_length} hari ke depan:
25
+ - Data historis demand: {scaled_demand[-100:]} # Ambil 100 data terakhir
26
  - Stok saat ini: {data['supply'].iloc[-1]}
27
+ - Safety stock: {safety_stock}
28
 
29
  [FORMAT]
30
+ 1 kalimat dalam Bahasa Indonesia dengan angka konkret
31
+ Estimasi ROI dalam persentase
32
  [/FORMAT]
33
  """
34
 
35
+ # Generate rekomendasi
36
+ response = chronos(
37
+ prompt,
38
+ max_new_tokens=100,
39
+ temperature=0.7
40
+ )[0]['generated_text']
41
 
42
  # Ekstrak teks rekomendasi
43
+ rekomendasi = response.split("[/FORMAT]")[-1].strip()
44
+
45
+ # ===== 3. Simulasi ROI ===== (Contoh Sederhana)
46
+ avg_demand = np.mean(data['demand'][-30:])
47
+ roi = round((avg_demand * 0.2) / (data['supply'].iloc[-1] + safety_stock) * 100, 1)
48
 
49
  return {
50
+ "rekomendasi": rekomendasi,
51
+ "prediksi": [avg_demand] * prediction_length, # Contoh prediksi
52
+ "roi": roi,
53
+ "stok_optimal": int(avg_demand * 1.2) + safety_stock,
54
+ "anomali": len(data) - len(clean_data(data))
55
  }
56
 
57
  except Exception as e: