enhance-this 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 hariharen9
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.4
2
+ Name: enhance-this
3
+ Version: 0.1.0
4
+ Summary: A CLI tool to enhance prompts using Ollama AI.
5
+ Author-email: Your Name <you@example.com>
6
+ Project-URL: Homepage, https://github.com/your-username/enhance-this
7
+ Project-URL: Bug Tracker, https://github.com/your-username/enhance-this/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: click>=8.0.0
15
+ Requires-Dist: requests>=2.25.0
16
+ Requires-Dist: pyyaml>=6.0
17
+ Requires-Dist: pyperclip>=1.8.0
18
+ Requires-Dist: rich>=10.0.0
19
+ Requires-Dist: importlib-resources; python_version < "3.9"
20
+ Dynamic: license-file
21
+
22
+ # enhance-this ✨
23
+
24
+ [![PyPI - Version](https://img.shields.io/pypi/v/enhance-this?style=for-the-badge)](https://pypi.org/project/enhance-this/)
25
+ [![npm - Version](https://img.shields.io/npm/v/enhance-this?style=for-the-badge)](https://www.npmjs.com/package/enhance-this)
26
+ [![Homebrew - Version](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fformulae.brew.sh%2Fapi%2Fformula%2Fenhance-this.json&query=%24.versions.stable&label=homebrew&style=for-the-badge)](https://formulae.brew.sh/formula/enhance-this)
27
+ [![License](https://img.shields.io/github/license/hariharen9/enhance-this?style=for-the-badge)](LICENSE)
28
+
29
+ **`enhance-this`** is a powerful, fast, and reliable CLI tool designed to elevate your prompts. It takes a simple idea, enhances it using local Ollama AI models, and delivers a comprehensive, structured prompt ready to generate superior AI responses. The enhanced prompt is streamed directly to your terminal and automatically copied to your clipboard for immediate use.
30
+
31
+ ## 🚀 Overview
32
+
33
+ The core mission of `enhance-this` is to bridge the gap between a simple user query and a high-quality, detailed prompt that AI models can understand and act upon effectively. By leveraging a sophisticated and customizable templating system, the power of local language models via Ollama, and a rich terminal interface, it transforms basic inputs into professional-grade prompts.
34
+
35
+ ## ✨ Features
36
+
37
+ - **Live Streaming Output**: Get instant feedback as the enhanced prompt is generated token by token, providing a dynamic user experience.
38
+ - **Powerful Prompt Enhancement**: Utilizes a system of style-based templates (`detailed`, `concise`, `creative`, `technical`) to convert simple prompts into comprehensive, actionable ones.
39
+ - **Fully Customizable Templates**: Extend the tool with your own unique enhancement styles by simply adding paths to your custom template files in `config.yaml`.
40
+ - **Diff View**: Use the `--diff` flag to see a clear, color-coded comparison between your original prompt and the enhanced version, highlighting the changes.
41
+ - **Full Ollama Integration**: Seamlessly connects to your local Ollama instance (`http://localhost:11434`) to manage and interact with AI models directly on your machine.
42
+ - **Intelligent Model Management**:
43
+ - Automatically detects if the Ollama service is running.
44
+ - Lists all available local models with `enhance --list-models`.
45
+ - Auto-selects an optimal model if one is not specified.
46
+ - Features resilient retry logic for network requests, ensuring robust communication.
47
+ - **Automatic Setup**: A simple `enhance --auto-setup` command downloads a recommended model (e.g., `llama3.1:8b`) if no models are found locally, with intelligent fallbacks.
48
+ - **Rich Terminal UI**: Employs the `rich` library for beautiful, color-coded output, elegant markdown rendering, and informative progress bars during operations.
49
+ - **Cross-Platform Clipboard**: Automatically copies the final enhanced prompt to your system's clipboard, ready for pasting into your AI interface. Works seamlessly across macOS, Linux, and Windows.
50
+ - **Highly Configurable**: Control everything from the Ollama host and default styles to temperature and maximum token length via a simple YAML configuration file.
51
+ - **Robust Testing**: Includes a comprehensive testing suite covering unit, integration, and end-to-end scenarios to ensure reliability and correctness.
52
+
53
+ ## 📦 Installation
54
+
55
+ `enhance-this` is designed for easy installation across multiple platforms.
56
+
57
+ **PyPI (Python Package Index)**
58
+
59
+ ```bash
60
+ pip install enhance-this
61
+ ```
62
+
63
+ **NPM (Node.js Package Manager)**
64
+
65
+ ```bash
66
+ npm install -g enhance-this
67
+ ```
68
+
69
+ **Homebrew (macOS & Linux)**
70
+
71
+ ```bash
72
+ brew install hariharen9/tap/enhance-this
73
+ ```
74
+
75
+ **For Local Development**
76
+
77
+ If you want to contribute or develop locally, clone the repository and install in editable mode:
78
+
79
+ ```bash
80
+ git clone https://github.com/hariharen9/enhance-this.git
81
+ cd enhance-this
82
+ pip install -e .
83
+ ```
84
+
85
+ ## 💡 Usage
86
+
87
+ First, ensure you have [Ollama](https://ollama.com/) installed and running. If you don't have any models downloaded, run:
88
+
89
+ ```bash
90
+ enhance --auto-setup
91
+ ```
92
+
93
+ Then, you can start enhancing your prompts:
94
+
95
+ **Basic Enhancement:**
96
+
97
+ ```bash
98
+ enhance "write a blog post about AI"
99
+ ```
100
+
101
+ **Using the Diff View:**
102
+
103
+ ```bash
104
+ enhance "review my code" --diff
105
+ ```
106
+
107
+ **Using a Custom Style:**
108
+
109
+ (First, define your custom style in `~/.enhance-this/config.yaml`)
110
+
111
+ ```bash
112
+ enhance "a logo for a coffee shop" -s my-logo-style
113
+ ```
114
+
115
+ ### Command-Line Options
116
+
117
+ | Option | Short | Description |
118
+ |---|---|---|
119
+ | `<prompt>` | | The initial prompt to enhance. |
120
+ | `--model <MODEL>` | `-m` | Ollama model to use. |
121
+ | `--temperature <T>` | `-t` | Temperature for generation (0.0-2.0). |
122
+ | `--length <LENGTH>` | `-l` | Max tokens for the enhanced prompt. |
123
+ | `--style <STYLE>` | `-s` | Enhancement style (e.g., `detailed`, `creative`). |
124
+ | `--diff` | | Show a diff between the original and enhanced prompt. |
125
+ | `--output <FILE>` | `-o` | Save the enhanced prompt to a file. |
126
+ | `--no-copy` | `-n` | Disable automatic copying to the clipboard. |
127
+ | `--verbose` | `-v` | Enable verbose output. |
128
+ | `--list-models` | | List all available Ollama models. |
129
+ | `--download-model <MODEL>`| | Download a specific model from Ollama. |
130
+ | `--auto-setup` | | Automatically download a recommended model. |
131
+ | `--version` | | Show the application version. |
132
+ | `--help` | `-h` | Show the help message. |
133
+
134
+ ## 🧪 Testing
135
+
136
+ The project includes a comprehensive test suite to ensure reliability and correctness.
137
+
138
+ **Running Tests Locally**
139
+
140
+ To run all tests, navigate to the project root and execute:
141
+
142
+ ```bash
143
+ pytest tests/
144
+ ```
145
+
146
+ **Test Strategy**
147
+
148
+ - **Unit Tests**: Verify individual functions and components in isolation.
149
+ - **Integration Tests**: Ensure different modules and external services (like Ollama, with proper mocking or live checks) work together correctly.
150
+ - **End-to-End Tests**: Simulate real-world usage scenarios through the CLI to confirm the entire workflow functions as expected.
151
+
152
+ ## 📚 Documentation
153
+
154
+ - **[Configuration Guide](./docs/CONFIGURATION.md)**: Learn how to customize every aspect of the tool, including setting up custom templates.
155
+ - **[Troubleshooting Guide](./docs/TROUBLESHOOTING.md)**: Find solutions to common problems and error messages.
156
+ - **[Examples](./examples)**: Explore more real-world usage examples and prompt enhancement scenarios.
157
+
158
+ ## 🤝 Contributing
159
+
160
+ Contributions are welcome! Please feel free to open issues, submit pull requests, or suggest new features. See the [CONTRIBUTING.md](CONTRIBUTING.md) (coming soon) for more details.
161
+
162
+ ## 📄 License
163
+
164
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
165
+
166
+ ---
167
+ *This README was generated and enhanced by Gemini based on the project's development specification and implemented features.*
@@ -0,0 +1,146 @@
1
+ # enhance-this ✨
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/enhance-this?style=for-the-badge)](https://pypi.org/project/enhance-this/)
4
+ [![npm - Version](https://img.shields.io/npm/v/enhance-this?style=for-the-badge)](https://www.npmjs.com/package/enhance-this)
5
+ [![Homebrew - Version](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fformulae.brew.sh%2Fapi%2Fformula%2Fenhance-this.json&query=%24.versions.stable&label=homebrew&style=for-the-badge)](https://formulae.brew.sh/formula/enhance-this)
6
+ [![License](https://img.shields.io/github/license/hariharen9/enhance-this?style=for-the-badge)](LICENSE)
7
+
8
+ **`enhance-this`** is a powerful, fast, and reliable CLI tool designed to elevate your prompts. It takes a simple idea, enhances it using local Ollama AI models, and delivers a comprehensive, structured prompt ready to generate superior AI responses. The enhanced prompt is streamed directly to your terminal and automatically copied to your clipboard for immediate use.
9
+
10
+ ## 🚀 Overview
11
+
12
+ The core mission of `enhance-this` is to bridge the gap between a simple user query and a high-quality, detailed prompt that AI models can understand and act upon effectively. By leveraging a sophisticated and customizable templating system, the power of local language models via Ollama, and a rich terminal interface, it transforms basic inputs into professional-grade prompts.
13
+
14
+ ## ✨ Features
15
+
16
+ - **Live Streaming Output**: Get instant feedback as the enhanced prompt is generated token by token, providing a dynamic user experience.
17
+ - **Powerful Prompt Enhancement**: Utilizes a system of style-based templates (`detailed`, `concise`, `creative`, `technical`) to convert simple prompts into comprehensive, actionable ones.
18
+ - **Fully Customizable Templates**: Extend the tool with your own unique enhancement styles by simply adding paths to your custom template files in `config.yaml`.
19
+ - **Diff View**: Use the `--diff` flag to see a clear, color-coded comparison between your original prompt and the enhanced version, highlighting the changes.
20
+ - **Full Ollama Integration**: Seamlessly connects to your local Ollama instance (`http://localhost:11434`) to manage and interact with AI models directly on your machine.
21
+ - **Intelligent Model Management**:
22
+ - Automatically detects if the Ollama service is running.
23
+ - Lists all available local models with `enhance --list-models`.
24
+ - Auto-selects an optimal model if one is not specified.
25
+ - Features resilient retry logic for network requests, ensuring robust communication.
26
+ - **Automatic Setup**: A simple `enhance --auto-setup` command downloads a recommended model (e.g., `llama3.1:8b`) if no models are found locally, with intelligent fallbacks.
27
+ - **Rich Terminal UI**: Employs the `rich` library for beautiful, color-coded output, elegant markdown rendering, and informative progress bars during operations.
28
+ - **Cross-Platform Clipboard**: Automatically copies the final enhanced prompt to your system's clipboard, ready for pasting into your AI interface. Works seamlessly across macOS, Linux, and Windows.
29
+ - **Highly Configurable**: Control everything from the Ollama host and default styles to temperature and maximum token length via a simple YAML configuration file.
30
+ - **Robust Testing**: Includes a comprehensive testing suite covering unit, integration, and end-to-end scenarios to ensure reliability and correctness.
31
+
32
+ ## 📦 Installation
33
+
34
+ `enhance-this` is designed for easy installation across multiple platforms.
35
+
36
+ **PyPI (Python Package Index)**
37
+
38
+ ```bash
39
+ pip install enhance-this
40
+ ```
41
+
42
+ **NPM (Node.js Package Manager)**
43
+
44
+ ```bash
45
+ npm install -g enhance-this
46
+ ```
47
+
48
+ **Homebrew (macOS & Linux)**
49
+
50
+ ```bash
51
+ brew install hariharen9/tap/enhance-this
52
+ ```
53
+
54
+ **For Local Development**
55
+
56
+ If you want to contribute or develop locally, clone the repository and install in editable mode:
57
+
58
+ ```bash
59
+ git clone https://github.com/hariharen9/enhance-this.git
60
+ cd enhance-this
61
+ pip install -e .
62
+ ```
63
+
64
+ ## 💡 Usage
65
+
66
+ First, ensure you have [Ollama](https://ollama.com/) installed and running. If you don't have any models downloaded, run:
67
+
68
+ ```bash
69
+ enhance --auto-setup
70
+ ```
71
+
72
+ Then, you can start enhancing your prompts:
73
+
74
+ **Basic Enhancement:**
75
+
76
+ ```bash
77
+ enhance "write a blog post about AI"
78
+ ```
79
+
80
+ **Using the Diff View:**
81
+
82
+ ```bash
83
+ enhance "review my code" --diff
84
+ ```
85
+
86
+ **Using a Custom Style:**
87
+
88
+ (First, define your custom style in `~/.enhance-this/config.yaml`)
89
+
90
+ ```bash
91
+ enhance "a logo for a coffee shop" -s my-logo-style
92
+ ```
93
+
94
+ ### Command-Line Options
95
+
96
+ | Option | Short | Description |
97
+ |---|---|---|
98
+ | `<prompt>` | | The initial prompt to enhance. |
99
+ | `--model <MODEL>` | `-m` | Ollama model to use. |
100
+ | `--temperature <T>` | `-t` | Temperature for generation (0.0-2.0). |
101
+ | `--length <LENGTH>` | `-l` | Max tokens for the enhanced prompt. |
102
+ | `--style <STYLE>` | `-s` | Enhancement style (e.g., `detailed`, `creative`). |
103
+ | `--diff` | | Show a diff between the original and enhanced prompt. |
104
+ | `--output <FILE>` | `-o` | Save the enhanced prompt to a file. |
105
+ | `--no-copy` | `-n` | Disable automatic copying to the clipboard. |
106
+ | `--verbose` | `-v` | Enable verbose output. |
107
+ | `--list-models` | | List all available Ollama models. |
108
+ | `--download-model <MODEL>`| | Download a specific model from Ollama. |
109
+ | `--auto-setup` | | Automatically download a recommended model. |
110
+ | `--version` | | Show the application version. |
111
+ | `--help` | `-h` | Show the help message. |
112
+
113
+ ## 🧪 Testing
114
+
115
+ The project includes a comprehensive test suite to ensure reliability and correctness.
116
+
117
+ **Running Tests Locally**
118
+
119
+ To run all tests, navigate to the project root and execute:
120
+
121
+ ```bash
122
+ pytest tests/
123
+ ```
124
+
125
+ **Test Strategy**
126
+
127
+ - **Unit Tests**: Verify individual functions and components in isolation.
128
+ - **Integration Tests**: Ensure different modules and external services (like Ollama, with proper mocking or live checks) work together correctly.
129
+ - **End-to-End Tests**: Simulate real-world usage scenarios through the CLI to confirm the entire workflow functions as expected.
130
+
131
+ ## 📚 Documentation
132
+
133
+ - **[Configuration Guide](./docs/CONFIGURATION.md)**: Learn how to customize every aspect of the tool, including setting up custom templates.
134
+ - **[Troubleshooting Guide](./docs/TROUBLESHOOTING.md)**: Find solutions to common problems and error messages.
135
+ - **[Examples](./examples)**: Explore more real-world usage examples and prompt enhancement scenarios.
136
+
137
+ ## 🤝 Contributing
138
+
139
+ Contributions are welcome! Please feel free to open issues, submit pull requests, or suggest new features. See the [CONTRIBUTING.md](CONTRIBUTING.md) (coming soon) for more details.
140
+
141
+ ## 📄 License
142
+
143
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
144
+
145
+ ---
146
+ *This README was generated and enhanced by Gemini based on the project's development specification and implemented features.*
File without changes
@@ -0,0 +1,174 @@
1
+ import click
2
+ from rich.console import Console
3
+ from rich.markdown import Markdown
4
+ from rich.panel import Panel
5
+ from rich.live import Live
6
+ import sys
7
+ import difflib
8
+
9
+ from .config import load_config, create_default_config_if_not_exists
10
+ from .ollama_client import OllamaClient
11
+ from .enhancer import PromptEnhancer
12
+ from .clipboard import copy_to_clipboard
13
+
14
+ @click.command()
15
+ @click.argument('prompt', required=False)
16
+ @click.option('-m', '--model', 'model_name', help='Ollama model to use (auto-selects optimal if not specified)')
17
+ @click.option('-t', '--temperature', type=click.FloatRange(0.0, 2.0), help='Temperature for generation (0.0-2.0)')
18
+ @click.option('-l', '--length', 'max_tokens', type=int, help='Max tokens for enhancement')
19
+ @click.option('-c', '--config', 'config_path', type=click.Path(), help='Configuration file path')
20
+ @click.option('-v', '--verbose', is_flag=True, help='Enable verbose output')
21
+ @click.option('-n', '--no-copy', is_flag=True, help="Don't copy to clipboard")
22
+ @click.option('-o', '--output', 'output_file', type=click.File('w'), help='Save enhanced prompt to file')
23
+ @click.option('-s', '--style', type=click.Choice(['detailed', 'concise', 'creative', 'technical']), help='Enhancement style')
24
+ @click.option('--diff', is_flag=True, help='Show a diff between the original and enhanced prompt')
25
+ @click.option('--list-models', is_flag=True, help='List available Ollama models')
26
+ @click.option('--download-model', 'download_model_name', help='Download specific model from Ollama')
27
+ @click.option('--auto-setup', is_flag=True, help='Automatically setup Ollama with optimal model')
28
+ @click.option('--version', is_flag=True, help='Show version information')
29
+ @click.help_option('-h', '--help')
30
+ def main(prompt, model_name, temperature, max_tokens, config_path, verbose, no_copy, output_file, style, diff, list_models, download_model_name, auto_setup, version):
31
+ """
32
+ Enhances a simple prompt using Ollama AI models, displays the enhanced version,
33
+ and automatically copies it to the clipboard.
34
+ """
35
+ if version:
36
+ from importlib.metadata import version as get_version
37
+ pkg_version = get_version("enhance-this")
38
+ click.echo(f"enhance-this version {pkg_version}")
39
+ return
40
+
41
+ create_default_config_if_not_exists()
42
+ config = load_config(config_path)
43
+
44
+ console = Console()
45
+ client = OllamaClient(host=config['ollama_host'], timeout=config['timeout'])
46
+
47
+ if not client.is_running():
48
+ console.print("[red]✖[/red] Ollama service is not running or is unreachable.")
49
+ console.print("Please start Ollama and try again.")
50
+ sys.exit(1)
51
+
52
+ if list_models:
53
+ models = client.list_models()
54
+ if models:
55
+ console.print("[bold green]Available Ollama models:[/bold green]")
56
+ for model in models:
57
+ console.print(f"- {model}")
58
+ else:
59
+ console.print("[yellow]No Ollama models found.[/yellow]")
60
+ return
61
+
62
+ if download_model_name:
63
+ console.print(f"Starting download for '{download_model_name}'...")
64
+ client.download_model(download_model_name)
65
+ return
66
+
67
+ available_models = client.list_models()
68
+
69
+ if auto_setup or not available_models:
70
+ if not available_models:
71
+ console.print("[yellow]No models found. Starting auto-setup.[/yellow]")
72
+ else:
73
+ console.print("Starting auto-setup...")
74
+
75
+ recommended_models = ["llama3.1:8b", "llama3", "mistral"]
76
+ for model_to_try in recommended_models:
77
+ if model_to_try not in available_models:
78
+ console.print(f"Downloading recommended model: {model_to_try}")
79
+ if client.download_model(model_to_try):
80
+ available_models.append(model_to_try)
81
+ break
82
+ else:
83
+ console.print(f"Recommended model '{model_to_try}' is already available.")
84
+ break
85
+ else:
86
+ console.print("[red]✖[/red] Auto-setup failed. Could not download a recommended model.")
87
+ sys.exit(1)
88
+
89
+ if auto_setup:
90
+ return
91
+
92
+ if not prompt:
93
+ ctx = click.get_current_context()
94
+ click.echo(ctx.get_help())
95
+ ctx.exit()
96
+
97
+ if model_name:
98
+ if model_name not in available_models:
99
+ console.print(f"[red]✖[/red] Model '{model_name}' not found. Available models:")
100
+ for model in available_models:
101
+ console.print(f"- {model}")
102
+ sys.exit(1)
103
+ final_model = model_name
104
+ else:
105
+ if not available_models:
106
+ console.print("[red]✖[/red] No models available. Please download a model first, e.g.:")
107
+ console.print("`enhance --download-model llama3.1:8b` or run `enhance --auto-setup`")
108
+ sys.exit(1)
109
+ final_model = available_models[0]
110
+ if verbose:
111
+ console.print(f"No model specified. Using first available model: [cyan]{final_model}[/cyan]")
112
+
113
+ final_style = style or config.get('default_style', 'detailed')
114
+ final_temperature = temperature if temperature is not None else config.get('default_temperature', 0.7)
115
+ final_max_tokens = max_tokens or config.get('max_tokens', 2000)
116
+ auto_copy_enabled = not no_copy and config.get('auto_copy', True)
117
+
118
+ enhancer = PromptEnhancer(config.get('enhancement_templates'))
119
+ system_prompt = enhancer.enhance(prompt, final_style)
120
+
121
+ if verbose:
122
+ console.print("\n[bold]System Prompt:[/bold]")
123
+ console.print(Panel(system_prompt, title="System Prompt", border_style="dim"))
124
+
125
+ enhanced_prompt = ""
126
+ console.print("\n[bold magenta]✨ Enhanced Prompt ✨[/bold magenta]")
127
+
128
+ status_obj = console.status("[bold green]Enhancing prompt...")
129
+ status_obj.start()
130
+
131
+ try:
132
+ stream_generator = client.generate_stream(final_model, system_prompt, final_temperature, final_max_tokens)
133
+
134
+ # Stop the status as soon as the generator is ready
135
+ status_obj.stop()
136
+
137
+ with Live(console=console, auto_refresh=False) as live:
138
+ for chunk in stream_generator:
139
+ enhanced_prompt += chunk
140
+ live.update(Markdown(enhanced_prompt), refresh=True)
141
+ finally:
142
+ status_obj.stop()
143
+
144
+ if enhanced_prompt:
145
+ if diff:
146
+ console.print("\n[bold yellow]↔️ Diff View ↔️[/bold yellow]")
147
+ diff_result = difflib.unified_diff(
148
+ prompt.splitlines(keepends=True),
149
+ enhanced_prompt.splitlines(keepends=True),
150
+ fromfile='Original',
151
+ tofile='Enhanced',
152
+ )
153
+ for line in diff_result:
154
+ if line.startswith('+'):
155
+ console.print(f"[green]{line}[/green]", end="")
156
+ elif line.startswith('-'):
157
+ console.print(f"[red]{line}[/red]", end="")
158
+ elif line.startswith('@'):
159
+ console.print(f"[dim]{line}[/dim]", end="")
160
+ else:
161
+ console.print(line, end="")
162
+
163
+ if output_file:
164
+ output_file.write(enhanced_prompt)
165
+ console.print(f"\n[green]✔[/green] Saved to {output_file.name}")
166
+
167
+ if auto_copy_enabled:
168
+ copy_to_clipboard(enhanced_prompt)
169
+ else:
170
+ console.print("\n[red]✖[/red] Failed to generate enhanced prompt.")
171
+ sys.exit(1)
172
+
173
+ if __name__ == '__main__':
174
+ main()
@@ -0,0 +1,12 @@
1
+ import pyperclip
2
+ from rich.console import Console
3
+
4
+ console = Console()
5
+
6
+ def copy_to_clipboard(text: str):
7
+ """Copies the given text to the clipboard."""
8
+ try:
9
+ pyperclip.copy(text)
10
+ console.print("[green]✔[/green] Enhanced prompt copied to clipboard.")
11
+ except pyperclip.PyperclipException:
12
+ console.print("[yellow]⚠[/yellow] Could not copy to clipboard. `xclip` or `xsel` may be required on Linux.")
@@ -0,0 +1,53 @@
1
+ import os
2
+ import yaml
3
+ from pathlib import Path
4
+ from typing import Dict, Any, Optional
5
+
6
+ DEFAULT_CONFIG = {
7
+ "default_temperature": 0.7,
8
+ "default_style": "detailed",
9
+ "ollama_host": "http://localhost:11434",
10
+ "timeout": 30,
11
+ "max_tokens": 2000,
12
+ "auto_copy": True,
13
+ "display_colors": True,
14
+ "auto_download_model": True,
15
+ "enhancement_templates": {},
16
+ }
17
+
18
+ def get_config_path(config_path_str: Optional[str] = None) -> Path:
19
+ if config_path_str:
20
+ return Path(config_path_str)
21
+ return Path.home() / ".enhance-this" / "config.yaml"
22
+
23
+ def load_config(config_path_str: Optional[str] = None) -> Dict[str, Any]:
24
+ config_path = get_config_path(config_path_str)
25
+ if not config_path.exists():
26
+ return DEFAULT_CONFIG
27
+
28
+ try:
29
+ with open(config_path, 'r') as f:
30
+ user_config = yaml.safe_load(f)
31
+
32
+ config = DEFAULT_CONFIG.copy()
33
+ if user_config:
34
+ config.update(user_config)
35
+ return config
36
+ except (yaml.YAMLError, IOError):
37
+ return DEFAULT_CONFIG
38
+
39
+ def ensure_config_dir_exists():
40
+ config_path = get_config_path()
41
+ config_path.parent.mkdir(parents=True, exist_ok=True)
42
+
43
+ def create_default_config_if_not_exists():
44
+ ensure_config_dir_exists()
45
+ config_path = get_config_path()
46
+ if not config_path.exists():
47
+ config_to_write = DEFAULT_CONFIG.copy()
48
+ # Example for user
49
+ config_to_write['enhancement_templates'] = {
50
+ 'my_style': '/path/to/your/custom_template.txt'
51
+ }
52
+ with open(config_path, 'w') as f:
53
+ yaml.dump(config_to_write, f, default_flow_style=False, sort_keys=False)
@@ -0,0 +1,58 @@
1
+ import importlib.resources
2
+ from typing import Dict, Optional
3
+ from pathlib import Path
4
+ from rich.console import Console
5
+
6
+ console = Console()
7
+
8
+ def load_templates(custom_template_paths: Optional[Dict[str, str]] = None) -> Dict[str, str]:
9
+ templates = {}
10
+ package = 'enhance_this.templates'
11
+
12
+ # Load built-in templates
13
+ try:
14
+ from importlib.resources import files
15
+ except ImportError:
16
+ from importlib_resources import files
17
+
18
+ try:
19
+ template_dir = files(package)
20
+ for style in ["detailed", "concise", "creative", "technical"]:
21
+ template_file = template_dir / f"{style}.txt"
22
+ if template_file.is_file():
23
+ templates[style] = template_file.read_text(encoding='utf-8')
24
+ except Exception:
25
+ for style in ["detailed", "concise", "creative", "technical"]:
26
+ try:
27
+ with importlib.resources.open_text(package, f"{style}.txt") as f:
28
+ templates[style] = f.read()
29
+ except FileNotFoundError:
30
+ pass
31
+
32
+ # Load custom templates from config
33
+ if custom_template_paths:
34
+ for style, path_str in custom_template_paths.items():
35
+ if not isinstance(path_str, str) or not path_str.strip():
36
+ continue # Skip if path is not a valid string
37
+ try:
38
+ path = Path(path_str).expanduser()
39
+ if path.is_file():
40
+ templates[style] = path.read_text(encoding='utf-8')
41
+ else:
42
+ console.print(f"[yellow]⚠[/yellow] Custom template for style '{style}' not found at: {path_str}")
43
+ except Exception as e:
44
+ console.print(f"[red]✖[/red] Error loading custom template for style '{style}': {e}")
45
+
46
+ return templates
47
+
48
+ class PromptEnhancer:
49
+ def __init__(self, custom_template_paths: Optional[Dict[str, str]] = None):
50
+ self.templates = load_templates(custom_template_paths)
51
+
52
+ def enhance(self, user_prompt: str, style: str) -> str:
53
+ if style not in self.templates:
54
+ available_styles = list(self.templates.keys())
55
+ raise ValueError(f"Unknown style: '{style}'. Available styles: {available_styles}")
56
+
57
+ template = self.templates[style]
58
+ return template.format(user_prompt=user_prompt)