CRYPTONEWS34 commited on
Commit
b4bdb8a
Β·
1 Parent(s): a6dbdd5

Fix matplotlib dir and add httpx to requirements

Browse files
Files changed (1) hide show
  1. app.py +25 -27
app.py CHANGED
@@ -23,6 +23,8 @@ from fastapi.responses import StreamingResponse
23
  import matplotlib
24
  matplotlib.use('Agg') # βœ… Force headless-safe backend
25
  import matplotlib.pyplot as plt # βœ… Safe to use now
 
 
26
  import requests
27
  import datetime
28
  from io import BytesIO
@@ -90,43 +92,39 @@ def analyze_ner(req: TextRequest):
90
  logger.error(f"NER analysis error: {e}")
91
  raise HTTPException(status_code=500, detail="NER analysis failed")
92
 
 
 
93
  @app.post("/chart")
94
  def generate_chart(req: CoinRequest):
95
  coin_id = req.coin_id.strip().lower()
96
- if not coin_id:
97
- raise HTTPException(status_code=400, detail="coin_id cannot be empty")
98
-
99
- url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart"
100
- params = {"vs_currency": "usd", "days": "1"}
101
 
102
  try:
103
- res = requests.get(url, params=params)
104
- if res.status_code != 200:
105
- logger.error(f"CoinGecko API error: {res.text}")
106
- raise HTTPException(status_code=502, detail="Failed to fetch coin data from CoinGecko")
107
 
108
- prices = res.json().get("prices", [])
109
- if not prices:
110
- raise HTTPException(status_code=404, detail="No price data available")
111
 
112
- times = [datetime.datetime.fromtimestamp(p[0] / 1000) for p in prices]
113
- values = [p[1] for p in prices]
114
 
115
- plt.figure(figsize=(12, 6))
116
- plt.fill_between(times, values, color="#1f77b4", alpha=0.3)
117
- plt.plot(times, values, color="#1f77b4", linewidth=3)
118
- plt.title(f"{coin_id.capitalize()} Price (24h)", fontsize=20)
119
  plt.xlabel("Time")
120
- plt.ylabel("USD Price")
121
- plt.grid(True, linestyle='--', alpha=0.5)
122
- plt.tight_layout()
123
 
124
- img_bytes = BytesIO()
125
- plt.savefig(img_bytes, format="png")
126
  plt.close()
127
- img_bytes.seek(0)
 
 
128
 
129
- return StreamingResponse(img_bytes, media_type="image/png")
130
  except Exception as e:
131
- logger.error(f"Chart generation error: {e}")
132
- raise HTTPException(status_code=500, detail="Failed to generate chart")
 
23
  import matplotlib
24
  matplotlib.use('Agg') # βœ… Force headless-safe backend
25
  import matplotlib.pyplot as plt # βœ… Safe to use now
26
+ import httpx
27
+ import io
28
  import requests
29
  import datetime
30
  from io import BytesIO
 
92
  logger.error(f"NER analysis error: {e}")
93
  raise HTTPException(status_code=500, detail="NER analysis failed")
94
 
95
+
96
+
97
  @app.post("/chart")
98
  def generate_chart(req: CoinRequest):
99
  coin_id = req.coin_id.strip().lower()
100
+ logger.info(f"Generating chart for coin: {coin_id}")
 
 
 
 
101
 
102
  try:
103
+ url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart"
104
+ params = {"vs_currency": "usd", "days": "7"}
105
+ response = httpx.get(url, params=params)
 
106
 
107
+ if response.status_code != 200:
108
+ logger.error(f"CoinGecko API error: {response.text}")
109
+ raise HTTPException(status_code=502, detail="Failed to fetch coin data from CoinGecko")
110
 
111
+ prices = response.json()["prices"]
112
+ timestamps, values = zip(*prices)
113
 
114
+ plt.figure(figsize=(6, 3))
115
+ plt.plot(values, color="blue")
116
+ plt.title(f"{coin_id.capitalize()} - Last 7 Days")
 
117
  plt.xlabel("Time")
118
+ plt.ylabel("Price (USD)")
119
+ plt.grid(True)
 
120
 
121
+ buffer = io.BytesIO()
122
+ plt.savefig(buffer, format="png")
123
  plt.close()
124
+ buffer.seek(0)
125
+
126
+ return StreamingResponse(buffer, media_type="image/png")
127
 
 
128
  except Exception as e:
129
+ logger.exception(f"Chart generation error: {e}")
130
+ raise HTTPException(status_code=500, detail="Chart generation failed")