46 lines
1.2 KiB
Ruby
46 lines
1.2 KiB
Ruby
|
class GenerateWeatherArtJob < ApplicationJob
|
||
|
queue_as :default
|
||
|
|
||
|
def perform(*args)
|
||
|
city = args[0]
|
||
|
return if city.last_weather_fetch&.today?
|
||
|
|
||
|
weather_service = WeatherService.new
|
||
|
ai_service = AiService.new
|
||
|
|
||
|
# 获取天气数据
|
||
|
weather_data = weather_service.get_weather(city.latitude, city.longitude)
|
||
|
return unless weather_data
|
||
|
|
||
|
# 生成提示词
|
||
|
prompt = ai_service.generate_prompt(city, weather_data)
|
||
|
return unless prompt
|
||
|
|
||
|
# 生成图像
|
||
|
image_url = ai_service.generate_image(prompt)
|
||
|
return unless image_url
|
||
|
|
||
|
# 创建天气艺术记录
|
||
|
weather_art = city.weather_arts.create!(
|
||
|
weather_date: Date.today,
|
||
|
**weather_data,
|
||
|
prompt: prompt
|
||
|
)
|
||
|
|
||
|
# 下载并附加图像
|
||
|
tempfile = Down.download(image_url)
|
||
|
weather_art.image.attach(
|
||
|
io: tempfile,
|
||
|
filename: "#{city.country.name}-#{city.name.parameterize}-#{Time.current.strftime('%Y%m%d-%H%M%S')}.png"
|
||
|
)
|
||
|
|
||
|
# 更新城市状态
|
||
|
city.update!(
|
||
|
last_weather_fetch: Time.current,
|
||
|
last_image_generation: Time.current
|
||
|
)
|
||
|
rescue => e
|
||
|
Rails.logger.error "Error generating weather art for #{city.name}: #{e.message}"
|
||
|
end
|
||
|
end
|