}) tmps = re.findall(r'/\*(.+?)/\*end-func', file_content) funcs = [] for tmp in tmps: func_s = ',' func_result = re.findall(r'.+?/\*func\*/(.+?)./\*func\*/', tmp) funcs.append(func_s.join(func_result)) document = Document() h1 = document.add_heading("", level=1) r1 = h1.add_run("1软件详细设计") r1.font.name = 'Times New Roman' r1.font.size = Pt(14) r1.bold = False r1._element.rPr.rFonts.set(qn('w:eastAsia'), u'黑体') r1.font.color.rgb = RGBColor(0, 0, 0) cnt = 1 for m in modules: strcnt = cnt h2 = document.add_heading("", level=2) r2 = h2.add_run('1.' + str(strcnt) + m['name']) r2.font.name = 'Times New Roman' r2.font.size = Pt(13) r2.bold = False r2._element.rPr.rFonts.set(qn('w:eastAsia'), u'黑体') r2.font.color.rgb = RGBColor(0, 0, 0) h3 = document.add_heading("", level=3) r3 = h3.add_run('1.' + str(strcnt) + '.1' + "功能概述") r3.font.name = 'Times New Roman'
from docx.shared import RGBColor import json def load_question(question_path): 'TODO: load question from local file.' que = [] with open(question_path, 'r') as question_file: for question in question_file: que.append(question.rstrip('\n')) return que global color color = [ RGBColor(255, 0, 0), RGBColor(34, 139, 34), RGBColor(238, 201, 0), RGBColor(160, 32, 240) ] def add_doc(question_list, color_id): for i, ch in enumerate(question_list): run = p.add_run(ch) run.font.color.rgb = color[color_id[i]] document = Document() document.add_heading('annotation', 0)
def Individual_Results(Asses1, ques, ans, Correct_ans, Latam_ave, Number_asess): question_flag = 0 #Create first page #section = document.sections[0] #document.add_heading('' , 1) # add a Space header #document.add_picture(r"C:\Users\Ipachon1\OneDrive - Rockwell Automation, Inc\LATAM\ASSESMENTS\others\RA-Partner.png", width=Inches(5.8)) #document.add_heading('' , 0) # add a Space header #document.add_heading('' , 0) # add a Space header #document.add_heading('' , 0) # add a Space header #document.add_heading('' , 0) # add a Space header #document.add_heading('' , 0) # add a Space header #document.add_heading('' , 0) # add a Space header #document.add_heading('' , 0) # add a Space header #document.add_heading('' , 0) # add a Space header #document.add_heading('' , 0) # add a Space header #document.add_heading('' , 0) # add a Space header #document.add_heading('Distributor Competency Specialist Assessment Results - 2020 ' , 0) # add a header #First_paragraph = document.add_paragraph(style='Body Text') #First_paragraph.add_run('This report includes the competency test results, we encourage you to study this information and consult the documents, links and articles suggested so you can improve your proficiency.') #document.add_page_break() for j in range( 0, Asses1.shape[0]): #trough all the assessments of the Data base first = 0 #Create the Word Document document = Document() # Create it #footer creation section = document.sections[0] Footer = section.footer paragraph = Footer.paragraphs[0] paragraph.text = "Rockwell Automation \t\tStrictly Confidential information Do not distribute" document.add_heading(" Assessment Results for: " + str(Asses1.iloc[j].Name), 1) # add a header Second_paragraph = document.add_paragraph(style='Body Text') Grade_Comparation = 'Higher' if Latam_ave < Asses1.iloc[ j].Grade else 'Lower' #Grade comparation string to include in the paragraph Second_paragraph.add_run( str(Asses1.iloc[j].Name) + '’s total grade in this assessment was ' + str(Asses1.iloc[j].Grade) + '% which is ' + Grade_Comparation + ' than the general average taken over ' + str(Number_asess) + ' specialists around Latin America. Overall average for Latin America is ' + str(Latam_ave) + '%') # add a information paragraph document.add_heading('General Information', level=1) #add general information header fourth_paragraph = document.add_paragraph( style='Body Text') # add a paragraph fourth_paragraph.add_run( 'This section includes specialist information and the overall results of the 2020 assessment.' ) Space_paragraph = document.add_paragraph( style='Body Text') # add a space as a paragraph Space_paragraph.add_run('') for i in range(0, Asses1.shape[1] - 1): #trough all the columns of the Data base if Asses1.columns[i].startswith( "Points") or Asses1.columns[i].startswith( "Feedback"): #skip feed-back and points columns pass else: if len( Asses1.columns[i] ) > 20: #this is a quick fix in order to correct only real questions question_flag = question_flag + 1 if Asses1.iloc[ j, i + 1] == 1: #see if the answer is correct or not #Answer.add_run("Your Response--"+str(Asses1.iloc[j,i])).font.color.rgb = RGBColor(0, 153, 0) #add answer green- correct answer pass else: ########################## first time the questions start to be printed ##################################### if first == 0: print("fuckkkkkkk" + str(i)) document.add_page_break( ) #add a page break when questions are about to be displayed document.add_heading(" Assessment Results for: " + str(Asses1.iloc[j].Name), 1) # add a header Third_paragraph = document.add_paragraph( style='Body Text' ) # add a information paragraph Third_paragraph.add_run( 'The following report provides a detailed list of results by APR and by specialist. For each question that was not correctly answered we provide below the question, the list of options, the correct answer, and the sources to learn more about this specific subject.' ) # add a information paragraph document.add_heading('', 0) # add a Space header first = first + 1 ########################## first time the questions start to be printed ##################################### ################change this in order to display all answers not only wrong answers##################### Question = document.add_paragraph( style='Body Text') #create Question Paragraph Question.add_run( str(question_flag) + (") ") + str(ques[3 + question_flag - 1])).bold = True #add normal questions All_ans = list(ans[3 + question_flag - 1].keys()) for k in range(0, len(All_ans)): Question = document.add_paragraph( style='List Bullet' ) #create Question Paragraph Question.add_run(str( All_ans[k])) #add normal questions Answer = document.add_paragraph( style='List Bullet') #create Answers Paragraph ################change this in order to display all answers not only wrong answers##################### Answer.add_run( "Your Response--" + str(Asses1.iloc[j, i])).font.color.rgb = RGBColor( 168, 0, 0) #add answer red- Incorrect answer Correct_Answer = document.add_paragraph( style='List Bullet' ) # Create Correct Answer paragraph Correct_Answer.add_run( " ---- Correct Answer-----" + str(Correct_ans[question_flag - 1]) ).italic = True #add correct answer from the database Learning_Data = document.add_paragraph( style='List Bullet' ) # Create Correct Answer paragraph Learning_Data.add_run( " ----Reference Materials -----" + str(Asses1.iloc[j, i + 2]) ).italic = True #add learning data from the database else: ################change this in order to display all answers not only wrong answers##################### Question = document.add_paragraph( style='Body Text') #create Question Paragraph Question.add_run(str( Asses1.columns[i])).bold = True #add normal questions Answer = document.add_paragraph( style='List Bullet') #create Answers Paragraph ################change this in order to display all answers not only wrong answers##################### Answer.add_run( str(Asses1.iloc[j, i]) ) # add questions that are not from the assessment (name, email, etc) #document.add_page_break() print(j) document.save(r".\Results\\" + str(Asses1.iloc[j].Distributor) + "--Email--" + str(Asses1.iloc[j].Email) + "--User Name--" + str(Asses1.iloc[j].Name) + "--ID--" + str(Asses1.iloc[j].ID) + '.docx') #Save Document; Name #first = 0 question_flag = 0 return str("The docx have been created, check the RESULTS folder")
if "certifications" not in order and usedAllCerts == False: certificationList = json["Certification"] if len(certificationList) > 1: multipleCertifications = True if multipleCertifications == True: for cert in range(1, len(certificationList)): newCert = paragraph.insert_paragraph_before( json["Certification"][cert]["CertName"] + ", " + json["Certification"][cert]["CertAssociation"] + " — " + json["Certification"][cert]["CertDate"]) pstyle = document.styles['Normal'] pfont = pstyle.font pfont.name = 'Cambria' pfont.size = Pt(11) pfont.color.rgb = RGBColor(64, 64, 64) create_list(newCert, "1") newCert.style = document.styles['Normal'] usedAllCerts = True #Skills Block if "langskills" in text and "skills" == order[0]: skills("Languages", parse_json_basic(json, "Skill", "Languages")) if "frameskills" in text and "skills" == order[0]: skills("Frameworks", parse_json_basic(json, "Skill", "Frameworks")) if "techskills" in text and "skills" == order[0]: skills("Technologies & Software", parse_json_basic(json, "Skill", "DatabaseTech"))
config = { 'data_paths': { 'store_dir': '' }, "max_categories_plot": 100, "alerte": { 'réfléchir': os.path.join(cwd, 'assets/arevoir.png'), "utilisable": os.path.join(cwd, 'assets/utilisable.png'), "inutilisable": os.path.join(cwd, 'assets/inutilisable.png'), "modelisable": os.path.join(cwd, 'assets/modelisable.png') } } styles = { "warning": { "color": RGBColor(0xFF, 0x00, 0x00) }, "note": { "italic": True } } def is_categoric(series, treshold=50): return len(series.unique()) < treshold def is_numeric(series): return np.issubdtype(series.dtype, np.number)
commonWords.add(line.rstrip()) #workbook = xlrd.open_workbook('fakeSessionNotes_dummyFile.xlsx') #workbook = xlrd.open_workbook('AllData_sample.xlsx') workbook = xlrd.open_workbook('AllData.xlsx') worksheet = workbook.sheet_by_index(0) nrows = worksheet.nrows ncols = worksheet.ncols document = Document() document.add_heading('Redacted Notes', level=1) p = document.add_paragraph() p.add_run( 'This document contains session notes with names redacted by a program. The words identified as names by the program are denoted by ' ) p.add_run('[NAME]').font.color.rgb = RGBColor(255, 0, 0) p.add_run(' tokens.') p = document.add_paragraph() p.add_run( 'The program also suggests words which it thinks could be names. These words are not redacted but indicated in ' ) p.add_run('blue').font.color.rgb = RGBColor(0, 0, 255) p.add_run(' color.') table = document.add_table(rows=40000, cols=1) namesList = [] namesCandidates = [] # Bad code, hardcoding the column in which the data is present # But this will do for now! notes = worksheet.col(0, start_rowx=0) lmtr = WordNetLemmatizer()
def setStyle(document): # 设置A4纸 section = document.sections[0] section.page_width = Cm(21) section.page_height = Cm(29.7) style_song = document.styles.add_style( 'Song', WD_STYLE_TYPE.CHARACTER) # 设置Song字样式 style_song.font.name = '宋体' document.styles['Song']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') # 将段落中的所有字体 # 正文标题 style_title = document.styles.add_style('title', WD_STYLE_TYPE.CHARACTER) # 设置一级字样式 style_title.font.name = '宋体' style_title.font.bold = True style_title.font.size = Pt(15) style_title.font.color.rgb = RGBColor(0x0, 0x0, 0x0) document.styles['title']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') # 将段落中的所有字体 # 一级标题:宋体 加粗 12号字体 style_first = document.styles.add_style('first', WD_STYLE_TYPE.CHARACTER) # 设置一级字样式 style_first.font.name = '宋体' style_first.font.bold = True style_first.font.size = Pt(12) style_first.font.color.rgb = RGBColor(0x0, 0x0, 0x0) document.styles['first']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') # 将段落中的所有字体 # 设置表格字体 tableCharacter = document.styles.add_style('tableSmallCharacter', WD_STYLE_TYPE.CHARACTER) tableCharacter.font.name = 'Arial' tableCharacter.font.size = Pt(9) document.styles['tableSmallCharacter']._element.rPr.rFonts.set( qn('w:eastAsia'), u'宋体') # 设置表格字体 tableCharacter = document.styles.add_style('tableSmallerCharacter', WD_STYLE_TYPE.CHARACTER) tableCharacter.font.name = 'Arial' tableCharacter.font.size = Pt(8) document.styles['tableSmallerCharacter']._element.rPr.rFonts.set( qn('w:eastAsia'), u'宋体') # 设置word表格字体 tableCharacter = document.styles.add_style('tableCharacter', WD_STYLE_TYPE.CHARACTER) tableCharacter.font.name = 'Arial' tableCharacter.font.size = Pt(10.5) document.styles['tableCharacter']._element.rPr.rFonts.set( qn('w:eastAsia'), u'宋体') # 正文: 宋体 style_zero = document.styles.add_style('zero', WD_STYLE_TYPE.CHARACTER) # 设置一级字样式 style_zero.font.name = '宋体' style_zero.font.size = Pt(12) style_zero.font.color.rgb = RGBColor(0x0, 0x0, 0x0) document.styles['zero']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') # 将段落中的所有字体 # 正文: 宋体 style_zero = document.styles.add_style('small', WD_STYLE_TYPE.CHARACTER) # 设置一级字样式 style_zero.font.name = '宋体' style_zero.font.size = Pt(8) style_zero.font.color.rgb = RGBColor(0x0, 0x0, 0x0) document.styles['small']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') # 将段落中的所有字体 # 定义段落样式:首行缩进2个字符、1.5倍行间距 paragraph_style = document.styles.add_style('paragraphAfterSpace', WD_STYLE_TYPE.PARAGRAPH) paragraph_format = paragraph_style.paragraph_format paragraph_format.first_line_indent = Pt(24) paragraph_format.line_spacing = 1.5 paragraph_format.space_after = Pt(2) paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY # 定义段落样式:首行缩进2个字符、1.5倍行间距 paragraph_style = document.styles.add_style('paragraph', WD_STYLE_TYPE.PARAGRAPH) paragraph_format = paragraph_style.paragraph_format paragraph_format.first_line_indent = Pt(24) paragraph_format.line_spacing = 1.5 paragraph_format.space_after = Pt(0) paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY # 定义段落样式:无缩进、1.5倍行间距 paragraph_style = document.styles.add_style('paragraphNoIndent', WD_STYLE_TYPE.PARAGRAPH) paragraph_format = paragraph_style.paragraph_format paragraph_format.line_spacing = 1.5 paragraph_format.space_after = Pt(0) paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
col_idx, 0] else "" for paragraph in cells[col_idx].paragraphs: for run in paragraph.runs: run.font.name = tbl_dt[row_idx, col_idx, 1].name run.font.bold = tbl_dt[row_idx, col_idx, 1].b run.font.size = Pt( int(tbl_dt[row_idx, col_idx, 1].sz)) run.font.italic = tbl_dt[row_idx, col_idx, 1].i def hex_to_rgb(value): value = value.lstrip('#') lv = len(value) return tuple( int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) try: run.font.color.rgb = RGBColor( *hex_to_rgb(tbl_dt[row_idx, col_idx, 1].color.rgb)[1:]) except: pass bar.update() bar.close() # Save the document doc.save('Word Report- Python Automation_re.docx')
def add_content(document, content, para=None, font_size=16): if content.__contains__('k.t.qq.com'): pattern = re.compile(r'(<a href="http://k.t.qq.com.*?</a>)', re.S) topics = re.findall(pattern, content) for topic in topics: topic_word = topic.split('#')[1] content = content.replace( topic, SPLIT_STRING + TOPIC_STRING + '#' + topic_word + '#' + SPLIT_STRING) if content.__contains__('www/mb/images/emoji'): pattern_emoji = re.compile(r'(<img.*?>)', re.S) pattern_emoji_img = re.compile(r"crs='(.*?)'", re.S) emojis = re.findall(pattern_emoji, content) for emoji in emojis: emoji_url = re.findall(pattern_emoji_img, emoji)[0] filename = download_pic(emoji_url, PNG_EXTENSION) content = content.replace( emoji, SPLIT_STRING + EMOJI_STRING + filename + SPLIT_STRING) if content.__contains__('em rel="@'): pattern_friend = re.compile(r'(<em rel=.*?</em>)', re.S) pattern_friend_name = re.compile(r'<em.*?title="(.*?)"', re.S) friends = re.findall(pattern_friend, content) for friend in friends: friend_name = re.findall(pattern_friend_name, friend)[0] content = content.replace( friend, SPLIT_STRING + FRIEND_STRING + friend_name + SPLIT_STRING) if content.__contains__('http://url.cn'): pattern_url = re.compile(r'(<a href=.*?</a>)', re.S) pattern_url_str = re.compile(r'<a href="(.*?)"', re.S) urls = re.findall(pattern_url, content) for url in urls: url_str = re.findall(pattern_url_str, url)[0] content = content.replace( url, SPLIT_STRING + URL_STRING + url_str + SPLIT_STRING) if content.__contains__('www/mb/images/face'): pattern_qqemo = re.compile(r'(<img.*?>)', re.S) pattern_qqemo_img = re.compile(r"crs='(.*?)'", re.S) qqemos = re.findall(pattern_qqemo, content) for qqemo in qqemos: qqemo_url = re.findall(pattern_qqemo_img, qqemo)[0] filename = download_pic(qqemo_url, GIF_EXTENSION) content = content.replace( qqemo, SPLIT_STRING + QQEMO_STRING + filename + SPLIT_STRING) if content.__contains__('<img class='): pattern_other_emo = re.compile(r'(<img.*?>)', re.S) pattern_other_emo_img = re.compile(r'<img.*?crs=(.*?) title=', re.S) pattern_other_emo_img_only = re.compile(r'<img.*?crs=(.*?)>', re.S) #<img class='crs dn' crs='http://qzonestyle.gtimg.cn/qzone/em/e2043.gif'> pattern_other_emos = re.findall(pattern_other_emo, content) for other_emo in pattern_other_emos: other_emo_match = re.findall(pattern_other_emo_img, other_emo) if not other_emo_match: # some emoji have special pattern other_emo_match = re.findall(pattern_other_emo_img_only, other_emo) other_emo_url = other_emo_match[0] other_emo_url = other_emo_url[1: -1] # delete start and end mark ' " filename = download_pic(other_emo_url, other_emo_url[-4:]) content = content.replace( other_emo, SPLIT_STRING + OTHEREMO_STRING + filename + SPLIT_STRING) content_parts = content.split(SPLIT_STRING) if not para: para = document.add_paragraph() for content_part in content_parts: # delete first <div> mark if content_part.startswith('<div>'): content_part = content_part[5:] if content_part.startswith(TOPIC_STRING): run = para.add_run(content_part.replace(TOPIC_STRING, '')) font = run.font font.italic = True font.bold = False font.size = Pt(font_size) font.color.rgb = RGBColor(0x00, 0x00, 0xCD) elif content_part.startswith(EMOJI_STRING): run = para.add_run() filename = content_part.replace(EMOJI_STRING, '') run.add_picture(filename) elif content_part.startswith(FRIEND_STRING): run = para.add_run(content_part.replace(FRIEND_STRING, '')) font = run.font font.italic = True font.bold = False font.size = Pt(font_size - 2) font.color.rgb = RGBColor(0xFF, 0x45, 0x00) elif content_part.startswith(URL_STRING): docx_ext.add_hyperlink(para, content_part.replace(URL_STRING, ''), content_part.replace(URL_STRING, ''), '1E90FF', True) elif content_part.startswith(QQEMO_STRING): run = para.add_run() filename = content_part.replace(QQEMO_STRING, '') run.add_picture(filename) elif content_part.startswith(OTHEREMO_STRING): run = para.add_run() filename = content_part.replace(OTHEREMO_STRING, '') run.add_picture(filename) else: content_part = content_part.replace('&', '&') content_part = content_part.replace('>', '>') content_part = content_part.replace('"', '"') content_part = content_part.replace('<', '<') run = para.add_run(content_part) font = run.font font.bold = False font.size = Pt(font_size) font.color.rgb = RGBColor(0x08, 0x08, 0x08)
# 对文字字体样式进行修改 from docx.shared import Pt, RGBColor from docx.oxml.ns import qn from docx import Document doc = Document('test.docx') for paragraph in doc.paragraphs: for run in paragraph.runs: run.font.bold = True run.font.italic = True run.font.underline = True run.font.strike = True # 删除线 run.font.shadow = True run.font.size = Pt(20) run.font.color.rgb = RGBColor(255, 255, 0) run.font.name = '微软雅黑' r = run._element.rPr.rFonts r.set(qn('w:eastAsia'), '微软雅黑') doc.save('test1.docx') # 段落样式的修改 from docx.enum.text import WD_PARAGRAPH_ALIGNMENT paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 行间距 paragraph.paragraph_format.line_spacing = 2.0 # 段前与段后间距
#set styles with open('index1.tsv','r') as original_index: index_ptr = csv.reader(original_index, delimiter='\t') #sort alphabetically by first word data = (list(index_ptr)) tracker='' for line in data: current = line[0][:1] if current.isalpha() and tracker.upper() != current.upper(): letter_header = document.add_paragraph().add_run(line[0][:1]) letter_font=letter_header.font letter_font.color.rgb = RGBColor(255, 165, 0) letter_font.name='Calibri(Headings)' letter_font.bold=True letter_font.size=Pt(20) para = document.add_paragraph('') #format term para.add_run(line[0], style="Heading 2 Char") #format book.page number para.add_run(" [") para.add_run(line[1]).italic = True para.add_run("] ") para.add_run("\n") #format definiton/context para.add_run(line[2])
def doc(): ri = tk.Tk() ri.filename = filedialog.askopenfilename( initialdir="C:/Users/JOEL/Desktop/apptest/vp", title="Select file", filetypes=(("wav files", "*.wav"), ("all files", "*.*"))) a = os.path.split(ri.filename) r = sr.Recognizer() with sr.AudioFile(a[1]) as source: audio = r.listen(source) #try: text = r.recognize_google(audio) messagebox.showinfo("Alert", "Converted Text: {}".format(text)) text = text.lower() str = text.split(" ") val = "mg" for i in range(str.count(val)): str.remove(val) val = "milligram" for i in range(str.count(val)): str.remove(val) val = "days" for i in range(str.count(val)): str.remove(val) val = "ml" for i in range(str.count(val)): str.remove(val) val = "for" for i in range(str.count(val)): str.remove(val) name = "" age = "" Date = date.today() ad = "" dia = "" sym = "" tablet = [] syrup = [] for i in range(len(str)): if (str[i] == 'name'): name = str[i + 2] if (str[i] == 'i' and str[i + 1] == 'am'): name = str[i + 2] if (str[i] == "i'm"): name = str[i + 2] if (str[i] == 'name' and str[i + 3] != 'age'): name += str[i + 3] if (str[i] == 'age'): age = str[i + 1] if (str[i] == 'tablet'): ar = [] default = "0-0-0" ar.append(str[i + 1]) if (str[i + 2].find("mg") >= 0): str[i + 2] = str[i + 2][:-2] ar.append(str[i + 2]) if (str[i + 3].find("days") >= 0): str[i + 3] = str[i + 3][:-4] ar.append(str[i + 3]) if (str[i + 4] == 'before'): ar.append(str[i + 4]) else: ar.append("After") for j in range(5): if (str[i + j + 3] == 'once'): default = '1' + '-' + default[2] + '-' + default[4] break if (str[i + j + 3] == 'twice'): default = '1' + '-' + default[2] + '-' + '1' break if (str[i + j + 3] == 'thrice' or str[i + j + 3] == 'prices' or str[i + j + 3] == 'rice'): default = '1' + '-' + '1' + '-' + '1' break if (str[i + j + 3] == 'night'): default = default[0] + '-' + default[2] + '-' + '1' if (str[i + j + 3] == 'afternoon'): default = default[0] + '-' + '1' + '-' + default[4] if (str[i + j + 3] == 'morning'): default = '1' + '-' + default[2] + '-' + default[4] if (str[i + j + 3] == 'done' or str[i + j + 3] == 'dun'): break ar.append(default) tablet.append(ar) if (str[i] == 'syrup'): arr = [] default = "0-0-0" arr.append(str[i + 1]) if (str[i + 2].find("ml") >= 0): str[i + 2] = str[i + 2][:-2] arr.append(str[i + 2]) if (str[i + 3].find("days") >= 0): str[i + 3] = str[i + 3][:-4] arr.append(str[i + 3]) if (str[i + 4] == 'before'): arr.append(str[i + 4]) else: arr.append("After") for j in range(8): if (str[i + j + 3] == 'once'): default = '1' + '-' + default[2] + '-' + default[4] break if (str[i + j + 3] == 'twice'): default = '1' + '-' + default[2] + '-' + '1' break if (str[i + j + 3] == 'thrice' or str[i + j + 3] == 'prices'): default = '1' + '-' + '1' + '-' + '1' break if (str[i + j + 3] == 'night'): default = default[0] + '-' + default[2] + '-' + '1' if (str[i + j + 3] == 'afternoon'): default = default[0] + '-' + '1' + '-' + default[4] if (str[i + j + 3] == 'morning'): default = '1' + '-' + default[2] + '-' + default[4] if (str[i + j + 3] == 'done' or str[i + j + 3] == 'dun'): break arr.append(default) syrup.append(arr) if ((len(name)) == 0): messagebox.showinfo( "Error", "No patient name is found, please retry again!") raise Exception('No name found') document = Document() para = document.add_heading("") runn = para.add_run("ABC HOSPITAL \n") run = para.add_run( " Dr.Jane Doe M.D.(Neurology) \t \t Dr.Smith M.S.(Ortho) \t Dr.Roshni M.S.(Ophthalmology) \n Sector: 17 Navi Mumbai \n Ph:0987654321 \n" ) font = run.font runn.font.size = Pt(18) runn.font.color.rgb = RGBColor(0, 0, 0) font.size = Pt(16) font.color.rgb = RGBColor(0, 0, 0) para.alignment = WD_ALIGN_PARAGRAPH.CENTER para1 = document.add_paragraph() run1 = para1.add_run("Name:{}".format(name)) run1.font.size = Pt(14) para2 = document.add_paragraph() run2 = para2.add_run("Age:{}".format(age)) run2.font.size = Pt(14) para3 = document.add_paragraph() run3 = para3.add_run("Date:{}".format(Date)) run3.font.size = Pt(14) if (len(tablet) == 0): messagebox.showinfo("Alert", "Please include atleast one tablet") else: table = document.add_table(len(tablet), 5) heading_cells = table.rows[0].cells heading_cells[0].text = 'Tablet name' heading_cells[1].text = 'dosage(mg)' heading_cells[2].text = 'No.of.days' heading_cells[3].text = 'Before or after food' heading_cells[4].text = 'No.of.times per day' for i in range(len(tablet)): cells = table.add_row().cells cells[0].text = tablet[i][0] cells[1].text = tablet[i][1] cells[2].text = tablet[i][2] cells[3].text = tablet[i][3] cells[4].text = tablet[i][4] #for space para4 = document.add_paragraph("\n \n") if (len(syrup) != 0): table1 = document.add_table(len(syrup), 5) heading_cells = table1.rows[0].cells heading_cells[0].text = 'Syrup name' heading_cells[1].text = 'dosage(ml)' heading_cells[2].text = 'No.of.days' heading_cells[3].text = 'Before or after food' heading_cells[4].text = 'No.of.times per day' # add a data row for each item for i in range(len(syrup)): cells = table1.add_row().cells cells[0].text = syrup[i][0] cells[1].text = syrup[i][1] cells[2].text = syrup[i][2] cells[3].text = syrup[i][3] cells[4].text = syrup[i][4] para5 = document.add_paragraph("\n \n") header = document.sections[0].footer f1 = header.add_paragraph() runf = f1.add_run( "\n Signature \n I hereby accept that this prescription was verified" ) runf.font.size = Pt(16) runf.font.color.rgb = RGBColor(0, 0, 0) f1.alignment = WD_ALIGN_PARAGRAPH.RIGHT document.save("{}.docx".format(name)) messagebox.showinfo( "Successfully completed", "Success! Please verify the document generated and click upload \n Document Name:{}.docx" .format(name)) verify(name) #except: #messagebox.showinfo("Error","please try again!") ri.destroy()
def listen(): r = sr.Recognizer() with sr.Microphone() as source: messagebox.showinfo("Alert", "Start Speaking") audio = r.listen(source) messagebox.showinfo("Alert", "completed.") text = r.recognize_google(audio) messagebox.showinfo("Alert", "Converted Text:{}".format(text)) text = text.lower() str = text.split(" ") val = "mg" var = "milligram" for i in range(str.count(val)): str.remove(val) for i in range(str.count(val)): str.remove(var) val = "days" for i in range(str.count(val)): str.remove(val) val = "ml" for i in range(str.count(val)): str.remove(val) val = "for" for i in range(str.count(val)): str.remove(val) name = "" age = "" Date = date.today() ad = "" dia = "" sym = "" tablet = [] syrup = [] for i in range(len(str)): if (str[i] == 'name'): name = str[i + 2] if (str[i] == 'name' and str[i + 3] != 'age'): name += str[i + 3] if (str[i] == 'age'): age = str[i + 1] if (str[i] == 'tablet'): ar = [] default = "0-0-0" ar.append(str[i + 1]) if (str[i + 2].find("mg") >= 0): str[i + 2] = str[i + 2][:-2] ar.append(str[i + 2]) if (str[i + 3].find("days") >= 0): str[i + 3] = str[i + 3][:-4] ar.append(str[i + 3]) if (str[i + 4] == 'before'): ar.append(str[i + 4]) else: ar.append("After") for j in range(5): if (str[i + j + 3] == 'once'): default = '1' + '-' + default[2] + '-' + default[4] break if (str[i + j + 3] == 'twice'): default = '1' + '-' + default[2] + '-' + '1' break if (str[i + j + 3] == 'thrice'): default = '1' + '-' + '1' + '-' + '1' break if (str[i + j + 3] == 'night'): default = default[0] + '-' + default[2] + '-' + '1' if (str[i + j + 3] == 'afternoon'): default = default[0] + '-' + '1' + '-' + default[4] if (str[i + j + 3] == 'morning'): default = '1' + '-' + default[2] + '-' + default[4] if (str[i + j + 3] == 'done' or str[i + j + 3] == 'dun'): break ar.append(default) tablet.append(ar) if (str[i] == 'syrup'): arr = [] default = "0-0-0" arr.append(str[i + 1]) if (str[i + 2].find("ml") >= 0): str[i + 2] = str[i + 2][:-2] arr.append(str[i + 2]) if (str[i + 3].find("days") >= 0): str[i + 3] = str[i + 3][:-4] arr.append(str[i + 3]) if (str[i + 4] == 'before'): arr.append(str[i + 4]) else: arr.append("After") for j in range(8): if (str[i + j + 3] == 'once'): default = '1' + '-' + default[2] + '-' + default[4] break if (str[i + j + 3] == 'twice'): default = '1' + '-' + default[2] + '-' + '1' break if (str[i + j + 3] == 'thrice'): default = '1' + '-' + '1' + '-' + '1' break if (str[i + j + 3] == 'night'): default = default[0] + '-' + default[2] + '-' + '1' if (str[i + j + 3] == 'afternoon'): default = default[0] + '-' + '1' + '-' + default[4] if (str[i + j + 3] == 'morning'): default = '1' + '-' + default[2] + '-' + default[4] if (str[i + j + 3] == 'done' or str[i + j + 3] == 'dun'): break arr.append(default) syrup.append(arr) if ((len(name)) == 0): messagebox.showinfo("Error", "No patient name is found, please retry again!") raise Exception('No name found') document = Document() para = document.add_heading("") runn = para.add_run("ABC HOSPITAL \n") run = para.add_run( " Dr.Jane Doe M.D.(Neurology) \t \t Dr.Smith M.S.(Ortho) \t Dr.Roshni M.S.(Ophthalmology) \n Sector: 17 Navi Mumbai \n Ph:0987654321 \n" ) font = run.font runn.font.size = Pt(18) runn.font.color.rgb = RGBColor(153, 17, 150) font.size = Pt(16) font.color.rgb = RGBColor(217, 17, 213) para.alignment = WD_ALIGN_PARAGRAPH.CENTER para1 = document.add_paragraph() run1 = para1.add_run("Name:{}".format(name)) run1.font.size = Pt(14) para2 = document.add_paragraph() run2 = para2.add_run("Age:{}".format(age)) run2.font.size = Pt(14) para3 = document.add_paragraph() run3 = para3.add_run("Date:{}".format(Date)) run3.font.size = Pt(14) if (len(tablet) == 0): messagebox.showinfo("Alert", "Please include atleast one tablet") raise Exception('No name found') else: table = document.add_table(len(tablet), 5) heading_cells = table.rows[0].cells heading_cells[0].text = 'Tablet name' heading_cells[1].text = 'dosage(mg)' heading_cells[2].text = 'No.of.days' heading_cells[3].text = 'Before or after food' heading_cells[4].text = 'No.of.times per day' # add a data row for each item for i in range(len(tablet)): cells = table.add_row().cells cells[0].text = tablet[i][0] cells[1].text = tablet[i][1] cells[2].text = tablet[i][2] cells[3].text = tablet[i][3] cells[4].text = tablet[i][4] #for space para4 = document.add_paragraph("\n \n") if (len(syrup) != 0): #syrup table1 = document.add_table(len(syrup), 5) # populate header row -------- heading_cells = table1.rows[0].cells heading_cells[0].text = 'Syrup name' heading_cells[1].text = 'dosage(ml)' heading_cells[2].text = 'No.of.days' heading_cells[3].text = 'Before or after food' heading_cells[4].text = 'No.of.times per day' # add a data row for each item for i in range(len(syrup)): cells = table1.add_row().cells cells[0].text = syrup[i][0] cells[1].text = syrup[i][1] cells[2].text = syrup[i][2] cells[3].text = syrup[i][3] cells[4].text = syrup[i][4] para5 = document.add_paragraph("\n \n") header = document.sections[0].footer f1 = header.add_paragraph() runf = f1.add_run( "\n Signature \n I hereby accept that this prescription was verified") runf.font.size = Pt(16) runf.font.color.rgb = RGBColor(0, 0, 0) f1.alignment = WD_ALIGN_PARAGRAPH.RIGHT document.save("{}.docx".format(name))
sku_head.style = doc.styles.add_style('Style Name SKU', WD_STYLE_TYPE.PARAGRAPH) sku_head.alignment = WD_ALIGN_PARAGRAPH.CENTER font = sku_head.style.font font.name = 'Times New Roman' font.size = Pt(85) font.bold = True font.italic = False # Title line (the name of the product) & styling title_head = doc.add_heading(title, 1) title_head.style = doc.styles.add_style('Style Name TITLE', WD_STYLE_TYPE.PARAGRAPH) title_head.alignment = WD_ALIGN_PARAGRAPH.CENTER font = title_head.style.font font.name = 'Calibri' font.size = Pt(34) font.color.rgb = RGBColor(0,0,0) font.bold = False title_head = title_head.paragraph_format title_head.space_after = Pt(40) # Populate image variables im1 = Image.open(folder + "/images/" + sku + suffix) im2 = Image.open(folder + "/images/qr-codes/" + sku + "-qrcode.png") im3 = Image.open("assets/usadd-logo.png") # Concatenate the images and save to a folder get_concat_h_multi_resize([im1, im2, im3]).save(folder + "/images/concat/" + sku + '-resize.jpg') # Add the picture to the document doc.add_picture(folder + "/images/concat/" + sku + "-resize.jpg", width=Inches(9))
def consignas(tabla_curso, tabla_datos_ejercicio): #Creamos un objeto para usarlo- Document sera el punto de entrada doc = docx.Document() my_image = doc.add_picture('logo_escuela.png') last_paragraph = doc.paragraphs[-1] last_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER texto_escuela = doc.add_paragraph() texto_escuela.add_run("E.E.N° 178 'San José de Calasanz'") texto_escuela.runs[0].font.size = Pt(8) texto_escuela.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER texto_escuela2 = doc.add_paragraph() texto_escuela2.add_run("General Vedia. Chaco.") texto_escuela2.runs[0].font.size = Pt(8) texto_escuela2.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER salto_de_linea_logo = doc.add_paragraph() #Linea doble encabezado linea_superior1 = doc.add_paragraph() linea_superior1.add_run("▬" * 37) linea_superior1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER linea_superior2 = doc.add_paragraph() linea_superior2.add_run("▬" * 37) linea_superior2.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER #Interior encabezado encabezado = doc.add_heading( f"--- CONSIGNAS Y DATOS POR NOMBRE DE ESTUDIANTE ---", level=2) encabezado.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER encabezado2 = doc.add_heading("".join(tabla_curso.split("real_")), level=2) encabezado2.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER encabezado2.runs[0].font.color.rgb = RGBColor(180, 0, 0) #Los encabezados también son runs #Aclaración para estudiante aclaracion = doc.add_paragraph() aclaracion.add_run( "Solo debés utilizar las consignas y datos que corresponden con tu nombre :)" ) aclaracion.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER linea_inferior = doc.add_paragraph() linea_inferior.add_run("▬" * 37) linea_inferior.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER salto_linea_portada = doc.add_paragraph() salto_linea_portada2 = doc.add_paragraph() salto_linea_portada3 = doc.add_paragraph() profesor = doc.add_paragraph() profesor.add_run("Profesor").bold = True profesor.add_run(": Wilson Díaz") profesor.runs[0].font.size = Pt(12) profesor.runs[1].font.size = Pt(12) formato_profesor = profesor.paragraph_format formato_profesor.first_line_indent = Cm(1) salto_linea_portada4 = doc.add_paragraph() asignatura = doc.add_paragraph() asignatura.add_run("Asignatura").bold = True asignatura.add_run(": Educación Tecnológica") asignatura.runs[0].font.size = Pt(12) asignatura.runs[1].font.size = Pt(12) formato_asignatura = asignatura.paragraph_format formato_asignatura.first_line_indent = Cm(1) salto_linea_portada4 = doc.add_paragraph() año = doc.add_paragraph() año.add_run("Fecha").bold = True año.add_run(": Marzo/2021") año.runs[0].font.size = Pt(12) año.runs[1].font.size = Pt(12) formato_año = año.paragraph_format formato_año.first_line_indent = Cm(1) salto_linea_portada5 = doc.add_paragraph() curso_div = doc.add_paragraph() curso_div.add_run("3er año").bold = True curso_div.runs[0].font.size = Pt(12) formato_curso_div = curso_div.paragraph_format formato_curso_div.first_line_indent = Cm(1) salto_de_pagina = doc.add_page_break() #El salto de página #Aquí se sabe que la tabla del curso su segundo atributo es "estudiante" (ajustar si usas otra tabla) #Conocer cantidad de registros(estudiantes) que hay en la tabla elegida cursor.execute(f"SELECT COUNT(*) FROM {tabla_curso}") estudiantes = cursor.fetchall()[0][ 0] #Los [0][0] es para eliminar su tupla dentro de una lista así da solo el int for cada_estudiante in range(estudiantes + 1): #+1 para eliminar conteo desde 0 #Se conoce q estudiante es donde esta el nombre dentro de la tabla cursor.execute( f"SELECT estudiante FROM {tabla_curso} WHERE id={cada_estudiante}") alumno = cursor.fetchall() for i in range( len(alumno) ): #No salía con alumno[0][0] así que tuve que hacerlo así alumno = alumno[i][0] #___________________________________________________________________________________________________________ estudiante = doc.add_paragraph(style="List Bullet") estudiante.add_run("Estudiante").bold = True estudiante.runs[0].font.size = Pt(12) estudiante.runs[0].underline = True estudiante.runs[0].font.color.rgb = RGBColor(180, 0, 0) formato_estudiante = estudiante.paragraph_format #Creando el objeto formato para manejarlo formato_estudiante.first_line_indent = Cm(0.5) #Un cm de sangria estudiante.add_run(f": {str(alumno).upper()}").bold = True estudiante.runs[1].font.size = Pt(12) estudiante.runs[1].font.color.rgb = RGBColor(180, 0, 0) espacio_mas = doc.add_paragraph() # ------------ EJERCICIOS ------------- #Generando punto 9) a) #id en este caso es igual al id foraneo cursor.execute( f"Select ej_9_a FROM {tabla_datos_ejercicio} WHERE id={cada_estudiante}" ) dato = cursor.fetchall() linea_libre2 = doc.add_paragraph() consigna = doc.add_paragraph() consigna.add_run("Consigna y/o datos del punto 9)a) :").bold = True consigna_formato = consigna.paragraph_format consigna_formato.first_line_indent = Cm(0.5) cuerpo_consigna = doc.add_paragraph() cuerpo_consigna.add_run("¿Qué ") cuerpo_consigna.add_run("grosor ").bold = True cuerpo_consigna.add_run( "de cable debés utilizar si el consumo de tu estufa es de ") cuerpo_consigna.add_run(f"{dato[0][0]} amperes?").bold = True #___________________________________________________________________________________________________________ #Generando punto 9) B) cursor.execute( f"Select ej_9_b FROM {tabla_datos_ejercicio} WHERE id={cada_estudiante}" ) dato = cursor.fetchall() linea_libre3 = doc.add_paragraph() consigna2 = doc.add_paragraph() consigna2.add_run( "Consigna y/o datos del punto 9)b) :").bold = True consigna_formato2 = consigna2.paragraph_format consigna_formato2.first_line_indent = Cm(0.5) cuerpo_consigna2 = doc.add_paragraph() cuerpo_consigna2.add_run("¿Si el cable que compraste es de ") cuerpo_consigna2.add_run(f"{dato[0][0]} mm").bold = True cuerpo_consigna2.add_run(", cuántos ") cuerpo_consigna2.add_run("amperes").bold = True cuerpo_consigna2.add_run( " soportará de consumo antes que comience a calentarse?") cuerpo_consigna2.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY #___________________________________________________________________________________________________________ #Generando punto 9) C) linea_libre4 = doc.add_paragraph() consigna3 = doc.add_paragraph() consigna3.add_run( "Consigna y/o datos del punto 9)c) :").bold = True consigna_formato3 = consigna3.paragraph_format consigna_formato3.first_line_indent = Cm(0.5) cuerpo_consigna2 = doc.add_paragraph() cuerpo_consigna2.add_run( "Si enchufamos EN UNA MISMA zapatilla los siguientes electrodomésticos:" ) cursor.execute( f"Select ej_9_c1 FROM {tabla_datos_ejercicio} WHERE id={cada_estudiante}" ) dato = cursor.fetchall() cuerpo_consigna3 = doc.add_paragraph() cuerpo_consigna3.add_run(" - Nuestra PC Gamer que consume ") cuerpo_consigna3.add_run(f"{dato[0][0][0]} amperes.").bold = True cursor.execute( f"Select ej_9_c2 FROM {tabla_datos_ejercicio} WHERE id={cada_estudiante}" ) dato1 = cursor.fetchall() cuerpo_consigna4 = doc.add_paragraph() cuerpo_consigna4.add_run( " - Una heladera con congelador que consume ") cuerpo_consigna4.add_run(f"{dato1[0][0]} amperes.").bold = True cursor.execute( f"Select ej_9_c3 FROM {tabla_datos_ejercicio} WHERE id={cada_estudiante}" ) dato2 = cursor.fetchall() cuerpo_consigna5 = doc.add_paragraph() cuerpo_consigna5.add_run(" - Un minicomponente que consume ") cuerpo_consigna5.add_run(f"{dato2[0][0]} amperes.").bold = True cuerpo_consigna6 = doc.add_paragraph() cuerpo_consigna6.add_run("PREGUNTA: ¿Qué ") cuerpo_consigna6.add_run("grosor").bold = True cuerpo_consigna6.add_run( " debería tener el cable que alimenta a esa zapatilla?") #___________________________________________________________________________________________________________ #Generando punto 11) cursor.execute( f"Select ej_11 FROM {tabla_datos_ejercicio} WHERE id={cada_estudiante}" ) dato = cursor.fetchall() linea_libre4 = doc.add_paragraph() consigna4 = doc.add_paragraph() consigna4.add_run("Consigna y/o datos del punto 11) :").bold = True consigna_formato4 = consigna4.paragraph_format consigna_formato4.first_line_indent = Cm(0.5) cuerpo_consigna7 = doc.add_paragraph() cuerpo_consigna7.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY cuerpo_consigna7.add_run( "Necesito un alargue para alimentar un acondicionador de aire que funciona a una potencia de " ) cuerpo_consigna7.add_run(f"{dato[0][0]} watts.").bold = True cuerpo_consigna8 = doc.add_paragraph() cuerpo_consigna8.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY cuerpo_consigna8.add_run("PREGUNTA: ¿Cuántos ") cuerpo_consigna8.add_run(f"milímetros").bold = True cuerpo_consigna8.add_run( " debe tener la sección de cable (grosor) del alargue que debemos usar para alimntar al acondicionador de aire?" ) cuerpo_consigna8b = doc.add_paragraph( "-dato: el voltaje en Argentina siempre es de 220 V.-") #___________________________________________________________________________________________________________ #Generando punto 13) #Use a y b en el mismo ejercicio para hacerlo más rápido cursor.execute( f"Select ej_13_a FROM {tabla_datos_ejercicio} WHERE id={cada_estudiante}" ) dato = cursor.fetchall() cursor.execute( f"Select ej_13_b FROM {tabla_datos_ejercicio} WHERE id={cada_estudiante}" ) dato1 = cursor.fetchall() linea_libre5 = doc.add_paragraph() consigna5 = doc.add_paragraph() consigna5.add_run("Consigna y/o datos del punto 13) :").bold = True consigna_formato5 = consigna5.paragraph_format consigna_formato5.first_line_indent = Cm(0.5) cuerpo_consigna9 = doc.add_paragraph() cuerpo_consigna9.add_run("Pasar a decimal ---> ") cuerpo_consigna9.add_run(f" {dato[0][0]}.").bold = True cuerpo_consigna10 = doc.add_paragraph() cuerpo_consigna10.add_run("Pasar a decimal ---> ") cuerpo_consigna10.add_run(f" {dato1[0][0]}.").bold = True #___________________________________________________________________________________________________________ #Generando punto 14) cursor.execute( f"Select ej_14 FROM {tabla_datos_ejercicio} WHERE id={cada_estudiante}" ) dato = cursor.fetchall() linea_libre6 = doc.add_paragraph() consigna6 = doc.add_paragraph() consigna6.add_run("Consigna y/o datos del punto 14) :").bold = True consigna_formato6 = consigna6.paragraph_format consigna_formato6.first_line_indent = Cm(0.5) cuerpo_consigna11 = doc.add_paragraph() cuerpo_consigna11.add_run("Calcular cuál es la capacidad real en ") cuerpo_consigna11.add_run("GIBIBYTES").bold = True cuerpo_consigna11.add_run( " que tiene una unidad de almacenamiento que compraste (ya sea pendrive o disco rígido, da igual), si la etiqueta dice que es de " ) cuerpo_consigna11.add_run(f"{dato[0][0]} Gigas.").bold = True cuerpo_consigna11.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY todos_los_parrafos = doc.paragraphs for cada_parrafo in todos_los_parrafos: cada_parrafo.paragraph_format.space_after = Pt( 3) #A todos los párrafos le daremos menos interlineado ultimo_espacio = doc.add_paragraph() ultimo_espacio2 = doc.add_paragraph() linea_final = doc.add_paragraph() linea_final.add_run("_" * 100) linea_final.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER if cada_estudiante != estudiantes: ultimo_salto_de_pagina = doc.add_page_break() #Aquí le pondrás doc.save("Ejercicios previa tecno marzo2021.docx") print("Proceso terminado con éxito.")
def it_can_construct_from_a_hex_string_rgb_value(self): rgb = RGBColor.from_string('123456') assert rgb == RGBColor(0x12, 0x34, 0x56)
#python-docx这个库。它只能解析docx文件,解析不了doc文件。安装方式直接pip install python-docx。 #安装的模块名与使用的模块名不一样,在python中常见,为了保持向下兼容 from docx import Document from docx.shared import RGBColor boldText = [] redText = [] doc = Document('test.docx') #在word中的一个自然段,就是一个paragraph,用一个for循环就可以获得全部的段落。这是一个可迭代的类型 for p in doc.paragraphs: #格式,是加粗,颜色,居中等等这些排版设计的东西,在paragraph中,叫做run,一个段落是由许多run组成的 #这同样是个可迭代的类型,可以循环获得每一个run相关的内容,比如alignment(对齐方式),bold(加粗),italic(斜体),text(具体文本内容)等等。 for r in p.runs: # 加粗字体 if r.bold: boldText.append(r.text) #列表追加元素 # 红色字体 if r.font.color.rgb == RGBColor(255, 0, 0): redText.append(r.text) #列表追加元素 result = { 'red text': redText, 'bold text': boldText, 'both': set(redText) & set(boldText) } #列表转成集合,集合取“与” # 输出结果 for title in result.keys(): print(title.center(30, '=')) for text in result[title]: print(text)
def when_I_assign_value_to_font_color_rgb(context, value): font = context.font new_value = None if value == 'None' else RGBColor.from_string(value) font.color.rgb = new_value
def __init__(self, chrome_path, folder_path): self.chrome = chrome_path self.path = folder_path from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.keys import Keys from docx import Document from docx.shared import Inches, Pt from docx.enum.text import WD_ALIGN_PARAGRAPH from datetime import date from docx.shared import RGBColor import pandas as pd import sys import random import string try: self.out_passed = True testdata_path = self.path + '\\' + '2_testcase.xlsx' Testdata = pd.read_excel(testdata_path) Step = 0 today = date.today() d4 = today.strftime("%b-%d-%Y") d3 = today.strftime("%b_%d_%Y") document = Document() p = document.add_paragraph() p.alignment = WD_ALIGN_PARAGRAPH.CENTER title = p.add_run("2_testcase") title.bold = True title.font.size = Pt(16) Para1 = document.add_paragraph() title1 = Para1.add_run(d4) title1.bold = True title1.font.size = Pt(12) title1.font.color.rgb = RGBColor(128, 0, 0) PathChrome = self.chrome driver = webdriver.Chrome(PathChrome) driver.get(" https://www.sogeti.com/") driver.maximize_window() WebDriverWait(driver, 20).until( EC.visibility_of_element_located(( By.XPATH, '//*[@id="header"]/div[1]/nav[1]/ul[1]/li[3]/div[1]/span[1]' ))) document.add_paragraph(Testdata.at[Step, 'Describtion']) document.add_paragraph('Passed') driver.save_screenshot(self.path + '\\' + 'pic.jpg') document.add_picture(self.path + '\\' + 'pic.jpg', width=Inches(7)) Step = Step + 1 driver.find_element_by_xpath( '//*[@id="header"]/div[1]/nav[1]/ul[1]/li[3]/div[1]/span[1]' ).click() WebDriverWait(driver, 20).until( EC.visibility_of_element_located( (By.XPATH, '//*[@id="header"]/div[1]/div[5]/ul[1]/li[7]/a[1]'))) driver.find_element_by_xpath( '//*[@id="header"]/div[1]/div[5]/ul[1]/li[7]/a[1]').click() WebDriverWait(driver, 20).until( EC.visibility_of_element_located(( By.XPATH, '//*[@id="primary_content"]/div[1]/div[2]/div[1]/h1[1]/span[1]' ))) r_name1 = '' r_name2 = '' r_number = '' for x in range(6): r_name1 = r_name1 + random.choice(string.ascii_letters) driver.find_element_by_xpath( '//*[@id="4ff2ed4d-4861-4914-86eb-87dfa65876d8"]').send_keys( r_name1) for x in range(6): r_name2 = r_name2 + random.choice(string.ascii_letters) driver.find_element_by_xpath( '//*[@id="11ce8b49-5298-491a-aebe-d0900d6f49a7"]').send_keys( r_name2) driver.find_element_by_xpath( '//*[@id="056d8435-4d06-44f3-896a-d7b0bf4d37b2"]').send_keys( r_name1 + '.' + r_name2 + '@rrr.com') for x in range(8): r_number = r_number + str(random.randint(0, 9)) driver.find_element_by_xpath( '//*[@id="755aa064-7be2-432b-b8a2-805b5f4f9384"]').send_keys( r_number) driver.find_element_by_xpath( '//*[@id="88459d00-b812-459a-99e4-5dc6eff2aa19"]').send_keys( 'Hello ' + r_name1 + ' ' + ' ' + r_name2) driver.find_element_by_xpath('//*[@value="I agree"]').click() document.add_paragraph(Testdata.at[Step, 'Describtion']) document.add_paragraph('Passed') driver.save_screenshot(self.path + '\\' + 'pic.jpg') document.add_picture(self.path + '\\' + 'pic.jpg', width=Inches(7)) Step = Step + 1 driver.find_element_by_xpath('//*[@name="submit"]').click() WebDriverWait(driver, 20).until( EC.visibility_of_element_located(( By.XPATH, '//*[@class="Form__Status__Message Form__Success__Message"]' ))) message = driver.find_element_by_xpath( '//*[@class="Form__Status__Message Form__Success__Message"]' ).text if (message == 'Thank you for contacting us.'): document.add_paragraph(Testdata.at[Step, 'Describtion']) document.add_paragraph('Passed') driver.save_screenshot(self.path + '\\' + 'pic.jpg') document.add_picture(self.path + '\\' + 'pic.jpg', width=Inches(7)) Step = Step + 1 else: document.add_paragraph(Testdata.at[Step, 'Describtion']) document.add_paragraph('Failed:Wrong Titel') driver.save_screenshot(self.path + '\\' + 'pic.jpg') document.add_picture(self.path + '\\' + 'pic.jpg', width=Inches(7)) raise Exception("BusinessError:wronge message") except: document.add_paragraph('sys.exc_info()') driver.save_screenshot(self.path + '\\' + 'pic.jpg') self.out_passed = False finally: docName = self.path + '\\' + '2_testcase' + '_' + d3 + '.docx' document.save(docName) self.report_path = docName self.report = [self.out_passed, self.report_path] driver.quit()
def create_lyric_page(doc, lyric): """ 创建新的页 """ p = doc.add_heading(u"", level=0) title_p = p.add_run(lyric['title']) title_p.font.name = u"华文楷体" title_p._element.rPr.rFonts.set(qn('w:eastAsia'), u'华文楷体') infos = lyric.get('info') if infos: if infos.get(u'歌手'): p = doc.add_paragraph(u"") p.alignment = WD_ALIGN_PARAGRAPH.RIGHT singer_p = p.add_run(infos.get(u'歌手')) singer_p.font.color.rgb = RGBColor(0, 32, 96) singer_p.font.name = "Microsoft YaHei" singer_p._element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft Yahei') if lyric.get('desc'): p = doc.add_paragraph(u"") desc_p = p.add_run(lyric['desc']) desc_p.font.name = "Microsoft YaHei" desc_p._element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft Yahei') #desc.style.font.color.rgb = RGBColor(0, 0, 0) if infos: for info in infos: p = doc.add_paragraph(u"", style="ListBullet") info_p = p.add_run(info + u": ") info_p.font.bold = True info_p.font.name = "Microsoft YaHei" info_p._element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft Yahei') item = " ".join(infos[info]) info_p = p.add_run(item) info_p.font.name = "Microsoft YaHei" info_p._element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft Yahei') p = doc.add_paragraph(u"") line_p = p.add_run(u"粤拼(Lyrics)") line_p.font.name = u"华文楷体" line_p._element.rPr.rFonts.set(qn('w:eastAsia'), u'华文楷体') line_p.bold = True line_p.font.color.rgb = RGBColor(0x3c, 0x76, 0x3d) line_p.font.size = Pt(12) lyric_text = lyric.get('lyric') lines = lyric_text.split("\n") i = 0 j = 0 for line in lines: if line: if i % 2 == 0: l = doc.add_paragraph(u"") chinese = l.add_run(lines[j] + "\n") chinese.font.name = "Microsoft Yahei" chinese._element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft Yahei') try: pinyin = l.add_run(lines[j+1]) pinyin.font.name = "Cambria" except Exception as e: print (e, lyric) i += 1 else: doc.add_paragraph(u"") j += 1 doc.add_paragraph(u"") lables = lyric.get('label') label = " ".join(lables) if lables: p = doc.add_paragraph(u'') label_p = p.add_run(u"标签(TAG):") label_p.font.name = u"幼圆" label_p = p.add_run(label) label_p.font.name = u"幼圆" label_p._element.rPr.rFonts.set(qn('w:eastAsia'), u'幼圆') label_p.font.color.rgb = RGBColor(0x33, 0x7a, 0xb7)
"qty": 2, "desc": "New item" }, ] table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id' #hdr_cells[2].paragraphs[0].text = 'XX' #print dir(hdr_cells[2].paragraphs[0]) #para = hdr_cells[2].add_paragraph('') run = hdr_cells[2].paragraphs[0].add_run('XX') font = run.font font.color.rgb = RGBColor(0x42, 0x24, 0xE9) shading_elm = parse_xml(r'<w:shd {} w:fill="dce3db"/>'.format(nsdecls('w'))) hdr_cells[0]._tc.get_or_add_tcPr().append(shading_elm) for item in recordset: row_cells = table.add_row().cells row_cells[0].text = str(item["qty"]) row_cells[1].text = str(item["id"]) row_cells[2].text = item["desc"] ## http://python-docx.readthedocs.io/en/latest/user/styles-understanding.html table.style = 'TableGrid' document.add_page_break() document.save('test.docx')
def add_content(document, content): if content.__contains__('k.t.qq.com'): pattern = re.compile(r'(<a href="http://k.t.qq.com.*?</a>)', re.S) topics = re.findall(pattern, content) for topic in topics: topic_word = topic.split('#')[1] content = content.replace( topic, SPLIT_STRING + TOPIC_STRING + '#' + topic_word + '#' + SPLIT_STRING) if content.__contains__('www/mb/images/emoji'): pattern_emoji = re.compile(r'(<img.*?>)', re.S) pattern_emoji_img = re.compile(r"crs='(.*?)'", re.S) emojis = re.findall(pattern_emoji, content) for emoji in emojis: emoji_url = re.findall(pattern_emoji_img, emoji)[0] filename = download_pic(emoji_url, PNG_EXTENSION) content = content.replace( emoji, SPLIT_STRING + EMOJI_STRING + filename + SPLIT_STRING) if content.__contains__('em rel="@'): pattern_friend = re.compile(r'(<em rel=.*?</em>)', re.S) pattern_friend_name = re.compile(r'<em.*?title="(.*?)"', re.S) friends = re.findall(pattern_friend, content) for friend in friends: friend_name = re.findall(pattern_friend_name, friend)[0] content = content.replace( friend, SPLIT_STRING + FRIEND_STRING + friend_name + SPLIT_STRING) # delete first <div> mark content = content[5:] if content.__contains__('http://url.cn'): pattern_url = re.compile(r'(<a href=.*?</a>)', re.S) pattern_url_str = re.compile(r'<a href="(.*?)"', re.S) urls = re.findall(pattern_url, content) for url in urls: url_str = re.findall(pattern_url_str, url)[0] content = content.replace( url, SPLIT_STRING + URL_STRING + url_str + SPLIT_STRING) content_parts = content.split(SPLIT_STRING) para = document.add_paragraph() for content_part in content_parts: if content_part.startswith(TOPIC_STRING): run = para.add_run(content_part.replace(TOPIC_STRING, '')) font = run.font font.italic = True font.size = Pt(16) font.color.rgb = RGBColor(0x00, 0x00, 0xCD) elif content_part.startswith(EMOJI_STRING): run = para.add_run() filename = content_part.replace(EMOJI_STRING, '') run.add_picture(filename) elif content_part.startswith(FRIEND_STRING): run = para.add_run(content_part.replace(FRIEND_STRING, '')) font = run.font font.italic = True font.size = Pt(16) font.color.rgb = RGBColor(0xFF, 0x45, 0x00) elif content_part.startswith(URL_STRING): docx_ext.add_hyperlink(para, content_part.replace(URL_STRING, ''), content_part.replace(URL_STRING, ''), '1E90FF', True) else: run = para.add_run(content_part) font = run.font font.size = Pt(16) font.color.rgb = RGBColor(0x08, 0x08, 0x08)
def make_puzzle(self, filename='puzzle'): difficulty = self.diff option = self.option if difficulty == 1: self.difficulty = 'random.choice([self.col, self.row_rev])(word)' elif difficulty == 2: self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev])(word)" elif difficulty == 3: self.difficulty = "random.choice([self.col, self.row_rev, self.diagup, self.diagdown])(word)" elif difficulty == 4: self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev, self.diagup, self.diagdown])(word)" elif difficulty == 5: self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev, self.diagup, self.diagup_rev, self.diagdown, self.diagdown_rev])(word)" elif difficulty == 6: self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev, self.diagup, self.diagup_rev, self.diagdown, self.diagdown_rev])(word)" self.puzzle_origin = [] for i in range(self.height): self.puzzle_origin.append([]) for j in range(self.width): self.puzzle_origin[i].append('0') print("퍼즐 만드는 중") words = [word[0] for word in self.word_image] for word in words: exec(self.difficulty) string_words = ''.join(words) from collections import Counter count_alpha = Counter(string_words) common_alph = '' for alph in count_alpha.most_common(5): common_alph += alph[0] data = '' if self.korean: f = open("random_words.txt", 'r') data = f.read() regex_f = r'[가-힣]+' search_target_f = data data = ''.join(list(set(re.findall(regex_f, search_target_f)))) printed_words = '' puzzle = copy.deepcopy(self.puzzle_origin) for i in range(self.height): for j in range(self.width): if self.puzzle_origin[i][j] == "0": fill_alph = random.choice(string.ascii_lowercase) if self.korean: fill_alph = random.choice(data) #글자들 되도록 겹치지 않게 하기 위해서 많이 나오는 글자 한번쯤은 피할 수 있도록 한다. if option == 0: puzzle[i][j] = fill_alph elif option == 1: if fill_alph in common_alph: fill_alph = random.choice(string.ascii_lowercase) if self.korean: fill_alph = random.choice(data) puzzle[i][j] = fill_alph printed_words += puzzle[i][j] #글자가 겹치도록 하기 위해서 많이 나온 글자와 무작위 글자들 중에서 고르도록 한다. elif option == 2: common_alph_list = [] puzzle[i][j] = random.choice([ fill_alph, random.choice(count_alpha.most_common(7))[0] ]) printed_words += puzzle[i][j] # write to docx file # Write to docx to puzzle.docx document = Document() #changing the page margins sections = document.sections for section in sections: section.top_margin = Cm(1) section.bottom_margin = Cm(0.8) section.left_margin = Cm(2.3) section.right_margin = Cm(2.3) heading = 'Word Puzzle' if self.korean: heading = "낱말 찾기" head = document.add_heading(heading, 0) head.alignment = WD_ALIGN_PARAGRAPH.CENTER para_belong = document.add_paragraph('__학년 __반 이름: _______') para_belong.alignment = WD_ALIGN_PARAGRAPH.RIGHT puzzle_table = document.add_table(rows=self.height, cols=self.width, style='Table Grid') puzzle_table.alignment = WD_TABLE_ALIGNMENT.CENTER self.set_height = 7200 / self.height for i, row in enumerate(puzzle_table.rows): #######################세로 길이 정하기! # accessing row xml and setting tr height tr = row._tr trPr = tr.get_or_add_trPr() trHeight = OxmlElement('w:trHeight') trHeight.set(qn('w:val'), str(self.set_height)) trHeight.set(qn('w:hRule'), "atLeast") trPr.append(trHeight) for j, cell in enumerate(row.cells): #####가로 길이 정하기! cell.width = Inches(5) cell.text = puzzle[i][j] for paragraph in cell.paragraphs: #####가운데 정렬!! paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER paragraph.style.font.bold = True #####상하 방향에서 가운데 정렬 tc = cell._tc tcPr = tc.get_or_add_tcPr() tcVAlign = OxmlElement('w:vAlign') tcVAlign.set(qn('w:val'), "center") tcPr.append(tcVAlign) if self.pic_on: word_num = len(words) if word_num <= 15: size = 5 elif word_num <= 21: size = (word_num + 2) // 3 else: size = 7 hint_table = document.add_table(rows=(len(words) + size - 1) // size * 2, cols=size, style='Table Grid') hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER for i, row in enumerate(hint_table.rows): #######################세로 길이 정하기! if i % 2 == 0: # accessing row xml and setting tr height tr = row._tr trPr = tr.get_or_add_trPr() trHeight = OxmlElement('w:trHeight') trHeight.set(qn('w:val'), '1000') trHeight.set(qn('w:hRule'), "atLeast") trPr.append(trHeight) elif i % 2 == 1: # accessing row xml and setting tr height tr = row._tr trPr = tr.get_or_add_trPr() trHeight = OxmlElement('w:trHeight') trHeight.set(qn('w:val'), '60') trHeight.set(qn('w:hRule'), "atLeast") trPr.append(trHeight) for j, cell in enumerate(row.cells): index = i // 2 * size + j #####가로 길이 정하기! cell.width = Inches(10) #단어 수 만큼 반복하기 if index < len(words): if i % 2 == 1: cell.text = words[index] if self.chosung: word = words[index] cho_word = '' for chr in word: chosung = hgtk.letter.decompose(chr)[0] cho_word += chosung cell.text = cho_word for paragraph in cell.paragraphs: if i % 2 == 0: if self.word_image[index][1] == "None": cell.text = "사진 없음" else: try: run = paragraph.add_run() if size > 8: run.add_picture( self.word_image[index][1], width=Mm(15), height=Mm(15)) else: run.add_picture( self.word_image[index][1], width=Mm(40 - size * 3.2), height=Mm(40 - size * 3.2)) except: paragraph.add_run( "에러 발생. 다른 사진 선택해주세요.") #####가운데 정렬!! paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER paragraph.style.font.bold = True #####상하 방향에서 가운데 정렬 tc = cell._tc tcPr = tc.get_or_add_tcPr() tcVAlign = OxmlElement('w:vAlign') tcVAlign.set(qn('w:val'), "center") tcPr.append(tcVAlign) else: if not self.korean: hint_table = document.add_table(rows=1, cols=1, style='Table Grid') hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER hint_table_row = hint_table.rows[0] hint_tr = hint_table_row._tr hint_trPr = hint_tr.get_or_add_trPr() hint_trHeight = OxmlElement('w:trHeight') hint_trHeight.set(qn('w:val'), '1000') hint_trHeight.set(qn('w:hRule'), "atLeast") hint_trPr.append(hint_trHeight) hint_table_cell = hint_table_row.cells[0] hint = '' parenthesis = re.compile(r'(\s)?\(.*\)(\s)?') bracket = re.compile(r'(\s)?\[.*\](\s)?') for word in words: print("사전에 찾는중... " + word) req = requests.get( 'http://endic.naver.com/small_search.nhn?query=' + word) html = req.text soup = BeautifulSoup(html, 'html.parser') meanings = soup.select('span.fnt_k05') if meanings: text = meanings[0].text text = re.sub(parenthesis, '', text) text = re.sub(bracket, '', text) print(text) hint += word + "({})".format(text) + ', ' hint_table_cell.width = Inches(100) for paragraph in hint_table_cell.paragraphs: paragraph.add_run(hint.strip(', ')) paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY tc = hint_table_cell._tc tcPr = tc.get_or_add_tcPr() tcVAlign = OxmlElement('w:vAlign') tcVAlign.set(qn('w:val'), "center") tcPr.append(tcVAlign) else: if self.chosung: hint_table = document.add_table(rows=1, cols=1, style='Table Grid') hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER hint_table_row = hint_table.rows[0] hint_tr = hint_table_row._tr hint_trPr = hint_tr.get_or_add_trPr() hint_trHeight = OxmlElement('w:trHeight') hint_trHeight.set(qn('w:val'), '1000') hint_trHeight.set(qn('w:hRule'), "atLeast") hint_trPr.append(hint_trHeight) hint_table_cell = hint_table_row.cells[0] hint = '' for word in words: cho_word = '' for chr in word: chosung = hgtk.letter.decompose(chr)[0] cho_word += chosung hint += cho_word + ', ' hint_table_cell.width = Inches(100) for paragraph in hint_table_cell.paragraphs: paragraph.add_run(hint.strip(', ')) paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY tc = hint_table_cell._tc tcPr = tc.get_or_add_tcPr() tcVAlign = OxmlElement('w:vAlign') tcVAlign.set(qn('w:val'), "center") tcPr.append(tcVAlign) else: hint_table = document.add_table(rows=1, cols=1, style='Table Grid') hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER hint_table_row = hint_table.rows[0] hint_tr = hint_table_row._tr hint_trPr = hint_tr.get_or_add_trPr() hint_trHeight = OxmlElement('w:trHeight') hint_trHeight.set(qn('w:val'), '1000') hint_trHeight.set(qn('w:hRule'), "atLeast") hint_trPr.append(hint_trHeight) hint_table_cell = hint_table_row.cells[0] hint = '' for word in words: hint += word + ', ' hint_table_cell.width = Inches(100) for paragraph in hint_table_cell.paragraphs: paragraph.add_run(hint.strip(', ')) paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY tc = hint_table_cell._tc tcPr = tc.get_or_add_tcPr() tcVAlign = OxmlElement('w:vAlign') tcVAlign.set(qn('w:val'), "center") tcPr.append(tcVAlign) # 정답 파일 쓰기 answ_doc = Document() answer_table = answ_doc.add_table(rows=self.height, cols=self.width, style='Table Grid') answer_table.alignment = WD_TABLE_ALIGNMENT.CENTER for i, row in enumerate(answer_table.rows): #######################세로 길이 정하기! # accessing row xml and setting tr height tr = row._tr trPr = tr.get_or_add_trPr() trHeight = OxmlElement('w:trHeight') trHeight.set(qn('w:val'), str(self.set_height)) trHeight.set(qn('w:hRule'), "atLeast") trPr.append(trHeight) for j, cell in enumerate(row.cells): #####가로 길이 정하기! cell.width = Inches(8) cell.text = self.puzzle_origin[i][j] for paragraph in cell.paragraphs: #####가운데 정렬!! paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER paragraph.style.font.bold = True if cell.text == '0': for run in paragraph.runs: run.font.color.rgb = RGBColor(255, 255, 255) else: for run in paragraph.runs: run.font.color.rgb = RGBColor(255, 0, 0) #####상하 방향에서 가운데 정렬 tc = cell._tc tcPr = tc.get_or_add_tcPr() tcVAlign = OxmlElement('w:vAlign') tcVAlign.set(qn('w:val'), "center") tcPr.append(tcVAlign) answ_doc.save(str(self.desktop) + '\{}_정답.hwp'.format(filename)) document.save(str(self.desktop) + '\{}.hwp'.format(filename)) print("바탕화면에 puzzle.docx와 puzzle.hwp 로 저장")
from docx import Document from docx.shared import RGBColor document = Document( '/home/navkrishna/Downloads/demo.docx') #path of document file to open color_to_check = RGBColor(0x4F, 0x81, 0xBD) #add the hex code of the color to find color_found = False for para in document.paragraphs: para_color = None if para.style.font.color.rgb: para_color = para.style.font.color.rgb for run in para.runs: final_color = None if run.font.color.rgb: final_color = run.font.color.rgb if run.style.font.color.rgb: final_color = run.style.font.color.rgb if not final_color: final_color = para_color if final_color:
def make_document(file, log): """Produce Word Document transcriptions using the automatic speech recognition from AWS Transcribe.""" # Initiate Document document = Document() # A4 Size document.sections[0].page_width = Mm(210) document.sections[0].page_height = Mm(297) # Font font = document.styles['Normal'].font font.name = 'Calibri' # Load Transcription output from command line input # eg: python3 application.py 'output.json' data = json.load(open(file)) click.echo(f"{click.format_filename(file)} opened...") # Document title and intro title = f"Transcription of {data['jobName']}" document.add_heading(title, level=1) # Set thresholds for formatting later threshold_for_grey = 0.98 # Intro document.add_paragraph( 'Transcription using AWS Transcribe automatic speech recognition.') document.add_paragraph(datetime.datetime.now().strftime( 'Document produced on %A %d %B %Y at %X.')) document.add_paragraph() # Spacing document.add_paragraph( f"Grey text has less than {int(threshold_for_grey * 100)}% confidence." ) # Stats dictionary stats = { 'timestamps': [], 'accuracy': [], '9.8': 0, '9': 0, '8': 0, '7': 0, '6': 0, '5': 0, '4': 0, '3': 0, '2': 0, '1': 0, '0': 0, 'total': len(data['results']['items']) } # Confidence count click.echo('Producing stats...') for item in data['results']['items']: if item['type'] == 'pronunciation': stats['timestamps'].append(float(item['start_time'])) stats['accuracy'].append( int(float(item['alternatives'][0]['confidence']) * 100)) if float(item['alternatives'][0]['confidence']) >= 0.98: stats['9.8'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.9: stats['9'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.8: stats['8'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.7: stats['7'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.6: stats['6'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.5: stats['5'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.4: stats['4'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.3: stats['3'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.2: stats['2'] += 1 elif float(item['alternatives'][0]['confidence']) >= 0.1: stats['1'] += 1 else: stats['0'] += 1 # Display confidence count table table = document.add_table(rows=1, cols=3) table.style = document.styles['Light List Accent 1'] table.alignment = WD_ALIGN_PARAGRAPH.CENTER hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Confidence' hdr_cells[1].text = 'Count' hdr_cells[2].text = 'Percentage' row_cells = table.add_row().cells row_cells[0].text = str('98% - 100%') row_cells[1].text = str(stats['9.8']) row_cells[2].text = str(round(stats['9.8'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('90% - 97%') row_cells[1].text = str(stats['9']) row_cells[2].text = str(round(stats['9'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('80% - 89%') row_cells[1].text = str(stats['8']) row_cells[2].text = str(round(stats['8'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('70% - 79%') row_cells[1].text = str(stats['7']) row_cells[2].text = str(round(stats['7'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('60% - 69%') row_cells[1].text = str(stats['6']) row_cells[2].text = str(round(stats['6'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('50% - 59%') row_cells[1].text = str(stats['5']) row_cells[2].text = str(round(stats['5'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('40% - 49%') row_cells[1].text = str(stats['4']) row_cells[2].text = str(round(stats['4'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('30% - 39%') row_cells[1].text = str(stats['3']) row_cells[2].text = str(round(stats['3'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('20% - 29%') row_cells[1].text = str(stats['2']) row_cells[2].text = str(round(stats['2'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('10% - 19%') row_cells[1].text = str(stats['1']) row_cells[2].text = str(round(stats['1'] / stats['total'] * 100, 2)) + '%' row_cells = table.add_row().cells row_cells[0].text = str('0% - 9%') row_cells[1].text = str(stats['0']) row_cells[2].text = str(round(stats['0'] / stats['total'] * 100, 2)) + '%' # Add paragraph for spacing document.add_paragraph() # Display scatter graph of confidence # Confidence of each word as scatter graph plt.scatter(stats['timestamps'], stats['accuracy']) # Mean average as line across graph plt.plot([stats['timestamps'][0], stats['timestamps'][-1]], [ statistics.mean(stats['accuracy']), statistics.mean(stats['accuracy']) ], 'r') # Formatting plt.xlabel('Time (seconds)') # plt.xticks(range(0, int(stats['timestamps'][-1]), 60)) plt.ylabel('Accuracy (percent)') plt.yticks(range(0, 101, 10)) plt.title('Accuracy during video') plt.legend(['Accuracy average (mean)', 'Individual words'], loc='lower center') plt.savefig('chart.png') document.add_picture('chart.png', width=Cm(14.64)) document.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER document.add_page_break() # Process and display transcript by speaker segments click.echo('Writing transcript...') table = document.add_table(rows=1, cols=3) table.style = document.styles['Light List Accent 1'] hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Time' hdr_cells[1].text = 'Speaker' hdr_cells[2].text = 'Content' with click.progressbar( data['results']['speaker_labels']['segments']) as bar: for segment in bar: # If there is content in the segment if len(segment['items']) > 0: # Add a row, write the time and speaker row_cells = table.add_row().cells row_cells[0].text = convert_time_stamp(segment['start_time']) row_cells[1].text = str(segment['speaker_label']) # Segments group individual word results by speaker. They are cross-referenced by time. # For each word in the segment... for word in segment['items']: # Run through the word results and get the corresponding result for result in data['results']['items']: if result['type'] == 'pronunciation': if result['start_time'] == word['start_time']: # Get the word with the highest confidence if len(result['alternatives']) > 0: current_word = dict() confidence_scores = [] for score in result['alternatives']: confidence_scores.append( score['confidence']) for alternative in result['alternatives']: if alternative['confidence'] == max( confidence_scores): current_word = alternative.copy() # Write and format the word run = row_cells[2].paragraphs[0].add_run( ' ' + current_word['content']) if float(current_word['confidence'] ) < threshold_for_grey: font = run.font font.color.rgb = RGBColor( 204, 204, 204) # If the next item is punctuation, add it try: if data['results']['items'][ data['results']['items'].index( result) + 1]['type'] == 'punctuation': run = row_cells[2].paragraphs[ 0].add_run( data['results']['items'] [data['results'] ['items'].index(result) + 1]['alternatives'][0] ['content']) # Occasional IndexErrors encountered except: pass # Formatting transcript table widthds click.echo('Formatting...') widths = (Inches(0.6), Inches(1), Inches(4.5)) with click.progressbar(table.rows) as bar: for row in bar: for idx, width in enumerate(widths): row.cells[idx].width = width # Save the file document_title = f"{data['jobName']}.docx" document.save(document_title) click.echo(f"{document_title} saved.") if log: # Logging logs = boto3.client( 'logs' ) # this might throw exception if we don't have `aws configure` def write_log(log_text): log_info = logs.describe_log_streams(logGroupName=log[0], logStreamNamePrefix=log[1]) log_time = int(datetime.datetime.now().timestamp() * 1000) response = logs.put_log_events( logGroupName=log[0], logStreamName=log[1], logEvents=[ { 'timestamp': log_time, 'message': log_text }, ], sequenceToken=log_info['logStreams'][0]['uploadSequenceToken']) job_finish = datetime.datetime.now() job_duration = job_finish - job_start write_log( f"Job name: {data['jobName']}, Word count: {stats['total']}, Accuracy average: {round(statistics.mean(stats['accuracy']), 2)}, Job duration: {job_duration.seconds}" ) click.echo(f"{data['jobName']} logged.")
driver.get("https://www.menalite.com/menaitech/application/hrms/index.php") driver.maximize_window() driver.save_screenshot('nos.jpg') username = driver.find_element_by_xpath('//*[@id="userid"]') username.screenshot('nos1.jpg') from docx import Document from docx.shared import Inches, Pt from docx.enum.text import WD_ALIGN_PARAGRAPH from datetime import date from docx.shared import RGBColor today = date.today() d4 = today.strftime("%b-%d-%Y") document = Document() p = document.add_paragraph() p.alignment = WD_ALIGN_PARAGRAPH.CENTER title = p.add_run("Test case 1") title.bold = True title.font.size = Pt(16) d = document.add_paragraph() title1 = d.add_run(d4) title1.bold = True title1.font.size = Pt(12) title1.font.color.rgb = RGBColor(128, 0, 0) document.add_picture('nos.jpg', width=Inches(7)) #p = document.add_paragraph() #p.add_run("titel") document.add_paragraph("yala bena") document.add_picture('nos.jpg', width=Inches(7)) document.save('my_report.docx')
def write_docx(instructor, sample_docx, dir_name): document = Document(sample_docx) outer_table = document.tables[0] inner_table = outer_table.cell(0, 1).tables[0] pic_file_name = instructor["照片"][instructor["照片"].rfind("/") + 1:] for i in range(2, 6): try: response = urllib.request.urlopen(instructor["照片"], timeout=10) f = open(pic_file_name, "w+b") f.write(response.read()) f.close() break except Exception as e: print(e, "获取头像超时, 尝试第" + str(i) + "次连接: " + instructor["照片"]) paragraph = outer_table.rows[0].cells[0].paragraphs[0] run = paragraph.add_run() if os.path.exists(pic_file_name) == True: # run.add_picture(temp_pic_file, width=Cm(4.2), height=Cm(6.2)) # 窄边框使用 try: run.add_picture(pic_file_name, width=Cm(4.0), height=Cm(5.7)) # 厚边框使用 os.remove(pic_file_name) except Exception as e: run.add_picture("default.gif", width=Cm(4.0), height=Cm(5.7)) # 厚边框使用 else: # run.add_picture(temp_pic_file, width=Cm(4.2), height=Cm(6.2)) # 窄边框使用 run.add_picture("default.gif", width=Cm(4.0), height=Cm(5.7)) # 厚边框使用 inner_table.cell(0, 1).text = instructor["导师代码"] inner_table.cell(1, 1).text = instructor["导师姓名"] inner_table.cell(2, 1).text = instructor["性别"] inner_table.cell(3, 1).text = instructor["出生年月"] inner_table.cell( 4, 1).text = instructor["特称"] if (len(instructor["特称"])) != 0 else "未介绍" inner_table.cell( 5, 1).text = instructor["职称"] if (len(instructor["职称"])) != 0 else "未介绍" inner_table.cell( 6, 1).text = instructor["学位"] if (len(instructor["学位"])) != 0 else "未介绍" inner_table.cell( 7, 1).text = instructor["属性"] if (len(instructor["属性"])) != 0 else "未介绍" inner_table.cell(8, 1).text = instructor["电子邮件"] inner_table.cell(9, 1).text = instructor["学院"] inner_table.cell(10, 1).text = instructor["网页地址"] paragraphs = [p for p in document.paragraphs] # 添加导师姓名在最开头并且是一级标题 run = paragraphs[0].add_run() font = run.font run.add_text(instructor["导师姓名"]) font.color.rgb = RGBColor(255, 0, 0) # 分别添加导师的每一项信息 for i in range(len(paragraphs)): if paragraphs[i].text == "个人简介": document.paragraphs[i + 1].text = instructor["个人简介"] if len( instructor["个人简介"]) != 0 else "未介绍" elif paragraphs[i].text == "学术经历": document.paragraphs[i + 1].text = instructor["学术经历"] if len( instructor["学术经历"]) != 0 else "未介绍" elif paragraphs[i].text == "科研项目": document.paragraphs[i + 1].text = instructor["科研项目"] if len( instructor["科研项目"]) != 0 else "未介绍" elif paragraphs[i].text == "发表文章": if len(instructor["发表文章"]) <= 500: document.paragraphs[i + 1].text = instructor["发表文章"] if len( instructor["发表文章"]) != 0 else "未介绍" else: document.paragraphs[ i + 1].text = "该导师发表文章项内容超级长, 为了不影响参阅, 详见请打开导师介绍页面" elif paragraphs[i].text == "博士招生专业": document.paragraphs[i + 1].text = gen_speciality_str( instructor["博士招生专业"]) elif paragraphs[i].text == "硕士招生专业": document.paragraphs[i + 1].text = gen_speciality_str( instructor["硕士招生专业"]) document.add_page_break() document.save(dir_name + "/" + "[" + instructor["导师代码"] + "]" + instructor["导师姓名"] + ".docx")
def make_text_red(cell: int, current, old) -> None: for paragraph in cell.paragraphs: for run in paragraph.runs: if current != old: run.font.color.rgb = RGBColor(255, 0, 0)
section = doc3.sections[0] new_width, new_height = section.page_height, section.page_width section.orientation = WD_ORIENT.LANDSCAPE section.page_width = new_width section.page_height = new_height # 2 - blue, 4 - bright green, 5 - dark_blue, 6 - dark red, 7 - dark yellow # 8 - gray, 10 - green, 11 -pink, 12 - red, 13- teal, 14- turquoise, 15- violet #141414 - black, FF0000 - red, F3FF69 - yellow, FFACB7 - pink, 808000- mehendi, 6897BB - blue FONT_MAP = { 0: { 'size': Pt(10), 'highlight': WD_COLOR_INDEX.BRIGHT_GREEN, 'color': RGBColor.from_string('141414') }, 1: { 'size': Pt(10), 'highlight': WD_COLOR_INDEX.PINK, 'color': RGBColor.from_string('141414') }, 2: { 'size': Pt(10), 'highlight': WD_COLOR_INDEX.RED, 'color': RGBColor.from_string('141414') }, 3: { 'size': Pt(10), 'highlight': WD_COLOR_INDEX.TURQUOISE, 'color': RGBColor.from_string('141414')
def generate_report_or_attachments(mission_id, zip_attachments=False): ''' Generates the report docx or attachments zip. :param mission_id: The id of the mission :param zip_attachments: True to return a zip of attachments, False to get the docx report as an IOStream :return: Returns StringIO if returning a report, a zip object otherwise ''' system_classification = DARTDynamicSettings.objects.get_as_object( ).system_classification system_classification_verbose = system_classification.verbose_legend system_classification_short = system_classification.short_legend mission = Mission.objects.get(id=mission_id) tests = TestSortingHelper.get_ordered_testdetails( mission_id=mission_id, reportable_tests_only=True) # Set some values we'll use throughout this section total_reportable_tests = len(tests) total_tests_with_findings = TestDetail.objects.filter( mission=mission, has_findings=True).count() total_tests_without_findings = TestDetail.objects.filter( mission=mission, has_findings=False).count() LIGHTEST_PERMISSIBLE_CLASSIFICATION_LABEL_COLOR = 0xbbbbbb DARKEN_OVERLY_LIGHT_CLASSIFICATION_LABEL_COLOR_BY = 0x444444 mission_data_dir = None report_has_attachments = False def replace_document_slugs(doc): """Cycle through the runs in each paragraph in the template & replace handlebar slugs""" logger.debug('> replace_document_slugs') handlebar_slugs = { r'{{AREA}}': str(mission.business_area), r'{{MISSION}}': str(mission.mission_name), r'{{GENERATION_DATE}}': now().strftime('%x'), r'{{TOTAL_TESTS}}': str(total_reportable_tests), r'{{TESTS_WITH_FINDINGS}}': str(total_tests_with_findings), r'{{TESTS_WITHOUT_FINDINGS}}': str(total_tests_without_findings), } for p in doc.paragraphs: for r in p.runs: for pattern in handlebar_slugs.keys(): if re.search(pattern, r.text): logger.debug('>> Replaced: {old} With: {new}'.format( old=r.text.encode('utf-8'), new=handlebar_slugs[pattern].encode('utf-8'))) r.text = re.sub(pattern, handlebar_slugs[pattern], r.text) def get_or_create_mission_data_dir(mission_data_dir): if mission_data_dir is None: mission_data_dir = os.path.join( settings.BASE_DIR, 'SUPPORTING_DATA_PACKAGE', str(mission.id) + "_" + str(now().strftime('%Y%m%d-%H%M%S'))) if not os.path.isdir(mission_data_dir): os.makedirs(mission_data_dir) return mission_data_dir def add_to_data_dir(mission_data_dir, test_case_number, supporting_data): # If test case directory path is not created, create it path = os.path.join(mission_data_dir, str(test_case_number)) # Shouldn't have race condition issues, but may need to add # try/catch if so later on if not os.path.isdir(path): os.makedirs(path) # Copy file to destination path shutil.copy( os.path.join(settings.MEDIA_ROOT, supporting_data.filename()), path) def prepend_classification(text): return '(' + system_classification_short + ') ' + text def portion_mark_and_insert(paragraphs, document): for paragraph in normalize_newlines(paragraphs).split('\n'): if len(paragraph) > 0: document.add_paragraph(prepend_classification(paragraph)) # Load the template file to get the styles document = Document(settings.REPORT_TEMPLATE_PATH) # Get the table templates table_no_findings = document.tables[0] table_with_findings = document.tables[1] data_table = document.tables[2] # Set the classification legend color from the background color of the banner classification_style = document.styles['Table Classification'] classification_font = classification_style.font # RGBColor doesn't handle shorthand hex codes, so let's just go ahead and expand it # if we come across a legacy or "misguided" entry if len(system_classification.background_color.hex_color_code) == 3: new_hex_code = '' for char in system_classification.background_color.hex_color_code: new_hex_code += char + char system_classification.background_color.hex_color_code = new_hex_code system_classification.background_color.save() if len(system_classification.text_color.hex_color_code) == 3: new_hex_code = '' for char in system_classification.text_color.hex_color_code: new_hex_code += char + char system_classification.text_color.hex_color_code = new_hex_code system_classification.text_color.save() classification_font.color.rgb = RGBColor.from_string( system_classification.get_report_label_color().hex_color_code) # Intro H1 and text document.add_heading('Introduction', level=1) portion_mark_and_insert(mission.introduction, document) # Scope H1 and text document.add_heading('Scope', level=1) portion_mark_and_insert(mission.scope, document) # Objectives H1 and text document.add_heading('Objectives', level=1) portion_mark_and_insert(mission.objectives, document) # Exec Summary H1 and text document.add_heading('Executive Summary', level=1) portion_mark_and_insert(mission.executive_summary, document) # Technical Assessment / Attack Architecture and text H1 document.add_heading('Technical Assessment / Attack Architecture', level=1) portion_mark_and_insert(mission.technical_assessment_overview, document) # Technical Assessment / Test Cases and Results and loop document.add_heading('Technical Assessment / Test Cases and Results', level=1) # For each test, Test # - Objective Attack Phase: H2 """ Note: If a test case is hidden from the report, the test_case number and the auto-generated paragraph number in Word won't align and it could cause confusion. The team may need to discuss how they want to handle this situation. """ """ WARNING Hidden test cases are NOT numbered in the report so the customer doesn't think something was accidentally left out. This will result in test case numbering differing between report and web when one or more test cases are hidden from the report. """ test_case_number = 0 tests_with_findings = 0 tests_without_findings = 0 # Let's just always craete a mission data dir when zipping attachments on report generation; this way # mission attachments will always return a zip file... it just may be empty - located here to account for times # when Get Attachments is actuated, but there are no test cases yet. if zip_attachments: mission_data_dir = get_or_create_mission_data_dir(mission_data_dir) for t in tests: if test_case_number > 0: document.add_page_break() test_case_number += 1 if t.has_findings: test_title = "*" tests_with_findings += 1 else: test_title = "" tests_without_findings += 1 if t.enclave: test_title += "(%s) %s" % (t.enclave, t.test_objective) else: test_title += "%s" % (t.test_objective, ) document.add_heading(test_title, level=2) # Duplicate one of the pre-made tables; if this is the last of a specific type of # test case (findings / no findings), use the cut operation to remove the blank # table. #TODO: convert to logging: print("T w/ F: {0}\nTotal: {1}\nT w/o F: {2}\nTotal: {3}".format(tests_with_findings, total_tests_with_findings, tests_without_findings, total_tests_without_findings)) is_last_test_case = True if test_case_number == total_reportable_tests else False if t.has_findings: if tests_with_findings == total_tests_with_findings or is_last_test_case: table = copy_table(document, table_with_findings, cut=True) else: table = copy_table(document, table_with_findings, cut=False) else: if tests_without_findings == total_tests_without_findings or is_last_test_case: table = copy_table(document, table_no_findings, cut=True) else: table = copy_table(document, table_no_findings, cut=False) # Classification Marking - Top cell = table.cell(0, 0) get_cleared_paragraph(cell).text = system_classification_verbose # Classification Marking - Bottom cell = table.cell(16, 1) get_cleared_paragraph(cell).text = system_classification_verbose # Test Case Number (Table Header Row) cell = table.cell(1, 0) get_cleared_paragraph(cell).text = 'Test #{0}'.format(test_case_number) row_number = 0 # # Test Case Title (Table Header Row) # row_number += 1 cell = table.cell(row_number, 1) get_cleared_paragraph(cell).text = t.test_objective # # Attack Phase / Type # row_number += 1 include_attack_phase = False include_attack_type = False if mission.attack_phase_include_flag \ and t.attack_phase_include_flag \ and len(t.get_attack_phase_display())> 0: include_attack_phase = True if mission.attack_type_include_flag \ and t.attack_type_include_flag \ and len(t.attack_type) > 0: include_attack_type = True left_cell = table.cell(row_number, 0) right_cell = table.cell(row_number, 1) if include_attack_phase or include_attack_type: if include_attack_phase and include_attack_type: # Table text in column 1 assumes both items are included already right_cell.text = ' - '.join( [t.get_attack_phase_display(), t.attack_type]) elif include_attack_phase: get_cleared_paragraph(left_cell).text = "Attack Phase:" right_cell.text = t.get_attack_phase_display() elif include_attack_type: get_cleared_paragraph(left_cell).text = "Attack Type:" right_cell.text = t.attack_type else: logger.debug('Removing Attack Phase/Type Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Assumptions # row_number += 1 if mission.assumptions_include_flag and t.assumptions_include_flag: cell = table.cell(row_number, 1) cell.text = standardize_report_output_field(t.assumptions) else: logger.debug('Removing Assumptions Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Description # row_number += 1 if mission.test_description_include_flag and t.test_description_include_flag: cell = table.cell(row_number, 1) cell.text = standardize_report_output_field(t.test_description) else: logger.debug('Removing Description Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Findings # row_number += 1 if mission.findings_include_flag and t.findings_include_flag: cell = table.cell(row_number, 1) cell.text = standardize_report_output_field(t.findings) else: logger.debug('Removing Findings Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Mitigations # row_number += 1 if mission.mitigation_include_flag and t.mitigation_include_flag: cell = table.cell(row_number, 1) cell.text = standardize_report_output_field(t.mitigation) else: logger.debug('Removing Mitigations Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Tools # row_number += 1 if mission.tools_used_include_flag and t.tools_used_include_flag: cell = table.cell(row_number, 1) cell.text = standardize_report_output_field(t.tools_used) else: logger.debug('Removing Tools Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Commands / Syntax # row_number += 1 if mission.command_syntax_include_flag and t.command_syntax_include_flag: cell = get_cleared_paragraph(table.cell(row_number, 1)) cell.style = 'Normal-LeftAlign' cell.text = standardize_report_output_field(t.command_syntax) else: logger.debug('Removing Commands/Syntax Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Targets # row_number += 1 if mission.targets_include_flag and t.targets_include_flag: cell = table.cell(row_number, 1) cell.text = '\n'.join([str(x) for x in t.target_hosts.all()]) else: logger.debug('Removing Targets Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Sources # row_number += 1 if mission.sources_include_flag and t.sources_include_flag: cell = table.cell(row_number, 1) cell.text = '\n'.join([str(x) for x in t.source_hosts.all()]) else: logger.debug('Removing Sources Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Date / Time # row_number += 1 if mission.attack_time_date_include_flag and t.attack_time_date_include_flag: cell = table.cell(row_number, 1) cell.text = localtime( t.attack_time_date).strftime('%b %d, %Y @ %I:%M %p') else: logger.debug('Removing Date/Time Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Side Effects # row_number += 1 if mission.attack_side_effects_include_flag and t.attack_side_effects_include_flag: cell = table.cell(row_number, 1) cell.text = standardize_report_output_field(t.attack_side_effects) else: logger.debug('Removing Side Effects Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Details # row_number += 1 if mission.test_result_observation_include_flag and t.test_result_observation_include_flag: cell = table.cell(row_number, 1) cell.text = standardize_report_output_field( t.test_result_observation) else: logger.debug('Removing Details Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Supporting Data # row_number += 1 supporting_data_cell = None supporting_data_row = None if mission.supporting_data_include_flag: supporting_data_cell = table.cell(row_number, 1) supporting_data_row = table.rows[row_number] else: logger.debug('Removing Supporting Data Row') remove_row(table, table.rows[row_number]) row_number -= 1 # # Notes - Used for post report generation notes / customer use # row_number += 1 if False: #TODO: add mission-level toggle logger.debug('Removing Customer Notes Row') remove_row(table, table.rows[row_number]) row_number -= 1 # Attachments section supporting_data_cell_items = [] if mission.supporting_data_include_flag: my_data = SupportingData.objects.filter( test_detail_id=t.id).filter(include_flag=True) if len(my_data) > 0: is_first_screenshot = True for d in my_data: allowed_image_types = [ 'gif', 'tiff', 'jpeg', 'bmp', 'png', ] try: file_path = os.path.join(settings.MEDIA_ROOT, d.filename()) logger.debug( '>> Beginning processing of {} at {}.'.format( d.filename(), file_path, )) if imghdr.what(file_path) not in allowed_image_types: raise UnrecognizedImageError( 'File type is not in the allowed image types. ' 'Handling as non-image.') if is_first_screenshot: document.add_heading('Screenshots / Diagrams', level=3) logger.debug( 'This is the first screenshot of this test case.' ) is_first_screenshot = False image_table = copy_table(document, data_table) logger.debug('Creating a new image table.') document.add_paragraph() # Classification Marking - Top cell = image_table.cell(0, 0) get_cleared_paragraph( cell).text = system_classification_verbose # Classification Marking - Bottom cell = image_table.cell(2, 0) get_cleared_paragraph( cell).text = system_classification_verbose content_cell = image_table.cell(1, 0) get_cleared_paragraph( content_cell).add_run().add_picture( d.test_file, width=Inches(5)) content_cell.paragraphs[0].add_run("\r" + d.caption) except UnrecognizedImageError as e: logger.debug( '>> Attachment {attachment_name} not recognized as an image; adding as file.' .format(attachment_name=d.filename())) supporting_data_cell_items.append( '- {filename}: {caption}'.format( filename=d.filename(), caption=d.caption, )) if zip_attachments: add_to_data_dir(mission_data_dir, test_case_number, d) except (InvalidImageStreamError, UnexpectedEndOfFileError) as e: logger.warning( '>> Attempting to add {file_name} to the report output resulted in an error: ' '\n{trace}'.format(file_name=d.filename, trace=traceback.format_exc(10))) except OSError as e: logger.warning( '>> Attempting to add {file_name} to the report output resulted in an error: ' '\n{trace}'.format(file_name=d.filename, trace=traceback.format_exc(10))) try: if not d.test_file.closed: d.test_file.close() except IOError as e: logger.warning( '>> Attempting to close {file_name} resulted in an error: ' '\n{trace}'.format( file_name=d.filename, trace=traceback.format_exc(10))) pass if len(supporting_data_cell_items) > 0: logger.debug( 'There are {} data cell items for TC {}.'.format( len(supporting_data_cell_items), t.id)) get_cleared_paragraph( supporting_data_cell).text = '\n'.join( supporting_data_cell_items) if len(supporting_data_cell_items) == 0: logger.debug( 'There are no supporting_data_cell_items; removing the supporting data row.' ) remove_row(table, supporting_data_row) # Conclusion H1 and text document.add_heading('Conclusion', level=1) portion_mark_and_insert(mission.conclusion, document) data_table.cell(0, 0).text = "" get_cleared_paragraph( data_table.cell(1, 0) ).text = "This table is used during report generation and can be deleted in the final report output." data_table.cell(2, 0).text = "" # Replace document slugs replace_document_slugs(document) if zip_attachments: zip_file = shutil.make_archive(mission_data_dir, 'zip', mission_data_dir) with open(mission_data_dir + '.zip', 'rb') as f: return io.BytesIO(f.read()) else: my_stream = StringIO() document.save(my_stream) return my_stream
def get_para_object(count, label, body, word_list, par, name): run = par.add_run("{}, Label: {}".format(count, str(label))) run.font.size = Pt(7) run.font.bold = True run.font.underline = True run.font.all_caps = True # run.font.outline = True if label >= 4: # run.font.highlight_color = WD_COLOR_INDEX.RED run.font.color.rgb = RGBColor.from_string('FF0000') elif label == 3: # run.font.highlight_color = WD_COLOR_INDEX.YELLOW run.font.color.rgb = RGBColor.from_string('808000') elif label < 3: # run.font.highlight_color = WD_COLOR_INDEX.BRIGHT_GREEN run.font.color.rgb = RGBColor.from_string('6897BB') run.add_break(WD_BREAK.LINE) body = ' '.join(body.split()) if type(name) != type(' '): names = [] else: names = name.split(";") # print (names) for word in word_list: f = word.split()[0] s = word.split()[1] if len(f) <= 3 and len(s) <= 3: word_list.remove(word) h_body = get_highlighted_body(body, word_list) h_body = unify_phrases(h_body) # print (h_body) r = re.compile('HSTART_') fragments = r.split(h_body) # par = doc.add_paragraph() second = fragments[0] done = False for n in names: if n in second: name_ind = second.lower().index(n.lower()) run = par.add_run(second[:name_ind]) run.font.size = Pt(6) run = par.add_run(second[name_ind:name_ind + len(n)]) run.font.size = Pt(9) run.font.italic = True run.font.underline = True run = par.add_run(second[name_ind + len(n):]) run.font.size = Pt(6) done = True break if not done: run = par.add_run(fragments[0]) run.font.size = Pt(6) # run.font.size = Pt(6) for ind, f in enumerate(fragments[1:]): first = f.split('HEND')[0] second = f.split('HEND')[1] # count = int(first[0]) count = int(first[0]) first = first[1:] run = par.add_run(first) font_map_obj = FONT_MAP[count] run.font.size = Pt(8) run.font.highlight_color = font_map_obj['highlight'] run.font.color.rgb = font_map_obj['color'] done = False if second: for n in names: if n in second: name_ind = second.lower().index(n.lower()) run = par.add_run(second[:name_ind]) run.font.size = Pt(6) run = par.add_run(second[name_ind:name_ind + len(n)]) run.font.size = Pt(9) run.font.italic = True run.font.underline = True run = par.add_run(second[name_ind + len(n):]) run.font.size = Pt(6) done = True break if not done: run = par.add_run(second) run.font.size = Pt(6) return par
if text[s:e][1] == 's': bold = 'b' elif text[s:e][1] == 'f': fontcode = text[s:e].replace('<font color="', '').replace('">', '') if fontcode[0] == '#': txtfont = color(fontcode.upper().ljust(7, '0')) else: txtfont = colour(fontcode) else: lines = text[s:e].replace('<', '').replace('>', '') paragraph = document.add_paragraph().add_run(lines) font = paragraph.font if bold == 'b': font.bold = True if txtfont != []: txtcolor = font.color txtcolor.rgb = RGBColor(txtfont[0], txtfont[1], txtfont[2]) bold = '' txtfont = [] # Move forward in text for the next search pos = e - 1 time.sleep(10) document.save('demo.docx') print("Done!")
def then_font_color_rgb_is_value(context, value): font = context.font expected_value = None if value == 'None' else RGBColor.from_string(value) assert font.color.rgb == expected_value
def rgb_get_fixture(self, request): r_cxml, rgb = request.param color_format = ColorFormat(element(r_cxml)) expected_value = None if rgb is None else RGBColor.from_string(rgb) return color_format, expected_value
# font.size = Pt(36) # Each Document object provides access to its CoreProperties object via its core_properties attribute. # About CoreProperties objects: https://python-docx.readthedocs.org/en/latest/api/document.html#id1 document.core_properties.author = 'author' document.core_properties.comments = 'comments' # document.add_heading('Document Title', 0) p = document.add_paragraph('A plain paragraph having some ') p.add_run('bold').bold = True p.add_run(' and some ') p.add_run('italic.').italic = True # About RGBColor objects: https://python-docx.readthedocs.org/en/latest/api/shared.html#rgbcolor-objects p.add_run('\n天蓝色').font.color.rgb = RGBColor(0x87, 0xCE, 0xEB) # 天蓝色 p.add_run('WHITE').font.color.rgb = RGBColor.from_string('FFFFFF') # white p.add_run('RED').font.color.rgb = RGBColor.from_string('FF0000') # red p.add_run('BLUE').font.color.rgb = RGBColor.from_string('0000FF') # blue p.add_run('BLACK').font.color.rgb = RGBColor.from_string('000000') # black # 紫色:800080 天蓝色:87CEEB 黄色:FFFF00 # 白色: FFFFFF 红色: FF0000 蓝色: 0000FF 黑色: 000000 # More: http://www.360doc.com/content/12/0219/22/19147_187921920.shtml # add pic, original size picname = 'pic.png' if os.path.exists(picname): p.add_run('\nCode: ').font.color.rgb = RGBColor.from_string('0000FF') # blue # See: http://stackoverflow.com/questions/26617218/python-docx-add-picture-size-wont-print-as-shown-on-screen # document.add_picture('pic.png', width=Inches(4.9)) im = Image.open(picname) width, height = im.size