this is my app.py
import os
import tempfile
import streamlit as st
import streamlit.components.v1 as components
from git import Repo, GitCommandError

from agents import (
    FilterAgent,
    AnalysisAgent,
    ConsolidationAgent,
    ImprovementAgent,
    DiagramAgent,
)
from file_handling.file_handler import FileHandler
from utils.azure_client import get_azure_client

from dotenv import load_dotenv
load_dotenv()

BASE_PROMPT_DIR = os.path.join(os.path.dirname(__file__), "agents", "prompts")

st.set_page_config(page_title="Project Architecture Analyzer", layout="wide")


def main():
    st.title("🔍 Project Architecture Analyzer")

    repo_url = st.text_input("GitHub Repository URL")

    # Sidebar for credentials & settings
    st.sidebar.header("Configuration")
    pat = st.sidebar.text_input("GitHub Personal Access Token", type="password")
    azure_endpoint = st.sidebar.text_input(
        "Azure OpenAI Endpoint",
        value=os.environ.get("AZURE_OPENAI_ENDPOINT", ""),
    )
    api_key = st.sidebar.text_input(
        "Azure OpenAI API Key",
        type="password",
        value=os.environ.get("AZURE_OPENAI_API_KEY", ""),
    )
    deployment_name = st.sidebar.text_input(
        "Azure OpenAI Chat Deployment Name",
        value=os.environ.get("AZURE_OPENAI_DEPLOYMENT_NAME", ""),
    )
    analysis_mode = st.sidebar.selectbox("Analysis Mode", ["Technical Blueprint", "Improvement Plan", "Cloud Architecture Diagram"])

    if st.button("Analyze Project"):
        if not all([repo_url, pat, azure_endpoint, api_key, deployment_name]):
            st.error("Please fill in all configuration fields.")
        else:
            run_analysis(repo_url, pat, azure_endpoint, api_key, deployment_name, analysis_mode)


def run_analysis(repo_url, pat, azure_endpoint, api_key, deployment_name, analysis_mode):
    try:
        client = get_azure_client(azure_endpoint, api_key)
    except Exception as e:
        st.error(f"Azure OpenAI client initialization failed: {e}")
        return

    # Initialize agents
    filter_agent = FilterAgent(client, deployment_name, os.path.join(BASE_PROMPT_DIR, "filter_agent_prompt.txt"))
    analysis_agent = AnalysisAgent(client, deployment_name, os.path.join(BASE_PROMPT_DIR, "analysis_agent_prompt.txt"))
    consolidation_agent = ConsolidationAgent(client, deployment_name, os.path.join(BASE_PROMPT_DIR, "consolidation_agent_prompt.txt"))
    improvement_agent = ImprovementAgent(client, deployment_name, os.path.join(BASE_PROMPT_DIR, "improvement_agent_prompt.txt"))

    # DiagramAgent only needs chat deployment and prompt path - image deployment handled internally
    diagram_agent = DiagramAgent(
        client,
        deployment_name,
        os.path.join(BASE_PROMPT_DIR, "diagram_agent_prompt.txt"),
    )

    with tempfile.TemporaryDirectory() as tmp_dir:
        try:
            with st.spinner("🌀 Cloning repository..."):
                if pat:
                    if not repo_url.startswith("https://"):
                        st.error("PAT can only be used with HTTPS URLs")
                        return
                    auth_repo_url = repo_url.replace("https://", f"https://{pat}@", 1)
                else:
                    auth_repo_url = repo_url

                Repo.clone_from(auth_repo_url, tmp_dir)
            st.success("Repository cloned successfully")

            with st.spinner("🔍 Loading analysis overview..."):
                file_handler = FileHandler(tmp_dir, filter_agent)

                st.subheader("📊 Analysis Overview")
                cols = st.columns(4)
                cols[0].metric("Total Files", file_handler.total_scanned)
                cols[1].metric("Included Files", len(file_handler.files))
                cols[2].metric("Excluded Files", len(file_handler.excluded_files))
                ratio = 0
                if file_handler.total_scanned > 0:
                    ratio = len(file_handler.files) / file_handler.total_scanned * 100
                cols[3].metric("Focus Ratio", f"{ratio:.1f}%")

            consolidated_summary = "## Project Architecture Blueprint\n"
            total_files = len(file_handler.files)

            progress_bar = st.progress(0)
            status_box = st.empty()

            for idx, file_path in enumerate(file_handler.files):
                content = file_handler.read_file_content(file_path)
                rel_path = os.path.relpath(file_path, tmp_dir)

                with st.spinner(f"Analyzing {rel_path}..."):
                    summary = analysis_agent.summarize_file(rel_path, content)
                    consolidated_summary = consolidation_agent.merge_summaries(consolidated_summary, summary)

                progress = (idx + 1) / total_files
                progress_bar.progress(progress)

                status_text = f"""
**Processing:** `{rel_path}`  
**Progress:** {idx + 1}/{total_files} ({progress * 100:.1f}%)  
**Summary Size:** {len(consolidated_summary) // 1024} KB
"""
                status_box.markdown(status_text)

            # Outputs depend on selected analysis mode
            if analysis_mode == "Technical Blueprint":
                st.subheader("📄 Architectural Analysis Report")
                tab1, tab2 = st.tabs(["Full Report", "Key Components"])
                with tab1:
                    st.markdown(consolidated_summary)
                with tab2:
                    st.markdown("### 🏗️ Architectural Pillars")
                    for file_path in file_handler.files[:10]:
                        st.markdown(f"- `{os.path.basename(file_path)}`")

            elif analysis_mode == "Improvement Plan":
                st.subheader("⚙️ Improvement Plan")
                with st.spinner("Generating improvement plan..."):
                    improvements = improvement_agent.generate_improvements(consolidated_summary)
                st.markdown(improvements)

            else:  # Cloud Architecture Diagram
                st.subheader("🌥️ Cloud Architecture Diagram")
                with st.spinner("Generating cloud architecture description and image diagram..."):
                    architecture_description, image_url = diagram_agent.generate_architecture_description(consolidated_summary)

                st.markdown(architecture_description)

                if image_url:
                    st.image(image_url, caption="Generated Cloud Architecture Diagram", use_column_width=True)
                else:
                    st.warning("No cloud architecture diagram image generated.")

            with st.expander("🚫 Excluded Items"):
                st.markdown("#### Directories")
                for d in sorted(file_handler.excluded_dirs):
                    st.markdown(f"- `{d}`")
                st.markdown("#### Files")
                for f in sorted(file_handler.excluded_files):
                    st.markdown(f"- `{f}`")

        except GitCommandError as e:
            st.error(f"Cloning failed: {e}")
        except Exception as e:
            st.error(f"Analysis error: {e}")


if __name__ == "__main__":
    main()

this is azure_image client
import os
from openai import AzureOpenAI

class AzureImageClient:
    """
    Wraps Azure OpenAI Image Generation (DALL·E) API calls with fixed env-configured deployment.
    """

    def __init__(self):
        self.endpoint = os.getenv("AZURE_OPENAI_IMAGE_ENDPOINT")
        self.api_key = os.getenv("AZURE_OPENAI_IMAGE_API_KEY")
        self.deployment_id = os.getenv("AZURE_OPENAI_IMAGE_DEPLOYMENT_NAME")  # DALL·E 3 deployment name
        self.api_version = "2024-02-01"

        if not all([self.endpoint, self.api_key, self.deployment_id]):
            raise ValueError("Azure OpenAI endpoint, API key, and image deployment name must be set as env vars.")

        self.client = AzureOpenAI(
            azure_endpoint=self.endpoint,
            api_key=self.api_key,
            api_version=self.api_version
        )

    def generate_image(self, prompt, size="1024x1024", n=1):
        """
        Generate image(s) from prompt using DALL·E 3.

        Args:
            prompt (str): Text prompt describing the image to generate.
            size (str): Image resolution ('256x256', '512x512', '1024x1024').
            n (int): Number of images to generate.

        Returns:
            list of str: URLs of generated images.
        """
        try:
            response = self.client.images.generate(
                prompt=prompt,
                model=self.deployment_id,
                size=size,
                n=n
            )

            print(response, "Generated image response")  # Debugging output
            image_urls = [img_data.url for img_data in response.data]
            return image_urls
        except Exception as ex:
            # Handle or log here as needed
            raise RuntimeError(f"DALL·E Image generation failed: {ex}")

this is azure client
import os
from openai import AzureOpenAI

def get_azure_client(azure_endpoint=None, api_key=None, api_version="2024-08-01-preview"):
    """
    Initialize the AzureOpenAI client. If endpoint or API key are not provided,
    retrieve from environment variables: AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_API_KEY.
    """
    if azure_endpoint is None:
        azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")

    if api_key is None:
        api_key = os.getenv("AZURE_OPENAI_API_KEY")

    if not azure_endpoint or not api_key:
        raise ValueError("Azure endpoint and API key must be provided either as arguments or environment variables.")

    client = AzureOpenAI(
        azure_endpoint=azure_endpoint,
        api_key=api_key,
        api_version=api_version
    )
    return client

this is daigram agent 
import streamlit as st
from datetime import datetime
from pathlib import Path
from utils.azure_image_client import AzureImageClient  # import the new image client module

class DiagramAgent:
    def __init__(self, client, deployment_chat, prompt_path):
        self.client = client
        self.deployment_chat = deployment_chat      # text chat model deployment (e.g. GPT-4 or GPT-35)
        self.activity_log = []
        self.prompt = Path(prompt_path).read_text()

        # Initialize image client from separate module (no params needed)
        try:
            self.image_client = AzureImageClient()
        except Exception as e:
            st.error(f"Failed to initialize AzureImageClient: {e}")
            self.image_client = None

    def log_activity(self, action):
        timestamp = datetime.now().strftime("%H:%M:%S")
        log_entry = f"{timestamp} | {'Diagram Agent'.ljust(15)} | {action.ljust(25)}"
        self.activity_log.append(log_entry)
        st.write(f"**Log:** {log_entry}")

    def generate_architecture_description(self, consolidated_summary):
        self.log_activity("Generating architecture description")
        try:
            response = self.client.chat.completions.create(
                model=self.deployment_chat,
                messages=[
                    {"role": "system", "content": self.prompt},
                    {"role": "user", "content": f"Project Summary:\n{consolidated_summary}\n\nGenerate a concise, high-level cloud architecture description explaining major components and interactions."}
                ],
                temperature=0.1,
                max_tokens=1000
            )
            architecture_description = response.choices[0].message.content.strip()
        except Exception as e:
            st.error(f"Chat model failed: {e}")
            return "", ""

        self.log_activity("Architecture description generated")

        if not self.image_client:
            st.error("Image generation client not initialized.")
            return architecture_description, ""

        # Construct prompt for DALL·E image generation
        image_prompt = (
            "Make a cloud architecture diagram showing major cloud components, "
            "services, data flows, and their relationships for the following project description provide by you only: "
            + architecture_description.replace("\n", " ")
        )

        self.log_activity("Generating architecture image")
        try:
            image_urls = self.image_client.generate_image(prompt=image_prompt, size="1024x1024", n=1)
            image_url = image_urls[0] if image_urls else ""
            self.log_activity("Image generated successfully")
        except Exception as e:
            st.error(f"Image generation failed: {e}")
            image_url = ""

        return architecture_description, image_url
this is daigram agent promt
You are an expert in cloud architecture and diagramming. Based on the provided project summary, please create the following:

A clear and concise explanation of the cloud architecture flow and its major components, describing their roles and interactions.
A Mermaid diagram illustrating the cloud architecture with:
Appropriate Mermaid syntax.
Nodes representing services/components with meaningful labels.
Clear connections and data flow between components.
Use of standard Mermaid shapes or cloud icons where applicable.


Output first the explanation, then the mermaid diagram code block enclosed with triple backticks. The diagram should be clear, use cloud icons or standard mermaid shapes, and highlight relationships and data flow.

this is analysis agent
import streamlit as st
from datetime import datetime
from pathlib import Path

class AnalysisAgent:
    def __init__(self, client, deployment, prompt_path):
        self.client = client
        self.deployment = deployment
        self.activity_log = []
        self.prompt = Path(prompt_path).read_text()

    def log_activity(self, action, file_path=""):
        timestamp = datetime.now().strftime("%H:%M:%S")
        log_entry = f"{timestamp} | {'Analysis Agent'.ljust(15)} | {action.ljust(25)} | {file_path}"
        self.activity_log.append(log_entry)

    def summarize_file(self, file_path, content):
        self.log_activity("Processing file", file_path)
        try:
            response = self.client.chat.completions.create(
                model=self.deployment,
                messages=[
                    {"role":"system", "content": self.prompt},
                    {"role":"user", "content": f"File: {file_path}\nContent:\n{content}"}
                ],
                temperature=0.1,
            )
        except Exception as e:
            st.error(f"AnalysisAgent API call failed: {e}")
            return ""
        return response.choices[0].message.content

this is analysis agent promt
Analyze how this file contributes to the overall project goals. Provide a detailed explanation covering:

1. Primary purpose in the project context:  
   - What role does this file play within the larger project?  
   - How does it help achieve the project’s main objectives?

2. Key technical implementations:  
   - What are the core functionalities and algorithms implemented here?  
   - Are there any notable patterns, optimizations, or complex logic applied?

3. Relationship to other components:  
   - How does this file interact with or depend on other modules/files?  
   - What is its significance in the data or control flow across the system?

4. Critical design decisions and rationale:  
   - Why was the code structured or implemented this way?  
   - What trade-offs, constraints, or architectural principles influenced these decisions?  
   - How do these affect maintainability, scalability, and performance?

5. Alignment with business and user needs:  
   - How does this file’s functionality deliver business value or support user workflows?  
   - Does it implement essential rules, workflows, or policies?

6. Potential bottlenecks, risks, or improvement areas:  
   - Are there limitations, technical debts, or fragile points to note?  
   - What improvements could enhance future goals?

7. Suggestions for further exploration:  
   - Which related files, modules, or documentation should be reviewed next?  
   - Are there external dependencies, configuration settings, or tests important for context?  
   - What other resources or data flows aid in fully understanding this file’s role?

8. Documentation:  
   - Provide a concise, clear documentation-style summary for this file suitable for project docs or developer onboarding.  
   - Include explanations of the file’s main classes, functions, or interfaces.

9. Code snippets:  
   - Extract and present 2-3 illustrative, important code snippets from this file that demonstrate key functionality or patterns.  
   - Add brief comments or explanations for each snippet to explain why it is important.

Focus on the ‘why’ behind the code, not just ‘what’ it does.

this is consolidate agent 
import streamlit as st
from datetime import datetime
from pathlib import Path

class ConsolidationAgent:
    def __init__(self, client, deployment, prompt_path):
        self.client = client
        self.deployment = deployment
        self.activity_log = []
        self.prompt = Path(prompt_path).read_text()

    def log_activity(self, action):
        timestamp = datetime.now().strftime("%H:%M:%S")
        log_entry = f"{timestamp} | {'Consolidation Agent'.ljust(15)} | {action.ljust(25)}"
        self.activity_log.append(log_entry)

    def merge_summaries(self, current_overview, new_summary):
        self.log_activity("Merging summaries")
        try:
            response = self.client.chat.completions.create(
                model=self.deployment,
                messages=[
                    {"role": "system", "content": self.prompt},
                    {"role": "user", "content": f"Current:\n{current_overview}\nNew:\n{new_summary}"}
                ],
                temperature=0.05,
            )
        except Exception as e:
            st.error(f"ConsolidationAgent API call failed: {e}")
            return current_overview
        return response.choices[0].message.content
this is consolidate agent promt
Synthesize the individual file analyses into a comprehensive project blueprint. Provide a structured summary covering:

[Project Purpose]  
- What are the core objectives driving the project?  
- What key problem statements or business challenges does the project address?

[Implementation Strategy]  
- Which architectural patterns are employed across the project?  
- What are the primary technology choices and platforms used?  
- Highlight notable design decisions and their rationale affecting system quality (e.g., maintainability, scalability).

[Crucial Components]  
- Identify key files or modules and clearly define their roles within the system.  
- Describe interactions and dependencies between components.  
- Pinpoint where core business logic and critical workflows reside.

[Workflow Overview]  
- Outline the main execution flow and how data moves through the system.  
- Detail important data transformation or processing points.  
- Highlight critical integration points between components, external systems, or services.

[Documentation Summary]  
- Present a consolidated, high-level developer documentation overview from the individual file docs.  
- Include descriptions of key classes, modules, and APIs necessary for understanding the project codebase.

[Representative Code Snippets]  
- Include a selection of significant code snippets across the project that illustrate core logic, design patterns, or complex algorithms.  
- For each snippet, briefly explain its role and importance.

[Risks and Improvement Opportunities]  
- Summarize any potential technical bottlenecks, risks, or areas of technical debt observed.  
- Suggest possible enhancements or refactoring opportunities valuable for future development.

now what i want is remove the mermid things from my code and all the explaanation of the flow of project or cosolidate make it like we need to send azure Image llm and then display the image which we get 

give me full coede