Skip to content

Commit

Permalink
new version supporting for chinese
Browse files Browse the repository at this point in the history
  • Loading branch information
li-xin-yi committed May 3, 2020
1 parent 1855bc5 commit b06b586
Show file tree
Hide file tree
Showing 12 changed files with 109 additions and 15 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -115,3 +115,4 @@ dmypy.json

.idea/
*.DS_Store
*/temp
26 changes: 26 additions & 0 deletions README.md
Expand Up @@ -23,6 +23,7 @@ It is a light and useful Python module, helping you generate a small size, prett
* [Run a `Journalist()` in your code to fetch variables](#run-a--journalist----in-your-code-to-fetch-variables)
* [Invite a journalist to make a big news report](#invite-a-journalist-to-make-a-big-news-report)
- [I am too lazy to write a `md` template](#i-am-too-lazy-to-write-an--md--template)
- [Support For zh_CN](#support-for-zh_cn)
- [What will my variables on slides look like?](#what-will-my-variables-on-slides-look-like-)
- [More examples and instructions](#more-examples-and-instructions)
- [Tips](#tips)
Expand Down Expand Up @@ -146,6 +147,31 @@ Output ([raw file](./demo/auto_report.pdf) ):

![](./demo/auto_report.png)

## Support For zh_CN

Yes, now, from version 0.0.5, it can use template contains chinese characters :tada:.

Just pass argument `zh=True` when creating a Journalist(), or set its `zh` property at any time before generating reports.

```py
reporter = Journalist(template_file='./reports/template.md', zh=True)
```

If you want to use your customized template with chinese characters, don't forget to add one line at first of the YAML metadata block in your `Markdown` template:

```markdown
---
documentclass: ctexbeamer
...
---
```

Here is a [simple example](./examples/3_zh_CN_support.py) similar to [Quick start](#quick-start), Except for [its template](./examples/reports/3_zh_cn_template.md) containing chinese characters. A perfect chinese [slides](./examples/reports/3_zh_report.pdf) file can be generated by the program as:

![](./demo/zh_demo.png)

**Note**: make sure `xelatex` is installed properly.

## What will my variables on slides look like?

All variables pass to `Journalist` via `hear` will display as strings just like what their `__str__` method does.
Expand Down
Binary file added demo/zh_big_news.pdf
Binary file not shown.
Binary file added demo/zh_demo.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
34 changes: 34 additions & 0 deletions examples/3_zh_CN_support.py
@@ -0,0 +1,34 @@
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from hkjournalist import Journalist

config = {}


def sin_2x_and_cos_2x(x):
y = np.sin(x) * np.sin(x) + np.cos(x) * np.cos(x)
return y


x = np.arange(0, 4 * np.pi, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

df = pd.DataFrame({'x': x, 'sin(x)': y1, 'cos(x)': y2})
df['sin^2^(x)+cos^2^(x)'] = sin_2x_and_cos_2x(df['x']).values
df = df.set_index('x')

# plot sine curve as sin_plot
ax = df.plot()
plt.tight_layout()
config['sin_plot'] = ax

# random select 5 point (x,y) as sin_table
config['sin_table'] = df.sample(5)

config['sin_func'] = sin_2x_and_cos_2x

reporter = Journalist(template_file='./reports/3_zh_cn_template.md', zh=True)
reporter.hear(config)
reporter.report(output_file='./reports/3_zh_report.pdf', beamer=True, overwrite=True)
Binary file removed examples/reports/.DS_Store
Binary file not shown.
Binary file modified examples/reports/2_feature_select.pdf
Binary file not shown.
9 changes: 5 additions & 4 deletions examples/reports/2_feature_select_template.md
@@ -1,7 +1,8 @@
% Report template
% Author
% {today}

---
title: template
author: Author
date: \today{{}}
---
### Cover_type

{Cover_type}
Expand Down
22 changes: 22 additions & 0 deletions examples/reports/3_zh_cn_template.md
@@ -0,0 +1,22 @@
---
documentclass: ctexbeamer
title: 中文报告
author: 香港记者
date: \today{{}}
---

### 正弦曲线

![]({sin_plot})

### 正弦取值

{sin_table}

### 正弦函数

```{{.python}}
{sin_func}
```


Binary file added examples/reports/3_zh_report.pdf
Binary file not shown.
30 changes: 20 additions & 10 deletions hkjournalist/journalist.py
Expand Up @@ -19,7 +19,7 @@ class Journalist():
Class to record and generate reports
"""

def __init__(self, template_file=None, fig_width=None, fig_height=None, tmp_path='./temp'):
def __init__(self, template_file=None, fig_width=None, fig_height=None, tmp_path='./temp', zh=False):
"""
:param template_file: file path of md template
:type template_file: str
Expand All @@ -29,14 +29,17 @@ def __init__(self, template_file=None, fig_width=None, fig_height=None, tmp_path
:type fig_height: None, int
:param tmp_path: temporary directory path to store temporary files (such as figures)
:type tmp_path: str
:param zh: if it supports chinese (zh_CN) usage
:type zh: bool
"""
self.template_file = template_file
self.report_config = {'today': datetime.datetime.today().date()}
self._width = fig_width
self._height = fig_height
self.var_type = {}
self.fig_counters = 0
self.tmp_path = tmp_path
self.report_config = {}
self.zh = zh
if not os.path.exists(tmp_path):
os.mkdir(tmp_path)
if fig_width:
Expand Down Expand Up @@ -112,8 +115,7 @@ def hear(self, config_dict: dict):
newest_config = self.__preprocess(config_dict)
self.report_config.update(newest_config)

def generate_template(self, template_file='./template.md',title='template',author='Author',append=False):

def generate_template(self, template_file='./template.md', title='template', author='Author', append=False):
"""Generate a `md` template according to mappings which previously passed to.
The output template will be structed as each variable on a single slide with variable name as its title
Expand All @@ -139,7 +141,13 @@ def generate_template(self, template_file='./template.md',title='template',autho
if append:
report_text = open(self.template_file).read() + '\n'
else:
report_text = f'% {title} \n% {author} \n% {{today}}\n\n'
report_text = '---\n'
if self.zh:
report_text += 'documentclass: ctexbeamer\n'
report_text += f'title: {title}\n'
report_text += f'author: {author}\n'
report_text += 'date: \\today{{}}\n'
report_text += '---\n'

for k, v in self.var_type.items():
k_name = '{' + k + '}'
Expand Down Expand Up @@ -181,25 +189,27 @@ def report(self, output_file='./final_report.pdf', beamer=True, theme='default',
raw_file = os.path.join(self.tmp_path, 'raw_report.md')
report_name, ext = os.path.splitext(output_file)
tex_command = f'--listings -H {tex_config_path}'
args_list = ""
if overwrite:
final_file = output_file
else:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
final_file = f"{report_name}_{timestamp}{ext}"

report_template_text = open(self.template_file, 'r').read()
Path(raw_file).write_text(report_template_text.format(**self.report_config))
report_template_text = open(self.template_file, 'r', encoding='utf8').read()
Path(raw_file).write_text(report_template_text.format(**self.report_config), encoding='utf8')

if beamer and ext == '.pdf':
beamer_command = '-t beamer'
else:
beamer_command = '-t'

if use_template_config:
args_list = ""
else:
if not use_template_config:
args_list = f"-V theme:{theme} -V colortheme:{color_theme} -V aspectratio:{aspectratio}"

if self.zh:
args_list += ' --pdf-engine=xelatex'

command = f'pandoc {beamer_command} {raw_file} {tex_command} {args_list} -s -o {final_file}'
return_code = os.system(command)

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Expand Up @@ -5,7 +5,7 @@

setuptools.setup(
name="hkjournalist",
version="0.0.4",
version="0.0.5",
author="Xinyi",
author_email="wolixinyi@gmail.com",
description="Custom Auto Report Generator for Python Program",
Expand Down

0 comments on commit b06b586

Please sign in to comment.