File size: 6,631 Bytes
cef3c81
 
 
a106fa2
 
cef3c81
 
a106fa2
cef3c81
 
a106fa2
 
 
 
 
 
 
 
 
 
 
 
cef3c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a106fa2
cef3c81
 
 
 
 
 
 
a106fa2
 
cef3c81
 
a106fa2
cef3c81
 
 
a106fa2
cef3c81
a106fa2
cef3c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a106fa2
cef3c81
a106fa2
cef3c81
 
 
 
a106fa2
cef3c81
 
 
 
 
 
a106fa2
cef3c81
a106fa2
cef3c81
 
a106fa2
cef3c81
 
 
 
 
 
a106fa2
cef3c81
 
 
 
 
 
 
a106fa2
cef3c81
a106fa2
cef3c81
 
 
 
 
 
 
a106fa2
 
 
 
 
 
 
 
 
 
cef3c81
a106fa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cef3c81
a106fa2
 
 
 
 
 
 
 
 
 
cef3c81
 
 
a106fa2
cef3c81
a106fa2
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
import streamlit as st
from datetime import datetime
import os
from typing import Dict
from fpdf import FPDF
import anthropic


class TemplateGenerator:
    def __init__(self):
        # Initialize Anthropic client with API key
        try:
            api_key = os.getenv("ANTHROPIC_API_KEY")
            if not api_key:
                st.error("Please set the ANTHROPIC_API_KEY in your environment variables.")
                st.stop()
            self.client = anthropic.Anthropic(api_key=api_key)
        except Exception as e:
            st.error(f"Error initializing Anthropic client: {str(e)}")
            st.stop()

        # Define templates
        self.templates = {
            "nda": {
                "name": "Non-Disclosure Agreement",
                "description": "Standard NDA for business confidentiality",
                "fields": {
                    "company_name": "Company requiring NDA",
                    "recipient_name": "Party signing the NDA",
                    "effective_date": "Start date of agreement",
                    "duration_months": "Duration in months",
                    "jurisdiction": "Governing law jurisdiction",
                    "confidential_info_description": "Description of confidential information",
                    "permitted_use": "Allowed uses of confidential information",
                    "return_period": "Days to return/destroy information"
                }
            },
            "services_agreement": {
                "name": "Services Agreement",
                "description": "Comprehensive contract for provision of services",
                "fields": {
                    "service_provider": "Provider company/individual name",
                    "client_name": "Client name",
                    "services_description": "Detailed service description",
                    "start_date": "Service start date",
                    "payment_terms": "Payment amount and schedule",
                    "termination_notice": "Notice period for termination",
                    "governing_law": "Jurisdiction",
                    "service_levels": "Service level agreements (SLAs)"
                }
            },
            # Extend templates here
        }

    def render(self):
        """Render template generator interface."""
        st.header("Legal Document Generator")
        st.write("Generate comprehensive legal documents using customizable templates.")

        # Template selection
        template_type = st.selectbox(
            "Select Document Type",
            options=list(self.templates.keys()),
            format_func=lambda x: self.templates[x]["name"]
        )

        # Show template description
        st.info(self.templates[template_type]["description"])

        # Input form
        with st.form(f"template_form_{template_type}"):
            inputs = {}
            for field, description in self.templates[template_type]["fields"].items():
                if "date" in field:
                    inputs[field] = st.date_input(f"{description}")
                elif "description" in field or "terms" in field:
                    inputs[field] = st.text_area(f"{description}", height=100)
                elif "amount" in field or "months" in field:
                    inputs[field] = st.number_input(f"{description}", min_value=0)
                else:
                    inputs[field] = st.text_input(f"{description}")

            # Submit form
            generate = st.form_submit_button("Generate Document")

        if generate:
            if all(inputs.values()):
                with st.spinner("Generating document..."):
                    document = self._generate_document(template_type, inputs)
                    self._display_document(document, template_type)
            else:
                st.error("Please fill in all required fields.")

    def _generate_document(self, template_type: str, inputs: Dict) -> str:
        """Generate document using Claude."""
        try:
            prompt = self._create_prompt(template_type, inputs)
            message = self.client.messages.create(
                model="claude-3-sonnet-20240229",
                max_tokens=2000,
                temperature=0.7,
                messages=[{"role": "user", "content": prompt}]
            )
            return message.content[0].text
        except Exception as e:
            st.error(f"Error generating document: {str(e)}")
            return ""

    def _create_prompt(self, template_type: str, inputs: Dict) -> str:
        """Create prompt for document generation."""
        template_name = self.templates[template_type]["name"]

        prompt = f"""Generate a detailed {template_name} using the following information:

Template Type: {template_name}
"""
        for field, value in inputs.items():
            prompt += f"{field}: {value}\n"

        prompt += """

Ensure the document:
1. Follows professional legal formatting.
2. Includes all necessary clauses and sections.
3. Is tailored for {inputs.get('jurisdiction', 'general')} jurisdiction.
4. Uses formal legal language.
5. Includes signature blocks and clear numbering.
"""
        return prompt

    def _display_document(self, document: str, template_type: str):
        """Display and provide download options for the generated document."""
        st.subheader("Generated Document")
        with st.expander("Preview", expanded=True):
            st.markdown(document)

        col1, col2 = st.columns(2)
        with col1:
            st.download_button(
                "Download as TXT",
                document,
                file_name=f"{template_type}_{datetime.now().strftime('%Y%m%d')}.txt",
                mime="text/plain"
            )
        with col2:
            pdf_document = self._generate_pdf(document)
            st.download_button(
                "Download as PDF",
                pdf_document,
                file_name=f"{template_type}_{datetime.now().strftime('%Y%m%d')}.pdf",
                mime="application/pdf"
            )

    def _generate_pdf(self, document: str) -> bytes:
        """Generate a PDF file for the document."""
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font("Arial", size=12)
        for line in document.split("\n"):
            pdf.cell(200, 10, txt=line, ln=True)
        output = bytes()
        pdf.output(name="document.pdf", dest="S").encode("latin1")
        return output


def render_template_generator():
    """Main function to render the template generator."""
    generator = TemplateGenerator()
    generator.render()