Spaces:
Runtime error
Runtime error
File size: 5,930 Bytes
5ad097b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | import gradio as gr
import json
import time
import os
from pathlib import Path
from PIL import Image
from typing import Dict, List, Tuple, Any
import logging
import sys
# Add src to path for imports
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# Simple imports without complex dependencies
try:
from src.character_pipeline import create_pipeline
PIPELINE_AVAILABLE = True
print("β
RL Pipeline loaded successfully!")
except Exception as e:
print(f"β οΈ Pipeline not available: {e}")
PIPELINE_AVAILABLE = False
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class SimpleCharacterApp:
def __init__(self):
self.pipeline = None
if PIPELINE_AVAILABLE:
try:
self.pipeline = create_pipeline({
'use_rl_primary': True,
'rl_model_path': None
})
logger.info("β
RL Pipeline initialized successfully")
except Exception as e:
logger.error(f"β Pipeline initialization failed: {e}")
self.pipeline = None
def extract_attributes(self, image):
if image is None:
return "Please upload an image first.", "{}", "No image provided"
try:
start_time = time.time()
if self.pipeline and PIPELINE_AVAILABLE:
# Use real RL pipeline
attributes = self.pipeline.extract_from_image(image)
processing_time = time.time() - start_time
# Format output
formatted_output = "**π Character Attributes Extracted:**\n\n"
attr_dict = attributes.to_dict() if hasattr(attributes, 'to_dict') else {
"Age": getattr(attributes, 'age', 'Unknown'),
"Gender": getattr(attributes, 'gender', 'Unknown'),
"Hair Color": getattr(attributes, 'hair_color', 'Unknown'),
"Eye Color": getattr(attributes, 'eye_color', 'Unknown'),
"Confidence": getattr(attributes, 'confidence_score', 0.0)
}
for key, value in attr_dict.items():
if key == "Confidence" or "Score" in key:
formatted_output += f"**{key}:** {value:.3f}\n"
else:
formatted_output += f"**{key}:** {value}\n"
json_output = json.dumps(attr_dict, indent=2)
stats = f"β‘ Processing Time: {processing_time:.2f}s\nπ€ Mode: RL Pipeline\nβ
Status: Success"
else:
# Fallback mode with basic analysis
processing_time = time.time() - start_time
# Simple mock attributes
attr_dict = {
"Age": "Young Adult",
"Gender": "Unknown",
"Hair Color": "Unknown",
"Eye Color": "Unknown",
"Confidence": 0.5
}
formatted_output = "**π Character Attributes (Fallback Mode):**\n\n"
for key, value in attr_dict.items():
if key == "Confidence":
formatted_output += f"**{key}:** {value:.3f}\n"
else:
formatted_output += f"**{key}:** {value}\n"
json_output = json.dumps(attr_dict, indent=2)
stats = f"β‘ Processing Time: {processing_time:.2f}s\nπ Mode: Fallback\nβ οΈ Status: Limited functionality"
return formatted_output, json_output, stats
except Exception as e:
error_msg = f"β Error processing image: {str(e)}"
logger.error(error_msg)
error_dict = {
"error": str(e),
"status": "error"
}
return error_msg, json.dumps(error_dict, indent=2), "β Processing failed"
def create_interface():
app = SimpleCharacterApp()
with gr.Blocks(title="RL Character Extraction") as interface:
gr.Markdown("""
# π RL-Enhanced Character Attribute Extraction
Upload a character image to extract detailed attributes using our RL-powered pipeline.
""")
with gr.Row():
with gr.Column():
image_input = gr.Image(
type="pil",
label="πΈ Upload Character Image"
)
extract_btn = gr.Button(
"π Extract Attributes",
variant="primary"
)
with gr.Column():
formatted_output = gr.Markdown(
label="π Extracted Attributes",
value="Upload an image and click 'Extract Attributes' to see results."
)
stats_output = gr.Textbox(
label="π Processing Stats",
lines=3
)
json_output = gr.Code(
label="π JSON Output",
language="json"
)
extract_btn.click(
fn=app.extract_attributes,
inputs=[image_input],
outputs=[formatted_output, json_output, stats_output]
)
return interface
def main():
logger.info("π Starting Simple Character Attribute Extraction Interface...")
interface = create_interface()
port = int(os.environ.get("PORT", 7860))
interface.launch(
server_name="127.0.0.1",
server_port=port,
share=False,
show_error=True
)
if __name__ == "__main__":
main() |