-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathdemo.py
More file actions
executable file
·2165 lines (1884 loc) · 84.3 KB
/
demo.py
File metadata and controls
executable file
·2165 lines (1884 loc) · 84.3 KB
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import gradio as gr
import sys
import argparse
import json
import time
import hashlib
import base64
from PIL import Image
import requests
from urllib.parse import urlparse
from gradio_image_annotation import image_annotator
from werkzeug.utils import secure_filename # Add this import
from utils.system_prompt import SHORT_SYSTEM_PROMPT_WITH_THINKING
from utils.lua_converter import LuaConverter
from openai import OpenAI
# =============================
# Lightroom remote request utils
# =============================
def _is_local_server(url: str):
try:
parsed = urlparse(url)
hostname = (parsed.hostname or "").lower()
return hostname in ["localhost", "127.0.0.1", "::1"]
except Exception:
return False
def _send_photo_request_local(photo_path: str, lua_path: str, url: str, timeout: int):
payload = {
"photo_path": photo_path,
"lua_path": lua_path,
}
return requests.post(url, json=payload, timeout=timeout)
def _send_photo_request_remote(photo_path: str, lua_path: str, url: str, timeout: int):
files = {
"photo_file": (os.path.basename(photo_path), open(photo_path, "rb")),
"lua_file": (os.path.basename(lua_path), open(lua_path, "rb")),
}
data = {
"mode": "upload",
"photo_filename": os.path.basename(photo_path),
"lua_filename": os.path.basename(lua_path),
}
try:
return requests.post(url, files=files, data=data, timeout=timeout)
finally:
for file_tuple in files.values():
try:
file_tuple[1].close()
except Exception:
pass
def send_lightroom_request(photo_path: str, lua_path: str, url: str, timeout: int = 60, remote_mode: bool | None = None):
if not url:
raise ValueError("Lightroom server URL is empty")
if not os.path.exists(photo_path):
raise FileNotFoundError(f"Photo not found: {photo_path}")
if not os.path.exists(lua_path):
raise FileNotFoundError(f"Lua file not found: {lua_path}")
mode_remote = remote_mode if remote_mode is not None else (not _is_local_server(url))
if not mode_remote:
resp = _send_photo_request_local(photo_path, lua_path, url, timeout)
else:
resp = _send_photo_request_remote(photo_path, lua_path, url, timeout)
try:
ok = 200 <= resp.status_code < 300
body = resp.json() if resp.headers.get("content-type", "").startswith("application/json") else resp.text
return ok, resp.status_code, body
except Exception:
return False, resp.status_code, resp.text
def extract_json_from_answer(answer):
"""
Extract configuration data from the answer string and convert to JSON
Args:
answer (str): The answer string containing configuration data
Returns:
list: List with exactly one configuration object
"""
import ast
import re
print(f"🔍 Extracting configuration from answer...")
def find_complete_dict(text, start_pos=0):
"""Find complete dictionary, handling nested cases"""
brace_count = 0
start_found = False
start_idx = 0
for i in range(start_pos, len(text)):
char = text[i]
if char == '{':
if not start_found:
start_idx = i
start_found = True
brace_count += 1
elif char == '}':
brace_count -= 1
if brace_count == 0 and start_found:
return text[start_idx:i+1]
return None
# Method 1: Find complete dictionary structure
dict_start = answer.find('{')
if dict_start != -1:
complete_dict_str = find_complete_dict(answer, dict_start)
if complete_dict_str:
print(f"Found complete dictionary, length: {len(complete_dict_str)}")
try:
config_dict = ast.literal_eval(complete_dict_str)
if isinstance(config_dict, dict) and len(config_dict) > 0:
print(f"✅ Successfully extracted configuration with {len(config_dict)} parameters")
print(f"📦 Config keys: {list(config_dict.keys())[:10]}...") # Show first 10 keys
return [config_dict]
except Exception as e:
print(f"⚠️ Failed to parse complete dict: {str(e)[:100]}...")
# Method 2: Fallback to original method (if new method fails)
print("🔄 Falling back to regex pattern matching...")
# Find Python dict pattern in answer
# Look for patterns like "{'key': value, ...}"
dict_pattern = r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}'
matches = re.findall(dict_pattern, answer, re.DOTALL)
print(f"Found {len(matches)} potential matches")
# Find the largest match
largest_match = None
largest_size = 0
for match in matches:
try:
# Try to parse as Python dict using ast.literal_eval
config_dict = ast.literal_eval(match)
if isinstance(config_dict, dict) and len(config_dict) > largest_size:
largest_match = config_dict
largest_size = len(config_dict)
print(f"📦 Found larger config with {len(config_dict)} parameters")
except Exception as e:
print(f"⚠️ Failed to parse dict: {str(e)[:50]}...")
continue
if largest_match:
print(f"✅ Successfully extracted configuration with {len(largest_match)} parameters")
print(f"📦 Config keys: {list(largest_match.keys())[:10]}...") # Show first 10 keys
return [largest_match]
print("❌ No valid configuration data found in answer")
return []
def json_to_lua(json_data, save_folder, filename="config.lua"):
"""
Convert JSON data to Lua format and save to file
Args:
json_data (dict or str): JSON data to convert
save_folder (str): Folder to save the Lua file
filename (str): Filename for the Lua file
Returns:
tuple: (file_path, error_message)
"""
try:
# Ensure save folder exists
os.makedirs(save_folder, exist_ok=True)
# Parse JSON if it's a string
if isinstance(json_data, str):
try:
json_obj = json.loads(json_data)
except:
return None, f"Error parsing JSON: Invalid JSON format"
else:
json_obj = json_data
save_path = os.path.join(save_folder, filename)
# Convert to Lua format using LuaConverter
try:
lua_content = LuaConverter.to_lua(json_obj)
with open(save_path, "w", encoding="utf-8") as f:
f.write('return %s' % lua_content)
return save_path, None
except Exception as e:
return None, f"Error writing Lua file: {str(e)}"
except Exception as e:
return None, f"Error in json_to_lua: {str(e)}"
# API client class, used to replace ChatModel
class APIClient:
def __init__(self, api_endpoint, api_port, model_name="qwen2_vl", api_key="0"):
"""
Initialize API client
Args:
api_endpoint (str): API server address
api_port (int): API server port
model_name (str): Model name
api_key (str): API key
"""
self.model_name = model_name
self.api_endpoint = api_endpoint
self.api_port = api_port
self.api_connected = False
try:
self.client = OpenAI(
api_key=api_key,
base_url=f"http://{api_endpoint}:{api_port}/v1",
timeout=30.0 # Increase timeout to 30 seconds
)
print(f"✅ API client initialized successfully, connected to http://{api_endpoint}:{api_port}/v1")
# Test API connection (non-blocking)
try:
print("🔍 Testing API connection...")
response = self.client.models.list()
available_models = [model.id for model in response.data]
print(f"✅ API connection test successful! Available models: {available_models}")
self.api_connected = True
except Exception as e:
print(f"⚠️ API connection test failed: {str(e)}")
print("⚠️ Program will continue to start, but API functionality may not be available")
self.api_connected = False
except Exception as e:
print(f"❌ API client initialization failed: {str(e)}")
print("⚠️ Program will continue to start, but API functionality is unavailable")
self.client = None
self.api_connected = False
def chat(self, messages, system=None, images=None, **kwargs):
"""
Chat with model via API
Args:
messages (list): Message list
system (str): System prompt
images (list): Image path list
**kwargs: Other parameters
Returns:
list: List containing Response objects
"""
try:
# Prepare message format
formatted_messages = []
# Add system message
if system:
formatted_messages.append({
"role": "system",
"content": system
})
# Process user messages and images
for msg in messages:
if images and msg["role"] == "user":
# If there are images, add them to user message
content = []
# Add images
for img_path in images:
# Read and encode image
with open(img_path, "rb") as img_file:
img_base64 = base64.b64encode(img_file.read()).decode("utf-8")
content.append({
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{img_base64}"
}
})
# Add text
content.append({
"type": "text",
"text": msg["content"]
})
formatted_messages.append({
"role": msg["role"],
"content": content
})
else:
# Regular text message
formatted_messages.append(msg)
# Call API
response = self.client.chat.completions.create(
model=self.model_name,
messages=formatted_messages,
stream=False,
timeout=60, # Increase timeout
**kwargs
)
# Create Response object for compatibility with existing code
class Response:
def __init__(self, text):
self.response_text = text
# Return list containing Response object
return [Response(response.choices[0].message.content)]
except Exception as e:
print(f"❌ API call failed: {str(e)}")
return [Response(f"Error occurred during API call: {str(e)}")]
def stream_chat(self, messages, system=None, images=None, **kwargs):
"""
Stream chat with model via API
Args:
messages (list): Message list
system (str): System prompt
images (list): Image path list
**kwargs: Other parameters
Yields:
str: Model generated text fragments
"""
# Check API connection status
if not self.api_connected or self.client is None:
yield f"❌ API connection unavailable. Please check the following settings:\n"
yield f"• API endpoint: {self.api_endpoint}:{self.api_port}\n"
yield f"• Ensure SSH port forwarding is running\n"
yield f"• Ensure API is running on remote server\n"
yield f"• Try restarting the program"
return
try:
# Prepare message format
formatted_messages = []
# Add system message
if system:
formatted_messages.append({
"role": "system",
"content": system
})
# Process user messages and images
for msg in messages:
if images and msg["role"] == "user":
# If there are images, add them to user message
content = []
# Add images
for img_path in images:
# Read and encode image
with open(img_path, "rb") as img_file:
img_base64 = base64.b64encode(img_file.read()).decode("utf-8")
content.append({
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{img_base64}"
}
})
# Add text
content.append({
"type": "text",
"text": msg["content"]
})
formatted_messages.append({
"role": msg["role"],
"content": content
})
else:
# Regular text message
formatted_messages.append(msg)
# Call API (streaming)
response_stream = self.client.chat.completions.create(
model=self.model_name,
messages=formatted_messages,
stream=True,
timeout=120, # Increase streaming call timeout
**kwargs
)
# Yield generated text fragments one by one
for chunk in response_stream:
if chunk.choices[0].delta.content is not None:
yield chunk.choices[0].delta.content
except Exception as e:
print(f"❌ Streaming API call failed: {str(e)}")
yield f"❌ API call error: {str(e)}\n"
yield f"Please check network connection and API service status."
# Parse command line arguments
def parse_args():
parser = argparse.ArgumentParser(description="JarvisArt Gradio Demo")
parser.add_argument(
"--model_name",
type=str,
default="qwen2_vl",
help="Model name to use for API calls"
)
parser.add_argument(
"--api_endpoint",
type=str,
default="localhost",
help="API server endpoint"
)
parser.add_argument(
"--api_port",
type=int,
default=8001,
help="API server port"
)
parser.add_argument(
"--api_key",
type=str,
default="0",
help="API key for authentication"
)
parser.add_argument(
"--server_port",
type=int,
default=7880, # Change to standard Gradio port
help="Port for the Gradio server"
)
parser.add_argument(
"--server_name",
type=str,
default="127.0.0.1",
help="Server name/IP for the Gradio server"
)
parser.add_argument(
"--share",
action="store_true",
help="Enable public sharing via Gradio tunnel (creates public URL)"
)
parser.add_argument(
"--lr_url",
type=str,
default=os.environ.get("LR_SERVER_URL", "http://127.0.0.1:7777"),
help="Lightroom server URL (e.g., http://127.0.0.1:7777)"
)
parser.add_argument(
"--lr_timeout",
type=int,
default=int(os.environ.get("LR_SERVER_TIMEOUT", "60")),
help="Lightroom request timeout in seconds"
)
parser.add_argument(
"--lr_remote",
type=str,
default=os.environ.get("LR_REMOTE", "true"),
help="Remote upload mode (true/false). Default: true"
)
return parser.parse_args()
# Get command line arguments
args = parse_args()
# Avatar file path configuration
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
USER_AVATAR_PATH = os.path.join(SCRIPT_DIR, "assets", "user_avatar.svg")
AI_AVATAR_PATH = os.path.join(SCRIPT_DIR, "assets", "ai_avatar.svg")
# System prompt - pre-designed system prompt
system_prompt = SHORT_SYSTEM_PROMPT_WITH_THINKING
# Default user prompt
default_user_prompt = "I want a dreamy, romantic sunset vibe with soft, warm colors and gentle glow."
# Initialize API client
print(f"Connecting to API server {args.api_endpoint}:{args.api_port}...")
print("🔧 Connection configuration:")
print(f" 📍 API Address: {args.api_endpoint}")
print(f" 🚪 API Port: {args.api_port}")
print(f" 🤖 Model Name: {args.model_name}")
print(f" 🔑 API Key: {'Set' if args.api_key != '0' else 'Default'}")
chat_model = APIClient(
api_endpoint=args.api_endpoint,
api_port=args.api_port,
model_name=args.model_name,
api_key=args.api_key
)
# Check API connection status
if hasattr(chat_model, 'api_connected') and chat_model.api_connected:
print("✅ Connecting to API server...")
else:
print("⚠️ API client initialized, but connection may have issues")
print("💡 Common solutions:")
print(f" 1. Check if API service is running at {args.api_endpoint}:{args.api_port}")
print(" 2. Check firewall settings")
print(" 3. Try using a different port (e.g., --api_port 8001)")
print(" 4. If API is on a remote server, check SSH port forwarding")
print(" 5. Use command line arguments: --api_endpoint <address> --api_port <port>")
print("="*60)
def parse_llm_response(response):
"""
Parse the LLM response to extract reason and answer sections
Args:
response (str): The raw response from the LLM
Returns:
tuple: (reason, answer) extracted from the response
"""
# Ensure response is a string
response = str(response)
# Try to parse <think> and <answer> tags (corresponding to SYSTEM_PROMPT_WITH_THINKING)
think_match = re.search(r'<think>(.*?)</think>', response, re.DOTALL)
answer_match = re.search(r'<answer>(.*?)</answer>', response, re.DOTALL)
if think_match and answer_match:
thinking = think_match.group(1).strip()
answer = answer_match.group(1).strip()
return thinking, answer
# If nothing found, return the entire response as the answer with empty thinking
return "AI is thinking...", response
def extract_models_from_answer(answer):
"""
Extract model names from the answer string using regex
Args:
answer (str): The answer string containing model recommendations
Returns:
list: List of extracted model names
"""
# Pattern to match [type:xxx]:(model:xxx)
pattern = r'\[type:[^\]]+\]:\(model:([^)]+)\)'
models = re.findall(pattern, answer)
return models
def get_llm_response_with_custom_prompt(image_path, user_prompt):
"""
Get response from JarvisArt model using API client
Args:
image_path (str): Path to the input image
user_prompt (str): User-defined prompt for analysis
Returns:
str: Complete response from the model
"""
try:
# Prepare message format according to training format
messages = [
{
"role": "user",
"content": str(user_prompt) # User prompt
}
]
# Prepare image input
images = [image_path] if image_path else None
# Use API client for inference
responses = chat_model.chat(
messages=messages,
system=system_prompt, # System prompt
images=images, # Image input
)
# Extract response text
if responses and len(responses) > 0:
return str(responses[0].response_text)
else:
return "Model did not return a valid response"
except Exception as e:
return f"Error occurred during inference: {str(e)}"
def get_llm_response_with_custom_prompt_stream(image_path, user_prompt, max_new_tokens=10240, top_k=50, top_p=0.8, temperature=0.7):
"""
Get streaming response from JarvisArt model using API client
Args:
image_path (str): Path to the input image
user_prompt (str): User-defined prompt for analysis
max_new_tokens (int): Maximum number of new tokens to generate
top_k (int): Top-k sampling parameter
top_p (float): Top-p (nucleus) sampling parameter
temperature (float): Temperature for sampling
Yields:
str: Streaming response tokens from the model
"""
global chat_model
if chat_model is None:
yield "❌ API client not initialized. Please restart the program."
return
try:
# Prepare message format according to training format
messages = [
{
"role": "user",
"content": str(user_prompt) # User prompt
}
]
# Prepare image input
images = [image_path] if image_path else None
# Prepare generation parameters
generation_kwargs = {
"max_tokens": max_new_tokens,
"temperature": temperature
}
# Only add top_k and top_p parameters when API supports them
if hasattr(chat_model, 'api_connected') and chat_model.api_connected:
# Note: OpenAI API may not support top_k parameter, only use temperature and top_p
generation_kwargs["top_p"] = top_p
# Use API client for streaming inference
for new_token in chat_model.stream_chat(
messages=messages,
system=system_prompt, # System prompt
images=images, # Image input
**generation_kwargs # Pass generation parameters
):
yield new_token
except Exception as e:
yield f"❌ Error during inference: {str(e)}"
def process_upload(file):
return file
def compact_text(text):
"""
Process the text, remove extra line breaks and spaces, and make the text more compact
Args:
text (str): Input text
Returns:
str: Processed text
"""
# Remove extra line breaks
text = re.sub(r'\n\s*\n', '\n', text)
# Remove leading whitespace
text = re.sub(r'\n\s+', '\n', text)
# Remove extra spaces
text = re.sub(r' {2,}', ' ', text)
return text
def send_to_lightroom_now(chat_history, lr_url, lr_timeout, remote_mode, last_image_path, last_lua_path):
"""Trigger Lightroom request manually from UI and append result to chat."""
chat_history = chat_history or []
if not last_image_path or not last_lua_path:
chat_history.append({
"role": "assistant",
"content": "<div style='margin:0;padding:0'>⚠️ <strong>No generated files</strong><br/>Please generate recommendations first to produce the Lua config and copied image.</div>"
})
return chat_history
try:
chat_history.append({
"role": "assistant",
"content": "<div style='margin:0;padding:0'>📤 <strong>Sending to Lightroom server...</strong></div>"
})
ok, status, body = send_lightroom_request(
last_image_path, last_lua_path, lr_url, int(lr_timeout) if lr_timeout else 60, bool(remote_mode)
)
if ok:
msg = f"<div style='margin:0;padding:0'>✅ <strong>Lightroom processed successfully</strong><br/><em>Status:</em> {status}<br/><em>Response:</em> {body}</div>"
else:
msg = f"<div style='margin:0;padding:0'>❌ <strong>Lightroom request failed</strong><br/><em>Status:</em> {status}<br/><em>Response:</em> {body}</div>"
chat_history.append({"role": "assistant", "content": msg})
except Exception as e:
chat_history.append({
"role": "assistant",
"content": f"<div style='margin:0;padding:0'>❌ <strong>Lightroom request error</strong><br/>{str(e)}</div>"
})
return chat_history
def get_box_coordinates(annotated_image_dict, prompt_original):
"""
Processes the output from the image_annotator to extract
and format the bounding box coordinates.
"""
global local_dict
if annotated_image_dict and annotated_image_dict["boxes"]:
# Get the last drawn box
input_image = annotated_image_dict["image"]
pil_image = Image.open(input_image)
last_box = annotated_image_dict["boxes"][-1]
width, height = pil_image.width, pil_image.height
xmin = last_box["xmin"] / width
ymin = last_box["ymin"] / height
xmax = last_box["xmax"] / width
ymax = last_box["ymax"] / height
local_dict[input_image] = [xmin, ymin, xmax, ymax]
# Format the coordinates into a string
return str([xmin, ymin, xmax, ymax]), " In the region <box></box>, xxx"
return "No box drawn", prompt_original
def process_analysis_pipeline_stream(image_dict, user_prompt, max_new_tokens, top_k, top_p, temperature, lr_url, lr_timeout, remote_mode, auto_send):
"""
Main analysis pipeline with streaming output, modern chat interface style, and image display support
Args:
image (str): Path to the input image
user_prompt (str): User-defined prompt for analysis
max_new_tokens (int): Maximum number of new tokens to generate
top_k (int): Top-k sampling parameter
top_p (float): Top-p (nucleus) sampling parameter
temperature (float): Temperature for sampling
Yields:
tuple: (chat_history, last_image_path, last_lua_path)
"""
# Track last paths for Lightroom request
last_image_path = ""
last_lua_path = ""
if image_dict is None:
yield [
{"role": "user", "content": "Please upload an image first! 📸"},
{"role": "assistant", "content": "I need an image to analyze before I can provide editing recommendations."}
], last_image_path, last_lua_path
return
image = image_dict['image']
if not user_prompt.strip():
user_prompt = default_user_prompt
elif len(local_dict) > 0 and local_dict[image][0] != local_dict[image][2]:
user_prompt = user_prompt.replace('<box></box>', f'<box>{str(local_dict[image])}</box>')
try:
# Initialize chat history with user message including image
chat_history = []
# Create user message with image and instructions - using messages format
user_message_text = f"**Instructions:** {user_prompt}".replace('<box>', f'(').replace('</box>', f')')
# Add user message with image
if image_dict:
# For messages format, we need to handle images differently
# First add the image
chat_history.append({
"role": "user",
"content": {
"path": image,
"mime_type": "image/jpeg"
}
})
# Then add text message
chat_history.append({
"role": "user",
"content": user_message_text
})
else:
chat_history.append({
"role": "user",
"content": user_message_text
})
yield chat_history, last_image_path, last_lua_path
# JarvisArt starts responding
chat_history.append({
"role": "assistant",
"content": "<div style='margin:0;padding:0'>🎨 <strong style='margin:0;padding:0'>JarvisArt is analyzing your image...</strong><br/><em>Please wait while I examine the details and understand your vision.</em></div>"
})
ai_message_index = len(chat_history) - 1 # Record AI message index position
recommendations_index = None # Initialize recommendations message index
yield chat_history, last_image_path, last_lua_path
# Get streaming response
full_response = ""
token_count = 0
update_frequency = 8 # Reduce update frequency for smoother experience
# Stage marker
stage = "starting" # starting, thinking, answer, completed
answer_completed = False # Flag to track if answer is completed
for new_token in get_llm_response_with_custom_prompt_stream(
image, user_prompt, max_new_tokens, top_k, top_p, temperature
):
full_response += new_token
token_count += 1
# Detect thinking stage
if "<think>" in full_response and stage == "starting":
stage = "thinking"
chat_history[ai_message_index] = {
"role": "assistant",
"content": "💭 **Thinking Process**\n*Analyzing image characteristics and understanding your creative vision...*"
}
yield chat_history, last_image_path, last_lua_path
continue
# Thinking completed
if "</think>" in full_response and stage == "thinking":
stage = "between"
think_match = re.search(r'<think>(.*?)</think>', full_response, re.DOTALL)
if think_match:
thinking_content = think_match.group(1).strip()
# Use the compact_text function to process text
thinking_content = compact_text(thinking_content).replace('<box>', f'(').replace('</box>', f')')
# Use special formatting to force eliminate spacing
formatted_thinking = f"<div style='margin:0;padding:0'>💭 <strong style='margin:0;padding:0'>Thinking</strong><div style='margin:0;padding:0'>{thinking_content}</div></div>"
chat_history[ai_message_index] = {
"role": "assistant",
"content": formatted_thinking
}
yield chat_history, last_image_path, last_lua_path
continue
# Detect answer stage
if "<answer>" in full_response and stage in ["between", "thinking"]:
stage = "answer"
# Use special formatting to force eliminate spacing
initial_recommendations = "<div style='margin:0;padding:0;margin-top:-30px'>✨ <strong style='margin:0;padding:0'>Professional Editing Recommendations</strong><div style='margin:0;padding:0'>*Generating personalized editing suggestions...*</div></div>"
chat_history.append({
"role": "assistant",
"content": initial_recommendations
})
recommendations_index = len(chat_history) - 1 # Record recommendations message index
yield chat_history, last_image_path, last_lua_path
continue
# Answer completed
if "</answer>" in full_response and stage == "answer" and not answer_completed:
stage = "completed"
answer_completed = True
answer_match = re.search(r'<answer>(.*?)</answer>', full_response, re.DOTALL)
if answer_match:
answer_content = answer_match.group(1).strip()
# Use the compact_text function to process text
answer_content = compact_text(answer_content)
# Use special formatting to force eliminate spacing
formatted_answer = f"<div style='margin:0;padding:0;margin-top:-30px'>✨ <strong style='margin:0;padding:0'>Professional Editing Recommendations</strong><div style='margin:0;padding:0'>{answer_content}</div></div>"
chat_history[recommendations_index] = {
"role": "assistant",
"content": formatted_answer
}
yield chat_history, last_image_path, last_lua_path
# Don't break here - continue to Final completion for JSON extraction
# Real-time content updates (reduced frequency) - only if answer not completed
if token_count % update_frequency == 0 and not answer_completed:
if stage == "thinking":
current_thinking = full_response.split("<think>")[-1].replace("</think>", "").strip()
if current_thinking and len(current_thinking) > 20: # Avoid displaying too short content
# Use the compact_text function to process text
current_thinking = compact_text(current_thinking)
# Use special formatting to force eliminate spacing
formatted_thinking = f"<div style='margin:0;padding:0'>💭 <strong style='margin:0;padding:0'>Thinking</strong><div style='margin:0;padding:0'>{current_thinking}...<br/><em>Still analyzing...</em></div></div>"
chat_history[ai_message_index] = {
"role": "assistant",
"content": formatted_thinking
}
yield chat_history, last_image_path, last_lua_path
elif stage == "answer":
current_answer = full_response.split("<answer>")[-1].replace("</answer>", "").strip()
if current_answer and len(current_answer) > 30: # Avoid displaying too short content
# Use the compact_text function to process text
current_answer = compact_text(current_answer)
# Use special formatting to force eliminate spacing
formatted_answer = f"<div style='margin:0;padding:0;margin-top:-30px'>✨ <strong style='margin:0;padding:0'>JarvisArt Recommendations</strong><div style='margin:0;padding:0'>{current_answer}...<br/><em>Generating more suggestions...</em></div></div>"
if recommendations_index is not None:
chat_history[recommendations_index] = {
"role": "assistant",
"content": formatted_answer
}
else:
chat_history.append({
"role": "assistant",
"content": formatted_answer
})
recommendations_index = len(chat_history) - 1
yield chat_history, last_image_path, last_lua_path
# Final completion
if stage == "completed":
# Analysis is complete, now process and save lua files
print(f"🔍 Debug: Final completion stage reached")
answer_match = re.search(r'<answer>(.*?)</answer>', full_response, re.DOTALL)
if answer_match:
answer_content = answer_match.group(1).strip()
print(f"🔍 Debug: Extracted answer content (first 200 chars): {answer_content[:200]}...")
# Extract JSON objects from the answer
json_objects = extract_json_from_answer(answer_content)
print(f"🔍 Debug: Found {len(json_objects)} JSON objects")
# Save JSON objects as lua files
if json_objects:
print(f"🔍 Debug: Processing {len(json_objects)} JSON objects for conversion")
conversion_index = None
chat_history.append({
"role": "assistant",
"content": "<div style='margin:0;padding:0;margin-top:-20px'>⚙️ <strong style='margin:0;padding:0'>Lightroom Configuration Converting...</strong><br/><em>Converting editing parameters to Lightroom-compatible format...</em></div>"
})
conversion_index = len(chat_history) - 1
yield chat_history, last_image_path, last_lua_path
# Create lua_results folder in the same directory as this script
script_dir = os.path.dirname(os.path.abspath(__file__))
results_dir = os.path.join(script_dir, "results")
os.makedirs(results_dir, exist_ok=True)
# Generate timestamp for unique session folder name
timestamp = int(time.time())
session_folder_name = f"example_{timestamp}"
session_dir = os.path.join(results_dir, session_folder_name)
os.makedirs(session_dir, exist_ok=True)
# Copy the uploaded image to the session folder
import shutil
# Use secure_filename and hash to generate unique original image filename, avoiding conflicts with processed images
original_filename = secure_filename(os.path.basename(image))
file_hash = hashlib.md5(f"{original_filename}_{time.time()}".encode()).hexdigest()
# Keep original extension
file_ext = os.path.splitext(original_filename)[1] or '.jpg'
unique_original_filename = f"original_{file_hash}{file_ext}"
image_dest_path = os.path.join(session_dir, unique_original_filename)
shutil.copy2(image, image_dest_path)
last_image_path = image_dest_path
# Save the full model response to a text file
response_file_path = os.path.join(session_dir, "full_response.txt")
with open(response_file_path, "w", encoding="utf-8") as f:
f.write(full_response)
# Save user prompt to a text file
prompt_file_path = os.path.join(session_dir, "user_prompt.txt")
with open(prompt_file_path, "w", encoding="utf-8") as f:
f.write(user_prompt)
saved_files = []
for i, json_obj in enumerate(json_objects):
filename = f"config_{i+1}.lua"
lua_path, error = json_to_lua(json_obj, session_dir, filename)
if lua_path:
saved_files.append(lua_path)
print(f"✅ Saved Lua config: {lua_path}")
if not last_lua_path:
last_lua_path = lua_path
else:
print(f"❌ Failed to save Lua config {i+1}: {error}")
# Update file save notification
if saved_files:
save_notification = "<div style='margin:0;padding:0;margin-top:-20px'>"
save_notification += "✅ <strong style='margin:0;padding:0'>Files saved successfully!</strong><br/>"
save_notification += "📁 <strong>Save location:</strong> <code>results/" + session_folder_name + "/</code><br/>"
save_notification += "📄 <strong>Generated files:</strong><br/>"
save_notification += " • Original image: <code>" + unique_original_filename + "</code><br/>"
save_notification += " • Full response: <code>full_response.txt</code><br/>"
save_notification += " • User prompt: <code>user_prompt.txt</code><br/>"
save_notification += " • Config files: " + str(len(saved_files)) + " files"
save_notification += "<br/><strong>Config files:</strong>"
for i, file_path in enumerate(saved_files):
filename = os.path.basename(file_path)
save_notification += "<br/> • <code>" + filename + "</code>"