Callmebowoo-22 commited on
Commit
d566c25
·
verified ·
1 Parent(s): c6f0c83

Update utils/model.py

Browse files
Files changed (1) hide show
  1. utils/model.py +39 -21
utils/model.py CHANGED
@@ -1,28 +1,46 @@
1
  from transformers import pipeline, AutoModelForTimeSeriesPrediction
2
  import torch
 
3
 
4
  device = "cuda" if torch.cuda.is_available() else "cpu"
5
 
6
  def predict_umkm(data):
7
- # Load model TTM
8
- ttm = AutoModelForTimeSeriesPrediction.from_pretrained(
9
- "ibm/granite-ttm-r2"
10
- ).to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- # Prediksi demand
13
- inputs = {"values": data['demand'].tolist()}
14
- demand_pred = ttm.generate(**inputs, max_length=7)
15
-
16
- # Rekomendasi dengan Chronos-T5
17
- chronos = pipeline(
18
- "text-generation",
19
- model="amazon/chronos-t5-small",
20
- device=device
21
- )
22
- prompt = f"""
23
- Data UMKM:
24
- - Prediksi demand: {demand_pred}
25
- - Stok saat ini: {data['supply'].iloc[-1]}
26
- Beri rekomendasi dalam 1 kalimat:
27
- """
28
- return chronos(prompt, max_length=50)[0]['generated_text']
 
1
  from transformers import pipeline, AutoModelForTimeSeriesPrediction
2
  import torch
3
+ import numpy as np
4
 
5
  device = "cuda" if torch.cuda.is_available() else "cpu"
6
 
7
  def predict_umkm(data):
8
+ try:
9
+ # ========== [1] GRANITE-TTM FORECASTING ==========
10
+ ttm_model = AutoModelForTimeSeriesPrediction.from_pretrained(
11
+ "ibm/granite-ttm-r2"
12
+ ).to(device)
13
+
14
+ # Format input khusus untuk TTM
15
+ inputs = {
16
+ "values": torch.tensor(data['demand'].tolist()).float().unsqueeze(0).to(device),
17
+ "attention_mask": torch.ones(len(data['demand'])).unsqueeze(0).to(device)
18
+ }
19
+
20
+ # Generate prediksi
21
+ with torch.no_grad():
22
+ demand_pred = ttm_model.generate(**inputs, max_length=7)
23
+
24
+ # Konversi output ke numpy
25
+ demand_pred = demand_pred.cpu().numpy().flatten().tolist()
26
+
27
+ # ========== [2] CHRONOS-T5 DECISION MAKING ==========
28
+ chronos = pipeline(
29
+ "text-generation",
30
+ model="amazon/chronos-t5-small",
31
+ device=device
32
+ )
33
+
34
+ prompt = f"""
35
+ Data UMKM:
36
+ - Prediksi demand 7 hari ke depan: {demand_pred}
37
+ - Stok saat ini: {data['supply'].iloc[-1]}
38
+ - Harga rata-rata: {data['harga'].mean() if 'harga' in data else 'N/A'}
39
+ Berikan rekomendasi pembelian dalam 1 kalimat:
40
+ """
41
+
42
+ recommendation = chronos(prompt, max_length=100)[0]['generated_text']
43
+ return recommendation
44
 
45
+ except Exception as e:
46
+ return f"Error: {str(e)}"