File size: 8,715 Bytes
2202b83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import gradio as gr
import requests
from transformers import pipeline
import json
import time
from typing import Dict, List
import os

class FinanceAgent:
    def __init__(self):
        # Initialize the summarization pipeline
        try:
            self.summarizer = pipeline(
                "summarization", 
                model="facebook/bart-large-cnn",
                max_length=512,
                min_length=100
            )
        except Exception as e:
            print(f"Error loading summarization model: {e}")
            self.summarizer = None
        
    def search_web(self, query: str, num_results: int = 5) -> List[Dict]:
        """
        Search the web using DuckDuckGo API (free alternative)
        """
        try:
            # Using DuckDuckGo Instant Answer API
            url = "https://api.duckduckgo.com/"
            params = {
                'q': f"{query} finance financial",
                'format': 'json',
                'no_html': '1',
                'skip_disambig': '1'
            }
            
            response = requests.get(url, params=params, timeout=10)
            data = response.json()
            
            results = []
            
            # Extract abstract if available
            if data.get('Abstract'):
                results.append({
                    'title': data.get('Heading', 'Financial Information'),
                    'content': data.get('Abstract', ''),
                    'url': data.get('AbstractURL', '')
                })
            
            # Extract related topics
            for topic in data.get('RelatedTopics', [])[:num_results-1]:
                if isinstance(topic, dict) and topic.get('Text'):
                    results.append({
                        'title': topic.get('Text', '')[:100] + '...',
                        'content': topic.get('Text', ''),
                        'url': topic.get('FirstURL', '')
                    })
            
            return results
            
        except Exception as e:
            print(f"Search error: {e}")
            return [{'title': 'Search Error', 'content': f'Unable to search: {str(e)}', 'url': ''}]
    
    def get_financial_context(self, topic: str) -> str:
        """
        Get basic financial context for common topics
        """
        financial_contexts = {
            'stock': 'Stocks represent ownership shares in publicly traded companies. Stock prices fluctuate based on company performance, market conditions, and investor sentiment.',
            'bond': 'Bonds are debt securities where investors lend money to entities for a defined period at a fixed interest rate.',
            'cryptocurrency': 'Cryptocurrencies are digital assets that use cryptography for security and operate on decentralized networks.',
            'inflation': 'Inflation is the rate at which the general level of prices for goods and services rises, eroding purchasing power.',
            'recession': 'A recession is a significant decline in economic activity across the economy lasting more than a few months.',
            'fed': 'The Federal Reserve is the central banking system of the United States, responsible for monetary policy.',
            'gdp': 'Gross Domestic Product (GDP) is the total monetary value of all goods and services produced within a country.',
            'market': 'Financial markets are platforms where buyers and sellers trade financial securities, commodities, and other assets.'
        }
        
        topic_lower = topic.lower()
        for key, context in financial_contexts.items():
            if key in topic_lower:
                return context
        
        return "This is a financial topic that may involve various economic, market, or investment-related concepts."
    
    def summarize_content(self, content: str, max_length: int = 300) -> str:
        """
        Summarize content using the transformer model
        """
        if not self.summarizer or not content.strip():
            return "Unable to generate summary."
        
        try:
            # Truncate content if too long
            if len(content) > 1000:
                content = content[:1000] + "..."
            
            summary = self.summarizer(content, max_length=max_length, min_length=50, do_sample=False)
            return summary[0]['summary_text']
        except Exception as e:
            print(f"Summarization error: {e}")
            return f"Summary unavailable: {str(e)}"
    
    def process_finance_query(self, prompt: str) -> str:
        """
        Main function to process finance queries
        """
        if not prompt.strip():
            return "Please enter a financial topic or question."
        
        # Add progress indicator
        progress_msg = f"πŸ” Searching for information about: {prompt}\n\n"
        
        # Search for relevant information
        search_results = self.search_web(prompt)
        
        if not search_results:
            return progress_msg + "❌ No search results found. Please try a different query."
        
        # Combine search results
        combined_content = ""
        sources = []
        
        for i, result in enumerate(search_results[:3], 1):  # Limit to top 3 results
            if result.get('content'):
                combined_content += f"\n{result['content']}\n"
                if result.get('url'):
                    sources.append(f"{i}. {result['url']}")
        
        # Get financial context
        context = self.get_financial_context(prompt)
        
        # Create comprehensive content for summarization
        full_content = f"{context}\n\nCurrent Information:\n{combined_content}"
        
        # Generate summary
        summary = self.summarize_content(full_content)
        
        # Format final response
        response = f"""## πŸ“Š Financial Summary: {prompt.title()}

### 🎯 Key Points:
{summary}

### πŸ“‹ Context:
{context}

### πŸ”— Sources:
"""
        
        if sources:
            for source in sources:
                response += f"\n{source}"
        else:
            response += "\nInformation compiled from web search results."
        
        response += f"\n\n⏰ *Generated on: {time.strftime('%Y-%m-%d %H:%M:%S')}*"
        
        return response

# Initialize the agent
agent = FinanceAgent()

def finance_chat_interface(message, history):
    """
    Gradio chat interface function
    """
    try:
        response = agent.process_finance_query(message)
        return response
    except Exception as e:
        return f"❌ Error processing your request: {str(e)}\n\nPlease try again with a different query."

# Create Gradio interface
def create_interface():
    with gr.Blocks(title="Financial AI Agent", theme=gr.themes.Soft()) as demo:
        gr.Markdown("""
        # 🏦 Financial AI Agent
        
        Ask me about any financial topic and I'll search the web for current information and provide you with a comprehensive summary.
        
        **Examples:**
        - "What is the current state of cryptocurrency market?"
        - "Explain inflation and its impact on the economy"
        - "Tell me about recent stock market trends"
        - "What are bonds and how do they work?"
        """)
        
        chatbot = gr.Chatbot(
            height=500,
            placeholder="Financial AI Agent is ready to help with your finance questions!"
        )
        
        msg = gr.Textbox(
            label="Ask a financial question",
            placeholder="e.g., What is inflation and how does it affect the stock market?",
            lines=2
        )
        
        clear = gr.Button("Clear Chat")
        
        def user(user_message, history):
            return "", history + [[user_message, None]]
        
        def bot(history):
            if history and history[-1][1] is None:
                user_message = history[-1][0]
                bot_message = finance_chat_interface(user_message, history[:-1])
                history[-1][1] = bot_message
            return history
        
        msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
            bot, chatbot, chatbot
        )
        
        clear.click(lambda: None, None, chatbot, queue=False)
        
        gr.Markdown("""
        ### πŸ“ Notes:
        - This agent searches the web for current financial information
        - Summaries are generated using AI and should be verified with official sources
        - For investment decisions, always consult with qualified financial advisors
        """)
    
    return demo

if __name__ == "__main__":
    demo = create_interface()
    demo.launch(share=True)