import requests import matplotlib.pyplot as plt import datetime import gradio as gr from openai import OpenAI import os # Coingecko API Base URL BASE_URL = "https://api.coingecko.com/api/v3/" # Coingecko API'den coin verilerini alma def get_coin_list(currency="usd"): url = f"{BASE_URL}coins/markets?vs_currency={currency}&order=market_cap_desc&per_page=100&page=1&sparkline=false" response = requests.get(url) return response.json() def get_single_coin(id, currency="usd"): url = f"{BASE_URL}coins/{id}" response = requests.get(url) return response.json() def get_historical_chart(id, days=365, currency="usd"): url = f"{BASE_URL}coins/{id}/market_chart?vs_currency={currency}&days={days}" response = requests.get(url) return response.json() # OpenAI API Key ve Client Initialization ACCESS_TOKEN = os.getenv("HF_TOKEN") client = OpenAI( base_url="https://api-inference.huggingface.co/v1/", api_key=ACCESS_TOKEN, ) # Hardcoded system message and other parameters system_message = "You are a cryptocurrency trading assistant and market analyst. Your role is to provide users with data-driven insights, technical analysis (RSI, MACD, Bollinger Bands, Moving Averages, Fibonacci retracements, volume analysis, and price action), and investment advice tailored to their risk tolerance. Focus on actionable information, such as market conditions, key indicators, and investment strategies. Avoid speculation and provide clear, concise, and unbiased recommendations based on current data." max_tokens = 1024 temperature = 0.3 top_p = 0.95 frequency_penalty = 0.0 seed = -1 # Random seed def respond(message, history: list[tuple[str, str]]): # Coin verisini al coin_data = search_coin_by_name(message) if coin_data: # LLM yanıtını oluştur llm_msg = llm_response(coin_data, message) # Grafik oluştur chart_image = plot_coin_chart(message) return llm_msg, chart_image else: return "Coin bulunamadı.", None def search_coin_by_name(name, currency="usd"): coin_list = get_coin_list(currency) for coin in coin_list: if name.lower() in coin['name'].lower() or name.lower() in coin['id'].lower(): return coin return None def llm_response(coin_data, coin_name): # LLM sistem mesajı ve coin verilerini kullanarak anlamlı bir cevap üretme response = f"{coin_name} ile ilgili bilgiler:\n" response += f"Fiyat: {coin_data['current_price']} USD\n" response += f"Piyasa Değeri: {coin_data['market_cap']} USD\n" response += f"24 Saatlik Değişim: {coin_data['price_change_percentage_24h']}%\n" return response def plot_coin_chart(id, days=30, currency="usd"): historical_data = get_historical_chart(id, days, currency) prices = historical_data['prices'] timestamps = [datetime.datetime.utcfromtimestamp(price[0] / 1000) for price in prices] price_values = [price[1] for price in prices] plt.figure(figsize=(10, 5)) plt.plot(timestamps, price_values) plt.title(f"{id} Coin {days} Günlük Fiyat Grafiği") plt.xlabel('Tarih') plt.ylabel(f'{currency.upper()} Fiyatı') plt.xticks(rotation=45) plt.tight_layout() plt.savefig("coin_chart.png") # Grafiği kaydediyoruz return "coin_chart.png" # Grafiğin yolunu döndürüyoruz # Gradio UI chatbot = gr.Chatbot(height=600, show_copy_button=True, placeholder="Start chatting!", likeable=True, layout="panel") demo = gr.ChatInterface( fn=respond, additional_inputs=[], # No additional inputs needed since everything is embedded fill_height=True, chatbot=chatbot, theme="Nymbo/Nymbo_Theme", ) with demo: # No need for system message input, model selection, or sliders pass if __name__ == "__main__": demo.launch()