logdetective 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.1
2
+ Name: logdetective
3
+ Version: 0.2.0
4
+ Summary: Log using LLM AI to search for build/test failures and provide ideas for fixing these.
5
+ License: Apache-2.0
6
+ Author: Jiri Podivin
7
+ Author-email: jpodivin@gmail.com
8
+ Requires-Python: >=3.11,<4.0
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Natural Language :: English
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Internet :: Log Analysis
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Software Development :: Debuggers
20
+ Requires-Dist: drain3 (>=0.9.11,<0.10.0)
21
+ Requires-Dist: llama-cpp-python (>=0.2.56,<0.3.0)
22
+ Requires-Dist: progressbar2 (>=4.0.0,<5.0.0)
23
+ Requires-Dist: requests (>=2.31.0,<3.0.0)
24
+ Requires-Dist: tiktoken (>=0.6.0,<0.7.0)
25
+ Project-URL: homepage, https://github.com/fedora-copr/logdetective
26
+ Project-URL: issues, https://github.com/fedora-copr/logdetective/issues
27
+ Description-Content-Type: text/markdown
28
+
29
+ Log Detective
30
+ =============
31
+
32
+ A Python tool to analyze logs using a Language Model (LLM) and Drain template miner.
33
+
34
+ Installation
35
+ ------------
36
+
37
+ # optionaly when you prefer system packages
38
+ dnf install python3-jsonpickle python3-tiktoken
39
+ # install all remaining packages
40
+ pip install .
41
+
42
+ Usage
43
+ -----
44
+
45
+ To analyze a log file, run the script with the following command line arguments:
46
+ - `url` (required): The URL of the log file to be analyzed.
47
+ - `--model` (optional, default: "Mistral-7B-Instruct-v0.2-GGUF"): The path or URL of the language model for analysis.
48
+ - `--summarizer` (optional, default: "drain"): Choose between LLM and Drain template miner as the log summarizer. You can also provide the path to an existing language model file instead of using a URL.
49
+ - `--n_lines` (optional, default: 5): The number of lines per chunk for LLM analysis. This only makes sense when you are summarizing with LLM.
50
+
51
+ Example usage:
52
+
53
+ ~/.local/bin/logdetective https://example.com/logs.txt
54
+
55
+
56
+ Contributing
57
+ ------------
58
+
59
+ Contributions are welcome! Please submit a pull request if you have any improvements or new features to add. Make sure your changes pass all existing tests before submitting.
60
+
61
+ To develop logdetective, you should fork this repository, clone your fork, and install dependencies using pip:
62
+
63
+ git clone https://github.com/yourusername/logdetective.git
64
+ cd logdetective
65
+ pip install .
66
+
67
+ Make changes to the code as needed and run pre-commit.
68
+
69
+ Tests
70
+ -----
71
+
72
+ The [tox](https://github.com/tox-dev/tox) is used to manage tests. Please install `tox` package into your distribution and run:
73
+
74
+ tox
75
+
76
+ This will create a virtual environment with dependencies and run all the tests. For more information follow the tox help.
77
+
78
+ To run only a specific test execute this:
79
+
80
+ tox run -e style # to run flake8
81
+
82
+ or
83
+
84
+ tox run -e lint # to run pylint
85
+
86
+ License
87
+ -------
88
+
89
+ This project is licensed under the Apache-2.0 License - see the LICENSE file for details.
90
+
@@ -0,0 +1,61 @@
1
+ Log Detective
2
+ =============
3
+
4
+ A Python tool to analyze logs using a Language Model (LLM) and Drain template miner.
5
+
6
+ Installation
7
+ ------------
8
+
9
+ # optionaly when you prefer system packages
10
+ dnf install python3-jsonpickle python3-tiktoken
11
+ # install all remaining packages
12
+ pip install .
13
+
14
+ Usage
15
+ -----
16
+
17
+ To analyze a log file, run the script with the following command line arguments:
18
+ - `url` (required): The URL of the log file to be analyzed.
19
+ - `--model` (optional, default: "Mistral-7B-Instruct-v0.2-GGUF"): The path or URL of the language model for analysis.
20
+ - `--summarizer` (optional, default: "drain"): Choose between LLM and Drain template miner as the log summarizer. You can also provide the path to an existing language model file instead of using a URL.
21
+ - `--n_lines` (optional, default: 5): The number of lines per chunk for LLM analysis. This only makes sense when you are summarizing with LLM.
22
+
23
+ Example usage:
24
+
25
+ ~/.local/bin/logdetective https://example.com/logs.txt
26
+
27
+
28
+ Contributing
29
+ ------------
30
+
31
+ Contributions are welcome! Please submit a pull request if you have any improvements or new features to add. Make sure your changes pass all existing tests before submitting.
32
+
33
+ To develop logdetective, you should fork this repository, clone your fork, and install dependencies using pip:
34
+
35
+ git clone https://github.com/yourusername/logdetective.git
36
+ cd logdetective
37
+ pip install .
38
+
39
+ Make changes to the code as needed and run pre-commit.
40
+
41
+ Tests
42
+ -----
43
+
44
+ The [tox](https://github.com/tox-dev/tox) is used to manage tests. Please install `tox` package into your distribution and run:
45
+
46
+ tox
47
+
48
+ This will create a virtual environment with dependencies and run all the tests. For more information follow the tox help.
49
+
50
+ To run only a specific test execute this:
51
+
52
+ tox run -e style # to run flake8
53
+
54
+ or
55
+
56
+ tox run -e lint # to run pylint
57
+
58
+ License
59
+ -------
60
+
61
+ This project is licensed under the Apache-2.0 License - see the LICENSE file for details.
@@ -0,0 +1,32 @@
1
+ [SNAPSHOT]
2
+ snapshot_interval_minutes = 10
3
+ compress_state = True
4
+
5
+ [MASKING]
6
+ masking = [
7
+ {"regex_pattern":"((?<=[^A-Za-z0-9])|^)(([0-9a-f]{2,}:){3,}([0-9a-f]{2,}))((?=[^A-Za-z0-9])|$)", "mask_with": "ID"},
8
+ {"regex_pattern":"((?<=[^A-Za-z0-9])|^)(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})((?=[^A-Za-z0-9])|$)", "mask_with": "IP"},
9
+ {"regex_pattern":"((?<=[^A-Za-z0-9])|^)([0-9a-f]{6,} ?){3,}((?=[^A-Za-z0-9])|$)", "mask_with": "SEQ"},
10
+ {"regex_pattern":"((?<=[^A-Za-z0-9])|^)([0-9A-F]{4} ?){4,}((?=[^A-Za-z0-9])|$)", "mask_with": "SEQ"},
11
+ {"regex_pattern":"((?<=[^A-Za-z0-9])|^)(0x[a-f0-9A-F]+)((?=[^A-Za-z0-9])|$)", "mask_with": "HEX"},
12
+ {"regex_pattern":"((?<=[^A-Za-z0-9])|^)([\\-\\+]?\\d+)((?=[^A-Za-z0-9])|$)", "mask_with": "NUM"},
13
+ {"regex_pattern":"(?<=executed cmd )(\".+?\")", "mask_with": "CMD"},
14
+ {"regex_pattern":"/usr/bin/systemd-nspawn.*", "mask_with":"CMD"},
15
+ {"regex_pattern":"INFO: .*", "mask_with": "INFO"}
16
+ ]
17
+ mask_prefix = <:
18
+ mask_suffix = :>
19
+
20
+ [DRAIN]
21
+ # engine is Optional parameter. Engine will be "Drain" if the engine argument is not specified.
22
+ # engine has two options: 'Drain' and 'JaccardDrain'.
23
+ # engine = Drain
24
+ sim_th = 0.4
25
+ depth = 4
26
+ max_children = 10000
27
+ max_clusters = 16
28
+ extra_delimiters = ["_"]
29
+
30
+ [PROFILING]
31
+ enabled = False
32
+ report_sec = 30
@@ -0,0 +1,275 @@
1
+ import argparse
2
+ import logging
3
+ import os
4
+ import sys
5
+ from urllib.request import urlretrieve
6
+
7
+ import drain3
8
+ import numpy as np
9
+ import progressbar
10
+ import requests
11
+ from drain3.template_miner_config import TemplateMinerConfig
12
+ from llama_cpp import Llama, LlamaGrammar
13
+
14
+ # pylint: disable=line-too-long
15
+ DEFAULT_ADVISOR = "https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.2-GGUF/resolve/main/mistral-7b-instruct-v0.2.Q4_K_S.gguf?download=true"
16
+
17
+ # pylint: disable=line-too-long
18
+ DEFAULT_LLM_RATER = "https://huggingface.co/TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF/resolve/main/tinyllama-1.1b-chat-v1.0.Q4_K_S.gguf?download=true"
19
+
20
+ PROMPT_TEMPLATE = """
21
+ Given following log snippets, and nothing else, explain what failure, if any occured during build of this package.
22
+ Ignore strings wrapped in <: :>, such as <:*:>.
23
+
24
+ {}
25
+
26
+ Analysis of the failure must be in a format of [X] : [Y], where [X] is a log snippet, and [Y] is the explanation.
27
+
28
+ Finally, drawing on information from all snippets, provide complete explanation of the issue.
29
+
30
+ Analysis:
31
+
32
+ """
33
+
34
+ SUMMARIZE_PROPT_TEMPLATE = """
35
+ Does following log contain error or issue?
36
+
37
+ Log:
38
+
39
+ {}
40
+
41
+ Answer:
42
+
43
+ """
44
+
45
+ CACHE_LOC = "~/.cache/logdetective/"
46
+
47
+ LOG = logging.getLogger("logdetective")
48
+
49
+
50
+ class MyProgressBar():
51
+ """Show progress when downloading model."""
52
+ def __init__(self):
53
+ self.pbar = None
54
+
55
+ def __call__(self, block_num, block_size, total_size):
56
+ if not self.pbar:
57
+ self.pbar = progressbar.ProgressBar(maxval=total_size)
58
+ self.pbar.start()
59
+
60
+ downloaded = block_num * block_size
61
+ if downloaded < total_size:
62
+ self.pbar.update(downloaded)
63
+ else:
64
+ self.pbar.finish()
65
+
66
+
67
+ def chunk_continues(text: str, index: int) -> bool:
68
+ """Set of heuristics for determining whether or not
69
+ does the current chunk of log text continue on next line.
70
+ """
71
+ conditionals = [
72
+ lambda i, string: string[i + 1].isspace(),
73
+ lambda i, string: string[i - 1] == "\\"
74
+ ]
75
+
76
+ for c in conditionals:
77
+ y = c(index, text)
78
+ if y:
79
+ return True
80
+
81
+ return False
82
+
83
+
84
+ def get_chunks(text: str):
85
+ """Split log into chunks according to heuristic
86
+ based on whitespace and backslash presence.
87
+ """
88
+ text_len = len(text)
89
+ i = 0
90
+ chunk = ""
91
+ while i < text_len:
92
+ chunk += text[i]
93
+ if text[i] == '\n':
94
+ if i + 1 < text_len and chunk_continues(text, i):
95
+ i += 1
96
+ continue
97
+ yield chunk
98
+ chunk = ""
99
+ i += 1
100
+
101
+
102
+ class LLMExtractor:
103
+ """
104
+ A class that extracts relevant information from logs using a language model.
105
+ """
106
+ def __init__(self, model_path: str, verbose: bool):
107
+ self.model = Llama(
108
+ model_path=model_path,
109
+ n_ctx=0,
110
+ verbose=verbose)
111
+ self.grammar = LlamaGrammar.from_string(
112
+ "root ::= (\"Yes\" | \"No\")", verbose=False)
113
+
114
+ def __call__(self, log: str, n_lines: int = 2, neighbors: bool = False) -> str:
115
+ chunks = self.rate_chunks(log, n_lines)
116
+ out = self.create_extract(chunks, neighbors)
117
+ return out
118
+
119
+ def rate_chunks(self, log: str, n_lines: int = 2) -> list[tuple]:
120
+ """Scan log by the model and store results.
121
+
122
+ :param log: log file content
123
+ :param n_lines: How many lines should the model take into consideration
124
+ """
125
+ results = []
126
+ log_lines = log.split("\n")
127
+
128
+ for i in range(0, len(log_lines), n_lines):
129
+ block = '\n'.join(log_lines[i:i + n_lines])
130
+ prompt = SUMMARIZE_PROPT_TEMPLATE.format(log)
131
+ out = self.model(prompt, max_tokens=7, grammar=self.grammar)
132
+ out = f"{out['choices'][0]['text']}\n"
133
+ results.append((block, out))
134
+
135
+ return results
136
+
137
+ def create_extract(self, chunks: list[tuple], neighbors: bool = False) -> str:
138
+ """Extract interesting chunks from the model processing.
139
+ """
140
+ interesting = []
141
+ summary = ""
142
+ # pylint: disable=consider-using-enumerate
143
+ for i in range(len(chunks)):
144
+ if chunks[i][1].startswith("Yes"):
145
+ interesting.append(i)
146
+ if neighbors:
147
+ interesting.extend([max(i - 1, 0), min(i + 1, len(chunks) - 1)])
148
+
149
+ interesting = np.unique(interesting)
150
+
151
+ for i in interesting:
152
+ summary += chunks[i][0] + "\n"
153
+
154
+ return summary
155
+
156
+
157
+ class DrainExtractor:
158
+ """A class that extracts information from logs using a template miner algorithm.
159
+ """
160
+ def __init__(self, verbose: bool = False, context: bool = False):
161
+ config = TemplateMinerConfig()
162
+ config.load(f"{os.path.dirname(__file__)}/drain3.ini")
163
+ config.profiling_enabled = verbose
164
+ self.miner = drain3.TemplateMiner(config=config)
165
+ self.verbose = verbose
166
+ self.context = context
167
+
168
+ def __call__(self, log: str) -> str:
169
+ out = ""
170
+ for chunk in get_chunks(log):
171
+ procesed_line = self.miner.add_log_message(chunk)
172
+ LOG.debug(procesed_line)
173
+ sorted_clusters = sorted(self.miner.drain.clusters, key=lambda it: it.size, reverse=True)
174
+ for chunk in get_chunks(log):
175
+ cluster = self.miner.match(chunk, "always")
176
+ if cluster in sorted_clusters:
177
+ out += f"{chunk}\n"
178
+ sorted_clusters.remove(cluster)
179
+ return out
180
+
181
+
182
+ def download_model(url: str, verbose: bool = False) -> str:
183
+ """ Downloads a language model from a given URL and saves it to the cache directory.
184
+
185
+ Args:
186
+ url (str): The URL of the language model to be downloaded.
187
+
188
+ Returns:
189
+ str: The local file path of the downloaded language model.
190
+ """
191
+ path = os.path.join(
192
+ os.path.expanduser(CACHE_LOC), url.split('/')[-1])
193
+
194
+ LOG.info("Downloading model from %s to %s", url, path)
195
+ if not os.path.exists(path):
196
+ if verbose:
197
+ path, _status = urlretrieve(url, path, MyProgressBar())
198
+ else:
199
+ path, _status = urlretrieve(url, path)
200
+
201
+ return path
202
+
203
+
204
+ def process_log(log: str, model: Llama) -> str:
205
+ """
206
+ Processes a given log using the provided language model and returns its summary.
207
+
208
+ Args:
209
+ log (str): The input log to be processed.
210
+ model (Llama): The language model used for processing the log.
211
+
212
+ Returns:
213
+ str: The summary of the given log generated by the language model.
214
+ """
215
+ return model(PROMPT_TEMPLATE.format(log), max_tokens=0)["choices"][0]["text"]
216
+
217
+
218
+ def main():
219
+ """Main execution function."""
220
+ parser = argparse.ArgumentParser("logdetective")
221
+ parser.add_argument("url", type=str, default="")
222
+ parser.add_argument("-M", "--model", type=str, default=DEFAULT_ADVISOR)
223
+ parser.add_argument("-S", "--summarizer", type=str, default="drain")
224
+ parser.add_argument("-N", "--n_lines", type=int, default=5)
225
+ parser.add_argument("-v", "--verbose", action='count', default=0)
226
+ parser.add_argument("-q", "--quiet", action='store_true')
227
+
228
+ args = parser.parse_args()
229
+
230
+ if args.verbose and args.quiet:
231
+ sys.stderr.write("Error: --quiet and --verbose is mutually exclusive.\n")
232
+ sys.exit(2)
233
+ log_level = logging.INFO
234
+ if args.verbose >= 1:
235
+ log_level = logging.DEBUG
236
+ if args.quiet:
237
+ log_level = 0
238
+ logging.basicConfig(stream=sys.stdout)
239
+ LOG.setLevel(log_level)
240
+
241
+ if not os.path.exists(CACHE_LOC):
242
+ os.makedirs(os.path.expanduser(CACHE_LOC), exist_ok=True)
243
+
244
+ if not os.path.isfile(args.model):
245
+ model_pth = download_model(args.model, not args.quiet)
246
+ else:
247
+ model_pth = args.model
248
+
249
+ if args.summarizer == "drain":
250
+ extractor = DrainExtractor(args.verbose > 1, context=True)
251
+ elif os.path.isfile(args.summarizer):
252
+ extractor = LLMExtractor(args.summarizer, args.verbose > 1)
253
+ else:
254
+ summarizer_pth = download_model(args.summarizer, not args.quiet)
255
+ extractor = LLMExtractor(summarizer_pth, args.verbose > 1)
256
+
257
+ LOG.info("Getting summary")
258
+ model = Llama(
259
+ model_path=model_pth,
260
+ n_ctx=0,
261
+ verbose=args.verbose > 2)
262
+
263
+ log = requests.get(args.url, timeout=60).text
264
+ log_summary = extractor(log)
265
+
266
+ ratio = len(log_summary.split('\n')) / len(log.split('\n'))
267
+ LOG.debug("Log summary: \n %s", log_summary)
268
+ LOG.info("Compression ratio: %s", ratio)
269
+
270
+ LOG.info("Analyzing the text")
271
+ print(f"Explanation: \n{process_log(log_summary, model)}")
272
+
273
+
274
+ if __name__ == "__main__":
275
+ main()
@@ -0,0 +1,46 @@
1
+ [tool.poetry]
2
+ name = "logdetective"
3
+ version = "0.2.0"
4
+ description = "Log using LLM AI to search for build/test failures and provide ideas for fixing these."
5
+ authors = ["Jiri Podivin <jpodivin@gmail.com>"]
6
+ license = "Apache-2.0"
7
+ readme = "README.md"
8
+ include = ["logdetective/drain3.ini"]
9
+ classifiers = [
10
+ "Development Status :: 4 - Beta",
11
+ "Environment :: Console",
12
+ "Intended Audience :: Developers",
13
+ "License :: OSI Approved :: Apache Software License",
14
+ "Natural Language :: English",
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
17
+ "Topic :: Software Development :: Debuggers",
18
+ "Topic :: Internet :: Log Analysis"
19
+ ]
20
+
21
+ [tool.poetry.urls]
22
+ homepage = "https://github.com/fedora-copr/logdetective"
23
+ issues = "https://github.com/fedora-copr/logdetective/issues"
24
+
25
+ [tool.poetry.dependencies]
26
+ python = "^3.11"
27
+ requests = "^2.31.0"
28
+ llama-cpp-python = "^0.2.56"
29
+ tiktoken = "^0.6.0"
30
+ drain3 = "^0.9.11"
31
+ progressbar2 = "^4.0.0"
32
+
33
+ [build-system]
34
+ requires = ["poetry-core"]
35
+ build-backend = "poetry.core.masonry.api"
36
+
37
+ [tool.poetry.scripts]
38
+ logdetective = 'logdetective.logdetective:main'
39
+
40
+ [tool.pylint]
41
+ disable = [
42
+ "inconsistent-return-statements",
43
+ "missing-module-docstring",
44
+ "too-few-public-methods",
45
+ "unspecified-encoding",
46
+ ]