ABDALLALSWAITI commited on
Commit
5e9c62d
·
verified ·
1 Parent(s): 9996b8e

Upload poster_server.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. poster_server.py +513 -0
poster_server.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mcp.server.fastmcp import FastMCP
2
+ from mcp import ClientSession
3
+ from mcp.client.sse import sse_client
4
+ import httpx
5
+ import os
6
+ import random
7
+ import sys
8
+ import json
9
+ import asyncio
10
+
11
+ # Initialize FastMCP server
12
+ mcp = FastMCP("PosterAgent - Modal Flux AI")
13
+
14
+ # Your Modal Flux MCP endpoint with SSE
15
+ FLUX_MCP_SSE_URL = "https://abedalswaity7--flux-mcp-app-ui.modal.run/gradio_api/mcp/sse"
16
+
17
+
18
+ def log(msg: str):
19
+ """Log to stderr to avoid interfering with MCP protocol on stdout"""
20
+ print(msg, file=sys.stderr, flush=True)
21
+
22
+
23
+ def estimate_trip_price(destination: str, budget: str, travelers: int, duration_days: int = 7) -> str:
24
+ """
25
+ Estimate trip price based on destination, budget level, and duration.
26
+ Returns formatted price string like "From $1,299" or "$2,500 Per Person"
27
+ """
28
+ # Base prices per person per day by budget level
29
+ budget_multipliers = {
30
+ "budget": (80, 150), # $80-150/day
31
+ "moderate": (200, 350), # $200-350/day
32
+ "luxury": (500, 1000) # $500-1000/day
33
+ }
34
+
35
+ # Destination cost factors (relative to average)
36
+ destination_factors = {
37
+ "paris": 1.2,
38
+ "tokyo": 1.3,
39
+ "dubai": 1.5,
40
+ "bali": 0.7,
41
+ "rome": 1.1,
42
+ "turkey": 0.8,
43
+ "india": 0.6,
44
+ "sri lanka": 0.65,
45
+ "maldives": 1.8,
46
+ "santorini": 1.3,
47
+ "new york": 1.4,
48
+ "london": 1.3,
49
+ "thailand": 0.6,
50
+ "vietnam": 0.5,
51
+ "morocco": 0.7,
52
+ "egypt": 0.6,
53
+ "mexico": 0.75,
54
+ "spain": 1.0,
55
+ "greece": 1.0,
56
+ "switzerland": 1.6,
57
+ }
58
+
59
+ # Get budget range
60
+ budget_lower = budget.lower() if budget else "moderate"
61
+ min_rate, max_rate = budget_multipliers.get(budget_lower, (200, 350))
62
+
63
+ # Get destination factor
64
+ dest_lower = destination.lower()
65
+ dest_factor = 1.0
66
+ for key, factor in destination_factors.items():
67
+ if key in dest_lower:
68
+ dest_factor = factor
69
+ break
70
+
71
+ # Calculate price range
72
+ base_price = ((min_rate + max_rate) / 2) * duration_days * dest_factor
73
+
74
+ # Add flight estimate based on destination
75
+ flight_estimates = {
76
+ "budget": 400,
77
+ "moderate": 800,
78
+ "luxury": 1500
79
+ }
80
+ flight_cost = flight_estimates.get(budget_lower, 800) * dest_factor
81
+
82
+ total_price = int(base_price + flight_cost)
83
+
84
+ # Round to nice numbers
85
+ if total_price < 1000:
86
+ total_price = round(total_price / 50) * 50
87
+ else:
88
+ total_price = round(total_price / 100) * 100
89
+
90
+ # Format based on budget level
91
+ if budget_lower == "luxury":
92
+ return f"${total_price:,} Per Person"
93
+ elif budget_lower == "budget":
94
+ return f"From ${total_price:,}"
95
+ else:
96
+ return f"From ${total_price:,} Per Person"
97
+
98
+
99
+ def create_professional_travel_poster_prompt(
100
+ destination: str,
101
+ origin: str = "",
102
+ dates: str = "",
103
+ duration: str = "",
104
+ price: str = "",
105
+ travelers: int = 2,
106
+ budget: str = "moderate",
107
+ interests: list = None,
108
+ company_name: str = "",
109
+ company_phone: str = "",
110
+ company_email: str = "",
111
+ company_website: str = "",
112
+ inclusions: list = None,
113
+ tagline: str = ""
114
+ ) -> str:
115
+ """
116
+ Create a professional travel agency poster prompt inspired by real tourism marketing.
117
+
118
+ Design elements from reference posters:
119
+ - Bold destination name with creative typography
120
+ - Polaroid-style photo collages with red pins
121
+ - Traveler silhouettes looking at horizon
122
+ - Trip details (dates, duration, price)
123
+ - Company branding section
124
+ - Icons for inclusions
125
+ - Gradient sky backgrounds (blue to orange sunset)
126
+ """
127
+
128
+ # Destination-specific landmarks and visual themes
129
+ destination_visuals = {
130
+ "paris": {
131
+ "landmarks": "Eiffel Tower, Arc de Triomphe, Seine River with bridges, Louvre pyramid",
132
+ "colors": "romantic sunset pink and orange, Parisian blue sky",
133
+ "vibe": "romantic, elegant, city of lights",
134
+ "hero_image": "Eiffel Tower at golden hour with city panorama"
135
+ },
136
+ "tokyo": {
137
+ "landmarks": "Mount Fuji with snow cap, Tokyo Tower, Shibuya crossing, cherry blossoms, traditional temples",
138
+ "colors": "cherry blossom pink, sunset orange, zen white, neon accents",
139
+ "vibe": "blend of ancient tradition and futuristic innovation",
140
+ "hero_image": "Mount Fuji with cherry blossoms in foreground"
141
+ },
142
+ "dubai": {
143
+ "landmarks": "Burj Khalifa, Palm Jumeirah, Dubai Marina yachts, desert dunes, Burj Al Arab",
144
+ "colors": "golden sand, luxury gold accents, Arabian blue sky",
145
+ "vibe": "ultra-luxury, futuristic architecture, desert mystique",
146
+ "hero_image": "Burj Khalifa piercing dramatic sunset sky"
147
+ },
148
+ "bali": {
149
+ "landmarks": "Tanah Lot temple, rice terraces, beach with palm trees, traditional gates, waterfalls",
150
+ "colors": "tropical green, turquoise ocean, sunset coral",
151
+ "vibe": "tropical paradise, spiritual serenity, natural beauty",
152
+ "hero_image": "iconic Bali temple silhouette at sunset over ocean"
153
+ },
154
+ "rome": {
155
+ "landmarks": "Colosseum, Trevi Fountain, St. Peter's Basilica dome, Roman Forum ruins",
156
+ "colors": "warm terracotta, marble white, Mediterranean blue",
157
+ "vibe": "ancient grandeur, timeless history, la dolce vita",
158
+ "hero_image": "majestic Colosseum with dramatic golden hour lighting"
159
+ },
160
+ "turkey": {
161
+ "landmarks": "Blue Mosque Istanbul, Cappadocia hot air balloons, Bodrum harbor, Hagia Sophia",
162
+ "colors": "turquoise blue, Ottoman gold, sunset orange",
163
+ "vibe": "crossroads of civilizations, exotic bazaars, coastal beauty",
164
+ "hero_image": "Blue Mosque with minarets against sunset sky"
165
+ },
166
+ "india": {
167
+ "landmarks": "Taj Mahal, Humayun's Tomb, Kerala backwaters, mountain peaks, colorful markets",
168
+ "colors": "marigold orange, royal purple, peacock blue",
169
+ "vibe": "incredible diversity, ancient wonders, spiritual journey",
170
+ "hero_image": "Taj Mahal at sunrise with reflection pool"
171
+ },
172
+ "sri lanka": {
173
+ "landmarks": "Sigiriya rock fortress, tea plantations, elephants, golden beaches, ancient temples",
174
+ "colors": "lush green, ocean blue, golden sand",
175
+ "vibe": "pearl of Indian Ocean, wildlife, ancient ruins",
176
+ "hero_image": "Sigiriya Lion Rock rising from misty jungle"
177
+ },
178
+ "maldives": {
179
+ "landmarks": "overwater bungalows, crystal lagoon, white sand beach, coral reefs",
180
+ "colors": "turquoise paradise blue, pure white, sunset gold",
181
+ "vibe": "ultimate luxury escape, pristine beaches, underwater paradise",
182
+ "hero_image": "overwater villas on crystal clear turquoise lagoon"
183
+ },
184
+ "santorini": {
185
+ "landmarks": "white-washed buildings, blue domes, caldera view, sunset at Oia",
186
+ "colors": "iconic Greek blue, pristine white, sunset pink",
187
+ "vibe": "romantic Greek island, breathtaking views, Mediterranean charm",
188
+ "hero_image": "famous blue domes overlooking Aegean Sea at sunset"
189
+ },
190
+ "new york": {
191
+ "landmarks": "Statue of Liberty, Empire State Building, Times Square, Brooklyn Bridge, Central Park",
192
+ "colors": "metropolitan silver, taxi yellow, skyline blue",
193
+ "vibe": "city that never sleeps, urban excitement, iconic skyline",
194
+ "hero_image": "Manhattan skyline with Statue of Liberty"
195
+ }
196
+ }
197
+
198
+ # Find matching destination style
199
+ dest_lower = destination.lower()
200
+ visuals = None
201
+ for key in destination_visuals:
202
+ if key in dest_lower:
203
+ visuals = destination_visuals[key]
204
+ break
205
+
206
+ if not visuals:
207
+ visuals = {
208
+ "landmarks": f"iconic landmarks and stunning scenery of {destination}",
209
+ "colors": "vibrant travel colors, sunset gradient sky",
210
+ "vibe": "adventure and discovery, wanderlust inspiration",
211
+ "hero_image": f"breathtaking panoramic view of {destination}"
212
+ }
213
+
214
+ # Build professional travel agency poster prompt
215
+ # Inspired by the reference images with polaroid collages, travelers, bold typography
216
+
217
+ dest_name = destination.split(",")[0].strip().upper()
218
+
219
+ # Tagline generation
220
+ if not tagline:
221
+ taglines = [
222
+ f"Explore Your {dest_name} Journey",
223
+ f"Discover {dest_name}",
224
+ f"Experience {dest_name}",
225
+ f"Your {dest_name} Adventure Awaits"
226
+ ]
227
+ tagline = random.choice(taglines)
228
+
229
+ # Build the professional prompt
230
+ prompt = f"""Professional travel agency advertisement poster for {destination} vacation package.
231
+
232
+ LAYOUT DESIGN (inspired by luxury travel marketing):
233
+ - Clean gradient background transitioning from bright blue sky at top to warm sunset orange/gold at bottom
234
+ - Large bold destination name "{dest_name}" displayed prominently in creative 3D typography with shadow effects, positioned in upper third
235
+ - Stylized tagline "{tagline}" in elegant script font above the destination name
236
+ - Main hero image: {visuals['hero_image']} as the dominant visual centerpiece
237
+
238
+ PHOTO COLLAGE ELEMENTS:
239
+ - 3 polaroid-style photo frames with white borders, slightly tilted at different angles
240
+ - Photos showing: {visuals['landmarks']}
241
+ - Red circular push-pins attached to each polaroid photo
242
+ - Photos arranged in artistic scattered layout
243
+
244
+ TRAVELERS ELEMENT:
245
+ - Silhouette of {travelers} travelers with backpacks and luggage standing on a road/path
246
+ - Looking towards the destination horizon, creating sense of adventure and anticipation
247
+ - Positioned in lower portion of poster
248
+
249
+ TRIP INFORMATION SECTION:"""
250
+
251
+ # Add trip details if provided
252
+ if dates:
253
+ prompt += f"\n- Travel dates: \"{dates}\" displayed in bold banner style"
254
+ if duration:
255
+ prompt += f"\n- Duration badge showing \"{duration}\" in rounded rectangle"
256
+
257
+ # Auto-calculate price if not provided
258
+ display_price = price
259
+ if not display_price:
260
+ # Extract duration days for price calculation
261
+ duration_days = 7 # default
262
+ if duration:
263
+ try:
264
+ # Parse "6N 7D" format
265
+ parts = duration.upper().split()
266
+ for p in parts:
267
+ if 'N' in p:
268
+ duration_days = int(p.replace('N', '')) + 1
269
+ break
270
+ elif 'D' in p:
271
+ duration_days = int(p.replace('D', ''))
272
+ break
273
+ except:
274
+ pass
275
+ display_price = estimate_trip_price(destination, budget, travelers, duration_days)
276
+
277
+ prompt += f"\n- Price display: \"{display_price}\" with 'Per Person' text in highlighted box"
278
+
279
+ # Add inclusions icons if provided
280
+ if inclusions:
281
+ icons_text = ", ".join(inclusions)
282
+ prompt += f"\n- Row of circular icons with labels for inclusions: {icons_text}"
283
+ else:
284
+ prompt += "\n- Row of circular icons for: Flights, Hotels, Tours & Transfers, Meals"
285
+
286
+ # Add company branding if provided
287
+ if company_name or company_phone or company_website:
288
+ prompt += "\n\nCOMPANY BRANDING SECTION (bottom of poster):"
289
+ if company_name:
290
+ prompt += f"\n- Company logo/name: \"{company_name}\" in professional styling"
291
+ if company_phone:
292
+ prompt += f"\n- Contact phone: \"{company_phone}\""
293
+ if company_email:
294
+ prompt += f"\n- Email: \"{company_email}\""
295
+ if company_website:
296
+ prompt += f"\n- Website: \"{company_website}\""
297
+ prompt += "\n- 'Book Now' call-to-action button"
298
+
299
+ prompt += f"""
300
+
301
+ VISUAL STYLE:
302
+ - Professional travel agency marketing design
303
+ - Color palette: {visuals['colors']}
304
+ - Mood: {visuals['vibe']}, inspiring wanderlust
305
+ - High-end glossy magazine advertisement quality
306
+ - Clean modern typography with excellent readability
307
+ - Balanced composition with clear visual hierarchy
308
+
309
+ TECHNICAL QUALITY:
310
+ - Ultra high resolution 4K quality
311
+ - Professional graphic design execution
312
+ - Photorealistic landmark images
313
+ - Clean vector-style graphics for icons and text
314
+ - Print-ready commercial quality"""
315
+
316
+ return prompt
317
+
318
+
319
+ @mcp.tool()
320
+ async def generate_poster_image(
321
+ destination: str,
322
+ origin: str = "",
323
+ dates: str = "",
324
+ duration: str = "",
325
+ price: str = "",
326
+ travelers: int = 2,
327
+ budget: str = "moderate",
328
+ interests: str = "",
329
+ company_name: str = "",
330
+ company_phone: str = "",
331
+ company_email: str = "",
332
+ company_website: str = "",
333
+ inclusions: str = "",
334
+ tagline: str = ""
335
+ ) -> str:
336
+ """
337
+ Generate a professional travel agency poster using Modal Flux AI.
338
+ Creates marketing-style posters with trip details, pricing, and company branding.
339
+
340
+ Args:
341
+ destination: The travel destination (e.g., "Paris, France", "Tokyo, Japan").
342
+ origin: Origin city for departure info (e.g., "New York").
343
+ dates: Travel dates to display (e.g., "Dec 28, 2025 - Jan 3, 2026").
344
+ duration: Trip duration (e.g., "6N 7D" for 6 nights 7 days).
345
+ price: Price to display (e.g., "$1,700" or "From $999").
346
+ travelers: Number of travelers (affects silhouette in poster).
347
+ budget: Budget level (budget/moderate/luxury) - affects styling.
348
+ interests: Comma-separated interests (e.g., "culture, food, adventure").
349
+ company_name: Travel company name for branding (e.g., "Wanderlust Travel").
350
+ company_phone: Contact phone number (e.g., "+1 800 555 1234").
351
+ company_email: Contact email (e.g., "[email protected]").
352
+ company_website: Company website (e.g., "www.travel.com").
353
+ inclusions: Comma-separated inclusions (e.g., "Visa, Flights, Hotels, Meals, Tours").
354
+ tagline: Custom tagline (e.g., "Discover Your Journey").
355
+
356
+ Returns:
357
+ Path to the generated poster image.
358
+ """
359
+ # Parse interests and inclusions
360
+ interests_list = [i.strip() for i in interests.split(",")] if interests else []
361
+ inclusions_list = [i.strip() for i in inclusions.split(",")] if inclusions else None
362
+
363
+ # Create the professional prompt
364
+ prompt = create_professional_travel_poster_prompt(
365
+ destination=destination,
366
+ origin=origin,
367
+ dates=dates,
368
+ duration=duration,
369
+ price=price,
370
+ travelers=travelers,
371
+ budget=budget,
372
+ interests=interests_list,
373
+ company_name=company_name,
374
+ company_phone=company_phone,
375
+ company_email=company_email,
376
+ company_website=company_website,
377
+ inclusions=inclusions_list,
378
+ tagline=tagline
379
+ )
380
+
381
+ safe_name = destination.lower().replace(' ', '_').replace(',', '').replace('.', '')
382
+ output_filename = f"poster_{safe_name}_{random.randint(1000, 9999)}.jpg"
383
+ full_path = os.path.abspath(output_filename)
384
+
385
+ log(f"🎨 Generating PROFESSIONAL travel agency poster for: '{destination}'")
386
+ log(f" Trip: {dates} | {duration} | {price}")
387
+ log(f" Company: {company_name or 'Generic'}")
388
+ log(f" MCP SSE: {FLUX_MCP_SSE_URL}")
389
+
390
+ # Use 9:16 portrait for social media / print poster style
391
+ aspect_ratio = "9:16 Portrait (768×1360)"
392
+
393
+ try:
394
+ # Connect to Flux MCP server via SSE
395
+ async with sse_client(FLUX_MCP_SSE_URL) as (read_stream, write_stream):
396
+ async with ClientSession(read_stream, write_stream) as session:
397
+ await session.initialize()
398
+
399
+ log("📡 Connected to Flux MCP server")
400
+
401
+ # List available tools
402
+ tools = await session.list_tools()
403
+ tool_name = "generate_flux_image"
404
+ for tool in tools.tools:
405
+ if "generate" in tool.name.lower():
406
+ tool_name = tool.name
407
+ break
408
+
409
+ log(f"🔧 Calling: {tool_name}")
410
+ log(f"📝 Prompt length: {len(prompt)} chars")
411
+
412
+ # Call with optimized parameters for quality
413
+ result = await session.call_tool(
414
+ tool_name,
415
+ arguments={
416
+ "prompt": prompt,
417
+ "aspect_ratio": aspect_ratio,
418
+ "quality_preset": "✨ Quality (35 steps)",
419
+ "guidance": 4.5, # Higher guidance for better prompt following
420
+ "seed": random.randint(1, 999999)
421
+ }
422
+ )
423
+
424
+ log(f"📦 Result received")
425
+
426
+ # Process the result
427
+ if result.content:
428
+ for item in result.content:
429
+ log(f"📄 Processing item type: {type(item).__name__}")
430
+
431
+ # Handle TextContent
432
+ if hasattr(item, 'text'):
433
+ text = item.text
434
+ log(f"📄 Text: {text[:200]}...")
435
+
436
+ if text.startswith("http"):
437
+ async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client:
438
+ img_resp = await client.get(text)
439
+ with open(full_path, "wb") as f:
440
+ f.write(img_resp.content)
441
+ log(f"✅ Professional poster saved: {full_path}")
442
+ return full_path
443
+
444
+ if "http" in text:
445
+ import re
446
+ urls = re.findall(r'https?://[^\s<>"{}|\\^`\[\]]+', text)
447
+ if urls:
448
+ async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client:
449
+ img_resp = await client.get(urls[0])
450
+ with open(full_path, "wb") as f:
451
+ f.write(img_resp.content)
452
+ log(f"✅ Professional poster saved: {full_path}")
453
+ return full_path
454
+
455
+ if text.startswith("/") and os.path.exists(text):
456
+ return text
457
+
458
+ return text
459
+
460
+ # Handle ImageContent
461
+ elif hasattr(item, 'data'):
462
+ data = item.data
463
+ log(f"📷 Image data type: {type(data)}")
464
+
465
+ if isinstance(data, str):
466
+ if data.startswith("http"):
467
+ async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client:
468
+ img_resp = await client.get(data)
469
+ with open(full_path, "wb") as f:
470
+ f.write(img_resp.content)
471
+ log(f"✅ Professional poster saved: {full_path}")
472
+ return full_path
473
+ elif data.startswith("data:image"):
474
+ import base64
475
+ base64_data = data.split(",")[1] if "," in data else data
476
+ img_bytes = base64.b64decode(base64_data)
477
+ with open(full_path, "wb") as f:
478
+ f.write(img_bytes)
479
+ log(f"✅ Professional poster saved: {full_path}")
480
+ return full_path
481
+ else:
482
+ try:
483
+ import base64
484
+ img_bytes = base64.b64decode(data)
485
+ with open(full_path, "wb") as f:
486
+ f.write(img_bytes)
487
+ log(f"✅ Professional poster saved: {full_path}")
488
+ return full_path
489
+ except:
490
+ return data
491
+ else:
492
+ with open(full_path, "wb") as f:
493
+ f.write(data)
494
+ log(f"✅ Professional poster saved: {full_path}")
495
+ return full_path
496
+
497
+ return "Error: No image data in response"
498
+
499
+ except Exception as e:
500
+ log(f"❌ Error: {e}")
501
+ import traceback
502
+ log(traceback.format_exc())
503
+ return f"Error: {str(e)}"
504
+
505
+
506
+ @mcp.tool()
507
+ def get_poster_status() -> str:
508
+ """Check if poster generation service is available."""
509
+ return f"Professional Travel Poster service ready. Creates marketing-style posters with trip details, pricing, and company branding. Using Modal Flux MCP at: {FLUX_MCP_SSE_URL}"
510
+
511
+
512
+ if __name__ == "__main__":
513
+ mcp.run()