File size: 5,390 Bytes
42c9f4e
 
 
 
 
 
 
 
5296288
 
42c9f4e
 
 
 
 
 
 
 
a83dc1f
42c9f4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb4b18c
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
import streamlit as st
import pandas as pd
import anthropic
import base64
from datetime import datetime
from pathlib import Path
from utils import EmbeddingManager
import json,os
from dotenv import load_dotenv

load_dotenv()

def get_excel_report(df):
    """Generate prompt for Claude to create complete HTML report"""
    columns = df.columns.tolist()
    dtypes = df.dtypes.to_dict()
    summary_stats = df.describe().to_json()
    
    prompt = f"""Given the Excel data by user:
    
    
    Create a complete, professional HTML report that includes:
    1. Executive summary
    2. Data insights and patterns
    3. Statistical analysis
    4. Visualizations using Plotly
    
    Important Requirements:
    - Include all necessary Plotly CDN scripts
    - Choose appropriate visualizations based on the data patterns
    - Include proper styling with CSS
    - Make it visually appealing and professional
    - Add explanations for each insight and visualization
    - Include the current date in the report
    
    For visualizations:
    - Use Plotly.js for all charts
    - Include the full Plotly JavaScript code
    - Choose appropriate chart types based on the data
    - Add proper titles, labels, and legends
    
    Return only the complete HTML code that's ready to be saved as an HTML file."""
    
    return prompt

def save_html(html_content):
    """Save HTML content and create download link"""
    b64 = base64.b64encode(html_content.encode()).decode()
    href = f'<a href="data:text/html;base64,{b64}" download="report.html">Download HTML Report</a>'
    return href

# def send_to_claude(data):
#     prompt = "Analyze the following data and provide visualizations in graph format."
    
#     for key, value in data.items():
#         if isinstance(value, pd.Timestamp):
#             data[key] = value.isoformat()

#     client = anthropic.AnthropicBedrock()
#     message = client.messages.create(
#         model="anthropic.claude-3-5-sonnet-20240620-v1:0",
#         max_tokens=256,
#         system=prompt,
#         messages=[{"role": "user", "content": str(data)}]
#     )
    
#     return message

def create_chunks_and_send(data: pd.DataFrame,filename):
    output_dir=Path('./output')
    embeddings_dir = output_dir / 'embeddings' / filename
    embeddings_dir.mkdir(parents=True, exist_ok=True)
    if embeddings_dir.exists():
        chunks_file = embeddings_dir / "chunks.json"
        if chunks_file.is_file():
            with open(chunks_file, "r", encoding="utf-8") as f:
                chunks = json.load(f)
            #print("File content as list:", chunks)
        else:
            print("chunks.json does not exist in the directory.")
    else:
     embedding_manager = EmbeddingManager(output_dir=Path('./output'))
     text = data.to_json()
     chunks, embedding_dir = embedding_manager.process_script(data=str(text),filename=filename)
    
    
    #analysis_results = send_to_claude({"chunks": chunks})
    return chunks

def main():
    st.title("Excel Analysis Report Generator")
    
    # API Key input
    #api_key = st.text_input("Enter your Anthropic API Key:", type="password")
    
    # File upload
    uploaded_file = st.file_uploader("Upload Excel File", type=['xlsx', 'xls'])
    query = st.text_input("Enter the query")
    if uploaded_file and query:
        try:
            # Read Excel file
           
            df_dict = pd.read_excel(uploaded_file,sheet_name = None)
            df = pd.concat(df_dict.values(),ignore_index=None)
            
            st.success("File uploaded successfully!")
            
            # Show data preview
            #st.subheader("Data Preview")
            #st.dataframe(df)
            
            if st.button("Enter"):
                with st.spinner("Generating report with Claude..."):
                    # Initialize Claude client
                    client = anthropic.AnthropicBedrock(
                        aws_access_key=os.getenv('aws_access_key_id'),
                        aws_secret_key=os.getenv('aws_secret_access_key'),
                    )
                    data = create_chunks_and_send(df,uploaded_file.name)
                    # Get complete HTML report from Claude
                    prompt = get_excel_report(df)
                    response = client.messages.create(
                    model="anthropic.claude-3-5-sonnet-20240620-v1:0",
                    max_tokens=4096,
                    system=prompt,
                    messages=[{"role": "user", "content": f"""{str(data)} query: {query}"""}]
                )
                    
                    # Get the HTML content (ensure it's a string)
                    html_report = ''.join(str(message.text) for message in response.content)
                    
                    # Create download link
                    st.markdown(save_html(html_report), unsafe_allow_html=True)
                    
                    # Show preview
                    st.components.v1.html(html_report, height=800, scrolling=True)
                    
                    st.success("Report generated successfully! Click the link above to download.")
                    
        except Exception as e:
            st.error(f"An error occurred: {str(e)}")
            #st.error("Please check your API key and file format, then try again.")

if __name__ == "__main__":
    main()