weeklyDataReport / template.py
HarveyChiu's picture
Upload folder using huggingface_hub
822c3cb verified
from docxtpl import DocxTemplate
import pandas as pd
import gradio as gr
import os
from dotenv import load_dotenv
# Load environment variables at the start of your script
load_dotenv()
def process_excel_and_generate_docs(excel_file, term, start_year, end_year, start_month, start_day, end_month, end_day):
# Read the Excel file
df = pd.read_excel(excel_file.name)
# Initialize the news dictionary
news_dict = {'news': {}}
# Group by area and convert to the desired format
for area, group in df.groupby('area'):
news_dict['news'][area.lower()] = [
{
'title': row['translated_title'],
'date': row['date'],
'content': str(row['translated_content']).replace('\r\n', '\n').replace('\r', '\n').replace('\n', '\r\n'), # 统一转换为 Word 兼容的换行符
'comment': row['comment'],
'country': row['country']
}
for _, row in group.iterrows()
]
# Create the context dictionary with all required fields
context = {
'term': term,
'start_year': start_year,
'end_year': end_year,
"start_month": start_month,
"start_day": start_day,
"end_month": end_month,
"end_day": end_day,
**news_dict
}
# Render PDF template
pdf_output_path = "pdf.docx"
pdf_tpl = DocxTemplate("v1.1 周报模板.docx")
pdf_tpl.render(context)
pdf_tpl.save(pdf_output_path)
# Render Email template
email_output_path = "email.docx"
email_tpl = DocxTemplate("v1.1 周报邮件格式调整.docx")
email_tpl.render(context)
email_tpl.save(email_output_path)
return [pdf_output_path, email_output_path]
def create_gradio_interface():
# Define authentication credentials
with gr.Blocks() as app:
gr.Markdown("# Weekly Report Generator")
with gr.Row():
excel_file = gr.File(label="Upload Excel File")
with gr.Row():
term = gr.Textbox(label="期数", value="201")
start_year = gr.Textbox(label="起始年", value="2024")
end_year = gr.Textbox(label="结束年", value="2024")
with gr.Row():
start_month = gr.Textbox(label="起始月份", value="9")
start_day = gr.Textbox(label="起始日", value="1")
end_month = gr.Textbox(label="结束月份", value="9")
end_day = gr.Textbox(label="结束日", value="15")
generate_btn = gr.Button("Generate Reports")
with gr.Row():
pdf_output = gr.File(label="Download PDF Report")
email_output = gr.File(label="Download Email Template")
generate_btn.click(
fn=process_excel_and_generate_docs,
inputs=[excel_file, term, start_year, end_year, start_month, start_day, end_month, end_day],
outputs=[pdf_output, email_output]
)
return app
if __name__ == "__main__":
app = create_gradio_interface()
app.launch(
share=True,
auth=auth,
max_threads=3, # Limit concurrent processing
show_error=True
)