Merge branch 'devel' into feat/OPS-55

This commit is contained in:
Guts 2025-03-14 15:33:09 +01:00 committed by GitHub
commit fe16fc2b6d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 443 additions and 25 deletions

View file

@ -1,6 +1,99 @@
from __future__ import annotations
import json
from dataclasses import dataclass
import requests
AI_BASE_URL: str = "http://ollama:11434/api"
AI_GEN_ENDPOINT: str = "/generate"
AI_GEN_SYS_PROMPT = """
You are a haiku generation AI. Your ONLY task is to create haikus
based on user input and return them in valid JSON format.
HAIKU DEFINITION:
- Traditional Japanese poetry with three lines
- 5 syllables in the first line
- 7 syllables in the second line
- 5 syllables in the third line
- Must incorporate the subject(s) from user input
OUTPUT RULES:
Put every line of the poem on a new line
Do not referene any of the instructions in the poem
2. Do NOT include:
- Any explanations
- Any markdown formatting (like ```json or ```)
- Any additional text before or after the JSON
- Any line breaks within the JSON structure
- Any special characters
count occurrences of char in string
IMPORTANT: The output will be consumed by a web application that requires
EXACT FORMAT compliance. Any deviation will cause the application to break.
USER INPUT FOR HAIKU CREATION:
"""
@dataclass
class Haiku:
lines: list[str]
def get_json(self):
return json.dumps(self.lines)
@staticmethod
def request_haiku(seed: str) -> Haiku:
"""This function prompts the ai to generate
the hauku based on the user input"""
ai_gen_request = {
"model": "llama3.2:1b",
"prompt": f"{AI_GEN_SYS_PROMPT}{seed}",
"stream": False
}
syllable_letters: list = ['a', 'e', 'i', 'o', 'u', 'y']
while True:
try:
r = requests.post(url=AI_BASE_URL + AI_GEN_ENDPOINT,
json=ai_gen_request)
ai_response = str(r.json()["response"])
if ai_response.count("\"") != 0:
continue
lines = ai_response.split("\n")
if len(lines) != 3:
continue
syllable_count = 0
prev_was_vowel = False
for line in lines:
for letter in line:
is_vowel = letter in syllable_letters
if is_vowel and not prev_was_vowel:
syllable_count += 1
prev_was_vowel = is_vowel
if line.endswith('e'):
syllable_count -= 1
if syllable_count == 0:
syllable_count = 1
if syllable_count != 17:
continue
haiku = Haiku(
[
lines[0],
lines[1],
lines[2]
])
break
except json.JSONDecodeError:
continue
return haiku

View file

@ -1,9 +1,15 @@
from __future__ import annotations
from pathlib import Path
from flask import Flask, redirect, render_template, url_for
from flask import (Flask, redirect, render_template, request, url_for,
send_from_directory)
from senju.haiku import Haiku
from senju.store_manager import StoreManager
import os
app = Flask(__name__)
store = StoreManager(Path("/tmp/store.db"))
@ -46,9 +52,28 @@ def prompt_view():
title="Haiku generation"
)
@app.route("/scan")
def scan_view():
return render_template(
"scan.html",
title="Image scanning"
)
@app.route("/api/v1/haiku", methods=['POST'])
def generate_haiku():
if request.method == 'POST':
json_data = request.get_json()
prompt = json_data["prompt"]
haiku = Haiku.request_haiku(prompt)
id = store.save_haiku(haiku)
return str(id)
else:
return "Method not allowed", 405
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static/img'),
'favicon.ico',
mimetype='image/vnd.microsoft.icon')

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View file

@ -1,8 +1,10 @@
from typing import Optional
from tinydb import TinyDB
from pathlib import Path
from logging import Logger
from __future__ import annotations
from logging import Logger
from pathlib import Path
from typing import Optional
from tinydb import TinyDB
from tinydb.queries import QueryImpl
from senju.haiku import Haiku

View file

@ -5,21 +5,21 @@
<div class="bg-white text-gray-900 p-8 rounded-xl shadow-lg max-w-lg w-full text-center transform transition duration-300 hover:scale-105">
<h1 class="text-3xl font-bold text-violet-700 mb-4">Very 1337 prompt input</h1>
<div class="flex flex-col gap-4">
<input
type="text"
id="user-input"
placeholder="Type your prompt here..."
<input
type="text"
id="user-input"
placeholder="Type your prompt here..."
class="w-full px-4 py-3 text-lg border-2 border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-violet-600"
/>
<button
id="submit-btn"
<button
id="submit-btn"
class="bg-violet-600 text-white font-bold py-3 px-6 rounded-lg text-lg shadow-md transition duration-300 hover:bg-violet-700 hover:scale-105"
>
🚀 Submit
</button>
</div>
</div>
<div id="response-box" class="mt-8 bg-white text-gray-900 p-6 rounded-lg shadow-lg max-w-lg w-full text-center opacity-0 transition-opacity duration-500 ease-in-out">
<h2 class="text-2xl font-semibold text-violet-700">Response:</h2>
<p id="ai-response" class="text-lg text-gray-700 mt-2 italic">Waiting for input...</p>
@ -48,12 +48,26 @@ document.getElementById("submit-btn").addEventListener("click", function() {
responseText.textContent = "🤖 AI is thinking...";
responseBox.classList.remove("opacity-0");
// Simulated AI response delay
setTimeout(() => {
responseText.textContent = `"${userInput}" sounds interesting! Let's explore more! 🌟`;
}, 1500);
console.log(userInput );
fetch('/api/v1/haiku', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({'prompt': userInput})
})
.then(response => response.text())
.then(data => {
console.log(data);
let id = parseInt(data, 10);
window.location.href = "/haiku/"+id;
})
.catch(error => {
document.getElementById('result').innerHTML = '<strong>Error:</strong> ' + error.message;
});
}
});
</script>
{% endblock %}