implemented offline cache

This commit is contained in:
2026-01-02 17:36:24 -07:00
parent 6dc8672dd8
commit d29ba781ba
9 changed files with 407 additions and 148 deletions

View File

@@ -31,6 +31,7 @@ class JournalPromptGenerator:
self.config_path = config_path
self.client = None
self.historic_prompts = []
self.pool_prompts = []
self.prompt_template = ""
self.settings = {}
@@ -41,6 +42,7 @@ class JournalPromptGenerator:
# Load data files
self._load_prompt_template()
self._load_historic_prompts()
self._load_pool_prompts()
def _load_config(self):
"""Load configuration from environment file."""
@@ -145,6 +147,106 @@ class JournalPromptGenerator:
with open("historic_prompts.json", "w") as f:
json.dump(self.historic_prompts, f, indent=2)
def _load_pool_prompts(self):
"""Load pool prompts from JSON file."""
try:
with open("pool_prompts.json", "r") as f:
self.pool_prompts = json.load(f)
except FileNotFoundError:
self.console.print("[yellow]Warning: pool_prompts.json not found, starting with empty pool[/yellow]")
self.pool_prompts = []
except json.JSONDecodeError:
self.console.print("[yellow]Warning: pool_prompts.json is corrupted, starting with empty pool[/yellow]")
self.pool_prompts = []
def _save_pool_prompts(self):
"""Save pool prompts to JSON file."""
with open("pool_prompts.json", "w") as f:
json.dump(self.pool_prompts, f, indent=2)
def add_prompts_to_pool(self, prompts: List[Dict[str, str]]):
"""Add generated prompts to the pool."""
for prompt_dict in prompts:
# Extract prompt text
prompt_key = list(prompt_dict.keys())[0]
prompt_text = prompt_dict[prompt_key]
# Add to pool with a pool-specific key
pool_key = f"poolprompt{len(self.pool_prompts):03d}"
self.pool_prompts.append({
pool_key: prompt_text
})
self._save_pool_prompts()
self.console.print(f"[green]Added {len(prompts)} prompts to pool[/green]")
def draw_prompts_from_pool(self, count: int = None) -> List[Dict[str, str]]:
"""Draw prompts from the pool (removes them from pool)."""
if count is None:
count = self.settings['num_prompts']
if len(self.pool_prompts) < count:
self.console.print(f"[yellow]Warning: Pool only has {len(self.pool_prompts)} prompts, requested {count}[/yellow]")
count = len(self.pool_prompts)
if count == 0:
self.console.print("[red]Error: Pool is empty[/red]")
return []
# Draw prompts from the beginning of the pool
drawn_prompts = self.pool_prompts[:count]
self.pool_prompts = self.pool_prompts[count:]
# Save updated pool
self._save_pool_prompts()
# Renumber remaining pool prompts
self._renumber_pool_prompts()
return drawn_prompts
def _renumber_pool_prompts(self):
"""Renumber pool prompts to maintain sequential numbering."""
renumbered_prompts = []
for i, prompt_dict in enumerate(self.pool_prompts):
# Get the prompt text from the first key in the dictionary
prompt_key = list(prompt_dict.keys())[0]
prompt_text = prompt_dict[prompt_key]
# Create new prompt with correct numbering
new_prompt_key = f"poolprompt{i:03d}"
renumbered_prompts.append({
new_prompt_key: prompt_text
})
self.pool_prompts = renumbered_prompts
def show_pool_stats(self):
"""Show statistics about the prompt pool."""
total_prompts = len(self.pool_prompts)
table = Table(title="Prompt Pool Statistics")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="green")
table.add_row("Prompts in pool", str(total_prompts))
table.add_row("Prompts per session", str(self.settings['num_prompts']))
# Get cached_pool_volume from settings if available
cached_pool_volume = 20 # Default
try:
config = configparser.ConfigParser()
config.read('settings.cfg')
if 'prefetch' in config and 'cached_pool_volume' in config['prefetch']:
cached_pool_volume = int(config['prefetch']['cached_pool_volume'])
except:
pass
table.add_row("Target pool size", str(cached_pool_volume))
table.add_row("Available sessions", str(total_prompts // self.settings['num_prompts']))
self.console.print(table)
def _renumber_prompts(self):
"""Renumber all prompts to maintain prompt00-prompt59 range."""
renumbered_prompts = []
@@ -277,6 +379,9 @@ class JournalPromptGenerator:
except Exception as e:
self.console.print(f"[red]Error calling AI API: {e}[/red]")
self.console.print(f"[yellow]Full response content for debugging:[/yellow]")
self.console.print(f"[yellow]{response_content}[/yellow]")
return []
# Parse the response
@@ -337,27 +442,30 @@ class JournalPromptGenerator:
while True:
self.console.print("\n[bold]Options:[/bold]")
self.console.print("1. Generate new prompts")
self.console.print("2. View history statistics")
self.console.print("3. Exit")
self.console.print("1. Draw prompts from pool (no API call)")
self.console.print("2. Fill prompt pool using API")
self.console.print("3. View pool statistics")
self.console.print("4. View history statistics")
self.console.print("5. Exit")
choice = Prompt.ask("\nEnter your choice", choices=["1", "2", "3"], default="1")
choice = Prompt.ask("\nEnter your choice", choices=["1", "2", "3", "4", "5"], default="1")
if choice == "1":
new_prompts = self.generate_prompts()
if new_prompts:
self.display_prompts(new_prompts)
# Draw prompts from pool
drawn_prompts = self.draw_prompts_from_pool()
if drawn_prompts:
self.display_prompts(drawn_prompts)
# Ask if user wants to save a prompt
if Confirm.ask("\nWould you like to save one of these prompts to a file?"):
prompt_num = Prompt.ask(
"Which prompt number would you like to save?",
choices=[str(i) for i in range(1, len(new_prompts) + 1)],
choices=[str(i) for i in range(1, len(drawn_prompts) + 1)],
default="1"
)
prompt_idx = int(prompt_num) - 1
prompt_dict = new_prompts[prompt_idx]
prompt_dict = drawn_prompts[prompt_idx]
prompt_key = list(prompt_dict.keys())[0]
prompt_text = prompt_dict[prompt_key]
@@ -379,9 +487,19 @@ class JournalPromptGenerator:
self.console.print(f"[green]Prompt added to history as prompt00[/green]")
elif choice == "2":
self.show_history_stats()
# Fill prompt pool using API
new_prompts = self.generate_prompts()
if new_prompts:
self.add_prompts_to_pool(new_prompts)
self.console.print(f"[green]Added {len(new_prompts)} prompts to pool[/green]")
elif choice == "3":
self.show_pool_stats()
elif choice == "4":
self.show_history_stats()
elif choice == "5":
self.console.print("[green]Goodbye! Happy journaling! 📓[/green]")
break
@@ -404,6 +522,16 @@ def main():
action="store_true",
help="Show history statistics"
)
parser.add_argument(
"--pool-stats", "-p",
action="store_true",
help="Show pool statistics"
)
parser.add_argument(
"--fill-pool", "-f",
action="store_true",
help="Fill prompt pool using API"
)
args = parser.parse_args()
@@ -412,13 +540,22 @@ def main():
if args.stats:
generator.show_history_stats()
elif args.pool_stats:
generator.show_pool_stats()
elif args.fill_pool:
# Fill prompt pool using API
new_prompts = generator.generate_prompts()
if new_prompts:
generator.add_prompts_to_pool(new_prompts)
generator.console.print(f"[green]Added {len(new_prompts)} prompts to pool[/green]")
elif args.interactive:
generator.interactive_mode()
else:
# Default: generate and display prompts
new_prompts = generator.generate_prompts()
if new_prompts:
generator.display_prompts(new_prompts)
# Default: draw prompts from pool (no API call)
drawn_prompts = generator.draw_prompts_from_pool()
if drawn_prompts:
generator.display_prompts(drawn_prompts)
generator.console.print("[yellow]Note: These prompts were drawn from the pool. Use --fill-pool to add more prompts.[/yellow]")
if __name__ == "__main__":