Spaces:
Runtime error
Runtime error
File size: 8,463 Bytes
4f038ca | 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 | import json
import streamlit as st
import matplotlib.pyplot as plt
import plotly.graph_objs as go
import plotly.express as px
import re
from json_repair import repair_json
def extract_week_data(json_str):
# Find all JSON-like objects in the string
json_objects = re.findall(r'\{[^{}]*\}', json_str)
weeks_data = []
for obj in json_objects:
try:
# Replace single quotes with double quotes for valid JSON
obj = obj.replace("'", '"')
data = json.loads(obj)
# Check if this object contains week data
if 'week_number' in data and 'domestic_projection' in data and 'international_projection' in data:
weeks_data.append(data)
except json.JSONDecodeError:
continue
return weeks_data
def analyze_and_process_market(analysis):
st.write("### Market Analysis")
st.write("Raw analysis:")
st.code(analysis)
try:
box_office_data = repair_json(analysis)
box_office_data = json.loads(box_office_data)
weeks = [f"Week {data['week_number']}" for data in box_office_data.values()]
domestic_projections = [data["domestic_projection"] for data in box_office_data.values()]
international_projections = [data["international_projection"] / 1000000 for data in box_office_data.values()] # Convert to millions
# Create a Streamlit app
st.title("Box Office Projections Over 8 Weeks")
st.write("This app visualizes the domestic and international box office projections for each week of a film's release.")
# Plotting Domestic Projections
fig_domestic, ax_domestic = plt.subplots(figsize=(10, 6))
domestic_bars = ax_domestic.bar(weeks, domestic_projections, color='b')
ax_domestic.set_ylabel('Domestic Earnings (₹ Crores)')
ax_domestic.set_title('Domestic Box Office Projections')
for bar in domestic_bars:
yval = bar.get_height()
ax_domestic.text(bar.get_x() + bar.get_width() / 2, yval + 0.2, f"{yval:.1f}", ha='center', va='bottom', fontsize=10)
st.pyplot(fig_domestic)
# Plotting International Projections
fig_international, ax_international = plt.subplots(figsize=(10, 6))
international_bars = ax_international.bar(weeks, international_projections, color='r')
ax_international.set_ylabel('International Earnings ($ Million)')
ax_international.set_title('International Box Office Projections')
for bar in international_bars:
yval = bar.get_height()
ax_international.text(bar.get_x() + bar.get_width() / 2, yval + 0.02, f"{yval:.2f}", ha='center', va='bottom', fontsize=10)
st.pyplot(fig_international)
except Exception as e:
st.error(f"Error processing data for Market Analysis: {e}")
# Display additional analysis text
additional_text = re.sub(r'\{[^{}]*\}', '', analysis).strip()
if additional_text:
st.write("#### Additional Analysis")
st.write(additional_text)
# import json
# from utils import client
# import streamlit as st
# import plotly.graph_objs as go
# import plotly.express as px
# import re
# def analyze_market(thread_id, additional_context=None):
# # Note: You might need to create a new assistant for market analysis
# run = client.beta.threads.runs.create(
# thread_id=thread_id,
# assistant_id="asst_ykSNeNu74RsJPkOxLTPYHQ36" # Replace with the actual assistant ID for market analysis
# )
# while run.status in ['queued', 'in_progress', 'cancelling']:
# run = client.beta.threads.runs.retrieve(
# thread_id=thread_id,
# run_id=run.id
# )
# if run.status == 'completed':
# messages = client.beta.threads.messages.list(thread_id=thread_id)
# analysis = next((msg.content[0].text.value for msg in reversed(list(messages)) if msg.role == "assistant"), "")
# return analysis
# else:
# return f"Error: Run status is {run.status}"
# def usd_to_inr(usd_value):
# return usd_value * 75
# def extract_number(value):
# if isinstance(value, (int, float)):
# return value
# if isinstance(value, str):
# return float(re.sub(r'[^\d.]', '', value))
# return 0
# def process_market_analysis(analysis):
# st.write("### Market Analysis")
# st.write(analysis) # Display the raw analysis first
# try:
# # Extract all JSON-like objects from the response
# json_objects = re.findall(r'\{[^}]+\}', analysis)
# weeks_data = []
# for json_str in json_objects:
# try:
# # Replace single quotes with double quotes, except within the "factors_influencing" field
# json_str = re.sub(r"'([^']*)':", r'"\1":', json_str)
# json_str = json_str.replace("'Pellichoopulu'", '"Pellichoopulu"')
# # Parse the JSON
# week_data = json.loads(json_str)
# # Clean up the data
# domestic = extract_number(week_data.get('domestic_projection', 0))
# international = extract_number(week_data.get('international_projection', 0))
# cleaned_data = {
# "week_number": week_data.get('week_number', 'Unknown'),
# "domestic_projection": domestic,
# "international_projection": international,
# "factors_influencing": week_data.get('factors_influencing', 'Not specified')
# }
# weeks_data.append(cleaned_data)
# except json.JSONDecodeError as e:
# st.warning(f"Couldn't parse JSON object: {json_str}\nError: {str(e)}")
# # Box office projections
# st.write("#### Box Office Projections")
# domestic_projections = []
# international_projections = []
# for week_data in weeks_data:
# domestic = week_data['domestic_projection']
# international = week_data['international_projection']
# # Convert to INR
# domestic_inr = usd_to_inr(domestic)
# international_inr = usd_to_inr(international)
# domestic_projections.append(domestic_inr)
# international_projections.append(international_inr)
# st.write(f"**{week_data['week_number']}**")
# st.write(f"Domestic: ₹{domestic_inr:,.2f}")
# st.write(f"International: ₹{international_inr:,.2f}")
# st.write(f"Factors: {week_data['factors_influencing']}")
# st.write("---")
# # Visualize box office projections
# if weeks_data:
# weeks = [data['week_number'] for data in weeks_data]
# fig = go.Figure()
# fig.add_trace(go.Bar(x=weeks, y=domestic_projections, name='Domestic'))
# fig.add_trace(go.Bar(x=weeks, y=international_projections, name='International'))
# fig.update_layout(title='Weekly Box Office Projections (in INR)', barmode='group')
# st.plotly_chart(fig)
# # Total projections
# total_domestic = sum(domestic_projections)
# total_international = sum(international_projections)
# st.write("#### Total Projections")
# st.write(f"Total Domestic: ₹{total_domestic:,.2f}")
# st.write(f"Total International: ₹{total_international:,.2f}")
# st.write(f"Total Global: ₹{total_domestic + total_international:,.2f}")
# # Pie chart for domestic vs international split
# fig = px.pie(values=[total_domestic, total_international],
# names=['Domestic', 'International'],
# title='Domestic vs International Box Office Split')
# st.plotly_chart(fig)
# else:
# st.warning("No valid data found for creating visualizations.")
# except Exception as e:
# st.error(f"Error processing data for Market Analysis: {e}")
# st.code(analysis) |