Really-amin commited on
Commit
ee486aa
·
verified ·
1 Parent(s): 59ea8e7

Upload 204 files

Browse files
.gitattributes CHANGED
@@ -41,3 +41,4 @@ final/__pycache__/hf_unified_server.cpython-313.pyc filter=lfs diff=lfs merge=lf
41
  final/data/crypto_monitor.db filter=lfs diff=lfs merge=lfs -text
42
  app/final/__pycache__/hf_unified_server.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
43
  app/final/data/crypto_monitor.db filter=lfs diff=lfs merge=lfs -text
 
 
41
  final/data/crypto_monitor.db filter=lfs diff=lfs merge=lfs -text
42
  app/final/__pycache__/hf_unified_server.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
43
  app/final/data/crypto_monitor.db filter=lfs diff=lfs merge=lfs -text
44
+ __pycache__/api_server_extended.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
DEPLOYMENT_GUIDE.md CHANGED
@@ -1,269 +1,215 @@
1
- # 🚀 Deployment Guide - HuggingFace Space
2
-
3
- ## مشکل Dependency Conflict و حل آن
4
-
5
- ### مشکل قبلی:
6
- ```
7
- ERROR: Cannot install gradio and websockets>=12.0 because these package versions have conflicting dependencies.
8
- ```
9
-
10
- ### حل شده:
11
- ```python
12
- websockets>=10.4,<12.0 # Compatible with gradio-client
13
- ```
14
-
15
- ## نصب و راه‌اندازی
16
-
17
- ### روش 1: Docker (توصیه می‌شود)
18
- ```bash
19
- # Build
20
- docker build -t crypto-hf-hub .
21
-
22
- # Run
23
- docker run -d \
24
- -p 7860:7860 \
25
- -e HF_TOKEN=your_token_here \
26
- --name crypto-hub \
27
- crypto-hf-hub
28
-
29
- # Logs
30
- docker logs -f crypto-hub
31
- ```
32
-
33
- ### روش 2: مستقیم (Local Development)
34
- ```bash
35
- # ایجاد virtual environment
36
- python3 -m venv venv
37
- source venv/bin/activate # Windows: venv\Scripts\activate
38
-
39
- # نصب dependencies
40
- pip install --upgrade pip
41
- pip install -r requirements.txt
42
-
43
- # تنظیم environment variables
44
- export HF_TOKEN=your_huggingface_token
45
- export PORT=7860
46
-
47
- # اجرا
48
- uvicorn hf_unified_server:app --host 0.0.0.0 --port 7860 --reload
49
- ```
50
-
51
- ### روش 3: HuggingFace Space
52
- ```bash
53
- # 1. ساخت Space جدید در HuggingFace
54
- # Space SDK: Docker
55
- # Hardware: CPU basic (free)
56
-
57
- # 2. کلون کردن repository
58
- git clone https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME
59
- cd YOUR_SPACE_NAME
60
-
61
- # 3. کپی کردن فایل‌های پروژه
62
- cp -r crypto-hf-integrated/* .
63
-
64
- # 4. Commit و Push
65
- git add .
66
- git commit -m "Initial deployment with HF integration"
67
- git push
68
- ```
69
-
70
- ## تنظیمات HuggingFace Space
71
-
72
- ### Dockerfile
73
- ```dockerfile
74
- FROM python:3.10-slim
75
-
76
- WORKDIR /app
77
-
78
- # Install system dependencies
79
- RUN apt-get update && apt-get install -y \
80
- build-essential \
81
- && rm -rf /var/lib/apt/lists/*
82
-
83
- # Copy requirements
84
- COPY requirements.txt .
85
-
86
- # Install Python dependencies
87
- RUN pip install --no-cache-dir -r requirements.txt
88
-
89
- # Copy application
90
- COPY . .
91
-
92
- # Create directories
93
- RUN mkdir -p data/database logs
94
-
95
- # Expose port
96
- EXPOSE 7860
97
-
98
- # Set environment
99
- ENV PORT=7860
100
- ENV PYTHONUNBUFFERED=1
101
-
102
- # Start server
103
- CMD ["uvicorn", "hf_unified_server:app", "--host", "0.0.0.0", "--port", "7860"]
104
- ```
105
-
106
- ### Space Settings (در UI)
107
- ```yaml
108
- # Secrets
109
- HF_TOKEN: your_token_here
110
-
111
- # Hardware
112
- - CPU basic (Free) - برای شروع
113
- - CPU upgrade (Paid) - برای production با traffic بیشتر
114
- ```
115
-
116
- ## تست Endpoints
117
-
118
- ### Health Check
119
- ```bash
120
- curl http://localhost:7860/api/health
121
- ```
122
-
123
- ### Top Coins
124
- ```bash
125
- curl http://localhost:7860/api/coins/top?limit=10
126
- ```
127
-
128
- ### Market Stats
129
- ```bash
130
- curl http://localhost:7860/api/market/stats
131
- ```
132
-
133
- ### Sentiment Analysis
134
- ```bash
135
- curl -X POST http://localhost:7860/api/sentiment/analyze \
136
- -H "Content-Type: application/json" \
137
- -d '{"text": "Bitcoin is breaking new ATH!"}'
138
- ```
139
-
140
- ### Models List
141
- ```bash
142
- curl http://localhost:7860/api/models/list
143
- ```
144
-
145
- ### Datasets List
146
- ```bash
147
- curl http://localhost:7860/api/datasets/list
148
- ```
149
-
150
- ### WebSocket Test (در browser console)
151
- ```javascript
152
- const ws = new WebSocket('ws://localhost:7860/ws');
153
-
154
- ws.onopen = () => console.log('Connected');
155
- ws.onmessage = (event) => console.log('Update:', JSON.parse(event.data));
156
- ws.onerror = (error) => console.error('Error:', error);
157
- ```
158
-
159
- ## مشکلات رایج و راه حل
160
-
161
- ### 1. Out of Memory
162
- ```bash
163
- # کاهش مدل‌های load شده
164
- # در ai_models.py فقط crypto_sent_0 و financial_sent_0 load میشه
165
-
166
- # یا استفاده از CPU basic به جای GPU
167
- ```
168
-
169
- ### 2. Slow Model Loading
170
- ```bash
171
- # استفاده از model caching در HuggingFace
172
- export TRANSFORMERS_CACHE=/app/.cache/huggingface
173
- ```
174
-
175
- ### 3. Rate Limiting
176
- ```bash
177
- # استفاده از HF_TOKEN برای rate limit بالاتر
178
- export HF_TOKEN=hf_your_token
179
- ```
180
-
181
- ### 4. WebSocket Connection Failed
182
- ```bash
183
- # چک کردن CORS settings
184
- # مطمئن شوید که در hf_unified_server.py:
185
- app.add_middleware(
186
- CORSMiddleware,
187
- allow_origins=["*"],
188
- allow_credentials=True,
189
- allow_methods=["*"],
190
- allow_headers=["*"],
191
- )
192
- ```
193
-
194
- ## بهینه‌سازی برای Production
195
-
196
- ### 1. Caching
197
- ```python
198
- # در hf_unified_server.py
199
- from functools import lru_cache
200
-
201
- @lru_cache(maxsize=128)
202
- def get_cached_coins(limit: int):
203
- # Cache results for 1 minute
204
- pass
205
- ```
206
-
207
- ### 2. Rate Limiting
208
- ```python
209
- from slowapi import Limiter
210
- from slowapi.util import get_remote_address
211
-
212
- limiter = Limiter(key_func=get_remote_address)
213
- app.state.limiter = limiter
214
-
215
- @app.get("/api/sentiment/analyze")
216
- @limiter.limit("10/minute")
217
- async def analyze_sentiment(...):
218
- pass
219
- ```
220
-
221
- ### 3. Model Optimization
222
- ```python
223
- # Use smaller models for faster inference
224
- # quantization برای کاهش حجم
225
- from transformers import AutoModelForSequenceClassification
226
- model = AutoModelForSequenceClassification.from_pretrained(
227
- "model_id",
228
- torch_dtype=torch.float16 # Half precision
229
- )
230
- ```
231
-
232
- ## Monitoring
233
-
234
- ### Logs
235
- ```bash
236
- # Docker logs
237
- docker logs -f crypto-hub
238
-
239
- # HuggingFace Space logs
240
- # قابل مشاهده در dashboard Space
241
- ```
242
-
243
- ### Metrics
244
- ```bash
245
- # Health endpoint برای monitoring
246
- curl http://your-space.hf.space/api/health
247
-
248
- # Response:
249
- {
250
- "status": "healthy",
251
- "uptime": 3600,
252
- "models_loaded": 2,
253
- "datasets_available": 14
254
- }
255
- ```
256
-
257
- ## Support
258
-
259
- - **Documentation**: README_HF_INTEGRATION.md
260
- - **Issues**: Check logs first
261
- - **Performance**: Use HF Space with GPU for heavy models
262
-
263
- ## نکات مهم
264
-
265
- 1. ⚠️ **HF_TOKEN**: حتماً در secrets تنظیم کنید
266
- 2. 🔥 **Models**: اولین بار کند است (downloading)
267
- 3. 💾 **Cache**: مدل‌ها cache می‌شوند
268
- 4. 🚀 **WebSocket**: برای real-time updates
269
- 5. 📊 **Dashboard**: در `/` قابل دسترسی
 
1
+ # 🚀 Deployment Guide - Modern Crypto Intelligence Hub
2
+
3
+ ## Overview
4
+ This guide explains how to deploy the **new modern UI** with sidebar navigation, glassmorphism theme, and visual sentiment analysis.
5
+
6
+ ---
7
+
8
+ ## 🎯 What Changed
9
+
10
+ ### New Features
11
+ 1. **Vertical Sidebar Navigation** - Replaces top tab bar, collapses to hamburger menu on mobile
12
+ 2. **Inline SVG Icons** - Replaced FontAwesome with crisp SVG icons (Heroicons/Feather style)
13
+ 3. **Glassmorphism Theme** - Deep dark theme with blur effects and neon accents
14
+ 4. **Modern News Cards** - Time-ago formatting, sorted by latest, image placeholders
15
+ 5. **Visual Sentiment Analysis**:
16
+ - Gauge/speedometer charts showing sentiment scores
17
+ - Animated trend arrows (green up for bullish, red down for bearish)
18
+ - Confidence bars with shimmer effects
19
+ 6. **Fixed Dashboard** - Loads immediately on page load
20
+
21
+ ### 📁 Files Updated
22
+ - `index.html` - New sidebar structure with SVG icons
23
+ - `static/css/main.css` - Glassmorphism styles, news cards, sentiment visualizations
24
+ - `static/js/app.js` - Visual sentiment functions, time-ago formatting, improved news display
25
+ - `app.py` - Forces FastAPI mode
26
+ - `Dockerfile` - Updated to run FastAPI directly
27
+ - `README.md` - Added Hugging Face Space metadata
28
+
29
+ ---
30
+
31
+ ## 🚀 Deployment Options
32
+
33
+ ### Option 1: Hugging Face Spaces (Recommended)
34
+
35
+ The app is configured to run on Hugging Face Spaces with Docker SDK.
36
+
37
+ **Steps:**
38
+ 1. Push all files to your Hugging Face Space repository
39
+ 2. Ensure `README.md` has the correct metadata (already added):
40
+ ```yaml
41
+ ---
42
+ title: Crypto Intelligence Hub
43
+ emoji: 🚀
44
+ sdk: docker
45
+ app_port: 7860
46
+ ---
47
+ ```
48
+ 3. The Space will automatically build and deploy using the `Dockerfile`
49
+ 4. The Dockerfile is configured to run: `uvicorn api_server_extended:app`
50
+
51
+ **Environment Variables (Optional):**
52
+ - `USE_FASTAPI_HTML=true` (default in Dockerfile)
53
+ - `PORT=7860` (default)
54
+
55
+ ### Option 2: Local Development
56
+
57
+ **Using PowerShell:**
58
+ ```powershell
59
+ # Navigate to project directory
60
+ cd "path\to\crypto-dt-source-main"
61
+
62
+ # Install dependencies
63
+ pip install -r requirements.txt
64
+
65
+ # Run FastAPI server directly
66
+ python -m uvicorn api_server_extended:app --host 0.0.0.0 --port 7860 --reload
67
+ ```
68
+
69
+ **Using the startup script:**
70
+ ```bash
71
+ # Make executable (Linux/Mac)
72
+ chmod +x start_app.sh
73
+ ./start_app.sh
74
+ ```
75
+
76
+ ### Option 3: Docker
77
+
78
+ ```bash
79
+ # Build image
80
+ docker build -t crypto-hub .
81
+
82
+ # Run container
83
+ docker run -p 7860:7860 crypto-hub
84
+ ```
85
+
86
+ ---
87
+
88
+ ## 🔧 Troubleshooting
89
+
90
+ ### Issue: Gradio UI shows instead of modern HTML UI
91
+
92
+ **Solution:**
93
+ The app should automatically use FastAPI mode. If you see Gradio:
94
+
95
+ 1. Check environment variables:
96
+ ```bash
97
+ export USE_FASTAPI_HTML=true
98
+ export USE_GRADIO=false
99
+ ```
100
+
101
+ 2. Run FastAPI directly:
102
+ ```bash
103
+ python -m uvicorn api_server_extended:app --host 0.0.0.0 --port 7860
104
+ ```
105
+
106
+ 3. Verify `Dockerfile` CMD:
107
+ ```dockerfile
108
+ CMD ["python", "-m", "uvicorn", "api_server_extended:app", "--host", "0.0.0.0", "--port", "7860"]
109
+ ```
110
+
111
+ ### Issue: Static files not loading
112
+
113
+ **Solution:**
114
+ 1. Verify `static/` folder exists with `css/` and `js/` subdirectories
115
+ 2. Check `api_server_extended.py` mounts static files:
116
+ ```python
117
+ app.mount("/static", StaticFiles(directory=str(static_path)), name="static")
118
+ ```
119
+ 3. Access files at: `http://localhost:7860/static/css/main.css`
120
+
121
+ ### Issue: News not loading
122
+
123
+ **Solution:**
124
+ 1. Click "Fetch Latest News" button to pull from CryptoCompare API
125
+ 2. Check database: `data/database/crypto_monitor.db`
126
+ 3. Verify `/api/news` endpoint returns data
127
+
128
+ ### Issue: Sentiment analysis not working
129
+
130
+ **Solution:**
131
+ 1. Check Hugging Face models are loaded: Visit `/api/models/status`
132
+ 2. Models use fallback lexical analysis if HF models unavailable
133
+ 3. Check logs for model loading errors
134
+
135
+ ---
136
+
137
+ ## 📊 API Endpoints
138
+
139
+ The FastAPI server provides these endpoints:
140
+
141
+ - `/` - Main dashboard (HTML UI)
142
+ - `/api/resources` - System resources summary
143
+ - `/api/market` - Cryptocurrency market data
144
+ - `/api/news` - News articles
145
+ - `/api/news/fetch` - Fetch latest news from CryptoCompare
146
+ - `/api/sentiment/analyze` - Sentiment analysis
147
+ - `/api/models/status` - AI models status
148
+ - `/api/models/list` - Available models
149
+ - `/docs` - Interactive API documentation
150
+ - `/health` - Health check
151
+
152
+ ---
153
+
154
+ ## 🎨 UI Features
155
+
156
+ ### Sidebar Navigation
157
+ - **Desktop:** Fixed sidebar on left, 280px wide
158
+ - **Mobile:** Collapsible hamburger menu with overlay
159
+ - **Icons:** Inline SVG for crisp rendering at any size
160
+
161
+ ### News Feed
162
+ - **Time-Ago:** Shows "2 hours ago" instead of dates
163
+ - **Sorting:** Latest news first
164
+ - **Cards:** Modern card design with image placeholders
165
+ - **Symbols:** Related crypto symbols as badges
166
+
167
+ ### Sentiment Analysis
168
+ - **Gauge Chart:** Semi-circular gauge (0-100 scale)
169
+ - **Trend Arrows:** Animated SVG arrows indicating direction
170
+ - **Confidence Bar:** Progress bar with shimmer animation
171
+ - **Color Coding:**
172
+ - Green (Bullish/Positive)
173
+ - Red (Bearish/Negative)
174
+ - Yellow (Neutral)
175
+
176
+ ---
177
+
178
+ ## 🔒 Security Notes
179
+
180
+ 1. **API Keys:** Store in environment variables, not in code
181
+ 2. **CORS:** Configured for all origins in development (restrict in production)
182
+ 3. **Rate Limiting:** Consider adding rate limiting for production
183
+ 4. **Database:** SQLite for development, consider PostgreSQL for production
184
+
185
+ ---
186
+
187
+ ## 📝 Next Steps
188
+
189
+ 1. **Deploy to Hugging Face Spaces**
190
+ 2. **Test all features:**
191
+ - Dashboard loads
192
+ - News fetches and displays
193
+ - Sentiment analysis works
194
+ - Sidebar navigation functions
195
+ - Mobile responsive design
196
+ 3. **Monitor logs** for any errors
197
+ 4. **Customize:**
198
+ - Add your own API keys
199
+ - Adjust theme colors in `main.css`
200
+ - Add more trading pairs in `trading_pairs.txt`
201
+
202
+ ---
203
+
204
+ ## 🆘 Support
205
+
206
+ If you encounter issues:
207
+ 1. Check browser console for JavaScript errors
208
+ 2. Check server logs for Python errors
209
+ 3. Verify all dependencies are installed
210
+ 4. Ensure `index.html`, `main.css`, and `app.js` are in correct locations
211
+
212
+ ---
213
+
214
+ **Enjoy your modern Crypto Intelligence Hub! 🚀**
215
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dockerfile CHANGED
@@ -33,5 +33,5 @@ ENV USE_GRADIO=false
33
 
34
  EXPOSE 7860
35
 
36
- # Run the application (will choose Gradio or FastAPI based on env vars)
37
- CMD ["python", "app.py"]
 
33
 
34
  EXPOSE 7860
35
 
36
+ # Run the FastAPI application directly for modern HTML UI
37
+ CMD ["python", "-m", "uvicorn", "api_server_extended:app", "--host", "0.0.0.0", "--port", "7860"]
__pycache__/ai_models.cpython-313.pyc CHANGED
Binary files a/__pycache__/ai_models.cpython-313.pyc and b/__pycache__/ai_models.cpython-313.pyc differ
 
__pycache__/api_server_extended.cpython-313.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25c377b2d08d563fce48c8cd8fda8166287ce225d1a7469a288227d1ab6b42e3
3
+ size 146136
__pycache__/config.cpython-313.pyc CHANGED
Binary files a/__pycache__/config.cpython-313.pyc and b/__pycache__/config.cpython-313.pyc differ
 
__pycache__/hf_unified_server.cpython-313.pyc CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:95d175b459a983f328419804aacfc0f73321bc4e516957dfabc266847afc655c
3
- size 113609
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:daa8c605bec5a177f1583e7c65957cbe2b6d7b9345bd816a4776b3f43e1d0b34
3
+ size 457
api_server_extended.py CHANGED
@@ -655,15 +655,15 @@ try:
655
  static_path = WORKSPACE_ROOT / "static"
656
  if static_path.exists():
657
  app.mount("/static", StaticFiles(directory=str(static_path)), name="static")
658
- print(f"Mounted static files from {static_path}")
659
  else:
660
  # Create static directories if they don't exist
661
  static_path.mkdir(parents=True, exist_ok=True)
662
  (static_path / "css").mkdir(exist_ok=True)
663
  (static_path / "js").mkdir(exist_ok=True)
664
- print(f"Created static directories at {static_path}")
665
  except Exception as e:
666
- print(f"Could not mount static files: {e}")
667
 
668
  # Serve trading pairs file
669
  @app.get("/trading_pairs.txt")
 
655
  static_path = WORKSPACE_ROOT / "static"
656
  if static_path.exists():
657
  app.mount("/static", StaticFiles(directory=str(static_path)), name="static")
658
+ logger.info(f"Mounted static files from {static_path}")
659
  else:
660
  # Create static directories if they don't exist
661
  static_path.mkdir(parents=True, exist_ok=True)
662
  (static_path / "css").mkdir(exist_ok=True)
663
  (static_path / "js").mkdir(exist_ok=True)
664
+ logger.info(f"Created static directories at {static_path}")
665
  except Exception as e:
666
+ logger.warning(f"Could not mount static files: {e}")
667
 
668
  # Serve trading pairs file
669
  @app.get("/trading_pairs.txt")
app.py CHANGED
@@ -768,11 +768,12 @@ if __name__ == "__main__":
768
  logger.info(f"🤖 Models available: {len(hub.get_available_models())}")
769
  logger.info(f"🔌 FastAPI available: {FASTAPI_AVAILABLE}")
770
 
771
- # Force FastAPI+HTML mode for HuggingFace Spaces
772
- # Choose mode based on environment variables
773
  if FASTAPI_AVAILABLE:
774
  # Run FastAPI with HTML interface (preferred for HF Spaces)
775
  logger.info("🌐 Starting FastAPI server with HTML interface...")
 
776
  import uvicorn
777
  port = int(os.getenv("PORT", "7860"))
778
  uvicorn.run(
@@ -781,17 +782,23 @@ if __name__ == "__main__":
781
  port=port,
782
  log_level="info"
783
  )
784
- elif USE_GRADIO:
785
- # Run Gradio interface (fallback)
786
- logger.info("🎨 Starting Gradio interface...")
787
- app = create_gradio_interface()
788
- app.launch(
789
- server_name="0.0.0.0",
790
- server_port=int(os.getenv("GRADIO_SERVER_PORT", "7860")),
791
- share=False,
792
- show_error=True
793
- )
794
  else:
795
- # No UI mode available
796
- logger.error(" No UI mode available (FastAPI unavailable and Gradio disabled). Exiting.")
797
- raise SystemExit(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
768
  logger.info(f"🤖 Models available: {len(hub.get_available_models())}")
769
  logger.info(f"🔌 FastAPI available: {FASTAPI_AVAILABLE}")
770
 
771
+ # FORCE FastAPI+HTML mode for modern UI
772
+ # Always prefer FastAPI with HTML interface over Gradio
773
  if FASTAPI_AVAILABLE:
774
  # Run FastAPI with HTML interface (preferred for HF Spaces)
775
  logger.info("🌐 Starting FastAPI server with HTML interface...")
776
+ logger.info("✨ Modern UI with Sidebar Navigation enabled")
777
  import uvicorn
778
  port = int(os.getenv("PORT", "7860"))
779
  uvicorn.run(
 
782
  port=port,
783
  log_level="info"
784
  )
 
 
 
 
 
 
 
 
 
 
785
  else:
786
+ # Fallback: Try to import and run api_server_extended directly
787
+ logger.warning("⚠️ FastAPI not imported via normal path, trying direct import...")
788
+ try:
789
+ import sys
790
+ sys.path.insert(0, str(WORKSPACE_ROOT))
791
+ from api_server_extended import app as fastapi_app_direct
792
+ import uvicorn
793
+ port = int(os.getenv("PORT", "7860"))
794
+ logger.info("🌐 Starting FastAPI server (direct import)...")
795
+ uvicorn.run(
796
+ fastapi_app_direct,
797
+ host="0.0.0.0",
798
+ port=port,
799
+ log_level="info"
800
+ )
801
+ except Exception as e:
802
+ logger.error(f"❌ Could not start FastAPI: {e}")
803
+ logger.error("❌ Modern UI unavailable. Please check api_server_extended.py")
804
+ raise SystemExit(1)