abolfazle80 commited on
Commit
1f43951
Β·
verified Β·
1 Parent(s): 371df03

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -75
app.py CHANGED
@@ -5,13 +5,15 @@ from datetime import datetime
5
  import time
6
  import csv
7
  import threading
 
8
  import os
9
- from huggingface_hub import HfApi, hf_hub_download
10
 
11
- # Hugging Face credentials
12
- HF_USERNAME = "abolfazle80" # Your Hugging Face username
13
- REPO_NAME = "crypto_data" # Your dataset repo name
14
- CSV_FILENAME = "USDT.csv" # File in your dataset
 
15
 
16
  # Define the markets (cryptocurrencies to monitor)
17
  markets = ['DOTUSDT', 'BTCUSDT', 'ADAUSDT', 'BNBUSDT', 'SUIUSDT', 'XRPUSDT']
@@ -19,27 +21,41 @@ markets = ['DOTUSDT', 'BTCUSDT', 'ADAUSDT', 'BNBUSDT', 'SUIUSDT', 'XRPUSDT']
19
  # Initialize Hugging Face API
20
  api = HfApi()
21
 
22
- # Flag to control fetching loop
23
- loop_running = False
 
 
24
 
25
- # Function to download CSV if missing
26
- def download_csv_if_needed():
27
- """Downloads CSV from Hugging Face if not present locally."""
28
- if not os.path.exists(CSV_FILENAME):
29
- try:
30
- hf_hub_download(
31
- repo_id=f"{HF_USERNAME}/{REPO_NAME}",
32
- filename=CSV_FILENAME,
33
- repo_type="dataset",
34
- local_dir=".", # Save in current directory
35
- )
36
- print("βœ… CSV downloaded successfully!")
37
- except Exception as e:
38
- print(f"❌ Download failed: {e}")
39
 
40
- # Function to upload CSV to Hugging Face
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  def upload_to_huggingface():
42
- """Uploads the CSV file to the Hugging Face dataset repo."""
43
  try:
44
  api.upload_file(
45
  path_or_fileobj=CSV_FILENAME,
@@ -51,85 +67,64 @@ def upload_to_huggingface():
51
  except Exception as e:
52
  print(f"❌ Upload failed: {e}")
53
 
54
- # Function to fetch and save data
55
  def fetch_data():
56
- """Fetches crypto data, appends to CSV, and uploads to Hugging Face."""
57
  global loop_running
58
  while loop_running:
59
  try:
60
  all_data = []
61
  for market in markets:
62
  crypto_data = get_crypto_price_from_coinex(market)
63
- all_data += crypto_data # Append price and volume
64
-
65
- timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Timestamp
66
- all_data.append(timestamp) # Append timestamp to row
67
 
68
- # Append data to the local CSV file
69
- file_exists = os.path.isfile(CSV_FILENAME)
70
- with open(CSV_FILENAME, "a", newline="") as file:
71
- writer = csv.writer(file)
72
- if not file_exists:
73
- # Write header if the file was just created
74
- header = [f"{m} Price" for m in markets] + [f"{m} Volume" for m in markets] + ["Timestamp"]
75
- writer.writerow(header)
76
- writer.writerow(all_data) # Append new row
77
 
78
- print(f"βœ… {all_data} added to CSV")
 
79
 
80
- # Upload updated CSV to Hugging Face
81
- upload_to_huggingface()
 
 
82
 
83
- time.sleep(1) # Fetch new data every second
84
- except Exception as e:
85
- print(f"❌ Error: {e}")
86
- loop_running = False # Stop loop if error occurs
87
 
88
- # Function to get price and volume data from CoinEx
89
- def get_crypto_price_from_coinex(symbol):
90
- url = 'https://api.coinex.com/v1/market/ticker'
91
- params = {'market': symbol}
92
 
93
- try:
94
- response = requests.get(url, params=params)
95
- response.raise_for_status() # Check for HTTP errors
96
- data = response.json()
97
 
98
- if 'data' in data:
99
- price = data['data']['ticker']['last']
100
- volume = data['data']['ticker']['vol']
101
- return [price, volume] # Return as list
102
- else:
103
- return ["Symbol not found", "Symbol not found"]
104
- except requests.exceptions.RequestException as e:
105
- return ["Request error", "Request error"]
106
- except ValueError as e:
107
- return ["JSON decode error", "JSON decode error"]
108
 
109
- # Streamlit UI elements
110
- st.title("πŸ“Š Live Crypto Data Fetcher")
 
 
111
 
112
- # Ensure CSV is available
113
- download_csv_if_needed()
114
 
115
- # Start button
116
  if st.button("Start Fetching Data"):
117
  if not loop_running:
118
  loop_running = True
119
  threading.Thread(target=fetch_data, daemon=True).start()
120
- st.success("βœ… Started fetching data and saving to CSV.")
121
  else:
122
- st.warning("⚠️ Data fetching is already running.")
123
 
124
- # Stop button
125
  if st.button("Stop Fetching Data"):
126
  loop_running = False
127
  st.success("πŸ›‘ Stopped fetching data.")
128
 
129
- # Show latest data
130
- st.subheader("πŸ“Œ Latest Data from CSV:")
131
  try:
132
  df = pd.read_csv(CSV_FILENAME)
133
- st.write(df.tail()) # Show last few rows
134
  except Exception as e:
135
- st.error(f"❌ Error reading CSV: {e}")
 
5
  import time
6
  import csv
7
  import threading
8
+ from huggingface_hub import HfApi
9
  import os
10
+ import io
11
 
12
+ # Hugging Face Info
13
+ HF_USERNAME = "abolfazle80"
14
+ REPO_NAME = "crypto_data"
15
+ CSV_FILENAME = "USDT.csv"
16
+ HF_CSV_URL = f"https://huggingface.co/datasets/{HF_USERNAME}/{REPO_NAME}/resolve/main/{CSV_FILENAME}"
17
 
18
  # Define the markets (cryptocurrencies to monitor)
19
  markets = ['DOTUSDT', 'BTCUSDT', 'ADAUSDT', 'BNBUSDT', 'SUIUSDT', 'XRPUSDT']
 
21
  # Initialize Hugging Face API
22
  api = HfApi()
23
 
24
+ # Function to fetch data from CoinEx
25
+ def get_crypto_price_from_coinex(symbol):
26
+ url = 'https://api.coinex.com/v1/market/ticker'
27
+ params = {'market': symbol}
28
 
29
+ try:
30
+ response = requests.get(url, params=params)
31
+ response.raise_for_status()
32
+ data = response.json()
 
 
 
 
 
 
 
 
 
 
33
 
34
+ if 'data' in data:
35
+ price = data['data']['ticker']['last']
36
+ volume = data['data']['ticker']['vol']
37
+ return [price, volume]
38
+ else:
39
+ return ["Symbol not found", "Symbol not found"]
40
+ except Exception as e:
41
+ st.error(f"Error fetching data: {e}")
42
+ return ["Error", "Error"]
43
+
44
+ # Function to download existing CSV from Hugging Face
45
+ def download_existing_csv():
46
+ try:
47
+ response = requests.get(HF_CSV_URL)
48
+ response.raise_for_status()
49
+
50
+ csv_data = io.StringIO(response.text)
51
+ df = pd.read_csv(csv_data)
52
+
53
+ return df # Return existing DataFrame
54
+ except requests.exceptions.RequestException:
55
+ return pd.DataFrame() # Return empty DataFrame if file doesn't exist
56
+
57
+ # Function to upload the CSV back to Hugging Face
58
  def upload_to_huggingface():
 
59
  try:
60
  api.upload_file(
61
  path_or_fileobj=CSV_FILENAME,
 
67
  except Exception as e:
68
  print(f"❌ Upload failed: {e}")
69
 
70
+ # Function to fetch, append & update the CSV
71
  def fetch_data():
 
72
  global loop_running
73
  while loop_running:
74
  try:
75
  all_data = []
76
  for market in markets:
77
  crypto_data = get_crypto_price_from_coinex(market)
78
+ all_data += crypto_data
 
 
 
79
 
80
+ timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
81
+ all_data.append(timestamp)
 
 
 
 
 
 
 
82
 
83
+ # Load existing data
84
+ df_existing = download_existing_csv()
85
 
86
+ # Convert new data to DataFrame
87
+ df_new = pd.DataFrame([all_data], columns=[f"{m} Price" for m in markets] +
88
+ [f"{m} Volume" for m in markets] +
89
+ ["Timestamp"])
90
 
91
+ # Append new data to existing data
92
+ df_combined = pd.concat([df_existing, df_new], ignore_index=True)
 
 
93
 
94
+ # Save updated data to CSV
95
+ df_combined.to_csv(CSV_FILENAME, index=False)
 
 
96
 
97
+ print(f"βœ… {all_data} added to CSV and uploaded.")
 
 
 
98
 
99
+ # Upload to Hugging Face
100
+ upload_to_huggingface()
 
 
 
 
 
 
 
 
101
 
102
+ time.sleep(1) # Fetch new data every second
103
+ except Exception as e:
104
+ st.error(f"An error occurred: {e}")
105
+ loop_running = False
106
 
107
+ # Streamlit UI
108
+ st.title("πŸ”„ Live Cryptocurrency Data Fetching")
109
 
110
+ # Start Fetching Button
111
  if st.button("Start Fetching Data"):
112
  if not loop_running:
113
  loop_running = True
114
  threading.Thread(target=fetch_data, daemon=True).start()
115
+ st.success("βœ… Started fetching and saving data.")
116
  else:
117
+ st.warning("⚠️ Fetching is already running.")
118
 
119
+ # Stop Fetching Button
120
  if st.button("Stop Fetching Data"):
121
  loop_running = False
122
  st.success("πŸ›‘ Stopped fetching data.")
123
 
124
+ # Show Latest Data
125
+ st.text("πŸ“Š Latest Data from CSV:")
126
  try:
127
  df = pd.read_csv(CSV_FILENAME)
128
+ st.write(df.tail())
129
  except Exception as e:
130
+ st.error(f"Error reading CSV: {e}")