lib/Business/LetterWriter.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package Business::LetterWriter;
2
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use OpenAPI::Client::OpenAI;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Archive::Zip;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 0 ▶use XML::Twig;
Subroutine BEGIN: called CC=1 SCAR=2.6
9
10 our $VERSION = '0.09';
11
12 sub get_one_answer_from_new_llm {
13 my ($request, $body_builder) = @_;
14
15 $body_builder //= sub {
16 return {
17 model => 'gpt-4o',
18 messages => [ { role => 'user', content => $request } ],
19 temperature => 0,
20 max_tokens => 1000,
21 };
22 };
23
24 my $client = OpenAPI::Client::OpenAI->new();
25 my $body = $body_builder->($request);
26 my $tx = $client->createChatCompletion({ body => $body });
27
28 my $response_data = $tx->res->json;
29 my $raw_response = $response_data->{choices}[0]{message}{content};
30 if ($raw_response =~ /({.*})/s) {
31 return $1;
32 }
33 die "Unexpected response format in get_one_answer_from_new_llm.\n";
34 }
35
36 sub get_hashref_from_template_file{
37 my $template_fname = shift;
38 open my $template_fh, "<:encoding(UTF-8)", $template_fname or die $!;
39 my $template = do{local $/; <$template_fh>};
40 my @arr = split /\n{2}/, $template;
41 my $counter = 1;
42 my %return_hash = ();
43 foreach my $para (@arr){
44 my $key = "paragraph_" . $counter++;
45 $return_hash{$key} = $para;
46 }
47 return \%return_hash;
48 }
49
50 sub out_parts{
51 my $text_hashref = shift;
52 my $parms = shift;
53 my $fn = $parms->{outfn};
54 my $preserved_parts = $parms->{preserved_parts};
55 open my $outfh, ">:encoding(UTF-8)", $fn or die $!;
56 foreach my $key (qw(paragraph_1 paragraph_2 paragraph_3 paragraph_4 paragraph_5 paragraph_6)){
57 print $outfh $text_hashref->{$key}, "\n\n";
58 # print $text_hashref->{$key}, "\n\n";
59 }
60 close $outfh;
61 }
62
63 sub signature{
64 return "John Doe";
65 }
66
67
68 sub replace_in_docx{
69 my $input_docx = shift;
70 my $output_docx = shift;
71 my $replacement_hashref = shift;
72 my $temp_dir = "docx_contents_simple";
73
74 # Step 1: Extract .docx contents
75 my $zip = Archive::Zip->new();
76 $zip->read($input_docx) == Archive::Zip::AZ_OK or die "Cannot read DOCX file";
77
78 mkdir $temp_dir unless -d $temp_dir;
79 $zip->extractTree('', "$temp_dir/");
80
81
82
83 # Step 2: Load and edit word/document.xml
84 my $xml_file = "$temp_dir/word/document.xml";
85 my $doc=XML::Twig->new(); # create the twig
86 $doc->parsefile( $xml_file); # build it
87
88 # my %replacement_hash = ('{Address1}' => 'Egasse 66', '{Address2}' => 'Bern 3044');
89 my %replacement_hash = %{$replacement_hashref};
90
91 # Step 3: Merge text and replace content
92 foreach my $p ($doc->findnodes('//w:p')) { # Process each paragraph
93 my @runs = $p->findnodes('.//w:t'); # Collect all text elements
94 my $full_text = join('', map { $_->text } @runs);
95
96 foreach my $placeholder (keys %replacement_hash) {
97 # my $replacement = decode("UTF-8", $full_replacement_hash{$placeholder});
98 # my $replacement = decode("UTF-8", $replacement_hash{$placeholder});
99 my $replacement = $replacement_hash{$placeholder};
100 $full_text =~ s/\{\Q$placeholder\E\}/$replacement/g;
101 }
102
103 # Update the XML: Replace text while keeping structure
104 if (@runs) {
105 $runs[0]->set_text($full_text);
106
107 # Remove extra <w:t> elements
108 for (my $i = 1; $i < @runs; $i++) {
109 $runs[$i]->delete();
110 }
111 }
112 }
113
114 # Save changes
115 open my $fh2, '>:utf8', $xml_file or die "Cannot write to XML file. $!" ;
116 print $fh2 $doc->toString(1);
117 close $fh2;
118
119 # Step 4: Repackage back into a .docx file
120 unlink $output_docx if -e $output_docx;
121 my $new_zip = Archive::Zip->new();
122 $new_zip->addTree($temp_dir, '');
123 $new_zip->writeToFileNamed($output_docx) == Archive::Zip::AZ_OK or die "Failed to create new DOCX file";
124
125 print "Editing complete. Output saved to $output_docx\n";
126
127 }
128
129 sub generate_meta_hashref_from_file{
130 my $input_fn = shift;
131 open my $fh, '<:utf8', $input_fn or die "Cannot open file: $!";
132 my %data;
133 while (<$fh>) {
134 chomp;
135 my ($key, $value) = split /:/, $_, 2;
136 next unless defined $key && defined $value;
137 $data{"$key"} = $value;
138 }
139 close $fh;
140 return \%data;
141 }
142
143 =pod
144 USAGE:
145 use strict;
146 use JSON;
147 use lib '../Business-LetterWriter/lib/';
148 use Business::LetterWriter;
149
150 my $template_href = Business::LetterWriter::get_hashref_from_template_file("./CL_TEMPLATE_DE.txt");
151
152 my $json = JSON->new->utf8(0)->pretty(1);
153 my $letter_template_json = $json->encode($template_href);
154
155 my $request
156 = "Here is a template letter in the JSON format: " . $letter_template_json .
157 " Tailor each part to make the whole letter friendier less formal and very short. Return the tailored version of the letter strictly in JSON format. Do not explain anything." ;
158 my $llm_answer_raw = Business::LetterWriter::get_one_answer_from_new_llm($request);
159 my $template_href = $json->decode($llm_answer_raw);
160 my %parms = (outfn => "outtest.txt");
161 Business::LetterWriter::out_parts($template_href, \%parms);
162
163 USAGE:
164 use strict;
165 use JSON;
166 use lib '../Business-LetterWriter/lib/';
167 use Business::LetterWriter;
168
169 my $template_href = Business::LetterWriter::get_hashref_from_template_file("./customer_req/LETTER_TEMPLATE_DE.txt");
170 my $json = JSON->new->utf8(0)->pretty(1);
171 my $letter_template_json = $json->encode($template_href);
172
173 my $customer_req_fn = "./customer_req/requirement_1.txt";
174 open my $customer_req_fh, "<:encoding(UTF-8)", $customer_req_fn;
175 my $customer_req_text = do{local $/; <$customer_req_fh>};
176
177 # binmode(STDOUT, ":encoding(UTF-8)"); # stdout is UTF-8
178 # print $customer_req;
179 # exit;
180
181 my $request
182 = "Here is a template letter in the JSON format: " . $letter_template_json .
183 "Here is requirement of the company: " . $customer_req_text .
184 " Tailor each part of the template letter to make the whole letter fit to the customer requirement. Return the tailored version of the letter strictly in JSON format. Do not explain anything." ;
185
186 my $llm_answer_raw = Business::LetterWriter::get_one_answer_from_new_llm($request);
187
188 my $template_href = $json->decode($llm_answer_raw);
189
190 # Business::LetterWriter::out_parts($template_href, {outfn => "TAILORED_VERSION.txt"});
191 my $metha_file_path_name = "./Customers/MyCustomer/META.txt";
192 my $address_hashref = Business::LetterWriter::generate_meta_hashref_from_file($metha_file_path_name);
193 my %combined_hash = ( %{$address_hashref} , %{$template_href});
194
195 Business::LetterWriter::replace_in_docx("template.docx", "./my_results.docx", \%combined_hash);
196 =cut
197
198 1;
↑ Summary