agharsallah
commited on
Commit
·
d82e593
1
Parent(s):
682ed52
adding 3d
Browse files- .env.example +4 -1
- app.py +4 -1
- controllers/app_controller.py +16 -9
- services/mesh_service.py +96 -0
- ui/components.py +141 -0
- util/mistral_api_client.py +9 -3
.env.example
CHANGED
@@ -18,4 +18,7 @@ MCP_SERVER_URL="your-mcp-server-url-here"
|
|
18 |
#Used to test mcp function calling
|
19 |
OPENAI_API_KEY="your-openai-api-key-here"
|
20 |
#Used to Parse the PDFs for story enrichment
|
21 |
-
LLAMA_CLOUD_API_KEY="your-llama-cloud-api-key-here"
|
|
|
|
|
|
|
|
18 |
#Used to test mcp function calling
|
19 |
OPENAI_API_KEY="your-openai-api-key-here"
|
20 |
#Used to Parse the PDFs for story enrichment
|
21 |
+
LLAMA_CLOUD_API_KEY="your-llama-cloud-api-key-here"
|
22 |
+
|
23 |
+
# Used for 3D mesh generation
|
24 |
+
THREE_D_API_URL="your-3d-api-url-here"
|
app.py
CHANGED
@@ -26,6 +26,7 @@ from ui.components import (
|
|
26 |
create_chapter_navigation,
|
27 |
create_chapter_accordion,
|
28 |
create_story_melody_section,
|
|
|
29 |
)
|
30 |
from ui.mcp_components import letter_counter_component
|
31 |
from controllers.app_controller import (
|
@@ -34,7 +35,6 @@ from controllers.app_controller import (
|
|
34 |
)
|
35 |
from ui.events import setup_event_handlers
|
36 |
|
37 |
-
|
38 |
# Configure logging
|
39 |
logging.basicConfig(
|
40 |
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
@@ -152,6 +152,9 @@ def create_app():
|
|
152 |
outputs=[melody_output, melody_status],
|
153 |
)
|
154 |
|
|
|
|
|
|
|
155 |
# TODO DELETE THIS AS IT IRRELEVENT TO STORY GENERATION
|
156 |
""" with gr.Tab("Character Counter"):
|
157 |
letter_counter_component() """
|
|
|
26 |
create_chapter_navigation,
|
27 |
create_chapter_accordion,
|
28 |
create_story_melody_section,
|
29 |
+
create_3d_model_viewer,
|
30 |
)
|
31 |
from ui.mcp_components import letter_counter_component
|
32 |
from controllers.app_controller import (
|
|
|
35 |
)
|
36 |
from ui.events import setup_event_handlers
|
37 |
|
|
|
38 |
# Configure logging
|
39 |
logging.basicConfig(
|
40 |
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
|
152 |
outputs=[melody_output, melody_status],
|
153 |
)
|
154 |
|
155 |
+
# 3D Model Viewer Tab (demo)
|
156 |
+
create_3d_model_viewer(story_text)
|
157 |
+
|
158 |
# TODO DELETE THIS AS IT IRRELEVENT TO STORY GENERATION
|
159 |
""" with gr.Tab("Character Counter"):
|
160 |
letter_counter_component() """
|
controllers/app_controller.py
CHANGED
@@ -46,16 +46,19 @@ def process_story_generation(
|
|
46 |
|
47 |
# Process PDF if provided
|
48 |
pdf_content = ""
|
|
|
|
|
49 |
if pdf_file:
|
50 |
logger.info("Extracting text from PDF")
|
51 |
pdf_content = extract_text_from_pdf(pdf_file)
|
52 |
# summarize the PDF content for better prompting using mistral
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
|
|
59 |
logger.error(f"PDF extraction error: {pdf_content}")
|
60 |
|
61 |
# Generate story
|
@@ -73,7 +76,7 @@ def process_story_generation(
|
|
73 |
|
74 |
if story_response.startswith("Error:"):
|
75 |
logger.error(f"Story generation error: {story_response}")
|
76 |
-
return "", story_response,
|
77 |
|
78 |
try:
|
79 |
# Parse JSON response
|
@@ -84,12 +87,16 @@ def process_story_generation(
|
|
84 |
return (title, story, gr.update(interactive=True, visible=True))
|
85 |
except json.JSONDecodeError:
|
86 |
logger.error("Failed to parse story JSON response")
|
87 |
-
return
|
|
|
|
|
|
|
|
|
88 |
|
89 |
except Exception as e:
|
90 |
error_msg = f"Unexpected error during story generation: {str(e)}"
|
91 |
logger.error(error_msg, exc_info=True)
|
92 |
-
return f"Error: {error_msg}"
|
93 |
|
94 |
|
95 |
def process_chapters(
|
|
|
46 |
|
47 |
# Process PDF if provided
|
48 |
pdf_content = ""
|
49 |
+
summarized_pdf = "" # Initialize with empty string by default
|
50 |
+
|
51 |
if pdf_file:
|
52 |
logger.info("Extracting text from PDF")
|
53 |
pdf_content = extract_text_from_pdf(pdf_file)
|
54 |
# summarize the PDF content for better prompting using mistral
|
55 |
+
if pdf_content and not pdf_content.startswith("Error:"):
|
56 |
+
mistral_api = MistralAPI()
|
57 |
+
summarized_pdf = mistral_api.send_request(
|
58 |
+
f"Summarize the following Text content into a single-sentence children's story without any explanations, tags, or formatting—just plain text in one line.: {pdf_content}"
|
59 |
+
)["choices"][0]["message"]["content"]
|
60 |
+
logger.info(f"summarized_pdf: {summarized_pdf}")
|
61 |
+
else:
|
62 |
logger.error(f"PDF extraction error: {pdf_content}")
|
63 |
|
64 |
# Generate story
|
|
|
76 |
|
77 |
if story_response.startswith("Error:"):
|
78 |
logger.error(f"Story generation error: {story_response}")
|
79 |
+
return "", story_response, gr.update(interactive=False)
|
80 |
|
81 |
try:
|
82 |
# Parse JSON response
|
|
|
87 |
return (title, story, gr.update(interactive=True, visible=True))
|
88 |
except json.JSONDecodeError:
|
89 |
logger.error("Failed to parse story JSON response")
|
90 |
+
return (
|
91 |
+
"",
|
92 |
+
f"Error: Failed to parse story response: {story_response}",
|
93 |
+
gr.update(interactive=False),
|
94 |
+
)
|
95 |
|
96 |
except Exception as e:
|
97 |
error_msg = f"Unexpected error during story generation: {str(e)}"
|
98 |
logger.error(error_msg, exc_info=True)
|
99 |
+
return "", f"Error: {error_msg}", gr.update(interactive=False)
|
100 |
|
101 |
|
102 |
def process_chapters(
|
services/mesh_service.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
from typing import Dict, Any, Optional, TypedDict, Union, Literal
|
5 |
+
from pathlib import Path
|
6 |
+
import base64
|
7 |
+
|
8 |
+
|
9 |
+
class ModelData(TypedDict):
|
10 |
+
prompt: str
|
11 |
+
model: str
|
12 |
+
format: str
|
13 |
+
mesh_base64: str
|
14 |
+
|
15 |
+
|
16 |
+
class MeshResponse(TypedDict):
|
17 |
+
text: str
|
18 |
+
model_data: ModelData
|
19 |
+
model: str
|
20 |
+
image_base64: str
|
21 |
+
used_image_input: bool
|
22 |
+
|
23 |
+
|
24 |
+
class ErrorResponse(TypedDict):
|
25 |
+
error: str
|
26 |
+
|
27 |
+
|
28 |
+
OutputFormatType = Literal["glb", "obj", "stl"]
|
29 |
+
|
30 |
+
|
31 |
+
def get_mesh_base64(
|
32 |
+
text: str, apply_texture: bool = False, output_format: OutputFormatType = "glb"
|
33 |
+
) -> Union[MeshResponse, ErrorResponse]:
|
34 |
+
"""
|
35 |
+
Retrieve the base64 encoded mesh data for the 3D model viewer by making an API call.
|
36 |
+
|
37 |
+
Args:
|
38 |
+
text (str): The description of the 3D model.
|
39 |
+
apply_texture (bool): Whether to apply texture to the model.
|
40 |
+
output_format (OutputFormatType): The desired output format ('glb', 'obj', or 'stl').
|
41 |
+
|
42 |
+
Returns:
|
43 |
+
Union[MeshResponse, ErrorResponse]: The API response as JSON or an error message.
|
44 |
+
"""
|
45 |
+
url = os.getenv("THREE_D_API_URL", "https://3d-model-inference-api.com")
|
46 |
+
|
47 |
+
headers = {"Content-Type": "application/json"}
|
48 |
+
payload = {
|
49 |
+
"text": text,
|
50 |
+
"apply_texture": apply_texture,
|
51 |
+
"output_format": output_format,
|
52 |
+
}
|
53 |
+
|
54 |
+
try:
|
55 |
+
response = requests.post(
|
56 |
+
url,
|
57 |
+
headers=headers,
|
58 |
+
data=json.dumps(payload),
|
59 |
+
)
|
60 |
+
response.raise_for_status() # Raise an exception for HTTP errors
|
61 |
+
return response.json()
|
62 |
+
except requests.exceptions.RequestException as e:
|
63 |
+
return {"error": f"Error retrieving mesh data: {str(e)}"}
|
64 |
+
except json.JSONDecodeError:
|
65 |
+
return {"error": "Failed to parse API response as JSON"}
|
66 |
+
|
67 |
+
|
68 |
+
def transform_base64_to_glb_file(base64_data, output_path=None):
|
69 |
+
"""
|
70 |
+
Transform a base64-encoded GLB model to a .glb file and return the path for gr.Model3D
|
71 |
+
|
72 |
+
Args:
|
73 |
+
base64_data (str): The base64-encoded GLB data
|
74 |
+
output_path (str, optional): Path where to save the .glb file.
|
75 |
+
If None, creates a temp file in assets/models/
|
76 |
+
|
77 |
+
Returns:
|
78 |
+
str: The path to the saved .glb file
|
79 |
+
"""
|
80 |
+
if output_path is None:
|
81 |
+
# Create models directory if it doesn't exist
|
82 |
+
models_dir = Path("assets/models")
|
83 |
+
models_dir.mkdir(parents=True, exist_ok=True)
|
84 |
+
output_path = models_dir / "model.glb"
|
85 |
+
|
86 |
+
# Ensure parent directories exist
|
87 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
88 |
+
|
89 |
+
# Decode the base64 data
|
90 |
+
binary_data = base64.b64decode(base64_data)
|
91 |
+
|
92 |
+
# Write the binary data to a .glb file
|
93 |
+
with open(output_path, "wb") as f:
|
94 |
+
f.write(binary_data)
|
95 |
+
|
96 |
+
return str(output_path)
|
ui/components.py
CHANGED
@@ -5,6 +5,9 @@ UI components for the Magic Story Creator application
|
|
5 |
import gradio as gr
|
6 |
from config import constants
|
7 |
|
|
|
|
|
|
|
8 |
|
9 |
def create_header():
|
10 |
"""Create the main header section of the application"""
|
@@ -415,3 +418,141 @@ def create_story_melody_section():
|
|
415 |
)
|
416 |
|
417 |
return generate_melody_button, melody_status, melody_output
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import gradio as gr
|
6 |
from config import constants
|
7 |
|
8 |
+
from services.mesh_service import get_mesh_base64, transform_base64_to_glb_file
|
9 |
+
from util.mistral_api_client import MistralAPI
|
10 |
+
|
11 |
|
12 |
def create_header():
|
13 |
"""Create the main header section of the application"""
|
|
|
418 |
)
|
419 |
|
420 |
return generate_melody_button, melody_status, melody_output
|
421 |
+
|
422 |
+
|
423 |
+
# TODO split this further later
|
424 |
+
def create_3d_model_viewer(story: str = "simple yellow duck"):
|
425 |
+
"""
|
426 |
+
Create a 3D model viewer component that displays a mesh from a base64 string.
|
427 |
+
For now, this uses a placeholder HTML with a message and a download link for the mesh.
|
428 |
+
In a real app, you would use a JS 3D viewer (e.g., Three.js) embedded in the HTML.
|
429 |
+
"""
|
430 |
+
|
431 |
+
def get_prompt_from_story(story_text):
|
432 |
+
"""
|
433 |
+
Extract a prompt from the story text for generating a 3D model.
|
434 |
+
|
435 |
+
Uses Mistral API to analyze the story and generate an appropriate
|
436 |
+
3D model prompt based on characters, objects, or scenes in the story.
|
437 |
+
|
438 |
+
Args:
|
439 |
+
story_text (str): The story text to analyze
|
440 |
+
|
441 |
+
Returns:
|
442 |
+
str: A concise prompt suitable for 3D model generation
|
443 |
+
"""
|
444 |
+
try:
|
445 |
+
import logging
|
446 |
+
|
447 |
+
logger = logging.getLogger(__name__)
|
448 |
+
|
449 |
+
# Initialize Mistral API
|
450 |
+
mistral_api = MistralAPI()
|
451 |
+
|
452 |
+
# Create a prompt for extracting a 3D model description
|
453 |
+
system_prompt = """
|
454 |
+
You are an assistant that analyzes children's stories and extracts
|
455 |
+
concise descriptions of key objects, characters, or scenes that would
|
456 |
+
make a good 3D model. Focus on something iconic from the story that
|
457 |
+
would be visually interesting and meaningful to the child.
|
458 |
+
"""
|
459 |
+
|
460 |
+
instruction_prompt = f"""
|
461 |
+
Read this children's story and suggest a simple, clear description for a 3D model
|
462 |
+
that represents an important element from the story (character, object, or scene).
|
463 |
+
|
464 |
+
Keep your response to a single phrase or short sentence (max 10 words)
|
465 |
+
that clearly describes what to model in 3D. Don't use any formatting,
|
466 |
+
explanations, or additional text - just the model description itself.
|
467 |
+
|
468 |
+
Story: {story_text[:1500]}...
|
469 |
+
"""
|
470 |
+
|
471 |
+
# Send request to Mistral API
|
472 |
+
logger.info("Generating 3D model prompt from story text")
|
473 |
+
response = mistral_api.send_request(instruction_prompt, system_prompt)
|
474 |
+
|
475 |
+
# Extract the model prompt from the response
|
476 |
+
if "choices" in response and len(response["choices"]) > 0:
|
477 |
+
model_prompt = response["choices"][0]["message"]["content"].strip()
|
478 |
+
|
479 |
+
# Clean up the prompt to ensure it's suitable for 3D generation
|
480 |
+
# Remove quotes if present and limit length
|
481 |
+
model_prompt = model_prompt.strip("\"'").split(".")[0]
|
482 |
+
if len(model_prompt) > 100:
|
483 |
+
model_prompt = model_prompt[:100]
|
484 |
+
|
485 |
+
logger.info(f"Generated 3D model prompt: {model_prompt}")
|
486 |
+
return model_prompt
|
487 |
+
else:
|
488 |
+
logger.error("Failed to generate model prompt from Mistral API")
|
489 |
+
return "magical storybook character"
|
490 |
+
|
491 |
+
except Exception as e:
|
492 |
+
logger.error(f"Error generating 3D model prompt: {e}")
|
493 |
+
return "friendly cartoon character from a children's story"
|
494 |
+
|
495 |
+
generated_prompt_from_story = get_prompt_from_story(story)
|
496 |
+
prompt_state = gr.State(value=generated_prompt_from_story)
|
497 |
+
|
498 |
+
gr.HTML("""
|
499 |
+
<div class="image-header-wrapper" style="margin: 30px 0 15px 0;">
|
500 |
+
<h1 class="sub-header" style="margin-left: 16px; padding-bottom: 36px;">
|
501 |
+
Create a Magical 3D Model from Your Story!
|
502 |
+
</h1>
|
503 |
+
</div>
|
504 |
+
<p class="text" style="font-size: 1.2em; text-align: center;">Click the button below to generate a 3D model from your story!</p>
|
505 |
+
""")
|
506 |
+
|
507 |
+
with gr.Blocks(elem_classes="melody-box"):
|
508 |
+
with gr.Row():
|
509 |
+
with gr.Column(scale=1, min_width=200):
|
510 |
+
generate_model_button = gr.Button(
|
511 |
+
"Create 3D Model 🎨",
|
512 |
+
variant="primary",
|
513 |
+
elem_classes="melody-button",
|
514 |
+
)
|
515 |
+
|
516 |
+
with gr.Column(scale=2):
|
517 |
+
model_viewer = gr.Model3D(label="3D Model Viewer", clear_color=[0.0, 0.0, 0.0, 0.0])
|
518 |
+
|
519 |
+
model_status = gr.Markdown("", visible=False)
|
520 |
+
|
521 |
+
# Add status message and model display
|
522 |
+
|
523 |
+
def generate_3d_model(prompt):
|
524 |
+
model_response = get_mesh_base64(
|
525 |
+
text=prompt, apply_texture=False, output_format="glb"
|
526 |
+
)
|
527 |
+
|
528 |
+
# Check if response contains an error
|
529 |
+
if "error" in model_response:
|
530 |
+
return None, f"Error: {model_response['error']}"
|
531 |
+
|
532 |
+
# Check if the expected data structure exists
|
533 |
+
if (
|
534 |
+
"model_data" not in model_response
|
535 |
+
or "mesh_base64" not in model_response["model_data"]
|
536 |
+
):
|
537 |
+
return (
|
538 |
+
None,
|
539 |
+
"Error: Received unexpected response format from 3D model API",
|
540 |
+
)
|
541 |
+
|
542 |
+
try:
|
543 |
+
glb_file_path = transform_base64_to_glb_file(
|
544 |
+
model_response["model_data"]["mesh_base64"]
|
545 |
+
)
|
546 |
+
return (
|
547 |
+
glb_file_path,
|
548 |
+
f"Successfully generated 3D model: {prompt}",
|
549 |
+
)
|
550 |
+
except Exception as e:
|
551 |
+
return None, f"Error processing model data: {str(e)}"
|
552 |
+
|
553 |
+
# Connect the button to the generation function
|
554 |
+
generate_model_button.click(
|
555 |
+
generate_3d_model,
|
556 |
+
inputs=[prompt_state],
|
557 |
+
outputs=[model_viewer, model_status],
|
558 |
+
)
|
util/mistral_api_client.py
CHANGED
@@ -8,8 +8,9 @@ logger = logging.getLogger(__name__)
|
|
8 |
|
9 |
# Constants
|
10 |
MISTRAL_API_ENDPOINT = "https://api.mistral.ai/v1/chat/completions"
|
11 |
-
MISTRAL_MODEL = "
|
12 |
API_KEY_ENV_VAR = "MISTRAL_API_KEY"
|
|
|
13 |
|
14 |
|
15 |
class MistralAPI:
|
@@ -26,7 +27,9 @@ class MistralAPI:
|
|
26 |
)
|
27 |
self.mistral_model = mistral_model
|
28 |
|
29 |
-
def send_request(
|
|
|
|
|
30 |
"""
|
31 |
Send a request to the Mistral API with the given prompt.
|
32 |
|
@@ -44,7 +47,10 @@ class MistralAPI:
|
|
44 |
|
45 |
data = {
|
46 |
"model": self.mistral_model,
|
47 |
-
"messages": [
|
|
|
|
|
|
|
48 |
}
|
49 |
|
50 |
try:
|
|
|
8 |
|
9 |
# Constants
|
10 |
MISTRAL_API_ENDPOINT = "https://api.mistral.ai/v1/chat/completions"
|
11 |
+
MISTRAL_MODEL = "ministral-8b-latest"
|
12 |
API_KEY_ENV_VAR = "MISTRAL_API_KEY"
|
13 |
+
DEFAULT_SYSTEM_PROMPT = "You are a helpful assistant. Please respond to the user's queries with just text and no additional formatting or explanations."
|
14 |
|
15 |
|
16 |
class MistralAPI:
|
|
|
27 |
)
|
28 |
self.mistral_model = mistral_model
|
29 |
|
30 |
+
def send_request(
|
31 |
+
self, prompt: str, system_prompt: str = DEFAULT_SYSTEM_PROMPT
|
32 |
+
) -> Dict:
|
33 |
"""
|
34 |
Send a request to the Mistral API with the given prompt.
|
35 |
|
|
|
47 |
|
48 |
data = {
|
49 |
"model": self.mistral_model,
|
50 |
+
"messages": [
|
51 |
+
{"role": "system", "content": system_prompt},
|
52 |
+
{"role": "user", "content": prompt},
|
53 |
+
],
|
54 |
}
|
55 |
|
56 |
try:
|