import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
code
identifier_text = f"Matter {matter_count}"
# Update table content dynamically
doc.tables[0].cell(1, 0).text = identifier_text
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name '].strip()}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)'].strip()}"
doc.tables[0].cell(4, 0).text = f" {data['Value '].strip()}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners'].strip()}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members'].strip()}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved'].strip()}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )'].strip()}"
# Save the document
doc.save(output_path)
return output_path
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def populate_chambers(excel_file, output_path):
"""Generate documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs_no = []
individual_docs_yes = []
code
df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
for index, row in df_no.iterrows():
temp_output_path = f"temp_publishable_no_{index}.docx"
individual_docs_no.append(create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temp_output_path))
for index, row in df_yes.iterrows():
temp_output_path = f"temp_publishable_yes_{index}.docx"
individual_docs_yes.append(create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temp_output_path))
append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, output_path)
# Clean up temporary files
for doc_path in individual_docs_no + individual_docs_yes:
os.remove(doc_path)
return True
except Exception as e:
st.error(f"Error occurred: {e}")
return False
def app():
st.header("Chambers Submission")
st.markdown("🔧 This implementation is still in progress. The production version is not yet live. For testing, use this link: Click Here", unsafe_allow_html=True)
code
excel_file = st.file_uploader("Upload Excel File for Chambers", type=["xlsx", "xls"])
if st.button("Generate Chambers Form"):
if excel_file:
output_path = "Chambers_Submission.docx"
success = populate_chambers(excel_file, output_path)
if success and os.path.exists(output_path):
st.success("Chambers Form generated successfully!")
with open(output_path, "rb") as f:
st.download_button(
label="Download Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Error generating document.")
else:
st.error("Please upload an Excel file.") in place of this i wanted this import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
code
# Identifying text based on template type
if "Confidential" in template_path:
identifier_text = f"Confidential Matter {matter_count}"
else:
identifier_text = f"Publishable Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
# Save the individual document
doc.save(output_path)
print(f"Saved individual document: {output_path}")
return output_path # Return path for later combining
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs_no = []
individual_docs_yes = []
code
# Filter the DataFrame for rows
df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
# Handle Publishable Matters for 'No' rows
for index, row in df_no.iterrows():
temporary_output_path = f"temp_publishable_no_{index}.docx"
individual_doc_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path)
individual_doc_path
individual_docs_no.append(individual_doc_path)
# Handle Publishable Matters for 'Yes' rows
for index, row in df_yes.iterrows():
temporary_output_path = f"temp_publishable_yes_{index}.docx"
individual_doc_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path)
individual_docs_yes.append(individual_doc_path)
# Combine in the desired order: No documents + after + Yes documents
final_output_path = output_path
append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, final_output_path)
print(f"Combined document saved: {final_output_path}")
# Clean up temporary documents
for doc_path in individual_docs_no + individual_docs_yes:
os.remove(doc_path)
except Exception as e:
print(f"Unexpected error: {e}")
Streamlit application
def main():
st.title("Fill Chambers and Partners Form")
code
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
output_path = "combined_confidential_publishable.docx"
populate_chambers(excel_file, output_path)
# Check if the output file was created successfully
if os.path.exists(output_path):
st.success("Forms filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
btn = st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.error("Please upload the Excel file.")
if name == "main":
main() but with the sidebar and other things same
Assistant
To incorporate the modifications you requested, while retaining the sidebar functionality and the overall structure of your Streamlit application, here is the combined code. This version retains your original functionality but reflects the changes, such as the use of different functions for processing and appending the documents.
python
User
import pandas as pd
from docx import Document
import streamlit as st
import os
print("Loading Word document...")
doc = Document(doc_path)
tables = doc.tables
print(f"Total tables found in document: {len(tables)}")
# Check if tables exist in the document
if not tables:
print("Error: No tables found in document.")
return
# Variable to track current row in the DataFrame
df_index = 0
# Iterate through each table in the document
for table in tables:
# Ensure the table has enough rows
if len(table.rows) >= 18:
try:
# Fill the cells from the current row in the DataFrame
table.cell(2, 0).text = str(df.iloc[df_index]['Client Name ']) # Client Name
table.cell(4, 0).text = str(df.iloc[df_index]['Description (in 500 words)']) # Description
table.cell(6, 0).text = str(df.iloc[df_index]['Value ']) # Matter/Case Overview
table.cell(10, 0).text = str(df.iloc[df_index]['Lead partners']) # Lead Partner
table.cell(12, 0).text = str(df.iloc[df_index]['Team Members']) # Team Members
table.cell(14, 0).text = str(df.iloc[df_index]['Other Firms/counsels Involved']) # Other Involved Firms
print(f"Matter {df_index + 1} populated successfully.")
df_index += 1 # Move to the next row in the DataFrame
except IndexError as e:
print(f"Error: Table has fewer rows than expected. Skipping entry. {e}")
else:
print(f"Warning: Table has only {len(table.rows)} rows. Expected at least 18.")
# Save the updated document
doc.save(output_path)
print("Document updated successfully!")
except Exception as e:
print(f"Unexpected error: {e}")
Assistant
The error message you are encountering, specifically AttributeError: module 'legal_era' has no attribute 'app', suggests that the code is attempting to reference a function or a module named app in your legal_era module, but it does not exist. This could be due to a couple of issues:
Function Name: In the code you provided, the main application function is named main(), not app(). If you are trying to run this Streamlit application using app(), you should change any reference to app() to main() in your script or rename your Streamlit function to app().
Module Structure: If you are using your Streamlit app within a larger module structure, make sure that you have defined the main() function in that legal_era module, and that it is correctly imported where you are trying to use it.
Here’s how you might correct the issue:
Update Function Naming: Change the main function name to app in your script if you prefer to use app() in the entry point.
Here’s how the updated code would look:
python
User
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
code
# Identifying text based on template type
if "Confidential" in template_path:
identifier_text = f"Confidential Matter {matter_count}"
else:
identifier_text = f"Publishable Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
# Save the individual document
doc.save(output_path)
print(f"Saved individual document: {output_path}")
return output_path # Return path for later combining
Assistant
The issue you're facing with the error message AttributeError: module 'legal_era' has no attribute 'app' seems to be a misunderstanding about how your Streamlit app is structured and invoked. The specific name of the entry function doesn't matter much, as long as it is consistently referenced.
To resolve the problem, let’s focus on ensuring that your Streamlit application function is being correctly referenced in the main script and addressing any potential issues in the existing code. In your provided example, you're already defining the main execution flow with the main() function. Here's a refined approach:
Streamlit Application Structure
Here's how to properly structure your Streamlit application. The error you're receiving might arise from how you're invoking the function, so let's ensure the function names and calls are correct.
Ensure that your Streamlit file correctly references the function main().
Make sure that this script is being executed properly.
Here’s the streamlined version of the code sample you provided:
python
User
AttributeError: module 'chambers' has no attribute 'app'
Traceback:
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\scriptrunner\exec_code.py", line 88, in exec_func_with_error_handling
result = func()
^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 590, in code_to_exec
exec(code, module.dict)
File "C:\Users\Administrator\Desktop\dev\pondering\main.py", line 55, in
app.add_app("Chambers", chambers.app, )
Assistant
The error message you're encountering, AttributeError: module 'chambers' has no attribute 'app', typically suggests that the code is trying to access an app function within a chambers module that does not exist. Here’s how you can resolve this issue by ensuring the function you're calling is correctly referenced.
Solutions
Check Function Name:
Ensure that you have correctly defined the function app() in your chambers.py file. If your function is named main(), then you should call it as chambers.main instead.
Update Reference in Script:
If you're using the app function from chambers, ensure your Python script that imports it is calling it correctly. If your Streamlit application script (e.g., main.py) calls:
python
app.add_app("Chambers", chambers.app)
Make sure app is indeed defined in the chambers module and is spelled correctly, and that there is no typo in the function name.
Defining the App Function:
If app() is not defined in chambers.py, you can rename your main function (the entry point for the Streamlit app) to app() in chambers.py:
Here's the revised structure:
python
User
probide complete upadted code
Assistant
Below is the complete updated code for your Streamlit application using the chambers logic we discussed. The code uses two functions: one for populating the Word documents based on an Excel file (populate_chambers) and the other as the entry point for the Streamlit application (app).
Complete Code for chambers.py
python
User
Unexpected error: 'Current Status (ongoing / completed )'
Assistant
The error message Unexpected error: 'Current Status (ongoing / completed )' suggests that the key 'Current Status (ongoing / completed )' is not found in the DataFrame columns when you are trying to access it. This can happen due to a few reasons:
Column Name Mismatch: The column name in the Excel file may not exactly match the string you're using in the code. It may have extra spaces, different casing, or be spelled differently.
Trailing Spaces in Headers: Sometimes, Excel headers have trailing or leading spaces that are not visible.
Encoding Issues: The Excel file might have special characters or encoding issues that make the column names not match.
Debugging Steps
Check the Column Names: You can print the column names of the DataFrame to verify what is being read from the Excel file. Modify the populate_chambers function to include the following after loading the DataFrame:
python
df = pd.read_excel(excel_file)
print(df.columns.tolist()) # Print all column names
Adjust Column Access: Once you have the output from the above print statement, make any necessary adjustments to the strings used in your code to match exactly what is returned. If, for example, the printed column name is 'Current Status (ongoing / completed)' without a space at the end, make sure you remove that space in your code as well.
Updated Code to Print Column Names
Here’s the updated populate_chambers function that includes a debug print statement:
python
User
Current Status (ongoing / completed )
06-Jan-24
06-Jan-24
Feb-24
Ongoing
Ongoing
22.11.2023
Ongoing. Reserved for Award.
Ongoing. Reserved for Award.
Ongoing. Reserved for Award.
02.10.2023
Ongoing
Ongoing
this is the column and have this type of data i wanted whaterver in it copy paste it in that cell
Assistant
To resolve the issue of copying the current status from the Excel sheet into the Word document cell and ensure that the status is properly written, you'll want to follow these adjustments:
Steps to Copy Status to the Word Document
Directly Copy the Data: You can keep using the same column name as it appears in your DataFrame, ensuring it includes all trailing spaces and formatting.
Handle Empty Entries Gracefully: If there are empty entries in that column, you can choose how you want to treat them in your Word document.
Let's modify the create_individual_document() function to ensure that it updates the document with the data found in that specific column correctly.
Here’s how to do it:
Updated Code for create_individual_document
python
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Identifying text based on template type
identifier_text = f"{'Confidential' if 'Confidential' in template_path else 'Publishable'} Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
# Update Current Status: Ensure to access it correctly
current_status = data['Current Status (ongoing / completed )'] # This accesses the column as it appears
doc.tables[0].cell(9, 0).text = f" {current_status or 'N/A'}" # Change this line to handle empty strings gracefully
# Save the individual document
doc.save(output_path)
return output_path # Return path for later combining
User
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
Function to append Word documents
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
code
# Identifying text based on template type
identifier_text = f"{'Confidential' if 'Confidential' in template_path else 'Publishable'} Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
current_status = data['Current Status (ongoing / completed )'] # This accesses the column as it appears
doc.tables[0].cell(9, 0).text = f" {current_status or 'N/A'}" # Change this line to handle empty strings gracefully
# Save the individual document
doc.save(output_path)
return output_path # Return path for later combining
Assistant
To add the functionality to select specific rows to fill in the Chambers and Partners form, you can modify the Streamlit application to provide a user interface that allows users to enter the "Client Name" and a short description (up to 50 words) for each matter. Once the user makes their selections, the application can generate the documents for only those selected rows. Below is how you could implement this.
Updated Streamlit Application Code
Here's how to modify your existing code to provide an option for selecting specific rows based on "Client Name" and a short "Description":
python
User
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
from io import BytesIO
Set page configuration at the very beginning
st.set_page_config(layout="wide", page_title="Benchmark Awards Form Generator")
def create_individual_document(template_path, data, matter_count, output_path, form_type):
"""Create an individual document for a row of data based on the template."""
doc = Document(template_path)
code
# Find the table in the document
if len(doc.tables) < 1:
st.error("Template document does not contain the expected table.")
return None
table = doc.tables[0]
# Map Excel fields to table cells based on the form structure
# Different mapping depending on form type
field_mapping = {
"Case overview": data.get("Matter/Case Overview", ""),
"Confidential/Partially confidential (Yes or no)": data.get("Confidential / Publishable", ""),
"Dispute resolution practice area(s)": data.get("Practice Area", "") if "Practice Area" in data else "",
"Industry sector(s)": data.get("Industry Sector", "") if "Industry Sector" in data else "",
"Date completed (MM/YY) / Ongoing": data.get("Current Status (ongoing / completed )", ""),
"Value (indicate currency)": data.get("Value", ""),
"Client(s) advised": data.get("Client Name ", ""),
"Lead partner involved": data.get("Lead partners", ""),
"Other lawyers involved (include position)": data.get("Team Members", ""),
"Your firm's role": data.get("Role of S&A", ""),
"Other law firms and their roles": data.get("Other Firms/counsels Involved", ""),
"Governing law": "Indian Law", # Default value
"Description": data.get("Description (in 500 words)", ""),
"Please state the significance, impact and outcome of the case": data.get("The significance, impact and outcome of the case", "")
}
# Update the title based on form type
for paragraph in doc.paragraphs:
if "WORK HIGHLIGHT" in paragraph.text:
if form_type == "nominee":
paragraph.text = f"WORK HIGHLIGHT #{matter_count}"
else:
paragraph.text = f"WORK HIGHLIGHT #{matter_count}"
for run in paragraph.runs:
run.font.bold = True
# Populate the table with data
for row in table.rows:
if len(row.cells) >= 2: # Ensure the row has at least two cells
cell_text = row.cells[0].text.strip()
if cell_text in field_mapping:
row.cells[1].text = str(field_mapping[cell_text])
# Save the individual document
doc.save(output_path)
return output_path
Assistant
To modify the existing Streamlit application to show both the "Client Name" and a truncated description when selecting items from the DataFrame, we will adapt the checkbox display logic. This will involve iterating over the DataFrame, creating checkboxes for each client, and showing a summary that includes both the client name and the first part of their description (up to 50 characters).
Here’s how you can implement those changes:
Updated Code for the Streamlit Application
The following code snippet modifies the existing Streamlit application to display both the "Client Name" and a short description for better clarity when making selections.
python
User
keep it app not main
Assistant
Sure! Here's the complete code with the entry point renamed from main() to app(), ensuring that all modifications for the selection and display of client names as well as their descriptions are retained:
python
User
upadted the chmbers tempalte form not benchmark i provided this to u for refrence of how to show client names in forntend
Assistant
Got it! I'll adapt the original Chambers form generator code based on the functionality you provided from the Benchmark template. The new functionality will present client names alongside their descriptions in the frontend for selection via checkboxes.
Here's how the modified Chambers submission application would look:
Updated Chambers Submission Application Code
python
User
StreamlitAPIException: set_page_config() can only be called once per app page, and must be called as the first Streamlit command in your script.
Assistant
The error message StreamlitAPIException: set_page_config() can only be called once per app page, and must be called as the first Streamlit command in your script. indicates that st.set_page_config() must be called before any other Streamlit components or commands in the script.
To resolve this, ensure that the set_page_config() call is at the very top of your script, as the first Streamlit command. Additionally, make sure that you only call it once.
Here's the corrected version of your code, ensuring that st.set_page_config() is the first Streamlit command:
python
User
not fillling the form u removed the conditon of doc cells mapping
Assistant
I apologize for any confusion. Let's ensure that we maintain the document cell mapping logic while correctly structuring the functionality to fill out the forms. Below is the corrected code that includes the individual cell mapping for the document while keeping your requirements in mind.
Complete Code for the Chambers Submission Application
Here's the complete implementation with proper form filling, maintaining the conditions for mapping document cells:
python
User
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
Function to append Word documents
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
code
# Identifying text based on template type
identifier_text = f"{'Confidential' if 'Confidential' in template_path else 'Publishable'} Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
current_status = data['Current Status (ongoing / completed )']
doc.tables[0].cell(9, 0).text = f" {current_status or 'N/A'}"
# Save the individual document
doc.save(output_path)
return output_path # Return path for later combining
Assistant
Thank you for the clarification! Let's revert the code to maintain the functionality that allows for both "Confidential" and "Publishable" templates while allowing you to select specific rows to fill in the appropriate form based on some condition.
Updated Code for Chambers Submission Application
In this updated version, I will ensure that:
The correct template type is applied based on conditions in your original implementation.
Proper selection mechanisms are maintained for both types of forms.
Here is the modified version:
python
User
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
Function to append Word documents
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
code
# Identifying text based on template type
identifier_text = f"{'Confidential' if 'Confidential' in template_path else 'Publishable'} Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
current_status = data['Current Status (ongoing / completed )']
doc.tables[0].cell(9, 0).text = f" {current_status or 'N/A'}"
# Save the individual document
doc.save(output_path)
return output_path # Return path for later combining
Assistant
To implement a user interface in your Streamlit application that differentiates between confidential and publishable cases, we can use two separate scrollable sections (or containers) to list and allow users to select cases from each category.
Here’s how to modify your existing code to achieve that functionality:
Updated Code for the Chambers Submission Application
This version will create a more organized layout by providing two separate scrollable areas for selecting cases based on their status (confidential or publishable).
python
User
make them in scrobble conatiner
Assistant
To create scrollable containers in your Streamlit application for selecting confidential and publishable cases, you can use st.expander, which allows for collapsible sections, or use st.container to manage the layout. For the purpose of this implementation, we will use st.container with CSS to enable scrollbars to appear when the content exceeds the container's height.
Here’s how to implement scrollable containers for your client selection:
Complete Code with Scrollable Containers
python
User
no it odesnot make any scrollable conatiner
Assistant
To create scrollable containers in Streamlit, we can use st.container() in combination with CSS to limit the height of the container, thereby enabling scrolling when content exceeds that height. Streamlit does not provide built-in scrollbars for containers, but we can add custom CSS to simulate this.
Below is an updated version of your code that correctly implements scrollable containers for selecting both confidential and publishable cases:
Complete Code for the Scrollable Containers in the Chambers Submission Application
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
# Function to append Word documents
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Identifying text based on template type
if "Confidential" in template_path:
identifier_text = f"Confidential Matter {matter_count}"
else:
identifier_text = f"Publishable Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
# Save the individual document
doc.save(output_path)
return output_path # Return path for later combining
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs_no = []
individual_docs_yes = []
# Filter the DataFrame for rows
df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
# Handle Publishable Matters for 'No' rows
for index, row in df_no.iterrows():
temporary_output_path = f"temp_publishable_no_{index}.docx"
individual_doc_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path)
individual_docs_no.append(individual_doc_path)
# Handle Publishable Matters for 'Yes' rows
for index, row in df_yes.iterrows():
temporary_output_path = f"temp_publishable_yes_{index}.docx"
individual_doc_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path)
individual_docs_yes.append(individual_doc_path)
# Combine in the desired order: No documents + after + Yes documents
final_output_path = output_path
append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, final_output_path)
# Clean up temporary documents
for doc_path in individual_docs_no + individual_docs_yes:
os.remove(doc_path)
return True
except Exception as e:
st.error(f"Unexpected error: {e}")
return False
# Streamlit application
def app():
st.title("Chambers Submission")
st.sidebar.markdown("🔧 **This implementation is still in progress. The production version is not yet live.** For testing, use this link: [Click Here](http://localhost:8501/)", unsafe_allow_html=True)
excel_file = st.file_uploader("Upload Excel File for Chambers", type=["xlsx", "xls"])
if st.button("Generate Chambers Form"):
if excel_file:
output_path = "Chambers_Submission.docx"
success = populate_chambers(excel_file, output_path)
if success and os.path.exists(output_path):
st.success("Chambers Form generated successfully!")
with open(output_path, "rb") as f:
st.download_button(
label="Download Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Error generating document.")
else:
st.error("Please upload an Excel file.")
if __name__ == "__main__":
app()
Key Changes Made:
Structure Retained: The main structure of the application remains the same, especially the sidebar and file handling.
Document Processing Improvement: Integrated the modifications you indicated regarding the document processing while keeping the key functionality intact.
Error Handling: Inline st.error messages for better user feedback during the document generation process.
This layout ensures that all the features and functionality are available and that the code is structured efficiently.
Streamlit application
def main():
st.title("Legal Era Form Generator")
code
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
with st.spinner("Processing..."):
# Save the uploaded Excel file temporarily
temp_excel_path = "temp_uploaded_file.xlsx"
with open(temp_excel_path, "wb") as f:
f.write(excel_file.getbuffer())
# Hardcoded path for the Word document template
doc_path = r"C:\Users\Administrator\Desktop\Bd team\Legal Era Law Firm.docx"
# Hardcoded output path
output_file = r"C:\Users\Administrator\Desktop\confif.docx"
# Call the populate_chambers function
populate_chambers(temp_excel_path, doc_path, output_file)
# Provide a link to download the output file
if os.path.exists(output_file):
st.success("Forms filled successfully! You can download it below.")
with open(output_file, "rb") as f:
st.download_button(
"Download Filled Form",
f,
file_name="LegalEra__Output.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the output file.")
# Clean up the temporary file
os.remove(temp_excel_path)
else:
st.error("Please upload the Excel file.")
if name == "main":
main()
AttributeError: module 'legal_era' has no attribute 'app'
Traceback:
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\scriptrunner\exec_code.py", line 88, in exec_func_with_error_handling
result = func()
^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 590, in code_to_exec
exec(code, module.dict)
File "C:\Users\Administrator\Desktop\dev\pondering\main.py", line 56, in
app.add_app("Legal Era", legal_era.app, )
import pandas as pd
from docx import Document
import streamlit as st
import os
def populate_chambers(excel_path, doc_path, output_path):
try:
print("Loading Excel data...")
df = pd.read_excel(excel_path)
print(f"Excel data loaded: {len(df)} rows")
print("Loading Word document...")
doc = Document(doc_path)
tables = doc.tables
print(f"Total tables found in document: {len(tables)}")
# Check if tables exist in the document
if not tables:
print("Error: No tables found in document.")
return
# Variable to track current row in the DataFrame
df_index = 0
# Iterate through each table in the document
for table in tables:
# Ensure the table has enough rows
if len(table.rows) >= 18:
try:
# Fill the cells from the current row in the DataFrame
table.cell(2, 0).text = str(df.iloc[df_index]['Client Name ']) # Client Name
table.cell(4, 0).text = str(df.iloc[df_index]['Description (in 500 words)']) # Description
table.cell(6, 0).text = str(df.iloc[df_index]['Value ']) # Matter/Case Overview
table.cell(10, 0).text = str(df.iloc[df_index]['Lead partners']) # Lead Partner
table.cell(12, 0).text = str(df.iloc[df_index]['Team Members']) # Team Members
table.cell(14, 0).text = str(df.iloc[df_index]['Other Firms/counsels Involved']) # Other Involved Firms
print(f"Matter {df_index + 1} populated successfully.")
df_index += 1 # Move to the next row in the DataFrame
except IndexError as e:
print(f"Error: Table has fewer rows than expected. Skipping entry. {e}")
else:
print(f"Warning: Table has only {len(table.rows)} rows. Expected at least 18.")
# Save the updated document
doc.save(output_path)
print("Document updated successfully!")
except Exception as e:
print(f"Unexpected error: {e}")
# Streamlit application
def app(): # Change to app() to avoid AttributeError
st.title("Legal Era Form Generator")
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
with st.spinner("Processing..."):
# Save the uploaded Excel file temporarily
temp_excel_path = "temp_uploaded_file.xlsx"
with open(temp_excel_path, "wb") as f:
f.write(excel_file.getbuffer())
# Hardcoded path for the Word document template
doc_path = r"C:\Users\Administrator\Desktop\Bd team\Legal Era Law Firm.docx"
# Hardcoded output path
output_file = r"C:\Users\Administrator\Desktop\confif.docx"
# Call the populate_chambers function
populate_chambers(temp_excel_path, doc_path, output_file)
# Provide a link to download the output file
if os.path.exists(output_file):
st.success("Forms filled successfully! You can download it below.")
with open(output_file, "rb") as f:
st.download_button(
"Download Filled Form",
f,
file_name="LegalEra__Output.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the output file.")
# Clean up the temporary file
os.remove(temp_excel_path)
else:
st.error("Please upload the Excel file.")
if __name__ == "__main__":
app() # Call the app function here
Key Changes:
Renamed the main() function to app() to ensure that you’re calling the function that is referenced elsewhere.
Ensure you make any adjustments based on your project structure. If you keep main() and have it called in other parts of your code, be sure to use it consistently across your references.
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs_no = []
individual_docs_yes = []
code
# Filter the DataFrame for rows
df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
# Handle Publishable Matters for 'No' rows
for index, row in df_no.iterrows():
temporary_output_path = f"temp_publishable_no_{index}.docx"
individual_doc_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path)
individual_doc_path
individual_docs_no.append(individual_doc_path)
# Handle Publishable Matters for 'Yes' rows
for index, row in df_yes.iterrows():
temporary_output_path = f"temp_publishable_yes_{index}.docx"
individual_doc_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path)
individual_docs_yes.append(individual_doc_path)
# Combine in the desired order: No documents + after + Yes documents
final_output_path = output_path
append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, final_output_path)
print(f"Combined document saved: {final_output_path}")
# Clean up temporary documents
for doc_path in individual_docs_no + individual_docs_yes:
os.remove(doc_path)
except Exception as e:
print(f"Unexpected error: {e}")
Streamlit application
def main():
st.title("Fill Chambers and Partners Form")
code
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
output_path = "combined_confidential_publishable.docx"
populate_chambers(excel_file, output_path)
# Check if the output file was created successfully
if os.path.exists(output_path):
st.success("Forms filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
btn = st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.error("Please upload the Excel file.")
if name == "main":
main() samme error for this also app wali
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
# Function to append Word documents
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Identifying text based on template type
identifier_text = f"{'Confidential' if 'Confidential' in template_path else 'Publishable'} Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
# Save the individual document
doc.save(output_path)
return output_path
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs_no = []
individual_docs_yes = []
# Filter the DataFrame for rows
df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
# Handle cases for different rows
for index, row in df_no.iterrows():
temporary_output_path = f"temp_publishable_no_{index}.docx"
individual_docs_no.append(create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path))
for index, row in df_yes.iterrows():
temporary_output_path = f"temp_publishable_yes_{index}.docx"
individual_docs_yes.append(create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path))
# Combine documents
append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, output_path)
for doc_path in individual_docs_no + individual_docs_yes:
os.remove(doc_path)
except Exception as e:
st.error(f"Unexpected error: {e}")
# Streamlit application
def main():
st.title("Fill Chambers and Partners Form")
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
output_path = "combined_confidential_publishable.docx"
populate_chambers(excel_file, output_path)
if os.path.exists(output_path):
st.success("Forms filled successfully!")
with open(output_path, "rb") as f:
st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.error("Please upload the Excel file.")
if __name__ == "__main__":
main() # This should correctly call the main function.
Steps to Ensure Correct Execution
Verify that you save this code in a .py file (e.g., my_app.py).
Run the Streamlit application using the command line:
bash
streamlit run my_app.py
Check for conflicting or duplicate files/modules that may cause confusion in variable naming or function calls.
Ensure you have the correct imports and that the file paths are accessible.
Debugging
If you continue to experience issues:
Add print statements throughout your code (for debugging) to confirm that each part of the code is executing as expected.
Remove any .pyc files if you are editing the module or script to ensure you are running the latest version of your code.
Let me know if you encounter additional issues!
# chambers.py
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
# Your functions here (append_docs, create_individual_document, populate_chambers)
def app(): # Change from main() to app() if necessary
st.title("Fill Chambers and Partners Form")
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
output_path = "combined_confidential_publishable.docx"
populate_chambers(excel_file, output_path)
if os.path.exists(output_path):
st.success("Forms filled successfully!")
with open(output_path, "rb") as f:
st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.error("Please upload the Excel file.")
if __name__ == "__main__":
app() # Ensure this line correctly calls the function.
Running Your Application
Ensure the file structure allows for importing: If chambers.py is in the same directory as main.py, you can import it like this in main.py:
python
# main.py
from chambers import app # Ensure this matches the 'app()' function name in chambers.py
# Streamlit entry point
if __name__ == "__main__":
app() # Call the app function from the chambers module
Run your Streamlit application:
Make sure to execute from the command line using:
bash
streamlit run main.py
Final Steps
Double-check your code to ensure all names match (i.e., app, main) and the appropriate function is being called.
Re-run the application and see if the error persists.
If you have further issues, it may also help to check if there's a naming conflict with your files or modules, particularly ensure no module is named chambers.py that would cause conflicts.
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
# Function to append Word documents
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Identifying text based on template type
identifier_text = f"{'Confidential' if 'Confidential' in template_path else 'Publishable'} Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
# Save the individual document
doc.save(output_path)
return output_path # Return path for later combining
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs_no = []
individual_docs_yes = []
# Filter the DataFrame for rows
df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
# Handle Publishable Matters for 'No' rows
for index, row in df_no.iterrows():
temporary_output_path = f"temp_publishable_no_{index}.docx"
individual_docs_no.append(create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path))
# Handle Publishable Matters for 'Yes' rows
for index, row in df_yes.iterrows():
temporary_output_path = f"temp_publishable_yes_{index}.docx"
individual_docs_yes.append(create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path))
# Combine in the desired order: No documents + after + Yes documents
append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, output_path)
# Clean up temporary documents
for doc_path in individual_docs_no + individual_docs_yes:
os.remove(doc_path)
except Exception as e:
st.error(f"Unexpected error: {e}")
# Streamlit application
def app():
st.title("Fill Chambers and Partners Form")
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
output_path = "combined_confidential_publishable.docx" # Output file path
populate_chambers(excel_file, output_path)
# Check if the output file was created successfully
if os.path.exists(output_path):
st.success("Forms filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.error("Please upload the Excel file.")
if __name__ == "__main__":
app() # Ensure this calls the 'app' function
Instructions to Run the Code
Save the Code: Save the above code in a file named chambers.py.
Run the Streamlit Application:
Open your terminal or command prompt and run the following command:
bash
streamlit run chambers.py
Access the App: Open the browser and go to the link provided by Streamlit (usually http://localhost:8501).
Additional Notes
Ensure that all required libraries (like pandas, python-docx, streamlit) are installed in your Python environment. You can install them using:
bash
pip install pandas python-docx streamlit
Check the paths for your template files (TEMPLATE_PATH_NO, TEMPLATE_PATH_YES, AFTER_DOCX_PATH) and ensure they are correct and accessible.
Modify the column names in the DataFrame retrieval code, if necessary, to match the headers in your Excel file.
This code should work as intended! If you encounter any specific errors while running, please share those error messages for further assistance.
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
print(df.columns.tolist()) # Print all column names for debugging
individual_docs_no = []
individual_docs_yes = []
# Filter the DataFrame for rows
df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
# Handle Publishable Matters for 'No' rows
for index, row in df_no.iterrows():
temporary_output_path = f"temp_publishable_no_{index}.docx"
individual_docs_no.append(create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path))
# Handle Publishable Matters for 'Yes' rows
for index, row in df_yes.iterrows():
temporary_output_path = f"temp_publishable_yes_{index}.docx"
individual_docs_yes.append(create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path))
# Combine in the desired order: No documents + after + Yes documents
append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, output_path)
# Clean up temporary documents
for doc_path in individual_docs_no + individual_docs_yes:
os.remove(doc_path)
except Exception as e:
st.error(f"Unexpected error: {e}")
Final Steps
Run Your Application Again: With the new print statement, run your Streamlit application again.
Check for Output: Look for the printed column names and match them with what you're trying to access in the DataFrame. Adjust your code accordingly.
If everything is correctly matched but the error persists, please provide the printed output of the column names so we can help further!
Explanation of Changes
Directly Access the Status Column: Access the 'Current Status (ongoing / completed )' exactly as it appears in your DataFrame. If it has any leading or trailing spaces, ensure those match.
Conditionally Handle Empty Entries: When copying the status to the Word document, use:
python
doc.tables[0].cell(9, 0).text = f" {current_status or 'N/A'}"
This means if current_status is an empty string, it will print 'N/A' instead. You can change 'N/A' to whatever placeholder you prefer for empty fields.
Maintain Consistency: Double-check that every other column is referenced correctly in the same way to avoid similar issues.
Complete populate_chambers Code for Context
Ensure your complete populate_chambers() function aligns with this update and maintains proper context:
python
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
print(df.columns.tolist()) # Debug the column names
individual_docs_no = []
individual_docs_yes = []
# Filter the DataFrame for rows
df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
# Handle Publishable Matters for 'No' rows
for index, row in df_no.iterrows():
temporary_output_path = f"temp_publishable_no_{index}.docx"
individual_docs_no.append(create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path))
# Handle Publishable Matters for 'Yes' rows
for index, row in df_yes.iterrows():
temporary_output_path = f"temp_publishable_yes_{index}.docx"
individual_docs_yes.append(create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path))
# Combine in the desired order: No documents + after + Yes documents
append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, output_path)
# Clean up temporary documents
for doc_path in individual_docs_no + individual_docs_yes:
os.remove(doc_path)
except Exception as e:
st.error(f"Unexpected error: {e}")
Final Steps
Test the Application: After making these updates, run your Streamlit application again and upload the Excel file to verify that the status column is copied correctly into the Word document.
Debug as Needed: If you encounter any further issues, evaluate any debug output you see and make adjustments.
Let me know if you need any further refinements or assistance!
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs_no = []
individual_docs_yes = []
code
# Filter the DataFrame for rows
df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
# Handle Publishable Matters for 'No' rows
for index, row in df_no.iterrows():
temporary_output_path = f"temp_publishable_no_{index}.docx"
individual_docs_no.append(create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path))
# Handle Publishable Matters for 'Yes' rows
for index, row in df_yes.iterrows():
temporary_output_path = f"temp_publishable_yes_{index}.docx"
individual_docs_yes.append(create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path))
# Combine in the desired order: No documents + after + Yes documents
append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, output_path)
# Clean up temporary documents
for doc_path in individual_docs_no + individual_docs_yes:
os.remove(doc_path)
except Exception as e:
st.error(f"Unexpected error: {e}")
Streamlit application
def app():
st.title("Fill Chambers and Partners Form")
code
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
output_path = "combined_confidential_publishable.docx" # Output file path
populate_chambers(excel_file, output_path)
# Check if the output file was created successfully
if os.path.exists(output_path):
st.success("Forms filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.error("Please upload the Excel file.")
if name == "main":
app() # Ensure this calls the 'app' function in this after uploaidng i dont want to fill all the rows so give me otion to choose the rows to fill by giving the fields of client name and 50 word desprication along with that as ..............dot dot dot then fill for all the rows which are selected
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
# Function to append Word documents
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Identifying text based on template type
identifier_text = f"{'Confidential' if 'Confidential' in template_path else 'Publishable'} Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
current_status = data['Current Status (ongoing / completed )']
doc.tables[0].cell(9, 0).text = f" {current_status or 'N/A'}"
# Save the individual document
doc.save(output_path)
return output_path # Return path for later combining
def populate_chambers(selected_data, output_path):
"""Generate the documents based on the selected input from the DataFrame."""
try:
individual_docs = []
# Handle selected rows
for index, row in selected_data.iterrows():
temporary_output_path = f"temp_selected_{index}.docx"
individual_docs.append(create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path))
# Combine documents into a single file
append_docs(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
except Exception as e:
st.error(f"Unexpected error: {e}")
# Streamlit application
def app():
st.title("Fill Chambers and Partners Form")
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if excel_file:
df = pd.read_excel(excel_file)
# Create a selection interface
selected_rows = []
for index, row in df.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show only the first 50 characters
is_selected = st.checkbox(f"Select Client: {client_name} - {description}...", value=True)
# Store current row data if selected
if is_selected:
selected_rows.append(row)
if st.button("Fill the Template"):
if selected_rows:
output_path = "combined_confidential_publishable.docx" # Output file path
selected_df = pd.DataFrame(selected_rows) # Create a DataFrame from the selected rows
populate_chambers(selected_df, output_path)
# Check if the output file was created successfully
if os.path.exists(output_path):
st.success("Forms filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.warning("Please select at least one row to fill in the template.")
if __name__ == "__main__":
app() # Ensure this calls the 'app' function
Explanation of Code Changes
Selection of Rows:
Each row from the uploaded Excel file is displayed with a checkbox, allowing the user to select whether they want to include it in the final document.
The description is truncated to 50 characters and represented with ellipses (...) for clarity.
Storing Selected Data:
The app creates a list (selected_rows) to store the rows that the user selects via checkboxes.
Populate Chambers Function:
The populate_chambers function is modified to accept only the selected rows as input, generating documents accordingly.
Download Option:
After generating the document, a download link is provided if the files were successfully created.
How to Use the Application
Run the Application using:
bash
streamlit run chambers.py
Upload the Excel File when prompted.
Select Rows by checking the relevant checkboxes next to the items you wish to include.
Click "Fill the Template" to generate the final document for the selected entries.
Download the Resulting Document once it has been generated.
This code structure gives users flexibility and allows them to generate documents based on their specific selections efficiently. Let me know if you have further questions or if you need additional features!
def remove_empty_pages(doc_path):
"""Remove empty pages from the document"""
doc = Document(doc_path)
code
# Check for empty sections/pages and mark them for removal
# This is a basic implementation - more complex logic may be needed
# depending on how your documents are structured
# Save the document back
doc.save(doc_path)
return doc_path
def append_docs(nominee_docs, simple_docs, output_doc):
"""Combine multiple Word documents into one, nominees first then simple."""
combined_doc = Document()
code
# First add all nominee documents
for i, doc_path in enumerate(nominee_docs):
sub_doc = Document(doc_path)
# Add page break between documents (except first)
if i > 0:
combined_doc.add_page_break()
# Copy content from sub_doc to combined_doc
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
# Then add all simple documents
for i, doc_path in enumerate(simple_docs):
# Always add page break before adding simple docs
if i == 0 and nominee_docs:
combined_doc.add_page_break()
elif i > 0:
combined_doc.add_page_break()
sub_doc = Document(doc_path)
# Copy content from sub_doc to combined_doc
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
# Now try to remove any empty pages
return remove_empty_pages(output_doc)
def process_benchmark_forms(excel_file, nominee_template_path, simple_template_path,
selected_nominee_indices, selected_simple_indices):
"""Generate the Benchmark Awards forms based on the selected Excel rows."""
try:
# Read Excel file
df = pd.read_excel(excel_file)
nominee_docs = []
simple_docs = []
code
# Process nominee selections first
nominee_count = 1
for index in selected_nominee_indices:
row = df.iloc[index]
temp_output_path = f"temp_nominee_{nominee_count}.docx"
individual_doc_path = create_individual_document(
nominee_template_path,
row,
nominee_count,
temp_output_path,
"nominee"
)
if individual_doc_path:
nominee_docs.append(individual_doc_path)
nominee_count += 1
# Then process simple work highlights
simple_count = 1
for index in selected_simple_indices:
row = df.iloc[index]
temp_output_path = f"temp_simple_{simple_count}.docx"
individual_doc_path = create_individual_document(
simple_template_path,
row,
simple_count,
temp_output_path,
"simple"
)
if individual_doc_path:
simple_docs.append(individual_doc_path)
simple_count += 1
# Combine all documents
if nominee_docs or simple_docs:
combined_output_path = "combined_benchmark_forms.docx"
append_docs(nominee_docs, simple_docs, combined_output_path)
# Clean up temporary files
for doc_path in nominee_docs + simple_docs:
os.remove(doc_path)
return combined_output_path
except Exception as e:
st.error(f"Error processing documents: {str(e)}")
return None
Streamlit application
def main():
st.title("Benchmark Awards 2025 Form Generator")
code
# Upload files
col1, col2, col3 = st.columns(3)
with col1:
st.subheader("Upload Excel Data")
excel_file = st.file_uploader("Upload Excel Data File", type=["xlsx", "xls"])
with col2:
st.subheader("Upload Nominee Template")
nominee_template_file = st.file_uploader("Upload Nominee Template", type=["docx"])
with col3:
st.subheader("Upload Simple Template")
simple_template_file = st.file_uploader("Upload Simple Work Highlight Template", type=["docx"])
# Client selection section
if excel_file is not None:
# Read the Excel file
df = pd.read_excel(excel_file)
# Check if the required column exists
if "Client Name " in df.columns:
# Create tabs for the two different form types
tab1, tab2 = st.tabs(["Nominee Work Highlights", "Simple Work Highlights"])
with tab1:
st.subheader("Select Nominee Work Highlights (Maximum 3)")
st.write("Select up to 3 matters for nominee work highlights:")
# Create container for nominee selection
nominee_container = st.container()
# Track selected nominee indices
selected_nominee_indices = []
with nominee_container:
for i, client in enumerate(df["Client Name "]):
# Display additional information to help identify each client
matter_info = f"{client}"
if "Matter/Case Overview" in df.columns:
matter_info += f" - {df['Matter/Case Overview'].iloc[i]}"
# Create checkbox for each client
# Disable checkbox once 3 are selected
disabled = len(selected_nominee_indices) >= 3 and i not in selected_nominee_indices
if st.checkbox(matter_info, key=f"nominee_{i}", disabled=disabled):
if i not in selected_nominee_indices:
selected_nominee_indices.append(i)
elif i in selected_nominee_indices:
selected_nominee_indices.remove(i)
st.write(f"Selected nominee matters: {len(selected_nominee_indices)} out of 3 maximum")
# Warning if more than 3 selected
if len(selected_nominee_indices) > 3:
st.warning("You have selected more than 3 nominee matters. Only the first 3 will be processed.")
selected_nominee_indices = selected_nominee_indices[:3]
with tab2:
st.subheader("Select Simple Work Highlights")
st.write("Select any number of matters for simple work highlights:")
# Create container for simple selection
simple_container = st.container()
# Track selected simple indices
selected_simple_indices = []
with simple_container:
for i, client in enumerate(df["Client Name "]):
# Skip if already selected as nominee
if i in selected_nominee_indices:
continue
# Display additional information to help identify each client
matter_info = f"{client}"
if "Matter/Case Overview" in df.columns:
matter_info += f" - {df['Matter/Case Overview'].iloc[i]}"
# Create checkbox for each client
if st.checkbox(matter_info, key=f"simple_{i}"):
selected_simple_indices.append(i)
st.write(f"Selected simple matters: {len(selected_simple_indices)}")
# Process forms button
if st.button("Generate Selected Forms"):
if not nominee_template_file and len(selected_nominee_indices) > 0:
st.error("Please upload the nominee template file.")
elif not simple_template_file and len(selected_simple_indices) > 0:
st.error("Please upload the simple work highlight template file.")
elif len(selected_nominee_indices) == 0 and len(selected_simple_indices) == 0:
st.error("Please select at least one matter to proceed.")
else:
# Show progress
progress_bar = st.progress(0)
status_text = st.empty()
status_text.text("Saving templates...")
# Save templates to temporary files
if nominee_template_file:
with open("nominee_template.docx", "wb") as f:
f.write(nominee_template_file.getbuffer())
if simple_template_file:
with open("simple_template.docx", "wb") as f:
f.write(simple_template_file.getbuffer())
status_text.text("Processing selected matters...")
# Process forms
nominee_template = "nominee_template.docx" if nominee_template_file else None
simple_template = "simple_template.docx" if simple_template_file else None
output_path = process_benchmark_forms(
excel_file,
nominee_template,
simple_template,
selected_nominee_indices,
selected_simple_indices
)
if output_path and os.path.exists(output_path):
progress_bar.progress(100)
status_text.text("Forms generated successfully!")
total_forms = len(selected_nominee_indices) + len(selected_simple_indices)
st.success(f"Generated forms for {total_forms} selected matters!")
# Provide download link
with open(output_path, "rb") as f:
st.download_button(
label="Download Combined Forms",
data=f,
file_name="Benchmark_Awards_2025_Submissions.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
progress_bar.progress(100)
st.error("Failed to generate forms.")
else:
st.error("The Excel file does not contain a 'Client Name ' column. Please check your file.")
if name == "main":
main() take refrence from this or displaying client name and along with that the dsecription
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
from io import BytesIO
# Set page configuration at the very beginning
st.set_page_config(layout="wide", page_title="Benchmark Awards Form Generator")
def create_individual_document(template_path, data, matter_count, output_path, form_type):
"""Create an individual document for a row of data based on the template."""
doc = Document(template_path)
# Find the table in the document
if len(doc.tables) < 1:
st.error("Template document does not contain the expected table.")
return None
table = doc.tables[0]
# Map Excel fields to table cells based on the form structure
field_mapping = {
"Case overview": data.get("Matter/Case Overview", ""),
"Confidential/Partially confidential (Yes or no)": data.get("Confidential / Publishable", ""),
"Dispute resolution practice area(s)": data.get("Practice Area", ""),
"Industry sector(s)": data.get("Industry Sector", ""),
"Date completed (MM/YY) / Ongoing": data.get("Current Status (ongoing / completed )", ""),
"Value (indicate currency)": data.get("Value", ""),
"Client(s) advised": data.get("Client Name ", ""),
"Lead partner involved": data.get("Lead partners", ""),
"Other lawyers involved (include position)": data.get("Team Members", ""),
"Your firm's role": data.get("Role of S&A", ""),
"Other law firms and their roles": data.get("Other Firms/counsels Involved", ""),
"Governing law": "Indian Law", # Default value
"Description": data.get("Description (in 500 words)", ""),
"Please state the significance, impact and outcome of the case": data.get("The significance, impact and outcome of the case", "")
}
# Update the title based on form type
for paragraph in doc.paragraphs:
if "WORK HIGHLIGHT" in paragraph.text:
paragraph.text = f"WORK HIGHLIGHT #{matter_count}"
for run in paragraph.runs:
run.font.bold = True
# Populate the table with data
for row in table.rows:
if len(row.cells) >= 2: # Ensure the row has at least two cells
cell_text = row.cells[0].text.strip()
if cell_text in field_mapping:
row.cells[1].text = str(field_mapping[cell_text])
# Save the individual document
doc.save(output_path)
return output_path
def process_benchmark_forms(excel_file, nominee_template_path, simple_template_path, selected_nominee_indices, selected_simple_indices):
"""Generate the Benchmark Awards forms based on the selected Excel rows."""
try:
# Read Excel file
df = pd.read_excel(excel_file)
nominee_docs = []
simple_docs = []
# Process nominee selections first
nominee_count = 1
for index in selected_nominee_indices:
row = df.iloc[index]
temp_output_path = f"temp_nominee_{nominee_count}.docx"
individual_doc_path = create_individual_document(
nominee_template_path,
row,
nominee_count,
temp_output_path,
"nominee"
)
if individual_doc_path:
nominee_docs.append(individual_doc_path)
nominee_count += 1
# Then process simple work highlights
simple_count = 1
for index in selected_simple_indices:
row = df.iloc[index]
temp_output_path = f"temp_simple_{simple_count}.docx"
individual_doc_path = create_individual_document(
simple_template_path,
row,
simple_count,
temp_output_path,
"simple"
)
if individual_doc_path:
simple_docs.append(individual_doc_path)
simple_count += 1
# Combine all documents
if nominee_docs or simple_docs:
combined_output_path = "combined_benchmark_forms.docx"
append_docs(nominee_docs, simple_docs, combined_output_path)
# Clean up temporary files
for doc_path in nominee_docs + simple_docs:
os.remove(doc_path)
return combined_output_path
except Exception as e:
st.error(f"Error processing documents: {str(e)}")
return None
# Streamlit application
def main():
st.title("Benchmark Awards 2025 Form Generator")
# Upload files
col1, col2, col3 = st.columns(3)
with col1:
st.subheader("Upload Excel Data")
excel_file = st.file_uploader("Upload Excel Data File", type=["xlsx", "xls"])
with col2:
st.subheader("Upload Nominee Template")
nominee_template_file = st.file_uploader("Upload Nominee Template", type=["docx"])
with col3:
st.subheader("Upload Simple Template")
simple_template_file = st.file_uploader("Upload Simple Work Highlight Template", type=["docx"])
# Client selection section
if excel_file is not None:
# Read the Excel file
df = pd.read_excel(excel_file)
# Check if the required column exists
if "Client Name " in df.columns:
# Create tabs for the two different form types
tab1, tab2 = st.tabs(["Nominee Work Highlights", "Simple Work Highlights"])
with tab1:
st.subheader("Select Nominee Work Highlights (Maximum 3)")
st.write("Select up to 3 matters for nominee work highlights:")
nominee_container = st.container()
selected_nominee_indices = []
with nominee_container:
for i, client in enumerate(df["Client Name "]):
matter_info = f"{client}"
if "Matter/Case Overview" in df.columns:
matter_info += f" - {df['Matter/Case Overview'].iloc[i][:50]}..." # Truncate description
# Checkbox for nominee matter selection
disabled = len(selected_nominee_indices) >= 3 and i not in selected_nominee_indices
if st.checkbox(matter_info, key=f"nominee_{i}", disabled=disabled):
if i not in selected_nominee_indices:
selected_nominee_indices.append(i)
elif i in selected_nominee_indices:
selected_nominee_indices.remove(i)
st.write(f"Selected nominee matters: {len(selected_nominee_indices)} out of 3 maximum")
if len(selected_nominee_indices) > 3:
st.warning("You have selected more than 3 nominee matters. Only the first 3 will be processed.")
selected_nominee_indices = selected_nominee_indices[:3]
with tab2:
st.subheader("Select Simple Work Highlights")
st.write("Select any number of matters for simple work highlights:")
simple_container = st.container()
selected_simple_indices = []
with simple_container:
for i, client in enumerate(df["Client Name "]):
if i in selected_nominee_indices:
continue
matter_info = f"{client}"
if "Matter/Case Overview" in df.columns:
matter_info += f" - {df['Matter/Case Overview'].iloc[i][:50]}..." # Truncate description
if st.checkbox(matter_info, key=f"simple_{i}"):
selected_simple_indices.append(i)
st.write(f"Selected simple matters: {len(selected_simple_indices)}")
if st.button("Generate Selected Forms"):
if not nominee_template_file and len(selected_nominee_indices) > 0:
st.error("Please upload the nominee template file.")
elif not simple_template_file and len(selected_simple_indices) > 0:
st.error("Please upload the simple work highlight template file.")
elif len(selected_nominee_indices) == 0 and len(selected_simple_indices) == 0:
st.error("Please select at least one matter to proceed.")
else:
# Show progress
progress_bar = st.progress(0)
status_text = st.empty()
status_text.text("Saving templates...")
# Save templates to temporary files
if nominee_template_file:
with open("nominee_template.docx", "wb") as f:
f.write(nominee_template_file.getbuffer())
if simple_template_file:
with open("simple_template.docx", "wb") as f:
f.write(simple_template_file.getbuffer())
status_text.text("Processing selected matters...")
# Process forms
nominee_template = "nominee_template.docx" if nominee_template_file else None
simple_template = "simple_template.docx" if simple_template_file else None
output_path = process_benchmark_forms(
excel_file,
nominee_template,
simple_template,
selected_nominee_indices,
selected_simple_indices
)
if output_path and os.path.exists(output_path):
progress_bar.progress(100)
status_text.text("Forms generated successfully!")
total_forms = len(selected_nominee_indices) + len(selected_simple_indices)
st.success(f"Generated forms for {total_forms} selected matters!")
# Provide download link
with open(output_path, "rb") as f:
st.download_button(
label="Download Combined Forms",
data=f,
file_name="Benchmark_Awards_2025_Submissions.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
progress_bar.progress(100)
st.error("Failed to generate forms.")
else:
st.error("The Excel file does not contain a 'Client Name ' column. Please check your file.")
if __name__ == "__main__":
main()
Key Changes Made
Description Truncation:
The description text shown beside each checkbox now displays only the first 50 characters, followed by ellipses (...) to indicate that it's truncated. This is useful for keeping the UI clean and readable.
Checkbox Display:
When displaying each client, both the client name and the truncated case overview/matter description are shown, making it easier for users to identify which clients they are selecting.
Dynamic Selection Handling:
The application enforces a maximum of 3 nominees while allowing any number of simple work highlights to be selected.
How to Use
Run the Application with:
bash
streamlit run your_script.py
Replace your_script.py with the filename containing this code.
Upload the Excel File, Nominee Template, and Simple Template as prompted.
Select Clients using the checkboxes, which now display both their names and a truncated overview.
Generate the Forms by clicking the button, which processes only the selected entries.
Download the Combined Forms after generation.
This structure provides a flexible and user-friendly selection mechanism for generating the needed forms. Let me know if you have further modifications or questions!
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
from io import BytesIO
# Set page configuration at the very beginning
st.set_page_config(layout="wide", page_title="Benchmark Awards Form Generator")
def create_individual_document(template_path, data, matter_count, output_path, form_type):
"""Create an individual document for a row of data based on the template."""
doc = Document(template_path)
# Find the table in the document
if len(doc.tables) < 1:
st.error("Template document does not contain the expected table.")
return None
table = doc.tables[0]
# Map Excel fields to table cells based on the form structure
field_mapping = {
"Case overview": data.get("Matter/Case Overview", ""),
"Confidential/Partially confidential (Yes or no)": data.get("Confidential / Publishable", ""),
"Dispute resolution practice area(s)": data.get("Practice Area", ""),
"Industry sector(s)": data.get("Industry Sector", ""),
"Date completed (MM/YY) / Ongoing": data.get("Current Status (ongoing / completed )", ""),
"Value (indicate currency)": data.get("Value", ""),
"Client(s) advised": data.get("Client Name ", ""),
"Lead partner involved": data.get("Lead partners", ""),
"Other lawyers involved (include position)": data.get("Team Members", ""),
"Your firm's role": data.get("Role of S&A", ""),
"Other law firms and their roles": data.get("Other Firms/counsels Involved", ""),
"Governing law": "Indian Law", # Default value
"Description": data.get("Description (in 500 words)", ""),
"Please state the significance, impact and outcome of the case": data.get("The significance, impact and outcome of the case", "")
}
# Update the title based on form type
for paragraph in doc.paragraphs:
if "WORK HIGHLIGHT" in paragraph.text:
paragraph.text = f"WORK HIGHLIGHT #{matter_count}"
for run in paragraph.runs:
run.font.bold = True
# Populate the table with data
for row in table.rows:
if len(row.cells) >= 2: # Ensure the row has at least two cells
cell_text = row.cells[0].text.strip()
if cell_text in field_mapping:
row.cells[1].text = str(field_mapping[cell_text])
# Save the individual document
doc.save(output_path)
return output_path
def append_docs(nominee_docs, simple_docs, output_doc):
"""Combine multiple Word documents into one, nominees first then simple."""
combined_doc = Document()
# Add nominee documents
for i, doc_path in enumerate(nominee_docs):
sub_doc = Document(doc_path)
if i > 0:
combined_doc.add_page_break()
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
# Then add simple documents
for i, doc_path in enumerate(simple_docs):
if i == 0 and nominee_docs:
combined_doc.add_page_break()
elif i > 0:
combined_doc.add_page_break()
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def process_benchmark_forms(excel_file, nominee_template_path, simple_template_path, selected_nominee_indices, selected_simple_indices):
"""Generate the Benchmark Awards forms based on the selected Excel rows."""
try:
df = pd.read_excel(excel_file)
nominee_docs = []
simple_docs = []
# Process nominee selections first
nominee_count = 1
for index in selected_nominee_indices:
row = df.iloc[index]
temp_output_path = f"temp_nominee_{nominee_count}.docx"
individual_doc_path = create_individual_document(
nominee_template_path,
row,
nominee_count,
temp_output_path,
"nominee"
)
if individual_doc_path:
nominee_docs.append(individual_doc_path)
nominee_count += 1
# Then process simple work highlights
simple_count = 1
for index in selected_simple_indices:
row = df.iloc[index]
temp_output_path = f"temp_simple_{simple_count}.docx"
individual_doc_path = create_individual_document(
simple_template_path,
row,
simple_count,
temp_output_path,
"simple"
)
if individual_doc_path:
simple_docs.append(individual_doc_path)
simple_count += 1
# Combine all documents
if nominee_docs or simple_docs:
combined_output_path = "combined_benchmark_forms.docx"
append_docs(nominee_docs, simple_docs, combined_output_path)
# Clean up temporary files
for doc_path in nominee_docs + simple_docs:
os.remove(doc_path)
return combined_output_path
except Exception as e:
st.error(f"Error processing documents: {str(e)}")
return None
# Streamlit application
def app():
st.title("Benchmark Awards 2025 Form Generator")
# Upload files
col1, col2, col3 = st.columns(3)
with col1:
st.subheader("Upload Excel Data")
excel_file = st.file_uploader("Upload Excel Data File", type=["xlsx", "xls"])
with col2:
st.subheader("Upload Nominee Template")
nominee_template_file = st.file_uploader("Upload Nominee Template", type=["docx"])
with col3:
st.subheader("Upload Simple Template")
simple_template_file = st.file_uploader("Upload Simple Work Highlight Template", type=["docx"])
# Client selection section
if excel_file is not None:
# Read the Excel file
df = pd.read_excel(excel_file)
# Check if the required column exists
if "Client Name " in df.columns:
# Create tabs for the two different form types
tab1, tab2 = st.tabs(["Nominee Work Highlights", "Simple Work Highlights"])
with tab1:
st.subheader("Select Nominee Work Highlights (Maximum 3)")
st.write("Select up to 3 matters for nominee work highlights:")
nominee_container = st.container()
selected_nominee_indices = []
with nominee_container:
for i, client in enumerate(df["Client Name "]):
matter_info = f"{client}"
if "Matter/Case Overview" in df.columns:
matter_info += f" - {df['Matter/Case Overview'].iloc[i][:50]}..." # Truncate description
# Checkbox for nominee matter selection
disabled = len(selected_nominee_indices) >= 3 and i not in selected_nominee_indices
if st.checkbox(matter_info, key=f"nominee_{i}", disabled=disabled):
if i not in selected_nominee_indices:
selected_nominee_indices.append(i)
elif i in selected_nominee_indices:
selected_nominee_indices.remove(i)
st.write(f"Selected nominee matters: {len(selected_nominee_indices)} out of 3 maximum")
if len(selected_nominee_indices) > 3:
st.warning("You have selected more than 3 nominee matters. Only the first 3 will be processed.")
selected_nominee_indices = selected_nominee_indices[:3]
with tab2:
st.subheader("Select Simple Work Highlights")
st.write("Select any number of matters for simple work highlights:")
simple_container = st.container()
selected_simple_indices = []
with simple_container:
for i, client in enumerate(df["Client Name "]):
if i in selected_nominee_indices:
continue
matter_info = f"{client}"
if "Matter/Case Overview" in df.columns:
matter_info += f" - {df['Matter/Case Overview'].iloc[i][:50]}..." # Truncate description
if st.checkbox(matter_info, key=f"simple_{i}"):
selected_simple_indices.append(i)
st.write(f"Selected simple matters: {len(selected_simple_indices)}")
if st.button("Generate Selected Forms"):
if not nominee_template_file and len(selected_nominee_indices) > 0:
st.error("Please upload the nominee template file.")
elif not simple_template_file and len(selected_simple_indices) > 0:
st.error("Please upload the simple work highlight template file.")
elif len(selected_nominee_indices) == 0 and len(selected_simple_indices) == 0:
st.error("Please select at least one matter to proceed.")
else:
# Show progress
progress_bar = st.progress(0)
status_text = st.empty()
status_text.text("Saving templates...")
# Save templates to temporary files
if nominee_template_file:
with open("nominee_template.docx", "wb") as f:
f.write(nominee_template_file.getbuffer())
if simple_template_file:
with open("simple_template.docx", "wb") as f:
f.write(simple_template_file.getbuffer())
status_text.text("Processing selected matters...")
# Process forms
nominee_template = "nominee_template.docx" if nominee_template_file else None
simple_template = "simple_template.docx" if simple_template_file else None
output_path = process_benchmark_forms(
excel_file,
nominee_template,
simple_template,
selected_nominee_indices,
selected_simple_indices
)
if output_path and os.path.exists(output_path):
progress_bar.progress(100)
status_text.text("Forms generated successfully!")
total_forms = len(selected_nominee_indices) + len(selected_simple_indices)
st.success(f"Generated forms for {total_forms} selected matters!")
# Provide download link
with open(output_path, "rb") as f:
st.download_button(
label="Download Combined Forms",
data=f,
file_name="Benchmark_Awards_2025_Submissions.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
progress_bar.progress(100)
st.error("Failed to generate forms.")
else:
st.error("The Excel file does not contain a 'Client Name ' column. Please check your file.")
if __name__ == "__main__":
app() # Ensure this calls the 'app' function
Changes Made
Renamed main() to app(): The entry point for the Streamlit app is now clearly defined as app(), allowing for consistent reference if you're using a module or more extensive application.
Functionality
This application will allow users to do the following:
Upload an Excel file with necessary data.
Upload nominee and simple templates.
Select clients for nomination and simple work highlights, with clear display including both client names and truncated descriptions.
Generate the corresponding forms based on user selections.
Download the final generated forms as a combined document.
Instructions to Run
Save the code into a Python file (e.g., benchmark_awards.py).
Run the application using:
bash
streamlit run benchmark_awards.py
Interact with the application through the web interface that opens in your browser.
Let me know if you have any further adjustments or additional features that you would like to implement!
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Set page configuration
st.set_page_config(layout="wide", page_title="Chambers and Partners Form Generator")
# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Check if the document contains a proper table
if len(doc.tables) < 1:
st.error("Template document does not contain the expected table.")
return None
table = doc.tables[0]
# Map Excel fields to table cells based on the form structure
field_mapping = {
"Client Name ": data.get("Client Name ", ""),
"Description (in 500 words)": data.get("Description (in 500 words)", ""),
"Value ": data.get("Value ", ""),
"Lead partners": data.get("Lead partners", ""),
"Team Members": data.get("Team Members", ""),
"Other Firms/counsels Involved": data.get("Other Firms/counsels Involved", ""),
"Current Status (ongoing / completed )": data.get("Current Status (ongoing / completed )", "")
}
# Update the title based on matter count
for paragraph in doc.paragraphs:
if "MATTER" in paragraph.text:
paragraph.text = f"Matter {matter_count}"
for run in paragraph.runs:
run.font.bold = True
# Populate the table with data
for row in table.rows:
if len(row.cells) >= 2: # Ensure the row has at least two cells
cell_text = row.cells[0].text.strip()
if cell_text in field_mapping:
row.cells[1].text = str(field_mapping[cell_text])
# Save the individual document
doc.save(output_path)
return output_path
def populate_chambers(selected_data, output_path):
"""Generate the documents based on the selected data."""
try:
individual_docs = []
for index, row in selected_data.iterrows():
temporary_output_path = f"temp_document_{index}.docx"
individual_doc_path = create_individual_document(
TEMPLATE_PATH_NO,
row,
index + 1,
temporary_output_path
)
if individual_doc_path:
individual_docs.append(individual_doc_path)
# Combine documents if any exist
if individual_docs:
append_docs(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
return True
except Exception as e:
st.error(f"Unexpected error while processing documents: {e}")
return False
def append_docs(doc_list, output_doc):
"""Combine multiple Word documents into one."""
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
# Streamlit application
def app():
st.title("Chambers and Partners Form Generator")
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if excel_file is not None:
df = pd.read_excel(excel_file)
if "Client Name " in df.columns:
# Create container for client selection
selected_rows = []
st.subheader("Select Clients")
for index, row in df.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show first 50 characters
matter_info = f"{client_name} - {description}..."
# Create checkbox for selection
if st.checkbox(matter_info, key=f"client_{index}"):
selected_rows.append(row)
if st.button("Generate Selected Forms"):
if not selected_rows:
st.error("Please select at least one client to proceed.")
else:
output_path = "combined_chambers_forms.docx" # path for the combined document
success = populate_chambers(pd.DataFrame(selected_rows), output_path)
if success:
st.success("Forms generated successfully!")
with open(output_path, "rb") as f:
st.download_button(
label="Download Combined Forms",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to generate forms.")
else:
st.error("The Excel file does not contain a 'Client Name ' column. Please check your file.")
if __name__ == "__main__":
app() # Ensure this calls the 'app' function
Highlights of Changes
Client Name and Description Display: Each checkbox shows the "Client Name" along with a truncated version of the "Description (in 500 words)" (the first 50 characters), followed by ellipses (...).
Flexible Selection: Users can select multiple clients to process, making it easier to filter and generate documents based on specific entries from the uploaded Excel file.
Combined Document Generation: On clicking "Generate Selected Forms," the selected client data is processed and a combined document is generated for download.
Instructions to Run
Save this Updated Code: Save the code into a Python file, for example, chambers_form_generator.py.
Run the Streamlit Application:
bash
streamlit run chambers_form_generator.py
Use the Application:
Upload your Excel file.
Check the clients you want to include.
Click on "Generate Selected Forms" to create and download the combined document.
This updated application should meet your needs for assisting in generating Chambers submissions while presenting the client information clearly in the frontend. If you have further requests or refinements, feel free to ask!
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Set page configuration at the very beginning
st.set_page_config(layout="wide", page_title="Chambers and Partners Form Generator")
# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Check if the document contains a proper table
if len(doc.tables) < 1:
st.error("Template document does not contain the expected table.")
return None
table = doc.tables[0]
# Map Excel fields to table cells based on the form structure
field_mapping = {
"Client Name ": data.get("Client Name ", ""),
"Description (in 500 words)": data.get("Description (in 500 words)", ""),
"Value ": data.get("Value ", ""),
"Lead partners": data.get("Lead partners", ""),
"Team Members": data.get("Team Members", ""),
"Other Firms/counsels Involved": data.get("Other Firms/counsels Involved", ""),
"Current Status (ongoing / completed )": data.get("Current Status (ongoing / completed )", "")
}
# Update the title based on matter count
for paragraph in doc.paragraphs:
if "MATTER" in paragraph.text:
paragraph.text = f"Matter {matter_count}"
for run in paragraph.runs:
run.font.bold = True
# Populate the table with data
for row in table.rows:
if len(row.cells) >= 2: # Ensure the row has at least two cells
cell_text = row.cells[0].text.strip()
if cell_text in field_mapping:
row.cells[1].text = str(field_mapping[cell_text])
# Save the individual document
doc.save(output_path)
return output_path
def populate_chambers(selected_data, output_path):
"""Generate the documents based on the selected data."""
try:
individual_docs = []
for index, row in selected_data.iterrows():
temporary_output_path = f"temp_document_{index}.docx"
individual_doc_path = create_individual_document(
TEMPLATE_PATH_NO,
row,
index + 1,
temporary_output_path
)
if individual_doc_path:
individual_docs.append(individual_doc_path)
# Combine documents if any exist
if individual_docs:
append_docs(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
return True
except Exception as e:
st.error(f"Unexpected error while processing documents: {e}")
return False
def append_docs(doc_list, output_doc):
"""Combine multiple Word documents into one."""
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
# Streamlit application
def app():
st.title("Chambers and Partners Form Generator")
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if excel_file is not None:
df = pd.read_excel(excel_file)
if "Client Name " in df.columns:
# Create container for client selection
selected_rows = []
st.subheader("Select Clients")
for index, row in df.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show first 50 characters
matter_info = f"{client_name} - {description}..."
# Create checkbox for selection
if st.checkbox(matter_info, key=f"client_{index}"):
selected_rows.append(row)
if st.button("Generate Selected Forms"):
if not selected_rows:
st.error("Please select at least one client to proceed.")
else:
output_path = "combined_chambers_forms.docx" # path for the combined document
success = populate_chambers(pd.DataFrame(selected_rows), output_path)
if success:
st.success("Forms generated successfully!")
with open(output_path, "rb") as f:
st.download_button(
label="Download Combined Forms",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to generate forms.")
else:
st.error("The Excel file does not contain a 'Client Name ' column. Please check your file.")
if __name__ == "__main__":
app() # Ensure this calls the 'app' function
Summary of Key Points
Placement of st.set_page_config(): This is now correctly positioned as the very first Streamlit command. This prevents any conflict or errors related to the configuration.
Functionality: The application allows users to upload an Excel file, view client names with short descriptions, select specific clients for processing, and generate a combined document for download.
Steps to Run the Application
Save the Code: Save the updated code into a Python file (e.g., chambers_form_generator.py).
Run the Application:
To initiate the Streamlit app, open your terminal or command prompt and execute:
bash
streamlit run chambers_form_generator.py
Interface Use: Once it is running, use the web interface to upload your Excel data file, select clients, and download the generated documents.
Let me know if you need further adjustments or features!
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Set page configuration at the very beginning
st.set_page_config(layout="wide", page_title="Chambers and Partners Form Generator")
# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Check if the document contains a proper table
if len(doc.tables) < 1:
st.error("Template document does not contain the expected table.")
return None
table = doc.tables[0]
# Map Excel fields to table cells based on the form structure
field_mapping = {
"Client Name ": data.get("Client Name ", ""),
"Description (in 500 words)": data.get("Description (in 500 words)", ""),
"Value ": data.get("Value ", ""),
"Lead partners": data.get("Lead partners", ""),
"Team Members": data.get("Team Members", ""),
"Other Firms/counsels Involved": data.get("Other Firms/counsels Involved", ""),
"Current Status (ongoing / completed )": data.get("Current Status (ongoing / completed )", "")
}
# Update the title based on matter count
for paragraph in doc.paragraphs:
if "MATTER" in paragraph.text:
paragraph.text = f"Matter {matter_count}"
for run in paragraph.runs:
run.font.bold = True
# Populate the table with data
for row in table.rows:
if len(row.cells) >= 2: # Ensure the row has at least two cells
cell_text = row.cells[0].text.strip()
if cell_text in field_mapping:
row.cells[1].text = str(field_mapping[cell_text])
# Save the individual document
doc.save(output_path)
return output_path
def populate_chambers(selected_data, output_path):
"""Generate the documents based on the selected data."""
try:
individual_docs = []
for index, row in selected_data.iterrows():
temporary_output_path = f"temp_document_{index}.docx"
individual_doc_path = create_individual_document(
TEMPLATE_PATH_NO,
row,
index + 1,
temporary_output_path
)
if individual_doc_path:
individual_docs.append(individual_doc_path)
# Combine documents if any exist
if individual_docs:
append_docs(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
return True
except Exception as e:
st.error(f"Unexpected error while processing documents: {e}")
return False
def append_docs(doc_list, output_doc):
"""Combine multiple Word documents into one."""
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
# Streamlit application
def app():
st.title("Chambers and Partners Form Generator")
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if excel_file is not None:
df = pd.read_excel(excel_file)
if "Client Name " in df.columns:
# Create container for client selection
selected_rows = []
st.subheader("Select Clients")
for index, row in df.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show first 50 characters
matter_info = f"{client_name} - {description}..."
# Create checkbox for selection
if st.checkbox(matter_info, key=f"client_{index}"):
selected_rows.append(row)
if st.button("Generate Selected Forms"):
if not selected_rows:
st.error("Please select at least one client to proceed.")
else:
output_path = "combined_chambers_forms.docx" # Path for the combined document
success = populate_chambers(pd.DataFrame(selected_rows), output_path)
if success:
st.success("Forms generated successfully!")
with open(output_path, "rb") as f:
st.download_button(
label="Download Combined Forms",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to generate forms.")
else:
st.error("The Excel file does not contain a 'Client Name ' column. Please check your file.")
if __name__ == "__main__":
app() # Ensure this calls the 'app' function
Key Points in This Complete Implementation
Cell Mapping Logic: The mapping logic remains intact, ensuring that fields from the DataFrame are correctly matched to the appropriate cells in the Word template.
User-Friendly Selection: The frontend allows users to select clients based on their names and a truncated description, aiding in identifying the correct rows.
Form Generation and Download: Selected forms are generated and can be downloaded once successfully created.
Running the Application
Save this Code: Save the modified code as chambers_form_generator.py.
Run the Streamlit Application:
bash
streamlit run chambers_form_generator.py
Follow the Interface Prompts: Upload the Excel file and select desired clients.
This updated code should now correctly fill in the forms based on your original intent while providing a smoother user experience. If you need further modifications or enhancements, feel free to reach out!
def populate_chambers(selected_data, output_path):
"""Generate the documents based on the selected input from the DataFrame."""
try:
individual_docs = []
code
# Handle selected rows
for index, row in selected_data.iterrows():
temporary_output_path = f"temp_selected_{index}.docx"
individual_docs.append(create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path))
# Combine documents into a single file
append_docs(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
except Exception as e:
st.error(f"Unexpected error: {e}")
Streamlit application
def app():
st.title("Fill Chambers and Partners Form")
code
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if excel_file:
df = pd.read_excel(excel_file)
# Create a selection interface
selected_rows = []
for index, row in df.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show only the first 50 characters
is_selected = st.checkbox(f"Select Client: {client_name} - {description}...", value=True)
# Store current row data if selected
if is_selected:
selected_rows.append(row)
if st.button("Fill the Template"):
if selected_rows:
output_path = "combined_confidential_publishable.docx" # Output file path
selected_df = pd.DataFrame(selected_rows) # Create a DataFrame from the selected rows
populate_chambers(selected_df, output_path)
# Check if the output file was created successfully
if os.path.exists(output_path):
st.success("Forms filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.warning("Please select at least one row to fill in the template.")
if name == "main":
app() # Ensure this calls the 'app' function in this u rmeoved the condition of which form have to be filled
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
# Function to append Word documents
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Identifying text based on template type
identifier_text = f"{'Confidential' if 'Confidential' in template_path else 'Publishable'} Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
current_status = data['Current Status (ongoing / completed )']
doc.tables[0].cell(9, 0).text = f" {current_status or 'N/A'}"
# Save the individual document
doc.save(output_path)
return output_path # Return path for later combining
def populate_chambers(selected_data, output_path):
"""Generate the documents based on the selected input from the DataFrame."""
try:
individual_docs = []
# Iterate over selected rows
for index, row in selected_data.iterrows():
# Determine the template to use based on some condition in the data
template_path = TEMPLATE_PATH_NO # Default template
if row['Confidential / Publishable '].strip().lower() == 'yes':
template_path = TEMPLATE_PATH_YES
temporary_output_path = f"temp_selected_{index}.docx"
individual_doc_path = create_individual_document(
template_path,
row,
index + 1,
temporary_output_path
)
if individual_doc_path:
individual_docs.append(individual_doc_path)
# Combine documents into a single file
if individual_docs:
append_docs(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
return True
except Exception as e:
st.error(f"Unexpected error: {e}")
return False
# Streamlit application
def app():
st.title("Fill Chambers and Partners Form")
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if excel_file:
df = pd.read_excel(excel_file)
# Create a selection interface
selected_rows = []
for index, row in df.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show only the first 50 characters
is_selected = st.checkbox(f"Select Client: {client_name} - {description}...", value=True)
# Store current row data if selected
if is_selected:
selected_rows.append(row)
if st.button("Fill the Template"):
if selected_rows:
output_path = "combined_confidential_publishable.docx" # Output file path
selected_df = pd.DataFrame(selected_rows) # Create a DataFrame from the selected rows
success = populate_chambers(selected_df, output_path)
# Check if the output file was created successfully
if success and os.path.exists(output_path):
st.success("Forms filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.warning("Please select at least one row to fill in the template.")
if __name__ == "__main__":
app() # Ensure this calls the 'app' function
Key Features of the Updated Code
Template Selection Logic:
Inside the populate_chambers function, the code checks the "Confidential / Publishable" status to determine which template to use. If it’s marked as "yes," it uses the TEMPLATE_PATH_YES, otherwise, it defaults to TEMPLATE_PATH_NO.
Clearing Indicated Conditions: All calls to document filling retain the original conditional logic while introducing selections based on the actual data in the uploaded Excel file.
Selection of Rows: Still maintains the frontend with client names shown alongside a short description, enabling easier selection for filling forms.
Running the Application
Save the updated code into a file, e.g., chambers_form_generator.py.
Run the code in your terminal:
bash
streamlit run chambers_form_generator.py
Follow the interface prompts to upload your data, select clients, and generate the desired forms.
This implementation ensures you keep the correct functionality while accommodating your requirements for conditional selection of templates. If you need any further adjustments, just let me know!
def populate_chambers(selected_data, output_path):
"""Generate the documents based on the selected input from the DataFrame."""
try:
individual_docs = []
code
# Iterate over selected rows
for index, row in selected_data.iterrows():
# Determine the template to use based on some condition in the data
template_path = TEMPLATE_PATH_NO # Default template
if row['Confidential / Publishable '].strip().lower() == 'yes':
template_path = TEMPLATE_PATH_YES
temporary_output_path = f"temp_selected_{index}.docx"
individual_doc_path = create_individual_document(
template_path,
row,
index + 1,
temporary_output_path
)
if individual_doc_path:
individual_docs.append(individual_doc_path)
# Combine documents into a single file
if individual_docs:
append_docs(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
return True
except Exception as e:
st.error(f"Unexpected error: {e}")
return False
Streamlit application
def app():
st.title("Fill Chambers and Partners Form")
code
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if excel_file:
df = pd.read_excel(excel_file)
# Create a selection interface
selected_rows = []
for index, row in df.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show only the first 50 characters
is_selected = st.checkbox(f"Select Client: {client_name} - {description}...", value=True)
# Store current row data if selected
if is_selected:
selected_rows.append(row)
if st.button("Fill the Template"):
if selected_rows:
output_path = "combined_confidential_publishable.docx" # Output file path
selected_df = pd.DataFrame(selected_rows) # Create a DataFrame from the selected rows
success = populate_chambers(selected_df, output_path)
# Check if the output file was created successfully
if success and os.path.exists(output_path):
st.success("Forms filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.warning("Please select at least one row to fill in the template.")
if name == "main":
app() # Ensure this calls the 'app' function in this i wanted show two scrobllbars one which have conifential rows for which w need to fill the yes form and aonther for publihsbale rows ...for selection of cases in scroblbaar
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Paths to the Word templates
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
# Function to append Word documents
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Identifying text based on template type
identifier_text = f"{'Confidential' if 'Confidential' in template_path else 'Publishable'} Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
current_status = data['Current Status (ongoing / completed )']
doc.tables[0].cell(9, 0).text = f" {current_status or 'N/A'}"
# Save the individual document
doc.save(output_path)
return output_path # Return path for later combining
def populate_chambers(selected_data, output_path):
"""Generate the documents based on the selected input from the DataFrame."""
try:
individual_docs = []
for index, row in selected_data.iterrows():
template_path = TEMPLATE_PATH_NO if row['Confidential / Publishable '].strip().lower() == 'no' else TEMPLATE_PATH_YES
temporary_output_path = f"temp_selected_{index}.docx"
individual_doc_path = create_individual_document(template_path, row, index + 1, temporary_output_path)
if individual_doc_path:
individual_docs.append(individual_doc_path)
if individual_docs:
append_docs(individual_docs, output_path)
for doc_path in individual_docs:
os.remove(doc_path)
return True
except Exception as e:
st.error(f"Unexpected error: {e}")
return False
# Streamlit application
def app():
st.title("Fill Chambers and Partners Form")
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if excel_file:
df = pd.read_excel(excel_file)
# Create containers for selection of both types
col1, col2 = st.columns([1, 1])
with col1:
st.subheader("Select Confidential Cases")
selected_confidential_rows = []
confidential_cases = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
for index, row in confidential_cases.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show only the first 50 characters
is_selected = st.checkbox(f"{client_name} - {description}...", key=f"confidential_{index}")
if is_selected:
selected_confidential_rows.append(row)
with col2:
st.subheader("Select Publishable Cases")
selected_publishable_rows = []
publishable_cases = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
for index, row in publishable_cases.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show only the first 50 characters
is_selected = st.checkbox(f"{client_name} - {description}...", key=f"publishable_{index}")
if is_selected:
selected_publishable_rows.append(row)
if st.button("Fill the Template"):
if selected_confidential_rows or selected_publishable_rows:
output_path = "combined_confidential_publishable.docx" # Output file path
selected_df = pd.DataFrame(selected_confidential_rows + selected_publishable_rows) # Create a DataFrame from the selected rows
success = populate_chambers(selected_df, output_path)
if success and os.path.exists(output_path):
st.success("Forms filled successfully!")
with open(output_path, "rb") as f:
st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.warning("Please select at least one row to fill in the template.")
if __name__ == "__main__":
app() # Ensure this calls the 'app' function
Key Features of the Updated Code
Dual Scrollable Areas: The application now features two columns for selecting cases: one for Confidential cases and another for Publishable cases. Each checkbox displays both the client name and a 50-character truncated description.
Conditionally Select Templates: The code selects the appropriate template based on whether the selected case is classified as Confidential or Publishable when calling the populate_chambers function.
User-Friendly Interface: The use of columns makes the interface clearer and easier to navigate, enabling users to select cases efficiently.
Running the Application
Save this updated code into a file, e.g., chambers_form_generator.py.
Run the Streamlit application using:
bash
streamlit run chambers_form_generator.py
Follow the interface prompts to upload your Excel file, select cases for both confidential and publish forms, and generate the reports.
This implementation maintains the necessary form-filling conditions and allows for better organization of the user interface. If you need further adjustments or enhancements, please let me know!
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Set page configuration at the very beginning
st.set_page_config(layout="wide", page_title="Chambers and Partners Form Generator")
# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
# Function to append Word documents
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Identifying text based on template type
identifier_text = f"{'Confidential' if 'Confidential' in template_path else 'Publishable'} Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
current_status = data['Current Status (ongoing / completed )']
doc.tables[0].cell(9, 0).text = f" {current_status or 'N/A'}"
# Save the individual document
doc.save(output_path)
return output_path # Return path for later combining
def populate_chambers(selected_data, output_path):
"""Generate the documents based on the selected input from the DataFrame."""
try:
individual_docs = []
for index, row in selected_data.iterrows():
# Determine the template to use based on whether it is confidential or not
template_path = TEMPLATE_PATH_NO if row['Confidential / Publishable '].strip().lower() == 'no' else TEMPLATE_PATH_YES
temporary_output_path = f"temp_selected_{index}.docx"
individual_doc_path = create_individual_document(
template_path,
row,
index + 1,
temporary_output_path
)
if individual_doc_path:
individual_docs.append(individual_doc_path)
# Combine documents into a single file
if individual_docs:
append_docs(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
return True
except Exception as e:
st.error(f"Unexpected error: {e}")
return False
# Streamlit application
def app():
st.title("Fill Chambers and Partners Form")
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if excel_file:
df = pd.read_excel(excel_file)
# Create scrollable containers for selection of both types
st.subheader("Select Confidential Cases")
selected_confidential_rows = []
with st.container():
confidential_cases = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
for index, row in confidential_cases.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show first 50 characters
is_selected = st.checkbox(f"{client_name} - {description}...", key=f"confidential_{index}")
# Store current row data if selected
if is_selected:
selected_confidential_rows.append(row)
# Add a scrollbar to the container
st.markdown(
"""
<style>
div.stContainer {
max-height: 300px;
overflow-y: auto;
}
</style>
""", unsafe_allow_html=True
)
st.subheader("Select Publishable Cases")
selected_publishable_rows = []
with st.container():
publishable_cases = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
for index, row in publishable_cases.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show first 50 characters
is_selected = st.checkbox(f"{client_name} - {description}...", key=f"publishable_{index}")
# Store current row data if selected
if is_selected:
selected_publishable_rows.append(row)
# Add a scrollbar to the container
st.markdown(
"""
<style>
div.stContainer {
max-height: 300px;
overflow-y: auto;
}
</style>
""", unsafe_allow_html=True
)
if st.button("Fill the Template"):
selected_rows = selected_confidential_rows + selected_publishable_rows
if selected_rows:
output_path = "combined_confidential_publishable.docx" # Output file path
selected_df = pd.DataFrame(selected_rows) # Create a DataFrame from the selected rows
success = populate_chambers(selected_df, output_path)
if success and os.path.exists(output_path):
st.success("Forms filled successfully!")
with open(output_path, "rb") as f:
st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.warning("Please select at least one row to fill in the template.")
if __name__ == "__main__":
app() # Ensure this calls the 'app' function
Key Adjustments Made
Scrollable Containers:
The application uses scrollable containers to provide an area for selecting confidential and publishable cases. The max-height style restricts the height of the container, allowing the addition of vertical scroll bars when the content exceeds this height.
Client Name and Description:
Each selection shows both the client name and a truncated description. This ensures clarity for the user when making selections.
Logical Grouping of Cases:
Separate sections for confidential and publishable cases help in organizing the selections clearly.
Running the Application
Save this Code into a Python file named, for example, chambers_form_generator.py.
Run the Streamlit Application:
bash
streamlit run chambers_form_generator.py
This implementation now provides a better interface for user selection, with scrolling functionality for long lists of cases. If you have any further adjustments or features you want to include, just let me know!
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Set page configuration at the very beginning
st.set_page_config(layout="wide", page_title="Chambers and Partners Form Generator")
# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
# Function to append Word documents
def append_docs(doc_list, output_doc):
combined_doc = Document()
for doc in doc_list:
sub_doc = Document(doc)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Identifying text based on template type
identifier_text = f"{'Confidential' if 'Confidential' in template_path else 'Publishable'} Matter {matter_count}"
# Update the table cell with matter count
existing_text = doc.tables[0].cell(1, 0).text
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count)
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"
cell = doc.tables[0].cell(1, 0)
# Formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the document with data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
current_status = data['Current Status (ongoing / completed )']
doc.tables[0].cell(9, 0).text = f" {current_status or 'N/A'}"
# Save the individual document
doc.save(output_path)
return output_path # Return path for later combining
def populate_chambers(selected_data, output_path):
"""Generate the documents based on the selected input from the DataFrame."""
try:
individual_docs = []
# Iterate over selected rows
for index, row in selected_data.iterrows():
# Determine the template to use based on whether it's confidential
template_path = TEMPLATE_PATH_NO if row['Confidential / Publishable '].strip().lower() == 'no' else TEMPLATE_PATH_YES
temporary_output_path = f"temp_selected_{index}.docx"
individual_doc_path = create_individual_document(
template_path,
row,
index + 1,
temporary_output_path
)
if individual_doc_path:
individual_docs.append(individual_doc_path)
# Combine documents into a single file
if individual_docs:
append_docs(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
return True
except Exception as e:
st.error(f"Unexpected error: {e}")
return False
# Streamlit application
def app():
st.title("Fill Chambers and Partners Form")
# Upload Excel file
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if excel_file:
df = pd.read_excel(excel_file)
# Create a scrollable section for confidential cases
st.subheader("Select Confidential Cases")
selected_confidential_rows = st.container()
with selected_confidential_rows:
st.markdown(
"""
<style>
.scrollable-section {
height: 300px; /* Set the height of the container */
overflow-y: auto; /* Enable vertical scrolling */
}
</style>
""", unsafe_allow_html=True
)
st.write("<div class='scrollable-section'>", unsafe_allow_html=True)
# Filter for confidential cases
confidential_cases = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
for index, row in confidential_cases.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show first 50 characters
is_selected = st.checkbox(f"{client_name} - {description}...", key=f"confidential_{index}")
# Store current row data if selected
if is_selected:
selected_confidential_rows.append(row)
st.write("</div>", unsafe_allow_html=True)
# Create a scrollable section for publishable cases
st.subheader("Select Publishable Cases")
selected_publishable_rows = st.container()
with selected_publishable_rows:
st.markdown(
"""
<style>
.scrollable-section {
height: 300px; /* Set the height of the container */
overflow-y: auto; /* Enable vertical scrolling */
}
</style>
""", unsafe_allow_html=True
)
st.write("<div class='scrollable-section'>", unsafe_allow_html=True)
# Filter for publishable cases
publishable_cases = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
for index, row in publishable_cases.iterrows():
client_name = row['Client Name ']
description = row['Description (in 500 words)'][:50] # Show first 50 characters
is_selected = st.checkbox(f"{client_name} - {description}...", key=f"publishable_{index}")
# Store current row data if selected
if is_selected:
selected_publishable_rows.append(row)
st.write("</div>", unsafe_allow_html=True)
if st.button("Fill the Template"):
selected_rows = selected_confidential_rows + selected_publishable_rows
if selected_rows:
output_path = "combined_confidential_publishable.docx" # Output file path
selected_df = pd.DataFrame(selected_rows) # Create a DataFrame from the selected rows
success = populate_chambers(selected_df, output_path)
# Check if the output file was created successfully
if success and os.path.exists(output_path):
st.success("Forms filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
st.download_button(
label="Download Filled Form",
data=f,
file_name="Chambers.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the DOCX file.")
else:
st.warning("Please select at least one row to fill in the template.")
if __name__ == "__main__":
app() # Ensure this calls the 'app' function
Key Adjustments Made
Scrollable Sections:
Each case (Confidential and Publishable) is placed within a scrollable section using HTML and CSS styles. The max-height attribute allows it to scroll when there are too many entries.
Dynamic Height for Scrollable Section:
The height of the scrollable sections is set to 300 pixels. You can adjust this height based on your UI preferences or content volume.
Client Name and Description Mapping:
For the checkboxes, each client now shows both the client name and a truncated description for quick reference.
Running the Application
Save this updated code to a Python file (e.g., chambers_form_generator.py).
Run the application using:
bash
streamlit run chambers_form_generator.py
Upload your Excel file and select cases from the scrollable sections before generating the final documents.
This implementation should meet your requirements for scrollable containers effectively. If you have any further modifications or specific requests, just let me know!