Spaces:
Sleeping
Sleeping
| 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() |