today_ai_weather/app/jobs/generate_weather_art_job.rb
songtianlun d728d7f50e feat: add batch weather art generation jobs
- Created BatchGenerateWeatherArtsJob to process eligible
  cities and generate weather art.
- Introduced GenerateWeatherArtJob for generating weather
  art and image attachment.
- Added AiService for obtaining prompts and generating
  images with OpenAI API.
- Implemented WeatherService to fetch current weather
  data from the QWeather API.
- Updated Gemfile with necessary gems (whenever,
  ruby-openai, httparty, down, aws-sdk-s3).

This commit introduces a system to create and store
weather art images for various cities based on current
weather conditions, leveraging external APIs for data
and image generation.
2025-01-22 16:50:00 +08:00

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