mirror of
https://github.com/senju1337/senju.git
synced 2025-12-24 07:39:29 +00:00
Merge pull request #19 from senju1337/feat/ai_promts
Add the AI promt generation and then redirect to Haiku page
This commit is contained in:
commit
632bdf6612
9 changed files with 320 additions and 19 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
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
|
||||
|
||||
from senju.haiku import Haiku
|
||||
from senju.store_manager import StoreManager
|
||||
|
|
@ -45,3 +48,15 @@ def prompt_view():
|
|||
"prompt.html",
|
||||
title="Haiku generation"
|
||||
)
|
||||
|
||||
|
||||
@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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 %}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue