cryogenic22 commited on
Commit
a106fa2
·
verified ·
1 Parent(s): 6f7c8e3

Update components/template_generator.py

Browse files
Files changed (1) hide show
  1. components/template_generator.py +74 -113
components/template_generator.py CHANGED
@@ -1,14 +1,25 @@
1
- # components/template_generator.py
2
  import streamlit as st
3
  from datetime import datetime
4
- import json
5
  import os
6
- from typing import Dict, List
 
7
  import anthropic
8
 
 
9
  class TemplateGenerator:
10
  def __init__(self):
11
- self.client = anthropic.Anthropic(api_key=st.secrets["Anthropic_API_KEY"])
 
 
 
 
 
 
 
 
 
 
 
12
  self.templates = {
13
  "nda": {
14
  "name": "Non-Disclosure Agreement",
@@ -24,69 +35,27 @@ class TemplateGenerator:
24
  "return_period": "Days to return/destroy information"
25
  }
26
  },
27
- "mou": {
28
- "name": "Memorandum of Understanding",
29
- "description": "Initial agreement outlining basic terms",
30
- "fields": {
31
- "party1_name": "First party name",
32
- "party2_name": "Second party name",
33
- "purpose": "Purpose of the collaboration",
34
- "start_date": "Start date",
35
- "end_date": "End date",
36
- "key_responsibilities": "Key responsibilities of parties",
37
- "financial_terms": "Basic financial arrangements",
38
- "termination_terms": "Termination conditions"
39
- }
40
- },
41
  "services_agreement": {
42
  "name": "Services Agreement",
43
- "description": "Contract for provision of services",
44
  "fields": {
45
  "service_provider": "Provider company/individual name",
46
  "client_name": "Client name",
47
  "services_description": "Detailed service description",
48
  "start_date": "Service start date",
49
  "payment_terms": "Payment amount and schedule",
50
- "service_levels": "Service level requirements",
51
  "termination_notice": "Notice period for termination",
52
- "governing_law": "Jurisdiction"
53
- }
54
- },
55
- "employment_contract": {
56
- "name": "Employment Contract",
57
- "description": "Standard employment agreement",
58
- "fields": {
59
- "employer_name": "Company name",
60
- "employee_name": "Employee full name",
61
- "position": "Job title/position",
62
- "start_date": "Employment start date",
63
- "salary": "Annual salary amount",
64
- "benefits": "Benefits package details",
65
- "work_hours": "Working hours/schedule",
66
- "notice_period": "Notice period for termination",
67
- "probation_period": "Probation period in months"
68
  }
69
  },
70
- "will": {
71
- "name": "Last Will and Testament",
72
- "description": "Basic will template",
73
- "fields": {
74
- "testator_name": "Full name of testator",
75
- "testator_address": "Current address",
76
- "executor_name": "Executor's full name",
77
- "executor_address": "Executor's address",
78
- "beneficiaries": "List of beneficiaries",
79
- "specific_bequests": "Specific property/asset allocations",
80
- "residuary_estate": "Disposition of remaining estate",
81
- "funeral_wishes": "Funeral arrangements (optional)"
82
- }
83
- }
84
  }
85
 
86
  def render(self):
87
- """Render template generator interface"""
88
  st.header("Legal Document Generator")
89
- st.write("Generate legal documents using AI-assisted templates")
90
 
91
  # Template selection
92
  template_type = st.selectbox(
@@ -101,73 +70,36 @@ class TemplateGenerator:
101
  # Input form
102
  with st.form(f"template_form_{template_type}"):
103
  inputs = {}
104
-
105
- # Add fields based on template type
106
  for field, description in self.templates[template_type]["fields"].items():
107
  if "date" in field:
108
  inputs[field] = st.date_input(f"{description}")
109
- elif any(word in field for word in ["description", "terms", "responsibilities", "bequests"]):
110
  inputs[field] = st.text_area(f"{description}", height=100)
111
- elif "amount" in field or "salary" in field:
112
  inputs[field] = st.number_input(f"{description}", min_value=0)
113
- elif "period" in field:
114
- inputs[field] = st.number_input(f"{description}", min_value=1)
115
  else:
116
  inputs[field] = st.text_input(f"{description}")
117
 
118
- # Jurisdiction selection where applicable
119
- if template_type in ["nda", "services_agreement"]:
120
- jurisdiction = st.selectbox(
121
- "Select Jurisdiction",
122
- ["UK", "India", "UAE"],
123
- help="Choose the governing law for this document"
124
- )
125
- inputs["jurisdiction"] = jurisdiction
126
-
127
  generate = st.form_submit_button("Generate Document")
128
 
129
  if generate:
130
  if all(inputs.values()):
131
  with st.spinner("Generating document..."):
132
  document = self._generate_document(template_type, inputs)
133
-
134
- # Preview
135
- st.subheader("Generated Document")
136
- with st.expander("Preview", expanded=True):
137
- st.markdown(document)
138
-
139
- # Download options
140
- col1, col2 = st.columns(2)
141
- with col1:
142
- st.download_button(
143
- "Download as TXT",
144
- document,
145
- file_name=f"{template_type}_{datetime.now().strftime('%Y%m%d')}.txt",
146
- mime="text/plain"
147
- )
148
- with col2:
149
- st.download_button(
150
- "Download as PDF",
151
- document,
152
- file_name=f"{template_type}_{datetime.now().strftime('%Y%m%d')}.pdf",
153
- mime="application/pdf"
154
- )
155
  else:
156
- st.error("Please fill in all required fields")
157
 
158
  def _generate_document(self, template_type: str, inputs: Dict) -> str:
159
- """Generate document using Claude"""
160
  try:
161
  prompt = self._create_prompt(template_type, inputs)
162
-
163
  message = self.client.messages.create(
164
  model="claude-3-sonnet-20240229",
165
  max_tokens=2000,
166
  temperature=0.7,
167
- messages=[{
168
- "role": "user",
169
- "content": prompt
170
- }]
171
  )
172
  return message.content[0].text
173
  except Exception as e:
@@ -175,34 +107,63 @@ class TemplateGenerator:
175
  return ""
176
 
177
  def _create_prompt(self, template_type: str, inputs: Dict) -> str:
178
- """Create prompt for document generation"""
179
  template_name = self.templates[template_type]["name"]
180
-
181
  prompt = f"""Generate a detailed {template_name} using the following information:
182
 
183
  Template Type: {template_name}
184
  """
185
-
186
- # Add inputs to prompt
187
  for field, value in inputs.items():
188
  prompt += f"{field}: {value}\n"
189
 
190
- prompt += f"""
 
 
 
 
 
 
 
 
 
191
 
192
- Please generate a complete and professionally formatted legal document that:
193
- 1. Follows standard legal document structure
194
- 2. Includes all necessary clauses and sections
195
- 3. Uses formal legal language
196
- 4. Incorporates all provided information
197
- 5. Follows the legal requirements for {inputs.get('jurisdiction', 'general')} jurisdiction
198
- 6. Includes proper signature blocks and dates
199
- 7. Has clear section numbering and formatting
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
- Return the complete document in a format ready for use."""
 
 
 
 
 
 
 
 
 
202
 
203
- return prompt
204
 
205
  def render_template_generator():
206
- """Main function to render template generator"""
207
  generator = TemplateGenerator()
208
- generator.render()
 
 
1
  import streamlit as st
2
  from datetime import datetime
 
3
  import os
4
+ from typing import Dict
5
+ from fpdf import FPDF
6
  import anthropic
7
 
8
+
9
  class TemplateGenerator:
10
  def __init__(self):
11
+ # Initialize Anthropic client with API key
12
+ try:
13
+ api_key = os.getenv("ANTHROPIC_API_KEY")
14
+ if not api_key:
15
+ st.error("Please set the ANTHROPIC_API_KEY in your environment variables.")
16
+ st.stop()
17
+ self.client = anthropic.Anthropic(api_key=api_key)
18
+ except Exception as e:
19
+ st.error(f"Error initializing Anthropic client: {str(e)}")
20
+ st.stop()
21
+
22
+ # Define templates
23
  self.templates = {
24
  "nda": {
25
  "name": "Non-Disclosure Agreement",
 
35
  "return_period": "Days to return/destroy information"
36
  }
37
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  "services_agreement": {
39
  "name": "Services Agreement",
40
+ "description": "Comprehensive contract for provision of services",
41
  "fields": {
42
  "service_provider": "Provider company/individual name",
43
  "client_name": "Client name",
44
  "services_description": "Detailed service description",
45
  "start_date": "Service start date",
46
  "payment_terms": "Payment amount and schedule",
 
47
  "termination_notice": "Notice period for termination",
48
+ "governing_law": "Jurisdiction",
49
+ "service_levels": "Service level agreements (SLAs)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  }
51
  },
52
+ # Extend templates here
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  }
54
 
55
  def render(self):
56
+ """Render template generator interface."""
57
  st.header("Legal Document Generator")
58
+ st.write("Generate comprehensive legal documents using customizable templates.")
59
 
60
  # Template selection
61
  template_type = st.selectbox(
 
70
  # Input form
71
  with st.form(f"template_form_{template_type}"):
72
  inputs = {}
 
 
73
  for field, description in self.templates[template_type]["fields"].items():
74
  if "date" in field:
75
  inputs[field] = st.date_input(f"{description}")
76
+ elif "description" in field or "terms" in field:
77
  inputs[field] = st.text_area(f"{description}", height=100)
78
+ elif "amount" in field or "months" in field:
79
  inputs[field] = st.number_input(f"{description}", min_value=0)
 
 
80
  else:
81
  inputs[field] = st.text_input(f"{description}")
82
 
83
+ # Submit form
 
 
 
 
 
 
 
 
84
  generate = st.form_submit_button("Generate Document")
85
 
86
  if generate:
87
  if all(inputs.values()):
88
  with st.spinner("Generating document..."):
89
  document = self._generate_document(template_type, inputs)
90
+ self._display_document(document, template_type)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  else:
92
+ st.error("Please fill in all required fields.")
93
 
94
  def _generate_document(self, template_type: str, inputs: Dict) -> str:
95
+ """Generate document using Claude."""
96
  try:
97
  prompt = self._create_prompt(template_type, inputs)
 
98
  message = self.client.messages.create(
99
  model="claude-3-sonnet-20240229",
100
  max_tokens=2000,
101
  temperature=0.7,
102
+ messages=[{"role": "user", "content": prompt}]
 
 
 
103
  )
104
  return message.content[0].text
105
  except Exception as e:
 
107
  return ""
108
 
109
  def _create_prompt(self, template_type: str, inputs: Dict) -> str:
110
+ """Create prompt for document generation."""
111
  template_name = self.templates[template_type]["name"]
112
+
113
  prompt = f"""Generate a detailed {template_name} using the following information:
114
 
115
  Template Type: {template_name}
116
  """
 
 
117
  for field, value in inputs.items():
118
  prompt += f"{field}: {value}\n"
119
 
120
+ prompt += """
121
+
122
+ Ensure the document:
123
+ 1. Follows professional legal formatting.
124
+ 2. Includes all necessary clauses and sections.
125
+ 3. Is tailored for {inputs.get('jurisdiction', 'general')} jurisdiction.
126
+ 4. Uses formal legal language.
127
+ 5. Includes signature blocks and clear numbering.
128
+ """
129
+ return prompt
130
 
131
+ def _display_document(self, document: str, template_type: str):
132
+ """Display and provide download options for the generated document."""
133
+ st.subheader("Generated Document")
134
+ with st.expander("Preview", expanded=True):
135
+ st.markdown(document)
136
+
137
+ col1, col2 = st.columns(2)
138
+ with col1:
139
+ st.download_button(
140
+ "Download as TXT",
141
+ document,
142
+ file_name=f"{template_type}_{datetime.now().strftime('%Y%m%d')}.txt",
143
+ mime="text/plain"
144
+ )
145
+ with col2:
146
+ pdf_document = self._generate_pdf(document)
147
+ st.download_button(
148
+ "Download as PDF",
149
+ pdf_document,
150
+ file_name=f"{template_type}_{datetime.now().strftime('%Y%m%d')}.pdf",
151
+ mime="application/pdf"
152
+ )
153
 
154
+ def _generate_pdf(self, document: str) -> bytes:
155
+ """Generate a PDF file for the document."""
156
+ pdf = FPDF()
157
+ pdf.add_page()
158
+ pdf.set_font("Arial", size=12)
159
+ for line in document.split("\n"):
160
+ pdf.cell(200, 10, txt=line, ln=True)
161
+ output = bytes()
162
+ pdf.output(name="document.pdf", dest="S").encode("latin1")
163
+ return output
164
 
 
165
 
166
  def render_template_generator():
167
+ """Main function to render the template generator."""
168
  generator = TemplateGenerator()
169
+ generator.render()